问:
Android Studio: Package name not set to a valid package name

I want to create an activity in the "layout" package so I right-clicked it and selected new activity and it's giving me this error. How do I resolve it?

答:
I want to create an activity in the "layout" package

First, I strongly recommend getting some fundamental knowledge about Android.

As for your question - layout is NOT a package name. Packages are visible under java node in your project structure view (in Android mode). What you see  in res node are resources (images, XMLs etc). It's not a place to put your code, yet you can create package "layout" by hand if you really need, however you'd be violating package name conventions: See docs on the subject http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html


来源: stackexchange

问:
Android checkbox and text box on top of the other
I have the following FrameLayout, this layout is used to my RecyclerView as the rows. In etch row I have text box and checkbox. The problem is the checkbox and the text box are connected to each other and the checkbox on the top of the text and it's hide the text box.

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style="@style/Base.Widget.AppCompat.Button.Borderless"
    />

<!-- quick and dirty divider -->
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</FrameLayout>
</code>```

I would be happy if someone can help me to fix this problem. Thanks.

答:
try the layout below:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style=""
    />

<!-- quick and dirty divider -->
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold"
    android:text="textview" />

</LinearLayout>
</FrameLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following FrameLayout, this layout is used to my RecyclerView as the rows. In etch row I have text box and checkbox. The problem is the checkbox and the text box are connected to each other and the checkbox on the top of the text and it's hide the text box.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style="@style/Base.Widget.AppCompat.Button.Borderless"
    />

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</FrameLayout>

I would be happy if someone can help me to fix this problem. Thanks.

Body:
try the layout below:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style=""
    />

<!-- quick and dirty divider -->
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold"
    android:text="textview" />

</LinearLayout>
</FrameLayout>


问:
$location.path() doesn't work despite setting $apply() or $timeout
I'm putting together my own Auth Service in an AngularJS application I am building and in my Controller I have the following code that calls a serive. The service deals with a log in, if there is a match I want to redirect to my home/main page... this is my Controller code

```<code>$scope.login = function (user) {
      // we have the user name and password let's see if account exists...
      AuthService.login(user).success(function (response) {

        // what have we received? if the length > 0 we have a match
        if (response.length !== 0) {
          StorageService.makeLocalKey('uuid', response[0].uuid); // this works!
          $location.path('/'); // the current path is /login, nothing happens, the browser path/ window doesn't change?
          console.log($location.path()); // this gives '/' but I am not taken to main route and the URL isn't changed in the browser, it's still /login
        } else {
          $scope.errorNotFound = true;
        }

}
</code>```

Now when I replace the $location.path('/'); with

```<code>$scope.$apply(function () {
  $location.path('/');
});
</code>```

I get the following error in the console: Error: [$rootScope:inprog] $digest already in progress

So I tried the following...

```<code>$timeout(function () {
  $location.path('/');
});
</code>```

but nothing happens! What am I doing wrong?

答:
I was getting this issue from a ng-click event from an  element. The cause was that the href="#" part of the  tag was causing a redirection before my $location.path('') code was executing.... Once I removed the href="#" attribute it worked fine.

Hope this helps other people.

Body:
I'm putting together my own Auth Service in an AngularJS application I am building and in my Controller I have the following code that calls a serive. The service deals with a log in, if there is a match I want to redirect to my home/main page... this is my Controller code

$scope.login = function (user) {
      // we have the user name and password let's see if account exists...
      AuthService.login(user).success(function (response) {

        // what have we received? if the length > 0 we have a match
        if (response.length !== 0) {
          StorageService.makeLocalKey('uuid', response[0].uuid); // this works!
          $location.path('/'); // the current path is /login, nothing happens, the browser path/ window doesn't change?
          console.log($location.path()); // this gives '/' but I am not taken to main route and the URL isn't changed in the browser, it's still /login
        } else {
          $scope.errorNotFound = true;
        }

}

Now when I replace the $location.path('/'); with

$scope.$apply(function () {
  $location.path('/');
});

I get the following error in the console: Error: [$rootScope:inprog] $digest already in progress

So I tried the following...

$timeout(function () {
  $location.path('/');
});

but nothing happens! What am I doing wrong?


问:
Select same table twice, in single query
My table:

```<code>id | views | date
1  | 100   | 2017-03-09
2  | 150   | 2017-03-10
3  | 300   | 2017-03-11
4  | 350   | 2017-03-12
</code>```

I need to calculate visit count difference between days something like this

```<code>2017-03-12-->Visitors:350
2017-03-11-->Visitors:300
Difference between days:50

2017-03-11-->Visitors:300
2017-03-10-->Visitors:150
Difference between days:150

2017-03-10-->Visitors:150
2017-03-09-->Visitors:100
Difference between days:50

and so on...
</code>```

I managed to get similar results, but not exatcly what i wanted

```<code>$sql = "SELECT * FROM `table` ORDER BY `table`.`id` DESC";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{

    $t = $row['views'];
    $dat = $row['date'];

    $sql1 = "SELECT * FROM `table` ORDER BY `table`.`id` DESC LIMIT 1, 99";
    $result1 = mysql_query($sql1) or die(mysql_error());
    while($row1 = mysql_fetch_array($result1))
    {

        $y = $row1['views'];
        $dat1 = $row1['date'];

        $d = $t-$y;

        echo "{$dat}-->Visitors:{$t}";
        echo "<br/>";
        echo "{$dat1}-->Visitors:{$y}";
        echo "<br/>";
        echo "Difference between days:{$d}";
        echo "<br/><br/><br/>";
    }
}
</code>```

So i guess i need to select same table twice with one query.

答:
No need for SQL acrobatics here.

You are displaying the lines in date order. Simply keep the count from last line inside a variable, substract in php, and you have your difference.

Remove your nested loops. You only need one loop.

```<code>$last_views = null;

while($row = mysql_fetch_array($result))
{
    $views = $row['views'];
    $dat   = $row1['date'];

    if( $last_views === null )
         $delta_views = "";
    else
         $delta_views = $last_views - $views;

    $last_views = $views;

    echo "{$dat}-->Visitors:{$views}";
    echo "<br/>";
    echo "Difference between days:{$delta_views}";
    echo "<br/>";
}
</code>```

Body:
My table:

id | views | date
1  | 100   | 2017-03-09
2  | 150   | 2017-03-10
3  | 300   | 2017-03-11
4  | 350   | 2017-03-12

I need to calculate visit count difference between days something like this

2017-03-12-->Visitors:350
2017-03-11-->Visitors:300
Difference between days:50

2017-03-11-->Visitors:300
2017-03-10-->Visitors:150
Difference between days:150

2017-03-10-->Visitors:150
2017-03-09-->Visitors:100
Difference between days:50

and so on...

I managed to get similar results, but not exatcly what i wanted

$sql = "SELECT * FROM `table` ORDER BY `table`.`id` DESC";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{

    $t = $row['views'];
    $dat = $row['date'];

    $sql1 = "SELECT * FROM `table` ORDER BY `table`.`id` DESC LIMIT 1, 99";
    $result1 = mysql_query($sql1) or die(mysql_error());
    while($row1 = mysql_fetch_array($result1))
    {

        $y = $row1['views'];
        $dat1 = $row1['date'];

        $d = $t-$y;

        echo "{$dat}-->Visitors:{$t}";
        echo "
";
        echo "{$dat1}-->Visitors:{$y}";
        echo "
";
        echo "Difference between days:{$d}";
        echo "

";
    }
}

So i guess i need to select same table twice with one query.

Body:
No need for SQL acrobatics here.

You are displaying the lines in date order. Simply keep the count from last line inside a variable, substract in php, and you have your difference.

Remove your nested loops. You only need one loop.

$last_views = null;

while($row = mysql_fetch_array($result))
{
    $views = $row['views'];
    $dat   = $row1['date'];

    if( $last_views === null )
         $delta_views = "";
    else
         $delta_views = $last_views - $views;

    $last_views = $views;

    echo "{$dat}-->Visitors:{$views}";
    echo "<br/>";
    echo "Difference between days:{$delta_views}";
    echo "<br/>";
}


问:
Any latex web services with an API?
Is there a web service API that takes this type of a latex http-request:

```<code>http://some_web_service/texfile?texfile=

\new\documentclass[12pt]{article}
\begin{document}
  bla
\end{document}
</code>```

and returns:

```<code>bla.pdf
</code>```

答:
Were you to be able to install software on your local server this wouldn't be too hard. Some combination of Perl / TT / latexmk along with a LaTeX system (e.g. TeXLive or MiKTeX).

I don't know about latexlab mentioned above. The closest thing I know of is http://www.tlhiv.org/ltxpreview/ , which perhaps you could wrap to do what you need (or even write a howto for your users).

ContentLicense: CC BY-SA 2.5

Title: Any latex web services with an API?

Body:
Is there a web service API that takes this type of a latex http-request:

http://some_web_service/texfile?texfile=

\new\documentclass[12pt]{article}
\begin{document}
  bla
\end{document}

and returns:

bla.pdf


问:
datatable plugin not display elements after clicking again on link to show
I am using data table plugin for table pagination, it work for the first time, but when I click again on link to show the table all elements of data table plugin disappears, do you know how to solve this problem. thanks.

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid text-center">
      <div class="row content">
       <div class="col-lg-2 sidenav">
      <a href="#" id="link3" class="list-group-item">Vertical link #3</a>
        </div>
        <div class="col-lg-10 text-left">
          <div class="row">
            <div class="col-lg-12" id="content"></div>
          </div>
        </div>
      </div>
    </div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<!-- link3 -->
<script src="link3.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
</html>
</code>```

link3.js

```<code>$(document).ready(function(){
var table = $('<table><thead><tr><th>Name</th><th>Age</th><th>Position</th><th>Note</th></tr></thead><tbody></tbody></table>').addClass('table table-bordered table-hover search-table');
    $("#link3").on("click", function () {
      $('#content').html(table);
    $.ajax({
        url:'test.json',
        dataType:'json',
        type:'GET',
        Accept:"aplication/json",
        cache:false,
        success:function(data){
            $.each(data, function(index, item){
                var id = item.name;
                var id2= item.age;
                var id3=item.position;
                var id4=item.note;
                $(".table").append("<tr><td>"+id+"</td><td>"+id2+"</td><td>"+id3+"</td><td>"+id4+"</td></tr>");
            });
            $('.search-table').DataTable();
        },
        error:function(e){
            alert("there is some thing wrong!")
        }
    });
});

});
</code>```

test.json

```<code>[

  {
    "name": "Olivia Doe",
    "age": "18",
    "position": "SW developer",
    "note": ""
  },
  {
    "name": "Sophia Doe",
    "age": "19",
    "position": "Graphic",
    "note": ""
  },
  {
    "name": "Ava Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Joshua Doe",
    "age": "21",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Viktor Doe",
    "age": "22",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Ahmed Doe",
    "age": "23",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Emma Doe",
    "age": "24",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Evelyn Doe",
    "age": "25",
    "position": "Analyst",
    "note": "Evelyn's work is always amazing!"
  },
  {
    "name": "Noah Doe",
    "age": "26",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Liam Doe",
    "age": "27",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Mason Doe",
    "age": "28",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Jacob Doe",
    "age": "29",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "William Doe",
    "age": "30",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Ethan Doe",
    "age": "18",
    "position": "Project manager",
    "note": "Great job Ethan\nas always!"
  },
  {
    "name": "James Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Alexander Doe",
    "age": "21",
    "position": "Project manager",
    "note": ""
  }
]
</code>```

Body:
I am using data table plugin for table pagination, it work for the first time, but when I click again on link to show the table all elements of data table plugin disappears, do you know how to solve this problem. thanks.

index.html

<!DOCTYPE html>

  <title></title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">

      Vertical link #3

link3.js

$(document).ready(function(){
var table = $('

Name	Age	Position	Note

').addClass('table table-bordered table-hover search-table');
    $("#link3").on("click", function () {
      $('#content').html(table);
    $.ajax({
        url:'test.json',
        dataType:'json',
        type:'GET',
        Accept:"aplication/json",
        cache:false,
        success:function(data){
            $.each(data, function(index, item){
                var id = item.name;
                var id2= item.age;
                var id3=item.position;
                var id4=item.note;
                $(".table").append("
"+id+"	"+id2+"	"+id3+"	"+id4+"
");
            });
            $('.search-table').DataTable();
        },
        error:function(e){
            alert("there is some thing wrong!")
        }
    });
});

});

test.json

[

  {
    "name": "Olivia Doe",
    "age": "18",
    "position": "SW developer",
    "note": ""
  },
  {
    "name": "Sophia Doe",
    "age": "19",
    "position": "Graphic",
    "note": ""
  },
  {
    "name": "Ava Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Joshua Doe",
    "age": "21",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Viktor Doe",
    "age": "22",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Ahmed Doe",
    "age": "23",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Emma Doe",
    "age": "24",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Evelyn Doe",
    "age": "25",
    "position": "Analyst",
    "note": "Evelyn's work is always amazing!"
  },
  {
    "name": "Noah Doe",
    "age": "26",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Liam Doe",
    "age": "27",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Mason Doe",
    "age": "28",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Jacob Doe",
    "age": "29",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "William Doe",
    "age": "30",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Ethan Doe",
    "age": "18",
    "position": "Project manager",
    "note": "Great job Ethan\nas always!"
  },
  {
    "name": "James Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Alexander Doe",
    "age": "21",
    "position": "Project manager",
    "note": ""
  }
]

Body:
Try this:

$(document).ready(function(){
            $(document).ready(function() {
            var data = [];
            data.push(
                [1,"Sasha","Brenna","0800 1111"],
                [2,"Sage","Mia","(01012) 405872"],
                [3,"Chelsea","Allistair","076 0578 0265"],
                [4,"Uta","Savannah","070 1247 5884"],
                [5,"Remedios","Berk","0995 181 0007"],
                [6,"Ruby","Wayne","0800 1111"],
                [7,"Faith","Fredericka","(01709) 099879"],
                [8,"Myra","Harrison","070 4241 9576"],
                [9,"Drake","Miriam","0800 733635"],
                [10,"Reed","Shannon","076 8597 5067"],
                [11,"Sasha","Brenna","0800 1111"],
                [12,"Sage","Mia","(01012) 405872"],
                [13,"Chelsea","Allistair","076 0578 0265"],
                [14,"Uta","Savannah","070 1247 5884"],
                [15,"Remedios","Berk","0995 181 0007"],
                [16,"Ruby","Wayne","0800 1111"],
                [17,"Faith","Fredericka","(01709) 099879"],
                [18,"Myra","Harrison","070 4241 9576"],
                [19,"Drake","Miriam","0800 733635"],
                [20,"Reed","Shannon","076 8597 5067"]
            );

            $('#data_table').DataTable( {
                data: data,
            });
        });
});

Working JSFiddle


问:
How to disable UITableViewRowAction (without clicking an edit button)?
Normally when this function is called, deleting a table view cell by swiping left is allowed:

```<code>    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        dataSource.remove(at: indexPath.row)

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
}
</code>```

But I created an edit button like this:

```<code>self.navigationItem.leftBarButtonItem = self.editButtonItem
</code>```

and I'd like to enable deleting a cell only when the edit button was clicked and NOT just by swiping. Is this possible?

答:
Create one Boolean instance property with default value false and set it to true on the action of your BarButttonItem after that use that boolean property in canEditRowAt method to allow/disallow row edit.

```<code>var allowEdit = false

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return allowEdit
}
</code>```

Note: Don't forgot it to set false again once your delete is complete.

Body:
Normally when this function is called, deleting a table view cell by swiping left is allowed:

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        dataSource.remove(at: indexPath.row)

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
}

But I created an edit button like this:

self.navigationItem.leftBarButtonItem = self.editButtonItem

and I'd like to enable deleting a cell only when the edit button was clicked and NOT just by swiping. Is this possible?

Body:
Create one Boolean instance property with default value false and set it to true on the action of your BarButttonItem after that use that boolean property in canEditRowAt method to allow/disallow row edit.

var allowEdit = false

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return allowEdit
}

Note: Don't forgot it to set false again once your delete is complete.


Title: How to divide array into small size chunks?

Body:
I am fetching this array in JavaScript program by ajax in every second, the response from the request takes about 3 to 4 second to be completed. Therefore I want to this array to be split in chunks but failed to complete the array was

{"m":true,
"s":true,
"q":{
"eur":{"b":"1.06783","a":"1.06790","h":"1.06978","l":"1.06729"},
"gbp":{"b":"1.24407","a":"1.24416","h":"1.25093","l":"1.24397"},
"aud":{"b":"0.76456","a":"0.76464","h":"0.76630","l":"0.76387"},
"cad":{"b":"1.33550","a":"1.33557","h":"1.33583","l":"1.33251"},
"jpy":{"b":"111.996","a":"112.002","h":"112.204","l":"111.700"},
"chf":{"b":"1.00110","a":"1.00117","h":"1.00188","l":"0.99850"},
"xau":{"b":"1241.75","a":"1242.1","h":"1244.69","l":"1239.53"},
"xag":{"b":"18.056","a":"18.098","h":"18.175","l":"18.02"},
"nok":{"b":"8.58853","a":"8.5901","h":"8.59342","l":"8.55128"},
"sek":{"b":"8.9308","a":"8.9323","h":"8.9515","l":"8.92151"},
"sgd":{"b":"1.3975","a":"1.3977","h":"1.3959","l":"1.3987"},
"pkr":{"b":"104.8300","a":"105.8300","h":"104.8300","l":"104.620"},
"dkk":{"b":"6.9645","a":"6.9648","h":"6.9500","l":"6.9691"},
"nzd":{"b":"0.69835","a":"0.69859","h":"0.70084","l":"0.69794"},
"zar":{"b":"13.3688","a":"13.37396","h":"13.6475","l":"13.232"},
"hkd":{"b":"7.77017","a":"7.77098","h":"7.77244","l":"7.76847"},
"inr":{"b":"64.8500","a":"64.8600","h":"64.925","l":"64.7800"},
"try":{"b":"3.63447","a":"3.63558","h":"3.65941","l":"3.63076"},
"pln":{"b":"3.9514","a":"3.9520","h":"3.9361","l":"3.9520"},
"cnh":{"b":"6.88261","a":"6.88352","h":"6.89029","l":"6.8706"},
"myr":{"b":"0.2255","a":"0.2265","h":"0.2253","l":"0.2257"},
"sar":{"b":"0.2662","a":"0.2672","h":"0.2662","l":"0.2662"}
}}

Please help me, I am getting stuck on this...


问:
C# Multiple Indexers
Is it possible to have something like the following:

```<code>class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}
</code>```

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

答: No you cant do it. Only methods that can have their signatures differ only by return type are conversion operators. Indexers must have different input parameter types to get it to compile.</p>

Title: C# Multiple Indexers

Body:
Is it possible to have something like the following:

class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

OwnerDisplayName: Krzysztof Koźmic


问:
Linking Services to components
I am importing my service in my component but for some reason it gives me cannot find module.

Here's my selectHotel.component.ts

```<code>import { Component } from '@angular/core';
import { GetHotelService } from '/src/app/services/gethotel/getHotel.service'; //Error Here

@Component({
    moduleId: module.id,
    selector: 'selectHotel',
    templateUrl: 'selectHotel.component.html',
    providers: [GetHotelService]
})
export class selectHotelComponent  {  }
</code>```

Here's my getHotel.service.ts

```<code>import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
    export class GetHotelService {
        constructor(private http: Http){
            console.log('Init');
        }
    }
</code>```

My project folder view is like this

Proj > src > app > components > selectHotel > selectHotel.component.ts

Proj > src > app > services > gethotel > getHotel.service.ts

What am I doing wrong here?

答:
The import path should be relative to the current file

Try:

```<code>import { GetHotelService } from '../../services/gethotel/getHotel.service';
</code>```

Title: Linking Services to components

Body:
I am importing my service in my component but for some reason it gives me cannot find module.

Here's my selectHotel.component.ts

import { Component } from '@angular/core';
import { GetHotelService } from '/src/app/services/gethotel/getHotel.service'; //Error Here

@Component({
    moduleId: module.id,
    selector: 'selectHotel',
    templateUrl: 'selectHotel.component.html',
    providers: [GetHotelService]
})
export class selectHotelComponent  {  }

Here's my getHotel.service.ts

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
    export class GetHotelService {
        constructor(private http: Http){
            console.log('Init');
        }
    }

My project folder view is like this

Proj > src > app > components > selectHotel > selectHotel.component.ts

Proj > src > app > services > gethotel > getHotel.service.ts

What am I doing wrong here?

Body:
The import path should be relative to the current file

Try:

import { GetHotelService } from '../../services/gethotel/getHotel.service';


问:
REST in Unity (send messages from webserver to unity)
Is there a way to have a simple webserver send messages to Unity?

At the moment, we're doing a GET using UnityWebRequest.Get() in the update method. Here's the code:

```<code>// Update is called once per frame
void Update () {
    StartCoroutine(GetData());
}

IEnumerator GetData()
{
    UnityWebRequest uwr = UnityWebRequest.Get(url);
    yield return uwr.Send();

    if (uwr.isError)
    {
        Debug.Log(uwr.error);
    }else
    {
        Debug.Log((float.Parse(uwr.downloadHandler.text) / 100));
        fnumber = ((float.Parse(uwr.downloadHandler.text) / 100));
        transform.position.Set(oldX, fnumber, oldZ);
    }
}
</code>```

However, this throws this error:

CANNOT RESOLVE DESTINATION HOST

I found this bug-report, which states, it would have been fixed, which doesn't seem so.

So, is there a way to have the server send messages to Unity?

Thanks

答:
Expanding my comment to be more descriptive and concrete, my suggestion is to create a simple Thread that will serve as the communication manager with your server.

First of all you have to implement this class to call methods on Unity's UI thread.

When you implement this just create a class :

```<code>public class CommunicationManager
{
    static readonly object syncRoot = new object();

    static CommunicationManager _Instance;
    public static CommunicationManager Instance
    {
        get
        {
            if ( _Instance == null )
            {
                lock ( syncRoot )
                {
                    if ( _Instance == null )
                    {
                        _Instance = new CommunicationManager();
                    }
                }
            }
            return _Instance;
        }
    }

    volatile bool working = false;

    Queue<Message> _messages;

    private CommunicationManager()
    {
        _messages = new Queue<Message>();
        InitializeCommunication();
    }

    void InitializeCommunication()
    {
        Thread t = new Thread(CommunicationLoop);
        t.Start();
    }

    void CommunicationLoop()
    {
        Socket s = null;
        try
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1337));
            working = true;
        }
        catch(Exception ex)
        {
            working = false;
        }
        while ( working )
        {
            lock ( syncRoot )
            {
                while ( _messages.Count > 0 )
                {
                    Message message = _messages.Dequeue();
                    MessageResult result = message.Process(s);
                    result.Notify();
                }
            }
            Thread.Sleep(100);
        }
    }

    public void EnqueueMessage(Message message)
    {
        lock ( syncRoot )
        {
            _messages.Enqueue( message );
        }
    }
}
</code>```

Now you have to make Message and MessageResult objects :

```<code>public class Message
{
    const string REQUEST_SCHEME = "{0} {1} HTTP/1.1\r\nHost: {hostname}\r\nContent-Length: 0\r\n\r\n";
    string request;
    Action<MessageResult> whenCompleted;

    public Message(string requestUri, string requestType, Action<MessageResult> whenCompleted)
    {
        request = string.Format(REQUEST_SCHEME, requestType, requestUri);
        this.whenCompleted = whenCompleted;
    }

    public MessageResult Process(Socket s)
    {
        IPEndPoint endPoint = (IPEndPoint)s.RemoteEndPoint;
        IPAddress ipAddress = endPoint.Address;
        request = request.Replace("{hostname}", ipAddress.ToString());
        s.Send(Encoding.UTF8.GetBytes(request));

        // receive header here which should look somewhat like this :
        /*
                HTTP/1.1 <status>
                Date: <date>
                <some additional info>
                Accept-Ranges: bytes
                Content-Length: <CONTENT_LENGTH>
                <some additional info>
                Content-Type: <content mime type>
         */
         // when you receive this all that matters is <CONTENT_LENGTH>
         int contentLength = <CONTENT_LENGTH>;
         byte[] msgBuffer = new byte[contentLength];
         if (s.Receive(msgBuffer) != contentLength )
         {
             return null;
         }

         return new MessageResult(msgBuffer, whenCompleted);
    }
}
</code>```

And lastly create MessageResult object :

```<code>public class MessageResult
{
    Action<MessageResult> notifier;
    byte[] messageBuffer;

    public MessageResult(byte[] message, Action<MessageResult> notifier)
    {
        notifier = notifier;
        messageBuffer = message;
    }

    public void Notify()
    {
        UnityThread.executeInUpdate(() =>
        {
            notifier(this);
        });
    }
}
</code>```

This method will run aside from your main application so that wont produce any freezes and whatever.

To use this you can just call something like this :

```<code>Message message = new Message("/index.html", "GET", IndexDownloaded);
CommunicationManager.Instance.EnqueueMessage(message);

// ...
public void IndexDownloaded(MessageResult result)
{
    // result available here
}
</code>```

For more informations read this wikipedia article about HTTP.

Body:
Is there a way to have a simple webserver send messages to Unity?

At the moment, we're doing a GET using UnityWebRequest.Get() in the update method. Here's the code:

// Update is called once per frame
void Update () {
    StartCoroutine(GetData());
}

IEnumerator GetData()
{
    UnityWebRequest uwr = UnityWebRequest.Get(url);
    yield return uwr.Send();

    if (uwr.isError)
    {
        Debug.Log(uwr.error);
    }else
    {
        Debug.Log((float.Parse(uwr.downloadHandler.text) / 100));
        fnumber = ((float.Parse(uwr.downloadHandler.text) / 100));
        transform.position.Set(oldX, fnumber, oldZ);
    }
}

However, this throws this error:

CANNOT RESOLVE DESTINATION HOST

I found this bug-report, which states, it would have been fixed, which doesn't seem so.

So, is there a way to have the server send messages to Unity?

Thanks

Body:
Expanding my comment to be more descriptive and concrete, my suggestion is to create a simple Thread that will serve as the communication manager with your server.

First of all you have to implement this class to call methods on Unity's UI thread.

When you implement this just create a class :

public class CommunicationManager
{
    static readonly object syncRoot = new object();

    static CommunicationManager _Instance;
    public static CommunicationManager Instance
    {
        get
        {
            if ( _Instance == null )
            {
                lock ( syncRoot )
                {
                    if ( _Instance == null )
                    {
                        _Instance = new CommunicationManager();
                    }
                }
            }
            return _Instance;
        }
    }

    volatile bool working = false;

    Queue<Message> _messages;

    private CommunicationManager()
    {
        _messages = new Queue<Message>();
        InitializeCommunication();
    }

    void InitializeCommunication()
    {
        Thread t = new Thread(CommunicationLoop);
        t.Start();
    }

    void CommunicationLoop()
    {
        Socket s = null;
        try
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1337));
            working = true;
        }
        catch(Exception ex)
        {
            working = false;
        }
        while ( working )
        {
            lock ( syncRoot )
            {
                while ( _messages.Count > 0 )
                {
                    Message message = _messages.Dequeue();
                    MessageResult result = message.Process(s);
                    result.Notify();
                }
            }
            Thread.Sleep(100);
        }
    }

    public void EnqueueMessage(Message message)
    {
        lock ( syncRoot )
        {
            _messages.Enqueue( message );
        }
    }
}

