问:
How to use c# tuple value types in a switch statement
I'm using the new tuple value types in .net 4.7. In this example I am trying to make a switch statement for one or more cases of a tuple:

```<code>using System;
namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            switch (_test)
            {
                case ('A', 'B'):
                    Console.WriteLine("Case ok.");
                    break;
            }

        }
    }
}
</code>```

This does not compile unfortunately.

How do I take a tuple and make cases in a switch statement correctly?

答:
Answering your question technically, you could use when to check tuple's values:

```<code>(char letterA, char letterB) _test = ('A', 'B');
Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

switch (_test)
{
    case var tuple when tuple.letterA == 'A' && tuple.letterB == 'B':
        Console.WriteLine("Case ok.");
        break;
    case var tuple when tuple.letterA == 'D' && tuple.letterB == '\0':
        Console.WriteLine("Case ok.");
        break;
}
</code>```

However, consider using if version because it may be a more readable and understandable solution.

Another side of this question is single responsibility. Your methods knows what do A and B, D and \0 characters mean which breaks the single-responsibility principle.

In terms of OOP, it is better to separate this knowledge from you main code into a separate method.

Something like that could make code a little cleaner:

```<code>private static bool IsCaseOk(char a, char b)
{
    return (a == 'A' && b == 'B') || (a == 'D' && b == '\0'); // any logic here
}

public static void Main()
{
    (char letterA, char letterB) _test = ('A', 'B');
    Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

    if (IsCaseOk(_test.letterA, _test.letterB)) {
        Console.WriteLine("Case ok.");
    } else {
        Console.WriteLine("Case not ok.");
    }
}
</code>```

If these letters have any meaning in your domain, then probably it is a better idea to even create a class with two char properties and encapsulate this logic there.

ContentLicense: CC BY-SA 4.0

Body:
I'm using the new tuple value types in .net 4.7. In this example I am trying to make a switch statement for one or more cases of a tuple:

using System;
namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            switch (_test)
            {
                case ('A', 'B'):
                    Console.WriteLine("Case ok.");
                    break;
            }

        }
    }
}

This does not compile unfortunately.

How do I take a tuple and make cases in a switch statement correctly?

Body:
Answering your question technically, you could use when to check tuple's values:

(char letterA, char letterB) _test = ('A', 'B');
Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

switch (_test)
{
    case var tuple when tuple.letterA == 'A' && tuple.letterB == 'B':
        Console.WriteLine("Case ok.");
        break;
    case var tuple when tuple.letterA == 'D' && tuple.letterB == '\0':
        Console.WriteLine("Case ok.");
        break;
}

However, consider using if version because it may be a more readable and understandable solution.

Another side of this question is single responsibility. Your methods knows what do A and B, D and \0 characters mean which breaks the single-responsibility principle.

In terms of OOP, it is better to separate this knowledge from you main code into a separate method.

Something like that could make code a little cleaner:

private static bool IsCaseOk(char a, char b)
{
    return (a == 'A' && b == 'B') || (a == 'D' && b == '\0'); // any logic here
}

public static void Main()
{
    (char letterA, char letterB) _test = ('A', 'B');
    Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

    if (IsCaseOk(_test.letterA, _test.letterB)) {
        Console.WriteLine("Case ok.");
    } else {
        Console.WriteLine("Case not ok.");
    }
}

If these letters have any meaning in your domain, then probably it is a better idea to even create a class with two char properties and encapsulate this logic there.


来源: stackexchange

问:
Uncaught Error: Call to undefined function
It was working but now it stops working why? it soppiest to write into a file and save it. it was working yesterday but today it stops and I can't figure out why a search the internet but still nothing I can't .</p>
```<code><!DOCTYPE html>
<html>
<head>
    <title>Contact us</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="aboutus.html">About US</a></li>
                <li><a href="contactus.php">Contact Us</a></li>
                <li><a href="property.php">Propertys</a></li>
            </ul>

        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>

<h1>Contact us</h1>

<form  method="post" action="contactus.php" >

    <label>Email</label>
    <input type="text" name="email" required>
    <br>
    <label>Mobile number</label>
    <input type="number" name="number" required>
    <br>
    <textarea name="comments" required></textarea>

    <button name="submit" type="submit"> submit</button>

</form>

<?php
if(isset($_POST['submit'])){
    $number = $_POST["number"];
    $email = $_POST["email"];

    $trueemail;

    $massage = $_POST["comments"];

    if(isset($number)){

    if (strlen($number) == 8) {
        $truenumber = true;
    } else {
        echo "Input your mobile number";
    }
}

if(isset($email)){
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<br>";
        echo "Enter a valid email";
    } else {
        $trueemail = true;
    }
}

if($trueemail == true && $truenumber == true){
    writeToFile($email,$number,$massage);

    function writeToFile($trueemail,$truenumber,$massage) {

        $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
        fwrite($myfile, $trueemail . PHP_EOL);
        fwrite($myfile, $truenumber . PHP_EOL);
        fwrite($myfile, $massage . PHP_EOL);
        fclose($myfile);
    }
}
}
?>
</body>
</html>
</code>```

答:
You are calling writeToFile($email,$number,$massage); before you even declare this function.

Move writeToFile($email,$number,$massage); after function declaration and your code will works fine.

Body:
It was working but now it stops working why? it soppiest to write into a file and save it. it was working yesterday but today it stops and I can't figure out why a search the internet but still nothing I can't .

<!DOCTYPE html>

    <title>Contact us</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>

About US

Contact Us

Propertys

Contact us

<form  method="post" action="contactus.php" >

    Email
    <input type="text" name="email" required>

    Mobile number
    <input type="number" name="number" required>

    <textarea name="comments" required></textarea>

    <button name="submit" type="submit"> submit</button>

</form>

<?php
if(isset($_POST['submit'])){
    $number = $_POST["number"];
    $email = $_POST["email"];

    $trueemail;

    $massage = $_POST["comments"];

    if(isset($number)){

    if (strlen($number) == 8) {
        $truenumber = true;
    } else {
        echo "Input your mobile number";
    }
}

if(isset($email)){
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "
";
        echo "Enter a valid email";
    } else {
        $trueemail = true;
    }
}

if($trueemail == true && $truenumber == true){
    writeToFile($email,$number,$massage);

    function writeToFile($trueemail,$truenumber,$massage) {

        $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
        fwrite($myfile, $trueemail . PHP_EOL);
        fwrite($myfile, $truenumber . PHP_EOL);
        fwrite($myfile, $massage . PHP_EOL);
        fclose($myfile);
    }
}
}
?>

ContentLicense: CC BY-SA 3.0


问:
Trying to move by point.x / .y less than 1
I'm trying to return a point from a method that calculates angle as a vector.

I'm then adding this points x & y to my player object (from example code)'s x and y Numbers - these are Numbers, not a point. In other places I see numbers defined as floats, so I didn't expect this to be a problem.

When I multiply distvar and distvar2 by * 2, then my object move, best I can tell because the values, formerly .59~ & -.8~, are greater than 1 (absolute value).

Any hints? Should I just use a Point variable on my player object instead? Is there something else I must do to convert from a point.x/y to a Number? New to flash, appreciate your help.

Thanks!

```<code>public function GetAngle(initialp:Point,secondp:Point):Point{
    distvar = ((initialp.x - secondp.x) * (initialp.x - secondp.x));
    distvar2 = ((initialp.y - secondp.y) * (initialp.y - secondp.y));

 //Emergency guard clause against dividing by 0
    if (distvar + distvar2 == 0){
        distvar = 1;
        distvar2 = 1;
    }
    veldistance = Math.sqrt((distvar+distvar2));

distvar = ((Math.abs(initialp.x-secondp.x))/veldistance);
distvar2 = ((Math.abs(initialp.y-secondp.y))/veldistance);

if (secondp.x < initialp.x){
    distvar = -distvar;
}
if (secondp.y < initialp.y){
    distvar2 = -distvar2;
}

apoint.x = distvar;
apoint.y = distvar2;

return apoint;
</code>```

答: The values of a point.x/y are numbers.  The way you are adding the point.x/y to your object.x/y should be fine.  I suspect there is something else wrong with the code, though without more of your code I'm not sure what. For one, I can't see where apoint is created.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to return a point from a method that calculates angle as a vector.

I'm then adding this points x & y to my player object (from example code)'s x and y Numbers - these are Numbers, not a point. In other places I see numbers defined as floats, so I didn't expect this to be a problem.

When I multiply distvar and distvar2 by * 2, then my object move, best I can tell because the values, formerly .59~ & -.8~, are greater than 1 (absolute value).

Any hints? Should I just use a Point variable on my player object instead? Is there something else I must do to convert from a point.x/y to a Number? New to flash, appreciate your help.

Thanks!

public function GetAngle(initialp:Point,secondp:Point):Point{
    distvar = ((initialp.x - secondp.x) * (initialp.x - secondp.x));
    distvar2 = ((initialp.y - secondp.y) * (initialp.y - secondp.y));

 //Emergency guard clause against dividing by 0
    if (distvar + distvar2 == 0){
        distvar = 1;
        distvar2 = 1;
    }
    veldistance = Math.sqrt((distvar+distvar2));

distvar = ((Math.abs(initialp.x-secondp.x))/veldistance);
distvar2 = ((Math.abs(initialp.y-secondp.y))/veldistance);

if (secondp.x < initialp.x){
    distvar = -distvar;
}
if (secondp.y < initialp.y){
    distvar2 = -distvar2;
}

apoint.x = distvar;
apoint.y = distvar2;

return apoint;


问:
Is there a way to audit every DML Events without writing triggers to each table?
Is there a way where I can audit every tables changes without writing each triggers for every table.

I have nearly   nearly 500 tables and writing triggers for each of them is very hectic task and managing them is a nightmare.

Furthermore most of the tables are normalized which makes the things that I need track more complicated.

However every insert,update,delete,select task is done through stored procedures.
One of the solution is auditing through those procedures . However I am looking to  an effortless Solution for auditing. Some sort like server level triggers on every stored procedure which tracks every tables that is being used on the procedure

答:
If you are on Enterprise Edition and @@version >= 2008 you can use database audit.

Here you can find an example of setting it SQL Server 2008 Auditing Feature

And here you find the official doc Create a Server Audit and Database Audit Specification


问:
Creating complex header and footer for my angular pages
We have a website of 30+ different pages.

All pages have the same header and footer.

The header and footer each contain a lot of logic and calls to nodejs for data.

How would I go about doing this in a smart way in Angular. Right now there is too much copy/paste and I see the same code again and again.

Should I write a header/footer controller and then call them on each page?

Or is there a way to setup header/footer once, and keep them cached for all pages (they rarely change)?

答:
You can use directive that returns a specific template of footer or header based on some logic you provide.

Sample Code

```<code>var app = angular.module('myApp', []);

app.directive('footer', function() {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: function(){
        return '/app/templates/footer.html';
      }
    };
});
</code>```

restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment) , let's assume that the name of the directive is Doc :

```<code>Type :  Usage
A = <div Doc></div>
C = <div class="Doc"></div>
E = <Doc> data="book_data"></Doc>
M = <!--directive:Doc -->
</code>```

Body:
You can use directive that returns a specific template of footer or header based on some logic you provide.

Sample Code

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

app.directive('footer', function() {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: function(){
        return '/app/templates/footer.html';
      }
    };
});

restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment) , let's assume that the name of the directive is Doc :

Type :  Usage
A = <div Doc></div>
C = <div class="Doc"></div>
E = <Doc> data="book_data"></Doc>
M = <!--directive:Doc -->


问:
Export PDF Telerik grid MVC
I have got a Telerik MVC grid and I would like to export it as a pdf and hide the column "Test2". I am not able to achieve the desired behavior.

```<code>@(Html.Kendo().Grid<Lagerbase.Models.Artikel>()
.Name("ArtikelGrid")
.ToolBar(tools => tools.Pdf())
    .Pdf(pdf => pdf
        .AllPages()
        .AvoidLinks()
        .PaperSize("A4")
        .Scale(0.8)
        .Margin("2cm", "1cm", "1cm", "1cm")
        .Landscape()
        .RepeatHeaders()
        .TemplateId("page-template")
        .FileName("Artikel.pdf")
        .ProxyURL(Url.Action("Pdf_Export_Save", "Grid"))
    )
   .Columns(columns =>
        {
            columns.Bound(o => o.Id).Hidden();
            columns.Bound(o => o.Test1);
            columns.Bound(o => o.Test2);
        })
}
</code>```

This is what I found for an Excel export. So I adjusted the bind to "pdfExport".
Unfortunately it doesn't work for the function e.sender.saveAsExcel();.

```<code><script type="text/javascript">
    $(document).ready(function () {
        var exportFlag = false;
        $("#ArtikelGrid").data("kendoGrid").bind("pdfExport", function (e) {
            if (!exportFlag) {
                e.sender.hideColumn(1);
                e.preventDefault();
                exportFlag = true;
                setTimeout(function () {
                    e.sender.saveAsExcel();
                });
            } else {
                e.sender.showColumn(1);
                exportFlag = false;
            }
        });
    });
</script>
</code>```

Does someone know a solution to this?

答:
View this Demo : FUll demo

Source

Title: Export PDF Telerik grid MVC

Body:
I have got a Telerik MVC grid and I would like to export it as a pdf and hide the column "Test2". I am not able to achieve the desired behavior.

@(Html.Kendo().Grid<Lagerbase.Models.Artikel>()
.Name("ArtikelGrid")
.ToolBar(tools => tools.Pdf())
    .Pdf(pdf => pdf
        .AllPages()
        .AvoidLinks()
        .PaperSize("A4")
        .Scale(0.8)
        .Margin("2cm", "1cm", "1cm", "1cm")
        .Landscape()
        .RepeatHeaders()
        .TemplateId("page-template")
        .FileName("Artikel.pdf")
        .ProxyURL(Url.Action("Pdf_Export_Save", "Grid"))
    )
   .Columns(columns =>
        {
            columns.Bound(o => o.Id).Hidden();
            columns.Bound(o => o.Test1);
            columns.Bound(o => o.Test2);
        })
}

This is what I found for an Excel export. So I adjusted the bind to "pdfExport".
Unfortunately it doesn't work for the function e.sender.saveAsExcel();.

Does someone know a solution to this?

Body:
View this Demo : FUll demo

Source


问:
how can run rake resque:scheduler in daemon mode
I am using resque:scheduler gem in my rails 3 application.

How can start rake resque:scheduler in daemon mode.

and if you know then please let me know,

How can I configure this task in GOD script?

答:
Try the following to configure resque-schedular in God script.

Install god gem

```<code>gem install god
</code>```

create a file with name as watch.god in your project folder.

Add following to watch.god

```<code>God.watch do |w|
  w.name = "resque_schedular"
  w.dir = '/home/machine_name/project_path'
  w.start = "BACKGROUND=yes bundle exec rake environment resque:scheduler"
  w.keepalive
end
</code>```

Run god in terminal to test

```<code>$ god -c path/to/watch.god -D
</code>```

Run god in daemon(background) from terminal

```<code>$ god -c path/to/watch.god
</code>```

Body:
Try the following to configure resque-schedular in God script.

Install god gem

gem install god

create a file with name as watch.god in your project folder.

Add following to watch.god

God.watch do |w|
  w.name = "resque_schedular"
  w.dir = '/home/machine_name/project_path'
  w.start = "BACKGROUND=yes bundle exec rake environment resque:scheduler"
  w.keepalive
end

Run god in terminal to test

$ god -c path/to/watch.god -D

Run god in daemon(background) from terminal

$ god -c path/to/watch.god


问:
Satellizer login JWT token is gone when page refresh

I am using the Angular-satellizer extension for the login/register feature but I am stuck at number 7.

Token was saved to localStorage but I when refresh the page it's gone and $auth.isAuthenticated() function is returning false.

```<code>.controller('loginCtrl', function($scope, $state, $auth, jwtHelper) {
  $scope.login = function() {
    $auth.login($scope.user)
      .then(function(response) {
        var gelenToken = response.data;
        var tokenPayload = jwtHelper.decodeToken(gelenToken.token);
        console.log(JSON.stringify(tokenPayload)); // Output:{"sub":"1","iat":1496346513,"exp":1497556113,"data":{"role":"admin"}}
        localStorage.setItem('token', JSON.stringify(tokenPayload));
        $state.go('baba.manga');
      })
  };
})
</code>```

答:
You should try this :

localStorage.setItem('token', data.token);

OR

$window.localStorage.token = JSON.stringify(data.token);

to save your token, You can see the token in browser local Storage, You don't need to decode that token unless you need it to.

It should not get deleted on page refresh, If its getting deleted the I suggest you to try breakpoints at places and debug which part is clearing local storage.

Browser does not delete any localstorage data at any point, Your code might be doing it.

Body:
I am using the Angular-satellizer extension for the login/register feature but I am stuck at number 7.

Token was saved to localStorage but I when refresh the page it's gone and $auth.isAuthenticated() function is returning false.

.controller('loginCtrl', function($scope, $state, $auth, jwtHelper) {
  $scope.login = function() {
    $auth.login($scope.user)
      .then(function(response) {
        var gelenToken = response.data;
        var tokenPayload = jwtHelper.decodeToken(gelenToken.token);
        console.log(JSON.stringify(tokenPayload)); // Output:{"sub":"1","iat":1496346513,"exp":1497556113,"data":{"role":"admin"}}
        localStorage.setItem('token', JSON.stringify(tokenPayload));
        $state.go('baba.manga');
      })
  };
})