Now you have to make Message and MessageResult objects :

public class Message
{
    const string REQUEST_SCHEME = "{0} {1} HTTP/1.1\r\nHost: {hostname}\r\nContent-Length: 0\r\n\r\n";
    string request;
    Action<MessageResult> whenCompleted;

    public Message(string requestUri, string requestType, Action<MessageResult> whenCompleted)
    {
        request = string.Format(REQUEST_SCHEME, requestType, requestUri);
        this.whenCompleted = whenCompleted;
    }

    public MessageResult Process(Socket s)
    {
        IPEndPoint endPoint = (IPEndPoint)s.RemoteEndPoint;
        IPAddress ipAddress = endPoint.Address;
        request = request.Replace("{hostname}", ipAddress.ToString());
        s.Send(Encoding.UTF8.GetBytes(request));

        // receive header here which should look somewhat like this :
        /*
                HTTP/1.1 <status>
                Date: <date>
                <some additional info>
                Accept-Ranges: bytes
                Content-Length: <CONTENT_LENGTH>
                <some additional info>
                Content-Type: <content mime type>
         */
         // when you receive this all that matters is <CONTENT_LENGTH>
         int contentLength = <CONTENT_LENGTH>;
         byte[] msgBuffer = new byte[contentLength];
         if (s.Receive(msgBuffer) != contentLength )
         {
             return null;
         }

         return new MessageResult(msgBuffer, whenCompleted);
    }
}

And lastly create MessageResult object :

public class MessageResult
{
    Action<MessageResult> notifier;
    byte[] messageBuffer;

    public MessageResult(byte[] message, Action<MessageResult> notifier)
    {
        notifier = notifier;
        messageBuffer = message;
    }

    public void Notify()
    {
        UnityThread.executeInUpdate(() =>
        {
            notifier(this);
        });
    }
}

This method will run aside from your main application so that wont produce any freezes and whatever.

To use this you can just call something like this :

Message message = new Message("/index.html", "GET", IndexDownloaded);
CommunicationManager.Instance.EnqueueMessage(message);

// ...
public void IndexDownloaded(MessageResult result)
{
    // result available here
}

For more informations read this wikipedia article about HTTP.


问:
ruamel.yaml octal in 1.1
I tried to run this code with PyYAML:

```<code>from yaml import safe_load
data = safe_load("""\
%YAML 1.2
---
x: 42
y: 0x2a
z: 0o52
""")

assert data['x'] == data['y'] == data['z']
</code>```

and did not expect it to throw an assertion error. After I read more documentation (found via http://yaml.org/), I realized PyYAML died some time ago and never supported the octal integers from the YAML 1.2 specficiation.

With ruamel.yaml (from ruamel.yaml import safe_load) the above works as expected.

Just out of curiosity I tried ruamel.yaml with the old octal format ( YAML 1.1 at the top and z: 052) and that works as well. I also tried the below:

```<code>from ruamel.yaml import safe_load
data = safe_load("""\
%YAML 1.1
---
x: 42
y: 0x2a
z: 0o52
""")
assert data['x'] == data['y'] == data['z']
</code>```

expecting it throw an error, as data['z'] should be a string, and not the integer 42. This doesn't throw an error, where I suppose it should.

Is my expectation wrong, or is this a bug in ruamel.yaml?

答:
Yes that that is a bug in ruamel.yaml 0.14.2.

The implicit resolvers for integers for 1.1 and 1.2 both include the 0o pattern, and only the one for 1.2 should have that. The old pattern (matching 052) is available only when version 1.1 is asked for.

This should be fixed in ruamel.yaml>=0.14.3

Title: ruamel.yaml octal in 1.1

Body:
I tried to run this code with PyYAML:

from yaml import safe_load
data = safe_load("""\
%YAML 1.2
---
x: 42
y: 0x2a
z: 0o52
""")

assert data['x'] == data['y'] == data['z']

and did not expect it to throw an assertion error. After I read more documentation (found via http://yaml.org/), I realized PyYAML died some time ago and never supported the octal integers from the YAML 1.2 specficiation.

With ruamel.yaml (from ruamel.yaml import safe_load) the above works as expected.

Just out of curiosity I tried ruamel.yaml with the old octal format ( YAML 1.1 at the top and z: 052) and that works as well. I also tried the below:

from ruamel.yaml import safe_load
data = safe_load("""\
%YAML 1.1
---
x: 42
y: 0x2a
z: 0o52
""")
assert data['x'] == data['y'] == data['z']

expecting it throw an error, as data['z'] should be a string, and not the integer 42. This doesn't throw an error, where I suppose it should.

Is my expectation wrong, or is this a bug in ruamel.yaml?


问:
Trailing black background on OpenGL SE (Android)
In my app, I have a ViewPager with fragments, and one of the fragments is running an OpenGL animation, whose background is white. What I have noticed is that when I swipe the viewpager, the OpenGL doesn't seem to move continuously, at the same speed as the fragments. This causes the back edge of the OpenGL layout to leave a black space, until I stop moving the pager, where the OpenGL layout seems to 'catch up' with the fragments. What may be causing this, and how can I avoid it?

Thanks!

答:
You have to use TextureView to animate it properly in ViewPager.
GLSurfaceView is not capable for proper animation.

Read about the differences here https://source.android.com/devices/graphics/arch-st.html

EDIT:
Yes, there's no such thing as GLTextureView. But you can implement it yourself, or use some lib.

Super simple example:
https://github.com/google/grafika/blob/master/app/src/main/java/com/android/grafika/TextureViewGLActivity.java

Advanced example:
https://github.com/romannurik/muzei/blob/master/main/src/main/java/com/google/android/apps/muzei/render/GLTextureView.java

ContentLicense: CC BY-SA 4.0


问:
Auto-increment not created
domain class

```<code>package testgrails12

class Teams {
    Integer id
    String name
    static mapping = {
        table 'teams'
        version false
        name column: 'name', sqlType: 'VARCHAR(200)'
        id generator: 'increment',
                params: [table:'teams', column: 'idteam', sqlType: 'INT(10)', updateable: false, insertable: false]
        /*id column: 'idteam', sqlType: 'INT(11)', updateable: false, insertable: false,
                generator: 'increment'*/
    }
    static constraints = {
        name nullable: true
    }
}
</code>```

This class creates a table

I need to create a table with a field id auto incremental. Help me whith mapping.

答:
In you mapping file you need to add generator like this.

```<code><hibernate-mapping>
  <class ...>
    <id ...>
     <generator class="increment"></generator>
    </id>

    .....

  </class>
 </hibernate-mapping>
</code>```

above you have to do mapping for id like this only. Because in Hibernate default generator is assigned. So you need to add your generator.

If you want to use Annotation in class than you need to add those annotation with you id property.

```<code>@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
</code>```

Here strategy=GenerationType.AUTO it will make id column to Auto Increment.

Title: Auto-increment not created

Body:
domain class

package testgrails12

class Teams {
    Integer id
    String name
    static mapping = {
        table 'teams'
        version false
        name column: 'name', sqlType: 'VARCHAR(200)'
        id generator: 'increment',
                params: [table:'teams', column: 'idteam', sqlType: 'INT(10)', updateable: false, insertable: false]
        /*id column: 'idteam', sqlType: 'INT(11)', updateable: false, insertable: false,
                generator: 'increment'*/
    }
    static constraints = {
        name nullable: true
    }
}

This class creates a table

I need to create a table with a field id auto incremental. Help me whith mapping.

Body:
In you mapping file you need to add generator like this.

<hibernate-mapping>
  <class ...>
    <id ...>
     <generator class="increment"></generator>
    </id>

    .....

  </class>
 </hibernate-mapping>

above you have to do mapping for id like this only. Because in Hibernate default generator is assigned. So you need to add your generator.

If you want to use Annotation in class than you need to add those annotation with you id property.

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

Here strategy=GenerationType.AUTO it will make id column to Auto Increment.


问:
atomic sequences in Promela. Contradictory in documentation
Here, http://spinroot.com/spin/Man/Manual.html, it is written that:

In Promela there is also another way to avoid the test and set
  problem: atomic sequences. By prefixing a sequence of statements
  enclosed in curly braces with the keyword atomic the user can indicate
  that the sequence is to be executed as one indivisible unit,
  non-interleaved with any other processes. It causes a run-time error
  if any statement, other than the first statement, blocks in an atomic
  sequence. This is how we can use atomic sequences to protect the
  concurrent access to the global variable state in the earlier example.

And here, http://spinroot.com/spin/Man/atomic.html, it is written that:

If any statement within the atomic sequence blocks, atomicity is lost
  If any statement within the atomic sequence blocks, atomicity is lost,
  and other processes are then allowed to start executing statements.
  When the blocked statement becomes executable again, the execution of
  the atomic sequence can be resumed at any time, but not necessarily
  immediately. Before the process can resume the atomic execution of the
  remainder of the sequence, the process must first compete with all
  other active processes in the system to regain control, that is, it
  must first be scheduled for execution.

So, what is the true? From the first citation we can learn that it is not allowed to block in atomic ( not the first statement)

From the second citation we learn that it is ok to block in atomic. You just lose the atomicity and that is it.

答:
Contradictory Documentation:

My guess is that the contradiction is merely the result of parts of the documentation not being updated to reflect changes that occurred within Spin over the years.

In fact, in the release notes of Spin v. 2.0 we can find the following piece of text (emphasis is mine):

2.3.1 Blocking Atomic Sequences

Until now it was considered an error if an atomic sequence contained
  any statement that could block the execution of the sequence. This
  caused much confusion and complicates modeling needlessly. Starting
  with Spin version 2, it is legal for an atomic sequence to block. If a
  process inside an atomic sequence blocks, control shifts
  non-deterministically to another process. If the statement later
  becomes executable, control can return to the process and the atomic
  execution of the remainder of the sequence resumed.

This change in semantics makes it relatively easy to model, for
  instance, co-routines where control does not pass from one process to
  another until and unless the running process blocks.

Atomic Statements in Promela:

In the current version of Promela/Spin there exist two atomic sequences:

atomic: from the docs, emphasis is mine:

DESCRIPTION

If a sequence of statements is enclosed in parentheses and prefixed with the keyword atomic, this indicates that the sequence is to be executed as one indivisible unit, non-interleaved with other processes. In the interleaving of process executions, no other process can execute statements from the moment that the first statement of an atomic sequence is executed until the last one has completed. The sequence can contain arbitrary Promela statements, and may be non-deterministic.

If any statement within the atomic sequence blocks, atomicity is lost, and other processes are then allowed to start executing statements. When the blocked statement becomes executable again, the execution of the atomic sequence can be resumed at any time, but not necessarily immediately. Before the process can resume the atomic execution of the remainder of the sequence, the process must first compete with all other active processes in the system to regain control, that is, it must first be scheduled for execution.

[...]

d_step: from the docs, emphasis is mine:

DESCRIPTION

A d_step sequence is executed as if it were one single indivisible statement. It is comparable to an atomic sequence, but it differs from such sequences on the following three points:

No goto jumps into or out of a d_step sequence are allowed.

The sequence is executed deterministically. If non-determinism is present, it is resolved in a fixed and deterministic way, for instance, by always selecting the first true guard in every selection and repetition structure.

It is an error if the execution of any statement inside the sequence can block. This means, for instance, that in most cases send and receive statements cannot be used inside d_step sequences.

[...]

Of course, one can actually test this behaviour with a simple Promela example.

TEST 1: loss of atomicity with atomic {}

Take the following Promela Model, in which two processes pippo and pluto execute an atomic {} sequence of instructions up to 10 times. Each process saves its unique _pid inside a global variable p when it starts executing the atomic sequence, and then checks a flag variable:

if flag is true, pippo can execute but pluto cannot, therefore pluto should temporarily loose atomicity (in some execution trace)

if flag is false, pluto can execute but pippo cannot, therefore pippo should temporarily loose atomicity (in some execution trace)

We check the latest case by adding an assert(p == _pid) instruction at the end of the atomic sequence in pippo. If the condition is not violated, then it means that there is no execution in which pippo looses atomicity from within the atomic sequence and pluto starts executing instead. Otherwise, we proved that the description in the linked documentation for atomic {} is accurate.

bool flag;
pid p;

active proctype pippo ()
{
    byte i;
    do
        :: i < 10 ->
            atomic {
                true ->
                p = _pid;
                flag;      /* executable only if flag is true */
                printf("pippo unblocked\n");
                flag = !flag;
                assert(p == _pid);
            };
            i++;
        :: else -> break;
    od;
};

active proctype pluto ()
{
    byte i;
    do
        :: i < 10 ->
            atomic {
                true ->
                p = _pid;
end:
                !flag;     /* executable only if flag is false */
                printf("pluto unblocked\n");
                flag = !flag;
            };
            i++;
        :: else -> break;
    od;
};
```

<p>If we perform formal verification with <strong>Spin</strong>, it finds an execution trace that violates the property:</p>

```~$ spin -search -bfs test.pml    # -bfs: breadth-first-search, results in a
                                 # shorter counter-example

pan:1: assertion violated (p==_pid) (at depth 6)
pan: wrote test.pml.trail

(Spin Version 6.4.3 -- 16 December 2014)
Warning: Search not completed
    + Breadth-First Search
    + Partial Order Reduction

Full statespace search for:
    never claim             - (none specified)
    assertion violations    +
    cycle checks            - (disabled by -DSAFETY)
    invalid end states      +

State-vector 20 byte, depth reached 6, errors: 1
       15 states, stored
          10 nominal states (stored-atomic)
        0 states, matched
       15 transitions (= stored+matched)
        5 atomic steps
hash conflicts:         0 (resolved)

Stats on memory usage (in Megabytes):
    0.001   equivalent memory usage for states (stored*(State-vector + overhead))
    0.290   actual memory usage for states
  128.000   memory used for hash table (-w24)
  128.195   total actual memory usage

pan: elapsed time 0 seconds
```

<p>The <em>assertion</em> is violated, as stated in the documentation. You can replay the invalid execution trace as follows:</p>

``` ~$ spin -t -p -l -g test.pml
```

<p><strong>Double Check.</strong> Now, if you comment the instruction <code>flag:</code> inside <code>pippo</code> and you repeat the verification process, you'll see that there won't be any execution trace violating the <em>assertion</em>. <em>This is because no other instruction in the atomic sequence of <code>pippo</code> can block, and therefore atomicity is never lost.</em></p>

<hr>

<p><strong>TEST 2: blocking error with <code>d_step {}</code></strong></p>

<p>Now, take the same code example and substitute the <code>atomic</code> keyword inside <code>pippo</code> with <code>d_step</code>:</p>

<pre class="lang-cpp prettyprint-override"><code>bool flag;
pid p;

active proctype pippo ()
{
    byte i;
    do
        :: i < 10 ->
            d_step {
                true ->
                p = _pid;
                flag;      /* executable only if flag is true */
                printf("pippo unblocked\n");
                flag = !flag;
                assert(p == _pid);
            };
            i++;
        :: else -> break;
    od;
};

active proctype pluto ()
{
    byte i;
    do
        :: i < 10 ->
            atomic {
                true ->
                p = _pid;
end:
                !flag;     /* executable only if flag is false */
                printf("pluto unblocked\n");
                flag = !flag;
            };
            i++;
        :: else -> break;
    od;
};
</code>```

If you formally verify this model, you'll see that it still finds a counter-example, but this time with a different error:

```<code>~$ spin -search -bfs test.pml
pan:1: block in d_step seq (at depth 2)
pan: wrote test.pml.trail

(Spin Version 6.4.3 -- 16 December 2014)
Warning: Search not completed
    + Breadth-First Search
    + Partial Order Reduction

Full statespace search for:
    never claim             - (none specified)
    assertion violations    +
    cycle checks            - (disabled by -DSAFETY)
    invalid end states      +

State-vector 20 byte, depth reached 2, errors: 1
        4 states, stored
           4 nominal states (stored-atomic)
        0 states, matched
        4 transitions (= stored+matched)
        0 atomic steps
hash conflicts:         0 (resolved)

Stats on memory usage (in Megabytes):
    0.000   equivalent memory usage for states (stored*(State-vector + overhead))
    0.290   actual memory usage for states
  128.000   memory used for hash table (-w24)
  128.195   total actual memory usage

pan: elapsed time 0 seconds
</code>```

Which corresponds to the following execution trace:

```<code>~$ spin -t -p -l -g test.pml
using statement merging
  1:    proc  1 (pluto:1) test.pml:26 (state 1) [((i<10))]
  2:    proc  0 (pippo:1) test.pml:8 (state 1)  [((i<10))]
  3:    proc  0 (pippo:1) test.pml:9 (state 8)  [(1)]
  3:    proc  0 (pippo:1) test.pml:11 (state 3) [p = _pid]
spin: trail ends after 3 steps
#processes: 2
        flag = 0
        p = 0
  3:    proc  1 (pluto:1) test.pml:27 (state 7)
  3:    proc  0 (pippo:1)
2 processes created
</code>```

The problem is that pippo blocks inside the d_step sequence, and this violates the third condition in the synopsis of d_step documentation, exactly as described.

Double Check. Again, if you comment the flag; instruction you'll see that there won't be any error trace.

Body:
Contradictory Documentation:

My guess is that the contradiction is merely the result of parts of the documentation not being updated to reflect changes that occurred within Spin over the years.

In fact, in the release notes of Spin v. 2.0 we can find the following piece of text (emphasis is mine):

2.3.1 Blocking Atomic Sequences

Until now it was considered an error if an atomic sequence contained
  any statement that could block the execution of the sequence. This
  caused much confusion and complicates modeling needlessly. Starting
  with Spin version 2, it is legal for an atomic sequence to block. If a
  process inside an atomic sequence blocks, control shifts
  non-deterministically to another process. If the statement later
  becomes executable, control can return to the process and the atomic
  execution of the remainder of the sequence resumed.

This change in semantics makes it relatively easy to model, for
  instance, co-routines where control does not pass from one process to
  another until and unless the running process blocks.

Atomic Statements in Promela:

In the current version of Promela/Spin there exist two atomic sequences:

atomic: from the docs, emphasis is mine:

DESCRIPTION

If a sequence of statements is enclosed in parentheses and prefixed with the keyword atomic, this indicates that the sequence is to be executed as one indivisible unit, non-interleaved with other processes. In the interleaving of process executions, no other process can execute statements from the moment that the first statement of an atomic sequence is executed until the last one has completed. The sequence can contain arbitrary Promela statements, and may be non-deterministic.

If any statement within the atomic sequence blocks, atomicity is lost, and other processes are then allowed to start executing statements. When the blocked statement becomes executable again, the execution of the atomic sequence can be resumed at any time, but not necessarily immediately. Before the process can resume the atomic execution of the remainder of the sequence, the process must first compete with all other active processes in the system to regain control, that is, it must first be scheduled for execution.

[...]

d_step: from the docs, emphasis is mine:

DESCRIPTION

A d_step sequence is executed as if it were one single indivisible statement. It is comparable to an atomic sequence, but it differs from such sequences on the following three points:

No goto jumps into or out of a d_step sequence are allowed.

The sequence is executed deterministically. If non-determinism is present, it is resolved in a fixed and deterministic way, for instance, by always selecting the first true guard in every selection and repetition structure.

It is an error if the execution of any statement inside the sequence can block. This means, for instance, that in most cases send and receive statements cannot be used inside d_step sequences.

[...]

Of course, one can actually test this behaviour with a simple Promela example.

TEST 1: loss of atomicity with atomic {}

Take the following Promela Model, in which two processes pippo and pluto execute an atomic {} sequence of instructions up to 10 times. Each process saves its unique _pid inside a global variable p when it starts executing the atomic sequence, and then checks a flag variable:

if flag is true, pippo can execute but pluto cannot, therefore pluto should temporarily loose atomicity (in some execution trace)

if flag is false, pluto can execute but pippo cannot, therefore pippo should temporarily loose atomicity (in some execution trace)

We check the latest case by adding an assert(p == _pid) instruction at the end of the atomic sequence in pippo. If the condition is not violated, then it means that there is no execution in which pippo looses atomicity from within the atomic sequence and pluto starts executing instead. Otherwise, we proved that the description in the linked documentation for atomic {} is accurate.

bool flag;
pid p;

active proctype pippo ()
{
    byte i;
    do
        :: i < 10 ->
            atomic {
                true ->
                p = _pid;
                flag;      /* executable only if flag is true */
                printf("pippo unblocked\n");
                flag = !flag;
                assert(p == _pid);
            };
            i++;
        :: else -> break;
    od;
};

active proctype pluto ()
{
    byte i;
    do
        :: i < 10 ->
            atomic {
                true ->
                p = _pid;
end:
                !flag;     /* executable only if flag is false */
                printf("pluto unblocked\n");
                flag = !flag;
            };
            i++;
        :: else -> break;
    od;
};

If we perform formal verification with Spin, it finds an execution trace that violates the property:

~$ spin -search -bfs test.pml    # -bfs: breadth-first-search, results in a
                                 # shorter counter-example

pan:1: assertion violated (p==_pid) (at depth 6)
pan: wrote test.pml.trail

(Spin Version 6.4.3 -- 16 December 2014)
Warning: Search not completed
    + Breadth-First Search
    + Partial Order Reduction

Full statespace search for:
    never claim             - (none specified)
    assertion violations    +
    cycle checks            - (disabled by -DSAFETY)
    invalid end states      +

State-vector 20 byte, depth reached 6, errors: 1
       15 states, stored
          10 nominal states (stored-atomic)
        0 states, matched
       15 transitions (= stored+matched)
        5 atomic steps
hash conflicts:         0 (resolved)

Stats on memory usage (in Megabytes):
    0.001   equivalent memory usage for states (stored*(State-vector + overhead))
    0.290   actual memory usage for states
  128.000   memory used for hash table (-w24)
  128.195   total actual memory usage

pan: elapsed time 0 seconds

The assertion is violated, as stated in the documentation. You can replay the invalid execution trace as follows:

 ~$ spin -t -p -l -g test.pml

Double Check. Now, if you comment the instruction flag: inside pippo and you repeat the verification process, you'll see that there won't be any execution trace violating the assertion. This is because no other instruction in the atomic sequence of pippo can block, and therefore atomicity is never lost.

TEST 2: blocking error with d_step {}

Now, take the same code example and substitute the atomic keyword inside pippo with d_step:

bool flag;
pid p;

active proctype pippo ()
{
    byte i;
    do
        :: i < 10 ->
            d_step {
                true ->
                p = _pid;
                flag;      /* executable only if flag is true */
                printf("pippo unblocked\n");
                flag = !flag;
                assert(p == _pid);
            };
            i++;
        :: else -> break;
    od;
};

active proctype pluto ()
{
    byte i;
    do
        :: i < 10 ->
            atomic {
                true ->
                p = _pid;
end:
                !flag;     /* executable only if flag is false */
                printf("pluto unblocked\n");
                flag = !flag;
            };
            i++;
        :: else -> break;
    od;
};

If you formally verify this model, you'll see that it still finds a counter-example, but this time with a different error:

~$ spin -search -bfs test.pml
pan:1: block in d_step seq (at depth 2)
pan: wrote test.pml.trail

(Spin Version 6.4.3 -- 16 December 2014)
Warning: Search not completed
    + Breadth-First Search
    + Partial Order Reduction

Full statespace search for:
    never claim             - (none specified)
    assertion violations    +
    cycle checks            - (disabled by -DSAFETY)
    invalid end states      +

State-vector 20 byte, depth reached 2, errors: 1
        4 states, stored
           4 nominal states (stored-atomic)
        0 states, matched
        4 transitions (= stored+matched)
        0 atomic steps
hash conflicts:         0 (resolved)

Stats on memory usage (in Megabytes):
    0.000   equivalent memory usage for states (stored*(State-vector + overhead))
    0.290   actual memory usage for states
  128.000   memory used for hash table (-w24)
  128.195   total actual memory usage

pan: elapsed time 0 seconds

Which corresponds to the following execution trace:

~$ spin -t -p -l -g test.pml
using statement merging
  1:    proc  1 (pluto:1) test.pml:26 (state 1) [((i<10))]
  2:    proc  0 (pippo:1) test.pml:8 (state 1)  [((i<10))]
  3:    proc  0 (pippo:1) test.pml:9 (state 8)  [(1)]
  3:    proc  0 (pippo:1) test.pml:11 (state 3) [p = _pid]
spin: trail ends after 3 steps
#processes: 2
        flag = 0
        p = 0
  3:    proc  1 (pluto:1) test.pml:27 (state 7)
  3:    proc  0 (pippo:1)
2 processes created

The problem is that pippo blocks inside the d_step sequence, and this violates the third condition in the synopsis of d_step documentation, exactly as described.

Double Check. Again, if you comment the flag; instruction you'll see that there won't be any error trace.


问:
The loop iterates only once in this code while in another code it iterates properly
Why is the loop running only once in this code?

```<code> // Example program
    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
    int n=5;
    int a[n];
    for(int i=0;i<sizeof(a);i++)
    {
        cout<<"mohit jain"<<endl;
    }
      return 0;
    }
</code>```

While in the code the loop iterate five-time?

```<code>// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a[5];
for(int i=0;i<sizeof(a);i++)
{
    cout<<"mohit jain"<<endl;
}
  return 0;
}
</code>```

So please tell me the rightful reason why it iterates once in the first code while iterating five times in the second code.

答:
Consider using const int n = 5 instead.
By default C++ does not allow dynamic size arrays (and in this case it is dynamic, because n is non-const). It works only because your compiler uses some kind of extension to allocate an array in this case, e.g. gcc's variable arrays.

So, the first example is non-standard C++ code and the reason why sizeof returns 1 instead of 5 * sizeof(int) lies in the compiler-specific implementation of the extension.

BTW, the second loop runs 5 * sizeof(int) times (20 times on most systems), not 5.

Body:
Why is the loop running only once in this code?

 // Example program
    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
    int n=5;
    int a[n];
    for(int i=0;i<sizeof(a);i++)
    {
        cout<<"mohit jain"<<endl;
    }
      return 0;
    }

While in the code the loop iterate five-time?

// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a[5];
for(int i=0;i<sizeof(a);i++)
{
    cout<<"mohit jain"<<endl;
}
  return 0;
}