问:
Spring: How to Extract Data from One Object and Insert Into Another
I currently have two tables: Workforce and Employees. The Workforce table is a collection of all potential employees who have submitted resumes to join the company. The Employees table is a collection of persons in the Workforce table that have actually been hired.

Environment:
1. Eclipse
2. Java (J2EE)
3. Maven
4. Spring
5. JPA (JpaRepository)

For brevity, I will stick to the files that are of concern for this extraction of data and insertion of data into another table.

Because of the similarities of both tables, many fields in the Workforce table will be similar to those in the Employees table:

First Name

Last Name

Department

Phone Number
etc...

If the person in the workforce is chosen, there is a boolean value called "isHired" that will have the value of 1. Every week, the person's in the Workforce table with values of "1" for "isHired" will be extracted from the Workforce table and inserted into the Employees table.

The general SQL Query looks something like this (and works in a regular IDE with no Spring HPQL constraints):

```<code>INSERT INTO Employees (firstName, lastName, dept, phone)
SELECT emp_firstName, emp_lastName, emp_dept, emp_phone
FROM Workforce WHERE isHired = 1
</code>```

This works without a hitch, but we're talking about JPA, so this is what I have done:

In a Repository, the process has been broken into two items: 1) extracting data from one table (Workforce) and then 2) inserting extracted data into another table (Employees)

WorkforceRepository.java

```<code>package com.example.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.example.entities.Workforce;

@Repository
public interface WorkforceRepository extends JpaRepository<Workforce, Long> {
    @Query("SELECT new Workforce("
        + "w.workforceid, "
        + "w.firstName, "
        + "w.lastName, "
        + "w.dept, "
        + "w.phone) "
        + "FROM Workforce w WHERE isHired = 1")
    public List<Workforce> getNewHires();

}
</code>```

Workforce.java

```<code>package com.example.entities;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Generatedvalue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table

@Entity
@Table(name = "WORKFORCE")
public class Workforce implements Serializable {
    private static final long serialVersionUID = 1L;

    public Workforce() {
    }
    public Workforce(long workforceid, String firstName, lastName, dept, phone) {
    this.workforceid = workforceid;
    this.firstName = firstName;
    this.lastName = lastName;
    this.dept = dept;
    this.phone = phone;
    }
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="workforceid")
    private long workforceid;

    @Column(name="firstName)
    private String firstName;
    // OTHER DECLARATIONS REMOVED FOR BREVITY
    // GETTERS AND SETTERS REMOVED FOR BREVITY
}
</code>```

NOTE: I have left out the Employee.java and EmployeesRepository.java for BREVITY They are pretty much the same and aside from the employeeid, that is the primary key for the Employee table, the other columns are exactly the same. The contructor class only contains the four columns that are the same as well.

I have a ton of CRUD operations that work, while the operations are only occurring within the same table. However, I would like to do this:

EmployeesController.java

```<code>// IMPORTS REMOVED FOR BREVITY
List<Workforce> retrievedRisks = Workforce.getNewHires();
for (Workforce w: retrievedRisks)
    Employees.saveAndFlush(w);
// MISC CODE REMOVED FOR BREVITY
</code>```

The error I receive of course is below:

```<code>Type mismatch: cannot convert from element type Workforce to Employees
</code>```

Anyone know how to extract data from one POJO object and insert it into another using JpaRepository?

答:
If Employees and Workforce almoust the same you can use hibernate inheritance  . Add copy constructor and resave entity.But it might not to help if you have different constraints or id  generator  (might be a case when Employees already exists with Workforce ids ).
Simple case it's just create Employees from Workforce and save created object via

```<code>employee = new Employees(w.firstName, w.lastName, w.dept, w.phone);
Employees.saveAndFlush(employee);
</code>```

in this case you create new Employees and repository saves it correct. Maybe after save newEmployees (copy of Workforce ) you should delete old Workforce

Body:
I currently have two tables: Workforce and Employees. The Workforce table is a collection of all potential employees who have submitted resumes to join the company. The Employees table is a collection of persons in the Workforce table that have actually been hired.

Environment:
1. Eclipse
2. Java (J2EE)
3. Maven
4. Spring
5. JPA (JpaRepository)

For brevity, I will stick to the files that are of concern for this extraction of data and insertion of data into another table.

Because of the similarities of both tables, many fields in the Workforce table will be similar to those in the Employees table:

First Name

Last Name

Department

Phone Number
etc...

If the person in the workforce is chosen, there is a boolean value called "isHired" that will have the value of 1. Every week, the person's in the Workforce table with values of "1" for "isHired" will be extracted from the Workforce table and inserted into the Employees table.

The general SQL Query looks something like this (and works in a regular IDE with no Spring HPQL constraints):

INSERT INTO Employees (firstName, lastName, dept, phone)
SELECT emp_firstName, emp_lastName, emp_dept, emp_phone
FROM Workforce WHERE isHired = 1

This works without a hitch, but we're talking about JPA, so this is what I have done:

In a Repository, the process has been broken into two items: 1) extracting data from one table (Workforce) and then 2) inserting extracted data into another table (Employees)

WorkforceRepository.java

package com.example.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.example.entities.Workforce;

@Repository
public interface WorkforceRepository extends JpaRepository<Workforce, Long> {
    @Query("SELECT new Workforce("
        + "w.workforceid, "
        + "w.firstName, "
        + "w.lastName, "
        + "w.dept, "
        + "w.phone) "
        + "FROM Workforce w WHERE isHired = 1")
    public List<Workforce> getNewHires();

}

Workforce.java

package com.example.entities;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Generatedvalue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table

@Entity
@Table(name = "WORKFORCE")
public class Workforce implements Serializable {
    private static final long serialVersionUID = 1L;

    public Workforce() {
    }
    public Workforce(long workforceid, String firstName, lastName, dept, phone) {
    this.workforceid = workforceid;
    this.firstName = firstName;
    this.lastName = lastName;
    this.dept = dept;
    this.phone = phone;
    }
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="workforceid")
    private long workforceid;

    @Column(name="firstName)
    private String firstName;
    // OTHER DECLARATIONS REMOVED FOR BREVITY
    // GETTERS AND SETTERS REMOVED FOR BREVITY
}

NOTE: I have left out the Employee.java and EmployeesRepository.java for BREVITY They are pretty much the same and aside from the employeeid, that is the primary key for the Employee table, the other columns are exactly the same. The contructor class only contains the four columns that are the same as well.

I have a ton of CRUD operations that work, while the operations are only occurring within the same table. However, I would like to do this:

EmployeesController.java

// IMPORTS REMOVED FOR BREVITY
List<Workforce> retrievedRisks = Workforce.getNewHires();
for (Workforce w: retrievedRisks)
    Employees.saveAndFlush(w);
// MISC CODE REMOVED FOR BREVITY

The error I receive of course is below:

Type mismatch: cannot convert from element type Workforce to Employees

Anyone know how to extract data from one POJO object and insert it into another using JpaRepository?

Body:
If Employees and Workforce almoust the same you can use hibernate inheritance  . Add copy constructor and resave entity.But it might not to help if you have different constraints or id  generator  (might be a case when Employees already exists with Workforce ids ).
Simple case it's just create Employees from Workforce and save created object via

employee = new Employees(w.firstName, w.lastName, w.dept, w.phone);
Employees.saveAndFlush(employee);

in this case you create new Employees and repository saves it correct. Maybe after save newEmployees (copy of Workforce ) you should delete old Workforce


问:
Checking JavaScript code for typos in Notepad++
I use a combination of Notepad++, JSHint and Cordova CLI to create my hybrid Android web apps - yes, I am aware that there are more sophisticated ways of doing this but tht is not what this question is about.

One of the issues I run into every now and again is a typographic - as opposed to syntactic which is easily caught by JSHint - error which only manifests itself once I am compiled the APK and tried to run it.  For instance

docment instead of document (missing u)

getElmentByID  instead of getElementById (missing e, wrong capitalization on ID)

The one thing I really love about Java is that the compiler stops you dead in your tracks and demands that you fix such errors first.  That is not the case with JavaScript where the best one can do is test for correct syntax.

However, I am wondering - perhaps there is a way (maybe a NPP plugin that I am unaware of) to check for such errors?

答: Use typescript or flowtype to catch those, and many more errors.  Alternatively, find a decent syntax theme that's set up to highlight DOM methods.</p>


问:
Usings variables AND regex within substitute routine in AWK?
Let's say I have an AWK script, where the string variable my_var is defined (and equals to ; -- just in case this matters). Now, I want to delete one or more occurrences of my_var from another string:

```<code>gsub(/my_var+/, "", another_string)
</code>```

Obviously, this doesn't work. But how should I construct this gsub command (or, how should I escape my_var) to make it happen?

答:
You can construct regex using string:</p>

```<code>gsub(my_var "+", "", another_string)
</code>```