So please tell me the rightful reason why it iterates once in the first code while iterating five times in the second code.


答:
You could write an auxiliary function that could take an array full of anonymous functions, I guess. It would work well if your code to execute was nice and simple. Otherwise, if you're on PHP5.3 you could use proper lambdas to do more complex things. That would make it neater.</p>

```<code>function integer_in_ranges($integer, $array) {
    foreach ($array as $range => $function) {
        if ($integer < $range) {
            $results[] = $function();
        }
    }

    return $results;
}

integer_in_ranges($c, array(
    101 => create_function('', "execute_function(); return TRUE;"),
    202 => create_function('', "execute_other_function(); return TRUE;"),
    // ...
));
</code>```

Title: Faster way to check if integer is in any of ranges?

Body:
I wonder if there is another way to shorten this ? Here is the example im looking for to do same thing just shorter.

if($c <= 100){
    echo 'A';
}elseif($c <= 200 && $c > 100){
    echo 'B';
}elseif($c <= 300 && $c > 200){
    echo 'C';
}elseif($c <= 400 && $c > 300){
    echo 'D';
}elseif($c <= 500 && $c > 400){
    echo 'E';
}elseif($c <= 600 && $c > 500){
    echo 'F';
}elseif($c <= 700 && $c > 600){
    echo 'Z';
}elseif($c <= 800 && $c > 700){
    echo 'H';
}elseif($c <= 900 && $c > 800){
    echo 'I';
}elseif($c < 1000 && $c > 900){
    echo 'K';
}elseif($c <= 1100 && $c > 1000){
    echo 'L';
}elseif($c <= 1200 && $c > 1100){
    echo 'M';
}elseif($c < 1300 && $c > 1200){
    echo 'N';
}elseif($c <= 1400 && $c > 1300){
    echo 'O';
}elseif($c <= 1500 && $c > 1400){
    echo 'P';
}elseif($c <= 1600 && $c > 1500){
    echo 'Q';
}elseif($c <= 1700 && $c > 1600){
    echo 'R';
}elseif($c <= 1800 && $c > 1700){
    echo 'S';
}elseif($c <= 1900 && $c > 1800){
    echo 'T';
}elseif($c <= 2000 && $c > 1900){
    echo 'V';
}elseif($c <= 2100 && $c > 2000){
    echo 'X';
}else{
    echo 'AA';
}