Body:
Let's say I have an AWK script, where the string variable my_var is defined (and equals to ; -- just in case this matters). Now, I want to delete one or more occurrences of my_var from another string:

gsub(/my_var+/, "", another_string)

Obviously, this doesn't work. But how should I construct this gsub command (or, how should I escape my_var) to make it happen?

Body:
You can construct regex using string:

gsub(my_var "+", "", another_string)


问:
Making a prime generator
This is supposed to be a prime generator. I try running this but it doesn't print out the integers. The program will also end right away. I don't know if its running  </p>

```<code>def prime_gen():

    start = 1

    while start:

        if start % start == 0:
            print(start)

            start += 1
</code>```

答:
First what is a prime? A number that have no divisors but itself.
The easy way is to load that numbers, starting by two and check if that number can't be divided by all the previous ones, if its so then you got a new one; you can make it a generator by using yield instead of return

```<code>def prime_gen():
    primes = [2]
    yield 2
    n = 3
    while True:
        for p in primes:
            if n % p == 0:
                n += 1
                break
        else:
            primes.append(n)
            yield n
</code>```

Example:

```<code>pg = prime_gen()
next(pg)
2
next(pg)
3
next(pg)
5
next(pg)
7
next(pg)
11
</code>```

Title: Making a prime generator

Body:
This is supposed to be a prime generator. I try running this but it doesn't print out the integers. The program will also end right away. I don't know if its running

def prime_gen():

    start = 1

    while start:

        if start % start == 0:
            print(start)

            start += 1

Body:
First what is a prime? A number that have no divisors but itself.
The easy way is to load that numbers, starting by two and check if that number can't be divided by all the previous ones, if its so then you got a new one; you can make it a generator by using yield instead of return

def prime_gen():
    primes = [2]
    yield 2
    n = 3
    while True:
        for p in primes:
            if n % p == 0:
                n += 1
                break
        else:
            primes.append(n)
            yield n

Example:

pg = prime_gen()
next(pg)
2
next(pg)
3
next(pg)
5
next(pg)
7
next(pg)
11


问:
Handling authentication failure in auto login in liferay
I have a theme where I have a popup to ask for the login credentials .

It has 2 fields ,login id and password followed by a submit button.

```<code><div class="x">
    <div class="y">
        <aui:input name="login" id="login" class="z"
        type="text" placeholder="Email"                                               showRequiredLabel="<%=false%>" label="" value="<%=login%>">
        </aui:input>
    </div>
</div>

<div class="x">
    <div class="y">
        <aui:input name="password" id="Password"
        class="z" type="password" placeholder="Password"
        showRequiredLabel="<%=false%>" label="" value="<%=password%>">
        </aui:input>
    </div>
</div>

<div class="x">
    <div class="y">
        <aui:button-row>
            <aui:button type="submit" class="btn z"
            value="Log in" id=z/>
            </aui:button-row>
        </div>
</div>

<script>
jQuery(document).ready(function($) {

$('#z').click(function(){
var textBoxEmail= $('#login').val();
var textBoxPassword=  $('#Password').val();
var redirecturl="/home";

var url = Liferay.ThemeDisplay.getPortalURL()+"/c/portal/login?login=" + textBoxEmail + "&password=" +textBoxPassword+"&rememberMe=false&redirect=" + redirecturl;
$("#loginDetails").attr('action',url);
document.getElementById('loginDetails').submit();

}
});

</script>
</code>```

This logins for the positive case , but if the password or the email entered is incorrecet it displays the

"This webpage is not available

ERR_CONTENT_DECODING_FAILED"

I want to show the failure message in the same page from where i am sending the login details or I want it to be redirected to some URL if the authentication fails.

I am using liferay-6.2-ce-ga3 and the theme is designed in the velocity.

答: I agree, go with the Login hook or with authentication pipeline using pre and post login filters. The redirection can be done from filters.</p>

Body:
I have a theme where I have a popup to ask for the login credentials .

It has 2 fields ,login id and password followed by a submit button.

        <aui:input name="login" id="login" class="z"
        type="text" placeholder="Email"                                               showRequiredLabel="<%=false%>" label="" value="<%=login%>">
        </aui:input>

        <aui:input name="password" id="Password"
        class="z" type="password" placeholder="Password"
        showRequiredLabel="<%=false%>" label="" value="<%=password%>">
        </aui:input>

        <aui:button-row>
            <aui:button type="submit" class="btn z"
            value="Log in" id=z/>
            </aui:button-row>

This logins for the positive case , but if the password or the email entered is incorrecet it displays the

"This webpage is not available

ERR_CONTENT_DECODING_FAILED"

I want to show the failure message in the same page from where i am sending the login details or I want it to be redirected to some URL if the authentication fails.

I am using liferay-6.2-ce-ga3 and the theme is designed in the velocity.


问:
Get text using selenium PhantomJS inside Span
I tried to get text inside span using Seleniung webdriver PhantomJS. My code is like this :

```<code>href = driver.find_elements_by_xpath("//a[@class='_8mlbc _vbtk2 _t5r8b']")
for rt in href:
    rt.click()
    if href:
        name = driver.find_elements_by_xpath("//*[@class='_99ch8']/span").text
        # name = driver.find_element_by_xpath("//li[a[@title='nike']]/span").text
        print(name)
</code>```

In HTML :

```<code><li class="_99ch8"><a class="_4zhc5 notranslate _ebg8h" title="nike" href="/nike/">nike</a><span><span>Nobody believed a boy from Madeira would make it to the stars. Except the boy from Madeira. </span><br><a href="/explore/tags/nike/">#nike</a><span> </span><a href="/explore/tags/soccer/">#soccer</a><span> </span><a href="/explore/tags/football/">#football</a><span> </span><a href="/explore/tags/cr7/">#CR7</a><span> </span><a href="/explore/tags/cristiano/">#Cristiano</a><span> </span><a href="/explore/tags/cristianoronaldo/">#CristianoRonaldo</a><span> </span><a href="/explore/tags/mercurial/">#Mercurial</a><span> </span><a href="/explore/tags/justdoit/">#justdoit</a></span></li>
</code>```

I want try to get text inside span.

答:
You cannot use XPath expression that returns text node as it unacceptable option for selenium- selector should return WebDriver element only

Also note that class name of li seem to be dynamic, so you might use title attribute value of child anchor instead:

```<code>driver.find_element_by_xpath("//li[a[@title='nike']]/span").text
</code>```

UPDATE

The complete code:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.instagram.com/nike/')

links = driver.find_elements_by_xpath('//a[contains(@href, "/?taken-by=nike")]')
for link in links:
    link.click()
    wait(driver, 5).until(EC.presence_of_element_located((By.XPATH, "//div/article")))
    print(driver.find_element_by_xpath("//li[a[@title='nike']]/span").text)
    driver.find_element_by_xpath("//div[@role='dialog']/button").click()
</code>```

UPDATE#2

You can also simply grab the same text without opening each image:

```<code>links = driver.find_elements_by_xpath('//img')
for img in links:
    print(img.get_attribute('alt'))