Body:
You could write an auxiliary function that could take an array full of anonymous functions, I guess. It would work well if your code to execute was nice and simple. Otherwise, if you're on PHP5.3 you could use proper lambdas to do more complex things. That would make it neater.

function integer_in_ranges($integer, $array) {
    foreach ($array as $range => $function) {
        if ($integer < $range) {
            $results[] = $function();
        }
    }

    return $results;
}

integer_in_ranges($c, array(
    101 => create_function('', "execute_function(); return TRUE;"),
    202 => create_function('', "execute_other_function(); return TRUE;"),
    // ...
));


问:
How does (orientation: landscape) really work in CSS Media Queries?
Acccording to the preffferd css syntax i am applying the Media Query and it doesnt change anything. This is not giving me any changed output. Help.!</p>

```<code>  /* Landscape */
  @media only screen
   and (min-device-width: 320px)
   and (max-device-width: 480px)
   and (-webkit-min-device-pixel-ratio: 2)
   and (orientation: landscape) {
     .someClass{
         display: none;
         }
   }
</code>```

答:
```<code>   @media only screen
   and (min-device-width: 320px)
   and (max-device-width: 480px)
   and (-webkit-min-device-pixel-ratio: 2)
   and (orientation: landscape) {
     *{ display: none; }
   }
</code>```

Try this, you didn't select anything to hide

Body:
Acccording to the preffferd css syntax i am applying the Media Query and it doesnt change anything. This is not giving me any changed output. Help.!

  /* Landscape */
  @media only screen
   and (min-device-width: 320px)
   and (max-device-width: 480px)
   and (-webkit-min-device-pixel-ratio: 2)
   and (orientation: landscape) {
     .someClass{
         display: none;
         }
   }

Body:
   @media only screen
   and (min-device-width: 320px)
   and (max-device-width: 480px)
   and (-webkit-min-device-pixel-ratio: 2)
   and (orientation: landscape) {
     *{ display: none; }
   }

Try this, you didn't select anything to hide


问:
How to extract multiple array & insert data to database
How to extract below array & insert 3 data & 2 query

Extract this array & give me 2 row & 3 columns

```<code>Array
(
    [name] => Array
        (
            [0] => AAAAA
            [1] => BBBBB
        )

    [number] => Array
        (
            [0] => 7878787878
            [1] => 9898989898
        )

    [email] => Array
        (
            [0] => a@gmail.com
            [1] => b@gmail.com
        )

)
</code>```

We need Below query by foreach loop

```<code>INSERT INTO `contact_person` SET customer_id='131',cp_name='AAAAA',cp_phone='7878787878',cp_email='a@gmail.com

INSERT INTO `contact_person` SET customer_id='131',cp_name='BBBBB',cp_phone='9898989898',cp_email='b@gmail.com'
</code>```

答:
```<code>$newArr = array();
foreach($arr as $key=>$val){
    foreach($val as $k=>$v){
      $newArr[$k][$key] =   $v;
    }
}
echo "```"; print_r($newArr);
```

<p>Now you can run your insert query in <code>foreach()</code> like:</p>

```foreach($newArr as $key=>$val){
echo "INSERT INTO `contact_person` SET customer_id='131',
                 cp_name='" . $val['name'] . "',
                 cp_phone='" . $val['number'] . "',
                 cp_email='" . $val['email'] " . "'";
echo "
";
}
```

Body:
How to extract below array & insert 3 data & 2 query

Extract this array & give me 2 row & 3 columns

Array
(
    [name] => Array
        (
            [0] => AAAAA
            [1] => BBBBB
        )

    [number] => Array
        (
            [0] => 7878787878
            [1] => 9898989898
        )

    [email] => Array
        (
            [0] => a@gmail.com
            [1] => b@gmail.com
        )

)

We need Below query by foreach loop

INSERT INTO `contact_person` SET customer_id='131',cp_name='AAAAA',cp_phone='7878787878',cp_email='a@gmail.com

INSERT INTO `contact_person` SET customer_id='131',cp_name='BBBBB',cp_phone='9898989898',cp_email='b@gmail.com'

Body:
$newArr = array();
foreach($arr as $key=>$val){
    foreach($val as $k=>$v){
      $newArr[$k][$key] =   $v;
    }
}
echo "<pre>"; print_r($newArr);

Now you can run your insert query in foreach() like:

foreach($newArr as $key=>$val){
echo "INSERT INTO `contact_person` SET customer_id='131',
                 cp_name='" . $val['name'] . "',
                 cp_phone='" . $val['number'] . "',
                 cp_email='" . $val['email'] " . "'";
echo "<br />";
}


问:
How to render simple React component in MVC6 application, for dummies
I have a simple mvc6 site solution in Visual Studio 2015.

In one of my pages, I have

```<code><script type="text/jsx">
    ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById('react-app-mount'));