</code>```

Body:
I tried to get text inside span using Seleniung webdriver PhantomJS. My code is like this :

href = driver.find_elements_by_xpath("//a[@class='_8mlbc _vbtk2 _t5r8b']")
for rt in href:
    rt.click()
    if href:
        name = driver.find_elements_by_xpath("//*[@class='_99ch8']/span").text
        # name = driver.find_element_by_xpath("//li[a[@title='nike']]/span").text
        print(name)

In HTML :

nikeNobody believed a boy from Madeira would make it to the stars. Except the boy from Madeira.
#nike #soccer #football #CR7 #Cristiano #CristianoRonaldo #Mercurial #justdoit

I want try to get text inside span.

Body:
You cannot use XPath expression that returns text node as it unacceptable option for selenium- selector should return WebDriver element only

Also note that class name of li seem to be dynamic, so you might use title attribute value of child anchor instead:

driver.find_element_by_xpath("//li[a[@title='nike']]/span").text

UPDATE

The complete code:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.instagram.com/nike/')

links = driver.find_elements_by_xpath('//a[contains(@href, "/?taken-by=nike")]')
for link in links:
    link.click()
    wait(driver, 5).until(EC.presence_of_element_located((By.XPATH, "//div/article")))
    print(driver.find_element_by_xpath("//li[a[@title='nike']]/span").text)
    driver.find_element_by_xpath("//div[@role='dialog']/button").click()

UPDATE#2

You can also simply grab the same text without opening each image:

links = driver.find_elements_by_xpath('//img')
for img in links:
    print(img.get_attribute('alt'))


问:
How to change property of more than one qlineedit at once
I have done some coding for L00 (name of my first QLineEdit).

I want to do the same for other 99 widgets (up to L99). I don't wanna copy paste it 100 hundred times.

```<code>void MainWindow::on_L00_returnPressed(){
    QString c = ui->L00->text();
    char d = QString(c).at(0).toLatin1();
    if(d>=65&&d<=90||d>=97&&d<=122)
    {
        square[0]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        ui->L00->setReadOnly(true);
        ui->L00->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        ui->L00->setText("");
    }
}
</code>```

答:
You can use the QObject::findChildren to do so. It must be called from the parent widget (your MainWindow). You can from it connect the QLineEdit individually, or change all values at once.

Example:

```<code>for (auto lineEdit : this->findChildren<QLineEdit*>()) {
  // connect lineEdit or change values
}
</code>```

Body:
I have done some coding for L00 (name of my first QLineEdit).

I want to do the same for other 99 widgets (up to L99). I don't wanna copy paste it 100 hundred times.

void MainWindow::on_L00_returnPressed(){
    QString c = ui->L00->text();
    char d = QString(c).at(0).toLatin1();
    if(d>=65&&d<=90||d>=97&&d<=122)
    {
        square[0]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        ui->L00->setReadOnly(true);
        ui->L00->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        ui->L00->setText("");
    }
}

Body:
You can use the QObject::findChildren to do so. It must be called from the parent widget (your MainWindow). You can from it connect the QLineEdit individually, or change all values at once.

Example:

for (auto lineEdit : this->findChildren<QLineEdit*>()) {
  // connect lineEdit or change values
}


问:
Programmatically navigate PowerPoint
I have PowerPoint 2008 running on my Mac. Is there a way to navigate, like forward and backward, the PowerPoint presentation using some program in Python, Java, C/C++ or other language?</p>

答: Yes, using Applescript. If you can't script Powerpoint directly (look in its script Library using the editor) you can send keypresses to it using the accessibility framework.</p>

Title: Programmatically navigate PowerPoint


问:
convertion of ObjectResult<Nullable<int>> type to int
Stored proc return as ObjectResult<Nullable<int>> using Entity frame work and want to convert this to int type
or how to check this value with another integer value

答:
First check if the nullable object has a value - if so then get its value</p>

```<code>if (someNullableIntObject.HasValue)
{
   int intValue = someNullabelObject.Value;
}
</code>```

Body:
First check if the nullable object has a value - if so then get its value

if (someNullableIntObject.HasValue)
{
   int intValue = someNullabelObject.Value;
}


问:
React Native Undefined is not an Object (evaluating 'this.state.input')
I am trying to build a word dictionary that translates English words to German words by following this tutorial. It utilize a json file which, I believe, contain keys with English words and its corresponding German words as values.

The tutorial do that by using the require statement var english_german = require('./english_german.json'); but I would like to know if there is an alternative by using the import statement instead.

The main problem I am facing, though, is that I am getting a "Undefined is not an Object (evaluating 'this.state.input')" error when I type in a word in the TextInput and hitting enter.

My source code is as follows:

import React, { Component } from 'react';
import {
  AppRegistry,
  Image,
  StyleSheet,
  Text,
  TextInput,
  View
} from 'react-native';

var english_german = require('./english_german.json');

class Dictionary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      output: ''
    }

  }

  showMeaning() {
    // Use the ternary operator to check if the word
    // exists in the dictionary.
    var meaning = this.state.input in english_german ?
                    english_german[this.state.input] :
                    "Not Found";
    // Update the state
    this.setState({output: meaning});
  }

 render() {
  var layout =
   <View style = { styles.parent }>
    <Text>
     Type something in English:
    </Text>
        <TextInput
          onChangeText={(e) => this.setState({input: e})}
          text = { this.state.input }
          onSubmitEditing = { this.showMeaning }
        />
    <Text style = { styles.germanLabel }>
     It's German equivalent is:
    </Text>
    <Text style = { styles.germanWord }>
          { this.state.output }
    </Text>
   </View>
  ;
  return layout;
 }
}

const styles = StyleSheet.create({
 // For the container View
 parent: {
  padding: 16
 },
 // For the Text Label
 germanLabel: {
  marginTop: 20,
  fontWeight: 'bold'
 },
 // For the Text meaning
 germanWord: {
  marginTop: 15,
  fontSize: 30,
  fontStyle: 'italic'
 }
});

AppRegistry.registerComponent('Dictionary', () => Dictionary);```

答:
This is because you are referring to this inside of showMeaning. Bind that function to right this inside constructor like this this.showMeaning = this.showMeaning.bind(this).

I highly recommend you to read basics of React. For example here is documentation for your problem: https://facebook.github.io/react/docs/handling-events.html


问:
Uncaught Error: Call to undefined function
It was working but now it stops working why? it soppiest to write into a file and save it. it was working yesterday but today it stops and I can't figure out why a search the internet but still nothing I can't .</p>
```<code><!DOCTYPE html>
<html>
<head>
    <title>Contact us</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="aboutus.html">About US</a></li>
                <li><a href="contactus.php">Contact Us</a></li>
                <li><a href="property.php">Propertys</a></li>
            </ul>

        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>

<h1>Contact us</h1>

<form  method="post" action="contactus.php" >

    <label>Email</label>
    <input type="text" name="email" required>
    <br>
    <label>Mobile number</label>
    <input type="number" name="number" required>
    <br>
    <textarea name="comments" required></textarea>

    <button name="submit" type="submit"> submit</button>

</form>

<?php
if(isset($_POST['submit'])){
    $number = $_POST["number"];
    $email = $_POST["email"];

    $trueemail;

    $massage = $_POST["comments"];

    if(isset($number)){

    if (strlen($number) == 8) {
        $truenumber = true;
    } else {
        echo "Input your mobile number";
    }
}

if(isset($email)){
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<br>";
        echo "Enter a valid email";
    } else {
        $trueemail = true;
    }
}

if($trueemail == true && $truenumber == true){
    writeToFile($email,$number,$massage);

    function writeToFile($trueemail,$truenumber,$massage) {

        $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
        fwrite($myfile, $trueemail . PHP_EOL);
        fwrite($myfile, $truenumber . PHP_EOL);
        fwrite($myfile, $massage . PHP_EOL);
        fclose($myfile);
    }
}
}
?>
</body>
</html>
</code>```

答:
Please put the function outside if condition. something like this</p>

```<code>function writeToFile($trueemail,$truenumber,$massage)
    {

            $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
            fwrite($myfile, $trueemail . PHP_EOL);
            fwrite($myfile, $truenumber . PHP_EOL);
            fwrite($myfile, $massage . PHP_EOL);
            fclose($myfile);
    }

if($trueemail == true && $truenumber == true){
    writeToFile($email,$number,$massage);

}
</code>```

Body:
It was working but now it stops working why? it soppiest to write into a file and save it. it was working yesterday but today it stops and I can't figure out why a search the internet but still nothing I can't .

<!DOCTYPE html>

    <title>Contact us</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>

About US

Contact Us

Propertys

Contact us

<form  method="post" action="contactus.php" >

    Email
    <input type="text" name="email" required>

    Mobile number
    <input type="number" name="number" required>

    <textarea name="comments" required></textarea>

    <button name="submit" type="submit"> submit</button>

</form>

<?php
if(isset($_POST['submit'])){
    $number = $_POST["number"];
    $email = $_POST["email"];

    $trueemail;

    $massage = $_POST["comments"];

    if(isset($number)){

    if (strlen($number) == 8) {
        $truenumber = true;
    } else {
        echo "Input your mobile number";
    }
}

if(isset($email)){
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "
";
        echo "Enter a valid email";
    } else {
        $trueemail = true;
    }
}

if($trueemail == true && $truenumber == true){
    writeToFile($email,$number,$massage);

    function writeToFile($trueemail,$truenumber,$massage) {

        $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
        fwrite($myfile, $trueemail . PHP_EOL);
        fwrite($myfile, $truenumber . PHP_EOL);
        fwrite($myfile, $massage . PHP_EOL);
        fclose($myfile);
    }
}
}
?>

Body:
Please put the function outside if condition. something like this

function writeToFile($trueemail,$truenumber,$massage)
    {

            $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
            fwrite($myfile, $trueemail . PHP_EOL);
            fwrite($myfile, $truenumber . PHP_EOL);
            fwrite($myfile, $massage . PHP_EOL);
            fclose($myfile);
    }

if($trueemail == true && $truenumber == true){
    writeToFile($email,$number,$massage);

}


答:
This is a binding problem, add this in your constructor:

```<code>this.showMeaning = this.showMeaning.bind(this);
</code>```

This will ensure that this object in your showMeaning method refers to your Dictionary component. Alternatively, you could use arrow function in your showMeaning method like so:

```<code>showMeaning = () => { /* rest of code */ }
</code>```

The arrow function preserves the context of this. So the use of bind isn't required.

Title: React Native Undefined is not an Object (evaluating 'this.state.input')

Body:
I am trying to build a word dictionary that translates English words to German words by following this tutorial. It utilize a json file which, I believe, contain keys with English words and its corresponding German words as values.