</script>
</code>```

But the component does not render. What scripts do I have to include in the page to make it render?
I am a total newbie to react.

Trying to figure it out on my own I got extremely confused with the gazillion of terms like 'npm, bower, babel' but nowhere I can find a decent from-scratch example on how to use those things in Visual Studio 2015. Moreover, I find suggestions that just don't work.

For instance, I read something like "you should run npm install babel", but nobody gives information on where in visual studio I should execute this command. Others speak about a package.json file that is supposed to exist somewhere in my solution, but it is just not there.

I really don't understand why things are so extremely complicated. In the old days, when you wanted to use a library, you just put a

答:
the right way, using ASP.NET MVC is:

bundle all react components & scipts using webpack to one file: bundle.js

1.2. you need entry point for your scripts, first script that will ReactDOM.render your root component, and alsi it will import this component:
import { App} from "./Components/App";

1.3. Your App component will import other components and so on

include bundle.js in your view layout

don't forget to include root node in your view file ("

Body:
I have a simple mvc6 site solution in Visual Studio 2015.

In one of my pages, I have

But the component does not render. What scripts do I have to include in the page to make it render?
I am a total newbie to react.

Trying to figure it out on my own I got extremely confused with the gazillion of terms like 'npm, bower, babel' but nowhere I can find a decent from-scratch example on how to use those things in Visual Studio 2015. Moreover, I find suggestions that just don't work.

For instance, I read something like "you should run npm install babel", but nobody gives information on where in visual studio I should execute this command. Others speak about a package.json file that is supposed to exist somewhere in my solution, but it is just not there.

I really don't understand why things are so extremely complicated. In the old days, when you wanted to use a library, you just put a


问:
HTTP Get Android with Basic Auth
I'm new to REST services and I'm looking for a few hours around the web...

I have a REST service url that gives me back JSON data.
The login (username & password) are basic auth.
I'm looking for a simple library/code snippet that lets me insert the uri, username & password and give me back the JSON string.

Any help would be appreciated!

答:
Note to @erad's answer (https://stackoverflow.com/a/26176707/1386969)

The method BasicScheme.authenticate is deprecated.

Instead of using this:

```<code>httpGet.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials("user", "password"), "UTF-8", false));
</code>```

you should use this:

```<code>    String userName = "bla bla";
    String password = "top secret";
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
    Header basicAuthHeader = new BasicScheme(Charset.forName("UTF-8")).authenticate(credentials, httpGet, null);
    httpGet.addHeader(basicAuthHeader);
</code>```

Title: HTTP Get Android with Basic Auth

Body:
Note to @erad's answer (https://stackoverflow.com/a/26176707/1386969)

The method BasicScheme.authenticate is deprecated.

Instead of using this:

httpGet.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials("user", "password"), "UTF-8", false));

you should use this:

    String userName = "bla bla";
    String password = "top secret";
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
    Header basicAuthHeader = new BasicScheme(Charset.forName("UTF-8")).authenticate(credentials, httpGet, null);
    httpGet.addHeader(basicAuthHeader);


答:
You can summarize the array by using below function.

```<code>function getSummary($array){
    $summary = [];
    foreach( $array as $col => $data ){
        foreach( $data as $key => $value ){
            $summary[$key][$col] = $value;
        }
    }
    return $summary;
}
</code>```

And once you pass the summarize array to the below function you will get the queries. I assume you need INSERT query.

```<code>function makeQueries($summary){
    foreach( $summary as $data ) {
        echo $sql = "INSERT INTO `contact_person` (customer_id, cp_name, cp_phone, cp_email) VALUES (131, '{$data['name']}', '{$data['number']}', '{$data['email']}');";
        echo "<br>";
    }
}
</code>```

I believe these 2 functions will solve your problems

Title: How to extract multiple array & insert data to database

Body:
You can summarize the array by using below function.

function getSummary($array){
    $summary = [];
    foreach( $array as $col => $data ){
        foreach( $data as $key => $value ){
            $summary[$key][$col] = $value;
        }
    }
    return $summary;
}

And once you pass the summarize array to the below function you will get the queries. I assume you need INSERT query.

function makeQueries($summary){
    foreach( $summary as $data ) {
        echo $sql = "INSERT INTO `contact_person` (customer_id, cp_name, cp_phone, cp_email) VALUES (131, '{$data['name']}', '{$data['number']}', '{$data['email']}');";
        echo "<br>";
    }
}

I believe these 2 functions will solve your problems


问:
Passing a 2-D array to a function returns an unexpected output
This program is meant to calculate the length of multiple vectors and sort them by size afterward, I wrote a function VL with a 1-dimensional array as input as well as the length of the aforementioned array and tested it in another program and it seems to work fine.

VL function

```<code>double VL(double w[], int num)                         /*Calculate vector length*/
{

int k;
double presqrt;
double length = 0;

for (k = 0; k < num; k++)
{
    presqrt += w[k] * w[k];
}
length = sqrt(presqrt);

return length;
}
</code>```

Main function (The majority of this function had already been given.) Under the line, I wrote a small for loop to test if the function returned the correct magnitudes with this input.

```<code>int main(void)
{
int dim, num ;
int i, j;
double **w;

scanf("%d %d",&dim,&num);                            /* read N and M */
w = calloc(num, sizeof (double *));                   /* allocate array of M        pointers */
for(i=0; i<num; i++)                                /* allocate space for N dimensional vector */
{
    w[i]= calloc(dim,sizeof(double));              /* read the vector */
    for (j=0; j<dim ; j++)
    {
        scanf("%le",&w[i][j]) ;
    }
}
</code>```

```<code>for(i=0; i<num; i++)                        /*printing vector lengths(test)*/
{
    printf("%.2f\n", VL(w[i], num));
}
</code>```

```<code>return 0 ;
}
</code>```

答:
In the VL function you add the result of the multiplication to presqrt

```<code>presqrt += w[k] * w[k];
</code>```

However the initial value of presqrt was not defined.

Please initialize it to 0.0 at the very beginning inside VL function:

```<code>double presqrt = 0.0;
</code>```

Body:
This program is meant to calculate the length of multiple vectors and sort them by size afterward, I wrote a function VL with a 1-dimensional array as input as well as the length of the aforementioned array and tested it in another program and it seems to work fine.

VL function

double VL(double w[], int num)                         /*Calculate vector length*/
{

int k;
double presqrt;
double length = 0;

for (k = 0; k < num; k++)
{
    presqrt += w[k] * w[k];
}
length = sqrt(presqrt);

return length;
}

Main function (The majority of this function had already been given.) Under the line, I wrote a small for loop to test if the function returned the correct magnitudes with this input.

int main(void)
{
int dim, num ;
int i, j;
double **w;

scanf("%d %d",&dim,&num);                            /* read N and M */
w = calloc(num, sizeof (double *));                   /* allocate array of M        pointers */
for(i=0; i<num; i++)                                /* allocate space for N dimensional vector */
{
    w[i]= calloc(dim,sizeof(double));              /* read the vector */
    for (j=0; j<dim ; j++)
    {
        scanf("%le",&w[i][j]) ;
    }
}

for(i=0; i<num; i++)                        /*printing vector lengths(test)*/
{
    printf("%.2f\n", VL(w[i], num));
}

return 0 ;
}

Body:
In the VL function you add the result of the multiplication to presqrt

presqrt += w[k] * w[k];

However the initial value of presqrt was not defined.

Please initialize it to 0.0 at the very beginning inside VL function:

double presqrt = 0.0;


问:
Magento 1.9 extend core class
I would like to extend core product class and add some functionality.

I made file app\code\local\ast\Catalog\etc\config.xml

```<code><?xml version="1.0"?>
<config>
    <modules>
         <ast_Catalog>
            <version>0.0.1</version>
        </ast_Catalog>
    </modules>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <product>ast_Catalog_Model_Product</product>
                </rewrite>
            </catalog>
        </models>
   </global>
</config>
</code>```

second file app\etc\modules\ast_Catalog.xml

```<code><?xml version="1.0"?>
<config>
     <modules>
        <ast_Catalog>
            <active>true</active>
            <codePool>local</codePool>
        </ast_Catalog>
     </modules>
</config>
</code>```

and file Product.php in app\code\local\ast\Catalog\Model\

```<code>class ast_Catalog_Model_Product extends Mage_Catalog_Model_Product
{

    public function makeBlue()
    {
        echo 'makeBlue';
    }

}
</code>```

Now when I try to use my function makeBlue() in app\design\frontend\ast\default\template\catalog\product\view.phtml file

```<code><div class="product-shop">
 <?php
               ....
               echo 'hello';
               echo $this->makeBlue();
               ....
 ?>
</code>```

I have got error below:

```<code>Invalid method Mage_Catalog_Block_Product_View::makeBlue(Array
(
)
)