The tutorial do that by using the require statement var english_german = require('./english_german.json'); but I would like to know if there is an alternative by using the import statement instead.

The main problem I am facing, though, is that I am getting a "Undefined is not an Object (evaluating 'this.state.input')" error when I type in a word in the TextInput and hitting enter.

My source code is as follows:

import React, { Component } from 'react';
import {
  AppRegistry,
  Image,
  StyleSheet,
  Text,
  TextInput,
  View
} from 'react-native';

var english_german = require('./english_german.json');

class Dictionary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      output: ''
    }

  }

  showMeaning() {
    // Use the ternary operator to check if the word
    // exists in the dictionary.
    var meaning = this.state.input in english_german ?
                    english_german[this.state.input] :
                    "Not Found";
    // Update the state
    this.setState({output: meaning});
  }

 render() {
  var layout =
   <View style = { styles.parent }>
    <Text>
     Type something in English:
    </Text>
        <TextInput
          onChangeText={(e) => this.setState({input: e})}
          text = { this.state.input }
          onSubmitEditing = { this.showMeaning }
        />
    <Text style = { styles.germanLabel }>
     It's German equivalent is:
    </Text>
    <Text style = { styles.germanWord }>
          { this.state.output }
    </Text>
   </View>
  ;
  return layout;
 }
}

const styles = StyleSheet.create({
 // For the container View
 parent: {
  padding: 16
 },
 // For the Text Label
 germanLabel: {
  marginTop: 20,
  fontWeight: 'bold'
 },
 // For the Text meaning
 germanWord: {
  marginTop: 15,
  fontSize: 30,
  fontStyle: 'italic'
 }
});

AppRegistry.registerComponent('Dictionary', () => Dictionary);

Body:
This is a binding problem, add this in your constructor:

this.showMeaning = this.showMeaning.bind(this);

This will ensure that this object in your showMeaning method refers to your Dictionary component. Alternatively, you could use arrow function in your showMeaning method like so:

showMeaning = () => { /* rest of code */ }

The arrow function preserves the context of this. So the use of bind isn't required.


问:
PHP - Session doesnt work on mobile
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?

My session_start code on index.php

```<code>session_start();
if (isset($_SESSION['username'])){
    session_id();
}
</code>```

Whole code for login.php file

```<code><?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $UserQuery = "SELECT username FROM `members` WHERE username='$username'";
        $userTestResult = mysqli_query($connection, $UserQuery);
        $usernameTEST = mysqli_num_rows($userTestResult);
        if($usernameTEST == 1){$usernameOK = true;}

        $PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
        $result = mysqli_query($connection,$PasswordQuery);
        $row = mysqli_fetch_row($result);

        if (password_verify($password, $row[0])){$passwordOK = true;}

        if($usernameOK == true && $passwordOK == true){
            $_SESSION['username'] = $username;
        }else{
            $error_message = "Incorrect login data";
        }
    }

    if (isset($_SESSION['username'])){
        header("Location: ../");
        exit;
    }else{?>
    <form class="login-form" method="POST">
        <?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>

        <span class="placeholder">username</span>
        <input type="text" name="username" placeholder="username" required>

        <span class="placeholder">password</span>
        <input type="password" name="password" id="inputPassword" placeholder="password" required>

        <button type="submit">Login</button>
        <a class="form-link" href="register.php">Register</a>
    </form>

<?php } ?>
</code>```

答:
Remove  session_start(); in index.php
and Add this in your config.php</p>

```<code>if (session_status() == PHP_SESSION_NONE)
{
    session_start();
}
</code>```

Title: PHP - Session doesnt work on mobile

Body:
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?

My session_start code on index.php

session_start();
if (isset($_SESSION['username'])){
    session_id();
}

Whole code for login.php file

<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $UserQuery = "SELECT username FROM `members` WHERE username='$username'";
        $userTestResult = mysqli_query($connection, $UserQuery);
        $usernameTEST = mysqli_num_rows($userTestResult);
        if($usernameTEST == 1){$usernameOK = true;}

        $PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
        $result = mysqli_query($connection,$PasswordQuery);
        $row = mysqli_fetch_row($result);

        if (password_verify($password, $row[0])){$passwordOK = true;}

        if($usernameOK == true && $passwordOK == true){
            $_SESSION['username'] = $username;
        }else{
            $error_message = "Incorrect login data";
        }
    }

    if (isset($_SESSION['username'])){
        header("Location: ../");
        exit;
    }else{?>
    <form class="login-form" method="POST">
        <?php if(isset($error_message)){ ?>
 <?php echo $error_message; ?>
<?php } ?>

        username
        <input type="text" name="username" placeholder="username" required>

        password
        <input type="password" name="password" id="inputPassword" placeholder="password" required>

        <button type="submit">Login</button>
        Register
    </form>

<?php } ?>

Body:
Remove  session_start(); in index.php
and Add this in your config.php

if (session_status() == PHP_SESSION_NONE)
{
    session_start();
}


问:
Django (grappelli): how add my own css to all the pages or how to extend admin's base.html?
In Django grappelli, how can I add my own css files to all the admin pages? Or is there a way to extend admin's base.html template?

答:
The admin 'base.html' template can be extended by making an admin directory inside the main app folder. Inside the admin directory create a new file named base.html. Copy these lines in new files.

```<code>{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
    {{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>

{% endblock %}
{% block stylesheets %}

    {{ block.super }}
{% endblock %}
</code>```

Here, I have overridden my javascript using an new script.

Body:
The admin 'base.html' template can be extended by making an admin directory inside the main app folder. Inside the admin directory create a new file named base.html. Copy these lines in new files.

{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
    {{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>

{% endblock %}
{% block stylesheets %}

    {{ block.super }}
{% endblock %}

Here, I have overridden my javascript using an new script.


问:
How to create nested ngFor loops for dynamically changing object child length in Angular?
I want to show a file tree in my Angular app. Of course a file tree can have multiple children in multiple levels.

Here is my example JSON object:

```<code>"root": {
    "element": {
        "displayName": "testFolder",
        "path": "testFolder/",
        "parent": ""
    },
    "children": [{
        "element": {
            "displayName": "folder1",
            "path": "testFolder/folder1/",
            "parent": "testFolder/"
        },
        "children": []
    }, {
        "element": {
            "displayName": "sub_folder",
            "path": "testFolder/sub_folder/",
            "parent": "testFolder/"
        },
        "children": [{
            "element": {
                "displayName": "testDir3",
                "path": "testFolder/sub_folder/testDir3/",
                "parent": "testFolder/sub_folder/"
            },
            "children": []
        }]
    }]
}
</code>```

The children property can be arbitrarily nested. How should I handle this?

答:
As far as nested for ngfor is concerned, you can use something like this:

```<code><template ngFor let-outer [ngForOf]="OuterArray" let-uterIndex="index">
         <template ngFor let-inner [ngForOf]="InnerArray" let-innerIndex="index">
         </template>
    </template>
</code>```

and for traversing the entire file tree use it recursively.

Body:
I want to show a file tree in my Angular app. Of course a file tree can have multiple children in multiple levels.

Here is my example JSON object:

"root": {
    "element": {
        "displayName": "testFolder",
        "path": "testFolder/",
        "parent": ""
    },
    "children": [{
        "element": {
            "displayName": "folder1",
            "path": "testFolder/folder1/",
            "parent": "testFolder/"
        },
        "children": []
    }, {
        "element": {
            "displayName": "sub_folder",
            "path": "testFolder/sub_folder/",
            "parent": "testFolder/"
        },
        "children": [{
            "element": {
                "displayName": "testDir3",
                "path": "testFolder/sub_folder/testDir3/",
                "parent": "testFolder/sub_folder/"
            },
            "children": []
        }]
    }]
}

The children property can be arbitrarily nested. How should I handle this?

Body:
As far as nested for ngfor is concerned, you can use something like this:

<template ngFor let-outer [ngForOf]="OuterArray" let-uterIndex="index">
         <template ngFor let-inner [ngForOf]="InnerArray" let-innerIndex="index">
         </template>
    </template>

and for traversing the entire file tree use it recursively.


问:
Need a way around this JSON Null exception
I fire a query and the result comes in JSON.I set it using setters.here is my Dataclass:

```<code>private String userstory;
private String task;
private int actual;
private int estimate;
private String ref;
private String uid;
private String tid;
--setters--
</code>```

Here is my main class:

```<code>for(JsonElement result : taskresponse.getResults())
    {
        JsonObject results = result.getAsJsonObject();
        MyData myData = new MyData(results.get("WorkProduct").getAsJsonObject().get("Name").getAsString(),results.get("Name").getAsString(),
        (int) Double.parseDouble(results.get("Actuals").getAsString()),
        (int) Double.parseDouble(results.get("Estimate").getAsString()),
        results.get("_ref").getAsString(),
        results.get("WorkProduct").getAsJsonObject().get("FormattedID").getAsString(),results.get("FormattedID").getAsString());
        data_list.add(myData);
    }
</code>```

When I get value int in fields "Actuals" and "Estimate" it is working well. But sometimes I get values null as the result from query. Thus I get JSONNULLEXCEPTION.
How should i handle this exception.I ultimately want the fields to be set 0 when query returns null.
Thanks

答:
You could use a mod statement like this where if the value is not null it will print the JSON response otherwise return 0</p>

```<code>Double.parseDouble(results.get("Estimate") == null ? 0 : results.get("Estimates").getAsString(),
</code>```

Body:
I fire a query and the result comes in JSON.I set it using setters.here is my Dataclass:

private String userstory;
private String task;
private int actual;
private int estimate;
private String ref;
private String uid;
private String tid;
--setters--

Here is my main class:

for(JsonElement result : taskresponse.getResults())
    {
        JsonObject results = result.getAsJsonObject();
        MyData myData = new MyData(results.get("WorkProduct").getAsJsonObject().get("Name").getAsString(),results.get("Name").getAsString(),
        (int) Double.parseDouble(results.get("Actuals").getAsString()),
        (int) Double.parseDouble(results.get("Estimate").getAsString()),
        results.get("_ref").getAsString(),
        results.get("WorkProduct").getAsJsonObject().get("FormattedID").getAsString(),results.get("FormattedID").getAsString());
        data_list.add(myData);
    }

When I get value int in fields "Actuals" and "Estimate" it is working well. But sometimes I get values null as the result from query. Thus I get JSONNULLEXCEPTION.
How should i handle this exception.I ultimately want the fields to be set 0 when query returns null.
Thanks

Body:
You could use a mod statement like this where if the value is not null it will print the JSON response otherwise return 0

Double.parseDouble(results.get("Estimate") == null ? 0 : results.get("Estimates").getAsString(),


答:
You have to loop over the ObjectResult<T> or use ObjectResult<T>.ElementAt() to retrieve individual elements. Then you can access the int values:

```<code>ObjectResult<Nullable<int>> queryResult = query.Execute(...);

foreach (Nullable<int> result in queryResult)
   Console.WriteLine("{0}", result.Value);
</code>```

You can check if a value is available using ObjectResult<T>.HasValue

Title: convertion of ObjectResult<Nullable<int>> type to int

Body:
Stored proc return as ObjectResult<Nullable<int>> using Entity frame work and want to convert this to int type
or how to check this value with another integer value

Body:
You have to loop over the ObjectResult<T> or use ObjectResult<T>.ElementAt() to retrieve individual elements. Then you can access the int values:

ObjectResult<Nullable<int>> queryResult = query.Execute(...);

foreach (Nullable<int> result in queryResult)
   Console.WriteLine("{0}", result.Value);

You can check if a value is available using ObjectResult<T>.HasValue


问:
Defined but have not been rendered for the layout page in MVC
I get this error:

```<code>The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts".
</code>```

With the following code:

Create.cshtml

```<code>@model BabyStoreII.Models.Category

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Category</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</code>```

_Layout.cshtml

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Modern Business - @ViewBag.Title</title>

    <!-- Bootstrap -->
    <link href="@Url.Content("/css/bootstrap.css")" rel="stylesheet">
    <link href="@Url.Content("/css/modern-business.css")" rel="stylesheet">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Shop by Category", "Index", "Categories")</li>
                    <li>@Html.ActionLink("View all our Products", "Index", "Products")</li>
                </ul>
                @using (Html.BeginForm("Index", "Products", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
                {
                    <div class="form-group">
                        @Html.TextBox("Search", null, new { @class = "form-control", @placeholder = "Search Products" })
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                }
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="@Url.Content("/js/bootstrap.js")"></script>
    <script src="@Url.Content("/js/modern-business.js")"></script>
</body>
</html>
</code>```

And my client side validation does not work. It only works when I send the form to server but when I just lose focus an input box, the validation does not kick in. Below is my Model Validation:

Category.cs

```<code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BabyStoreII.Models
{
    public class Category
    {
        public int ID { get; set; }
        [Required(ErrorMessage = "The Category name cannot be blank.")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Please enter a category name between 3 and 50 characters in length.")]
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Please enter a category beginning with a capital letter and made up of letters and spaces only.")]
        [Display(Name="Category Name")]
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }
}
</code>```

Your help is greatly appreciated.

答:
Replace your create.cshtml with below code </p>

```<code>    @model BabyStoreII.Models.Category

    @{
        ViewBag.Title = "Create";
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
    }

    <h2>Create</h2>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Category</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
</code>```

Body:
I get this error:

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts".

With the following code:

Create.cshtml

@model BabyStoreII.Models.Category

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Category

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

_Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Modern Business - @ViewBag.Title</title>

    <link href="@Url.Content("/css/bootstrap.css")" rel="stylesheet">
    <link href="@Url.Content("/css/modern-business.css")" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Shop by Category", "Index", "Categories")

@Html.ActionLink("View all our Products", "Index", "Products")

                @using (Html.BeginForm("Index", "Products", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
                {

                        @Html.TextBox("Search", null, new { @class = "form-control", @placeholder = "Search Products" })

                    <button type="submit" class="btn btn-default">Submit</button>
                }
                @Html.Partial("_LoginPartial")

        @RenderBody()

© @DateTime.Now.Year - My ASP.NET Application

And my client side validation does not work. It only works when I send the form to server but when I just lose focus an input box, the validation does not kick in. Below is my Model Validation:

Category.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BabyStoreII.Models
{
    public class Category
    {
        public int ID { get; set; }
        [Required(ErrorMessage = "The Category name cannot be blank.")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Please enter a category name between 3 and 50 characters in length.")]
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Please enter a category beginning with a capital letter and made up of letters and spaces only.")]
        [Display(Name="Category Name")]
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }
}

Your help is greatly appreciated.

Body:
Replace your create.cshtml with below code

    @model BabyStoreII.Models.Category

    @{
        ViewBag.Title = "Create";
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
    }

    <h2>Create</h2>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Category</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }


问:
How to recode 0 in a column to the median of the column
Hi I have a column in a dataframe in R which consist of 0

```<code>Sample -
mdfam0
25870
28670
21345
85100
0
</code>```

Its right skewed, and I want it to be replaced with the median value of the column.

I am learning to do Data Cleaning with R. Any help would be great.

答:
```<code>Sample = data.frame("mdfam0" = c(25870, 28670, 21345, 85100, 0))
Sample %>%
  dplyr::mutate(mdfam0 = ifelse(mdfam0 == 0, NA, mdfam0),
                mdfam0 = ifelse(is.na(mdfam0), median(mdfam0, na.rm = TRUE), mdfam0))
</code>```

Body:
Hi I have a column in a dataframe in R which consist of 0

Sample -
mdfam0
25870
28670
21345
85100
0

Its right skewed, and I want it to be replaced with the median value of the column.

I am learning to do Data Cleaning with R. Any help would be great.


问:
how to create a service in python in windows?
I want to run a service in windows which will keep running in background and will run a cron with specific time.

how i can do that in windows using python?

答:
Make sure win32 api is installed. Basically, you subclass the BasicNTService. The win32 package docs has some more information. I also have a working example in some code I wrote that does this.
WindowsServer.py that also mixes in Pyro for a Python remote control agent.</p>


问:
How to delete section of UITableView on click of view in swift3
I want to remove a table cell on click of view which is on cell in swift3.

Following function is called on click of View and remove method is used to delete table section.But this solution is not working.

```<code>func remove(sender: UITapGestureRecognizer)
        {
            let indexView = sender.view
            let index = indexView?.tag

            self.removeAddresses(position: index!)
        }

    func remove(position: Int)
    {
        tableView.deleteSections(IndexSet(index: position,with. automatic))
        tableView.reloadData()
    }
</code>```

答:
Try this :</p>

```<code>func remove(position: Int)
    {
        yourDataSourceArray?.removeAtIndex(position)

        tableView.deleteSections(IndexSet(index: position,with. automatic))
        tableView.reloadData()
    }
</code>```

Body:
I want to remove a table cell on click of view which is on cell in swift3.

Following function is called on click of View and remove method is used to delete table section.But this solution is not working.

func remove(sender: UITapGestureRecognizer)
        {
            let indexView = sender.view
            let index = indexView?.tag

            self.removeAddresses(position: index!)
        }

    func remove(position: Int)
    {
        tableView.deleteSections(IndexSet(index: position,with. automatic))
        tableView.reloadData()
    }

Body:
Try this :

func remove(position: Int)
    {
        yourDataSourceArray?.removeAtIndex(position)

        tableView.deleteSections(IndexSet(index: position,with. automatic))
        tableView.reloadData()
    }


答:
You need to call Layout on your page, Please change your Create.cshtml code :

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Create";
}
```

Cheers !!

Title: Defined but have not been rendered for the layout page in MVC

Body:
You need to call Layout on your page, Please change your Create.cshtml code :

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Create";
}

Cheers !!


问:
Difference between same value in array using only one loop javascript
How to find the difference between the min and max indexes of the same value in an array with one loop with complexity exactly O(N)?

For example, given array A:

```<code>[4, 6, 2, 2, 6, 6, 1];
</code>```

the function returns 4.

答:
Try with Array#filter .filter the array without max and min value .Then find max value in filtered array .... its spread syntax

var data = [4, 6, 2, 2, 6, 6, 1];

function bet(data) {
  return Math.max(...data.filter(a => a != Math.max(...data) && a != Math.min(...data)))
}

console.log(bet(data))```

Body:
How to find the difference between the min and max indexes of the same value in an array with one loop with complexity exactly O(N)?

For example, given array A:

[4, 6, 2, 2, 6, 6, 1];

the function returns 4.


问:
Move ImageView from one layout to another layout within same activity using animation
I want to translate this imageview from relative_bottom to relative_top layout through animation. I want to put that image in center of relative_top layout. this is my splashscreen so i want this to transit automatically.

here is hiiii as imageview.I want to animate this automatically:

I want to place this image here with animation

I dont know how to set exact position.

What should I add to get such output? I have tried many ways but couldn't get a solution.

Sample xml file:

```<code><LinearLayout android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:id="@+id/relative_top"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:id="@+id/bottom"
            android:layout_gravity="center_horizontal"
            android:gravity="top">
            <ProgressBar>
               ....
               </Progressbar>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/relative_bottom"
                android:layout_alignTop="@id/progressBar"
                android:layout_centerInParent="true"
                >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview"
                    android:src="@drawable/logo"
                    android:scaleType="fitCenter"
                    />

            </RelativeLayout>

        </RelativeLayout>

</LinearLayout>
</code>```

答:
Try below animation

```<code>//0,0 is the  current coordinates
Animation an = new TranslateAnimation(fromX,fromY,toX,toY);
an.setFillAfter(true);// to keep the state after animation is finished
imageView.startAnimation(an);// to start animation obviously
</code>```

Get screen height and use it to set "toY" parameter to make it move from bottom to top.

Body:
I want to translate this imageview from relative_bottom to relative_top layout through animation. I want to put that image in center of relative_top layout. this is my splashscreen so i want this to transit automatically.

here is hiiii as imageview.I want to animate this automatically:

I want to place this image here with animation

I dont know how to set exact position.

What should I add to get such output? I have tried many ways but couldn't get a solution.

Sample xml file:

<LinearLayout android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:id="@+id/relative_top"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:id="@+id/bottom"
            android:layout_gravity="center_horizontal"
            android:gravity="top">
            <ProgressBar>
               ....
               </Progressbar>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/relative_bottom"
                android:layout_alignTop="@id/progressBar"
                android:layout_centerInParent="true"
                >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview"
                    android:src="@drawable/logo"
                    android:scaleType="fitCenter"
                    />

            </RelativeLayout>

        </RelativeLayout>

</LinearLayout>

Body:
Try below animation

//0,0 is the  current coordinates
Animation an = new TranslateAnimation(fromX,fromY,toX,toY);
an.setFillAfter(true);// to keep the state after animation is finished
imageView.startAnimation(an);// to start animation obviously

Get screen height and use it to set "toY" parameter to make it move from bottom to top.


问:
getting an NSException not sure why
so my app is crashing on launch and i am getting this in the console when i run and debug:

```<code>[Session started at 2010-12-08 20:46:52 -0500.]
2010-12-08 20:46:53.921 WotT-Codename_Savior[64325:207] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<WotT_Codename_SaviorViewController 0x4b0b380> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key CreateCharacter.'
2010-12-08 20:46:53.924 WotT-Codename_Savior[64325:207] Stack: (
    42190928,
    43348780,
    42190817,
    209120,
    208670,
    5050527,
    41679989,
    5044964,
    5053145,
    3542950,
    3534896,
    3534602,
    10353,
    2918724,
    2922831,
    2948414,
    2929911,
    2961880,
    51183996,
    41470108,
    41466024,
    2920993,
    2954098,
    10244,
    10098
)
terminate called after throwing an instance of 'NSException'
</code>```

i'm kinda new to obj-c and cocoa touch so i don't really know why it's throwing the exception can anyone help decipher this for me?also if you need more code just let me know...i wasn't sure what to post here

答: You should define CreateCharacter property in your view controller and you should be good.

Title: getting an NSException not sure why

Body:
so my app is crashing on launch and i am getting this in the console when i run and debug:

[Session started at 2010-12-08 20:46:52 -0500.]
2010-12-08 20:46:53.921 WotT-Codename_Savior[64325:207] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<WotT_Codename_SaviorViewController 0x4b0b380> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key CreateCharacter.'
2010-12-08 20:46:53.924 WotT-Codename_Savior[64325:207] Stack: (
    42190928,
    43348780,
    42190817,
    209120,
    208670,
    5050527,
    41679989,
    5044964,
    5053145,
    3542950,
    3534896,
    3534602,
    10353,
    2918724,
    2922831,
    2948414,
    2929911,
    2961880,
    51183996,
    41470108,
    41466024,
    2920993,
    2954098,
    10244,
    10098
)
terminate called after throwing an instance of 'NSException'

i'm kinda new to obj-c and cocoa touch so i don't really know why it's throwing the exception can anyone help decipher this for me?also if you need more code just let me know...i wasn't sure what to post here


问:
Pros and Cons of multiple region databases
Can someone tell me pros and cons of using multiple region databases? I am working on an application which would be mostly used in one particular region but may be rarely used in different regions as well. So, I am thinking that should I make my application multi-region or not? That's why asking about pros and cons.</p>

答: With "regions", I'm assuming you're referring to the requirement of your database to support multiple language/locale formats etc. If that's the question than I strongly recommend the use of NoSQL databases as they offer flexible schema of the objects which you can use to store data in different languages/locale settings. etc.</p>


问:
SonarQube: Invoke method(s) only conditionally
The following part of code raises a major bug at SonarQube :
"Invoke method(s) only conditionally."

How am I supposed to fix this?

```<code>if(us != null){
    logger.info("Log this: {}", us.toString());
}
</code>```

答:
As stated at the comments of the question, another working answer is:</p>

```<code>if(logger.isInfoEnabled() && us != null){
    logger.info("Log this: {}", us.toString());
}
</code>```

Body:
The following part of code raises a major bug at SonarQube :
"Invoke method(s) only conditionally."

How am I supposed to fix this?

if(us != null){
    logger.info("Log this: {}", us.toString());
}

Body:
As stated at the comments of the question, another working answer is:

if(logger.isInfoEnabled() && us != null){
    logger.info("Log this: {}", us.toString());
}


问:
AttributeError: 'module' object has no attribute 'to_numeric' in Pandas
The following code is throwing AttributeError on a server where the version of Pandas is 0.16.2 whereas it runs fine on my machine where version is 0.20.

```<code>df = pandas.read_csv('filename', header = None, error_bad_lines = False, warn_bad_lines =True,quoting=csv.QUOTE_NONE)

df = df.drop(df[pandas.to_numeric(df[599], errors='coerce').isnull()].index)
</code>```

The error message is the following:

```<code>Traceback (most recent call last):
  File "train_model.py", line 11, in <module>
    df = df.drop(df[pandas.to_numeric(df[599], errors='coerce').isnull()].index)
AttributeError: 'module' object has no attribute 'to_numeric'
</code>```

Is there a way to avoid this error in 0.16.2 version? The update to the server is not possible.

答:
Pandas.to_numeric is only available for version 0.17 and higher. You can use DataFrame.convert_objects with convert_numeric=True argument instead, errors are automatically coerced.

```<code>df = df.drop(df[df[599].convert_objects(convert_numeric=True).isnull()].index)
</code>```

Body:
The following code is throwing AttributeError on a server where the version of Pandas is 0.16.2 whereas it runs fine on my machine where version is 0.20.

df = pandas.read_csv('filename', header = None, error_bad_lines = False, warn_bad_lines =True,quoting=csv.QUOTE_NONE)

df = df.drop(df[pandas.to_numeric(df[599], errors='coerce').isnull()].index)

The error message is the following:

Traceback (most recent call last):
  File "train_model.py", line 11, in <module>
    df = df.drop(df[pandas.to_numeric(df[599], errors='coerce').isnull()].index)
AttributeError: 'module' object has no attribute 'to_numeric'

Is there a way to avoid this error in 0.16.2 version? The update to the server is not possible.

Body:
Pandas.to_numeric is only available for version 0.17 and higher. You can use DataFrame.convert_objects with convert_numeric=True argument instead, errors are automatically coerced.

df = df.drop(df[df[599].convert_objects(convert_numeric=True).isnull()].index)