#0 I:\WWW\Sklep_www4\app\design\frontend\ast\default\template\catalog\product\view.phtml(45): Varien_Object->__call('makeBlue', Array)
.......
</code>```

What is wrong ?

答: The problem was I extend class ast_Catalog_Model_Product not Mage_Catalog_Block_Product_View. After change extend class to Mage_Catalog_Block_Product_View everything works fine.</p>

Title: Magento 1.9 extend core class

Body:
I would like to extend core product class and add some functionality.

I made file app\code\local\ast\Catalog\etc\config.xml

<?xml version="1.0"?>
<config>
    <modules>
         <ast_Catalog>
            <version>0.0.1</version>
        </ast_Catalog>
    </modules>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <product>ast_Catalog_Model_Product</product>
                </rewrite>
            </catalog>
        </models>
   </global>
</config>

second file app\etc\modules\ast_Catalog.xml

<?xml version="1.0"?>
<config>
     <modules>
        <ast_Catalog>
            <active>true</active>
            <codePool>local</codePool>
        </ast_Catalog>
     </modules>
</config>

and file Product.php in app\code\local\ast\Catalog\Model\

class ast_Catalog_Model_Product extends Mage_Catalog_Model_Product
{

    public function makeBlue()
    {
        echo 'makeBlue';
    }

}

Now when I try to use my function makeBlue() in app\design\frontend\ast\default\template\catalog\product\view.phtml file

 <?php
               ....
               echo 'hello';
               echo $this->makeBlue();
               ....
 ?>

I have got error below:

Invalid method Mage_Catalog_Block_Product_View::makeBlue(Array
(
)
)

#0 I:\WWW\Sklep_www4\app\design\frontend\ast\default\template\catalog\product\view.phtml(45): Varien_Object->__call('makeBlue', Array)
.......

What is wrong ?


问:
Android Studio: Package name not set to a valid package name

I want to create an activity in the "layout" package so I right-clicked it and selected new activity and it's giving me this error. How do I resolve it?

答: Package is not layout. You can get your package name in the manifest file. example: manifest package="com.example.helloworld.android"</p>


答:
This isn't giving you an output since the usage is wrong. You want to use the property with an HTML selector.

Right syntax:

/* Landscape */
  @media only screen
   and (min-device-width: 320px)
   and (max-device-width: 480px)
   and (-webkit-min-device-pixel-ratio: 2)
   and (orientation: landscape) {
     body {
      display: none;
     }
   }```

Title: How does (orientation: landscape) really work in CSS Media Queries?


问:
Compare smoothed signal to the input signal
I smooth a series of data points using the algorithm described here: http://www.scipy.org/Cookbook/SignalSmooth .

How could I compare the smoothed signal with the input signal afterward? I'm hoping I could get a scalar describing how "close" the output is from the input. Is there any standard way to do this? Some term I could look for?

I have no idea what to even look for. Thanks!

答:
Discrete correlation is a way to detect a known waveform in a noisy background. Just find the correlation between two signals. Discrete correlation is simply a vector dot product:

```<code>for n in range(N):
   y[n] = sum( [x1[i]*x2[i+n] for i in range(N)] )
</code>```

in pure Python, or:

```<code>y = xcorr(x1,x2);
</code>```

in Matlab, or:

```<code>y = correlate(x1,x2)
</code>```

in Python+Scipy.

Correlation is a very sensitive measure of similarity of two signals. It is maximized when the two signals are similar in frequency content and are in phase with each other.

Body:
Discrete correlation is a way to detect a known waveform in a noisy background. Just find the correlation between two signals. Discrete correlation is simply a vector dot product:

for n in range(N):
   y[n] = sum( [x1[i]*x2[i+n] for i in range(N)] )

in pure Python, or:

y = xcorr(x1,x2);

in Matlab, or:

y = correlate(x1,x2)

in Python+Scipy.

Correlation is a very sensitive measure of similarity of two signals. It is maximized when the two signals are similar in frequency content and are in phase with each other.


问:
SQL Server: checkident: "[S00014][2560] Parameter 3 is incorrect for this DBCC statement."
Using an SQL Server database. A lookup table is having 50 new items added to it using a database versioning tool so the same script will be run on all three databases. There is a Dev, QA, and Prod version of the database and because of political reasons prod can't be cloned to the other environments. The table has an autoincremented ID column and another table of child records. In order to tie the children to the new parents the autoincremented id sequence must be repeatable and predictable. At this point it can't be switched to a sequence.

```<code>DBCC checkident ('inspectionitem', reseed, 9990)
</code>```

will set the autosequence's next number so that new items will get a predictable id. The maximum ID among all three databases for the current ID fields is about 5000 so for the script, just bumping it to 10000 is fairly guaranteed to not be a problem. The autoincrement is stepping by 10 each time so to get the first record to be ID 10000, had to set the seed to 9990.

When setting the seed to 9990, SQL Server gets the error:

[S00014][2560] Parameter 3 is incorrect for this DBCC statement.

When setting the seed to 9991->10000 it works, but setting the seed to 9990 gets the error.

I'll try a different starting place and some other workarounds, but why does 9990 get this error?

Thanks

答:
I had a same issue and when I checked my table. There was no record in it.

Also, check if identity is ON for the table.

Body:
Using an SQL Server database. A lookup table is having 50 new items added to it using a database versioning tool so the same script will be run on all three databases. There is a Dev, QA, and Prod version of the database and because of political reasons prod can't be cloned to the other environments. The table has an autoincremented ID column and another table of child records. In order to tie the children to the new parents the autoincremented id sequence must be repeatable and predictable. At this point it can't be switched to a sequence.

DBCC checkident ('inspectionitem', reseed, 9990)

will set the autosequence's next number so that new items will get a predictable id. The maximum ID among all three databases for the current ID fields is about 5000 so for the script, just bumping it to 10000 is fairly guaranteed to not be a problem. The autoincrement is stepping by 10 each time so to get the first record to be ID 10000, had to set the seed to 9990.

When setting the seed to 9990, SQL Server gets the error:

[S00014][2560] Parameter 3 is incorrect for this DBCC statement.

When setting the seed to 9991->10000 it works, but setting the seed to 9990 gets the error.

I'll try a different starting place and some other workarounds, but why does 9990 get this error?

Thanks


问:
How to remove background line of plotly area graph
I don't want line in background of plotly area graph. My graph is coming like this.

I want to remove this lines from graph. But I didn't get any solution for it.

I referred this code.

And following is my code:
demo.html

```<code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>

<body>

 <div id="myDiv" style="width: 480px; height: 400px;"><!-- Plotly chart will be drawn inside this DIV --></div>
 <script>
   var trace1 = {
   x: ['2013-10-04 22:23:00', '2016-10-06 22:23:00',  '2013-11-04 22:23:00', '2013-11-07 22:23:00','2013-12-04 22:23:00', '2013-12-08 22:23:00'],
   y: [1, 3, 6,9, 4, 5],
   fill: 'tozeroy',
   fillcolor: 'red',
   text: server1,
   hoverinfo: "x+y+text",
   name:"Server 1",
   type: 'scatter',
   mode:"markers",
   marker:
   {
    size:5,
    color:"gray"
   },
   uid:"c2e171"
   };
   var layout = {
    margin: {
     l: 35,
     r: 40,
     b: 50,
     t: 10
    },
    legend: {
     "orientation": "h"
    },
    yaxis : {
     fixedrange: true
    },
   };
   var data = [trace1];
   Plotly.newPlot('myDiv', data,layout);

   var plotDiv = document.getElementById('myDiv');
 </script>
 </body>
 </html>
</code>```

And when I'm expanding graph means dragging graph x axis date is hiding,

Please give me solution for it. I'm new with plotly.js

答:
You can use showgrid:

```<code>xaxis: {
    showgrid: false
},
yaxis: {
    showgrid: false,
    showline: true
}
</code>```

More plot.ly layout reference: https://plot.ly/javascript/reference/#layout-xaxis

Body:
I don't want line in background of plotly area graph. My graph is coming like this.

I want to remove this lines from graph. But I didn't get any solution for it.

I referred this code.

And following is my code:
demo.html

And when I'm expanding graph means dragging graph x axis date is hiding,

Please give me solution for it. I'm new with plotly.js

Body:
You can use showgrid:

xaxis: {
    showgrid: false
},
yaxis: {
    showgrid: false,
    showline: true
}

More plot.ly layout reference: https://plot.ly/javascript/reference/#layout-xaxis


问:
python regard a dict object as a _csv.reader
i write a python program to convert a csv file to a list of my own class,here is the code

```<code>class node:
    def __init__(self):
        self.cst_code = 0
        self.detail={};
    def setdata(self,CST_CODE,DATE,NUMBER):
        self.cst_code = CST_CODE
        self.detail[DATE]=NUMBER
    def add(self,DATE,NUMBER):
        if detail.get(DATE):
            self.detail[DATE]+=NUMBER
        else:
            self.detail[DATE]=NUMBER
    def sort(self):
        sorted(self.detail.items(),key = lambda e:e[0],reverse=True)
    def get_code(self):
        return self.cst_code
</code>```

detail is a dict object,but python regard it as a _csv.reader

```<code>    ---> 16         if detail.get(DATE):
         17             self.detail[DATE]+=NUMBER
         18         else:

AttributeError: '_csv.reader' object has no attribute 'get'
</code>```

did anyone meet the same question and get a solution?

答:
You've probably created a variable named detail in an outer scope to that of method node.add(). Because you are referring to detail, and there is no object named detail in the method's scope, the outer scope will be checked for an object with that name. You might have an instance of a csv.reader defined outside of the method.

It would seem that your method should actually be referring to self.detail, not detail. To access the dictionary stored in the instance, not an outer scope:

```<code>def add(self,DATE,NUMBER):
    if self.detail.get(DATE):        # N.B. use self
        self.detail[DATE]+=NUMBER
    else:
        self.detail[DATE]=NUMBER
</code>```

Note also that method node.sort() is missing a return.

Body:
i write a python program to convert a csv file to a list of my own class,here is the code

class node:
    def __init__(self):
        self.cst_code = 0
        self.detail={};
    def setdata(self,CST_CODE,DATE,NUMBER):
        self.cst_code = CST_CODE
        self.detail[DATE]=NUMBER
    def add(self,DATE,NUMBER):
        if detail.get(DATE):
            self.detail[DATE]+=NUMBER
        else:
            self.detail[DATE]=NUMBER
    def sort(self):
        sorted(self.detail.items(),key = lambda e:e[0],reverse=True)
    def get_code(self):
        return self.cst_code

detail is a dict object,but python regard it as a _csv.reader

    ---> 16         if detail.get(DATE):
         17             self.detail[DATE]+=NUMBER
         18         else:

AttributeError: '_csv.reader' object has no attribute 'get'

did anyone meet the same question and get a solution?

Body:
You've probably created a variable named detail in an outer scope to that of method node.add(). Because you are referring to detail, and there is no object named detail in the method's scope, the outer scope will be checked for an object with that name. You might have an instance of a csv.reader defined outside of the method.

It would seem that your method should actually be referring to self.detail, not detail. To access the dictionary stored in the instance, not an outer scope:

def add(self,DATE,NUMBER):
    if self.detail.get(DATE):        # N.B. use self
        self.detail[DATE]+=NUMBER
    else:
        self.detail[DATE]=NUMBER

Note also that method node.sort() is missing a return.