问:
don't work edit spring mvc crud jdbctemplate
this is the FabricanteEditController:

```<code>package Controller;

import Modelo.Conectar;
import Modelo.Fabricante;
import Modelo.FabricanteValidar;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
*
* @author x2010s
*/

@Controller
@RequestMapping("fabricanteedit.htm")
public class FabricanteEditController {

FabricanteValidar fabricanteValidar;
private JdbcTemplate jdbcTemplate;

public FabricanteEditController()
{
   this.fabricanteValidar=new FabricanteValidar();
   Conectar con=new Conectar();
   this.jdbcTemplate=new JdbcTemplate(con.conectar() );
}

@RequestMapping(method=RequestMethod.GET)
public ModelAndView form(HttpServletRequest request)
{
    ModelAndView mav=new ModelAndView();
    int id=Integer.parseInt(request.getParameter("id"));
    Fabricante datos=this.selectFabricante(id);
    mav.setViewName("fabricanteedit");
    mav.addObject("fabricante",new  Fabricante(id,datos.getNombre(),datos.getDireccion(),datos.getTelefono(),datos.getTipo()));
    return mav;
}

 @RequestMapping(method=RequestMethod.POST)
 public ModelAndView form
    (
            @ModelAttribute("fabricante") Fabricante f,
            BindingResult result,
            SessionStatus status,
            HttpServletRequest request
    )
{
 this.fabricanteValidar.validate(f, result);
    if(result.hasErrors())
    {
         ModelAndView mav=new ModelAndView();
        int id=Integer.parseInt(request.getParameter("id"));
        Fabricante datos=this.selectFabricante(id);
        mav.setViewName("fabricanteedit");
        mav.addObject("fabricante",new Fabricante(id,datos.getNombre(),datos.getDireccion(),datos.getTelefono(),datos.getTipo()));
        return mav;
    }else
    {
        int id=Integer.parseInt(request.getParameter("id"));
    this.jdbcTemplate.update(
                "update fabricante "
            + "set nombre=?,"
            + "direccion=?,"
            + "telefono=? "
            + "tipo=? "
            + "where "
            + "id=? ",
     f.getNombre(),f.getDireccion(),f.getTelefono(),f.getTipo(),id);
     return new ModelAndView("redirect:/fabricante.htm");
    }

}
    public Fabricante selectFabricante(int id)
{
    final Fabricante maker = new Fabricante();
    String quer = "SELECT * FROM fabricante WHERE id="+id;
    return (Fabricante) jdbcTemplate.query
    (
            quer, new ResultSetExtractor<Fabricante>()
        {
            public Fabricante extractData(ResultSet rs) throws SQLException, DataAccessException {
                if (rs.next()) {
                    maker.setNombre(rs.getString("nombre"));
                    maker.setDireccion(rs.getString("direccion"));
                    maker.setTelefono(rs.getString("telefono"));
                    maker.setTipo(rs.getString("tipo"));

                }
                return maker;
            }

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

this is the view fabricanteedit.jsp

```<code><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"   %>
<%@taglib  prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Editar Fabricante</title>
    <link href="css/estilos.css" rel="stylesheet">
    <link href="css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
    <div class="container">
        <ol class="breadcrumb">
            <li><a href="<c:url value="/fabricante.htm" />">Listado de  fabricante</a></li>
            <li class="active">Editar</li>
        </ol>
        <div class="panel panel-primary">
            <div class="panel-heading">Editar</div>
            <div class="panel-body">

                    <form:form method="post" commandName="fabricante">
                        <h1>Complete el formulario</h1>

                        <form:errors path="*" element="div"  cssClass="alert alert-danger" />

                       <p>
                            <form:label path="nombre">Nombre:  </form:label>
                            <form:input path="nombre" cssClass="form-control" />

                        </p>

                        <p>
                            <form:label  path="direccion">Direccion</form:label>
                            <form:input path="direccion" cssClass="form-control" />
                        </p>

                        <p>
                            <form:label path="telefono">Telefono</form:label>
                            <form:input path="telefono" cssClass="form-control" />
                        </p>

                        <p>
                            <form:label path="tipo">Tipo</form:label>
                            <form:input path="tipo" cssClass="form-control" />
                        </p>

                        <hr />
                        <input type="submit" value="Enviar" class="btn btn-danger" />
                    </form:form>
              </div>
          </div>
      </div>
  </body>
</code>```

my database is derby.

when trying to edit a manufacturer, the following error occurs:

HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [update fabricante set nombre=?,direccion=?,telefono=?, tipo=?, where id=? ]; nested exception is java.sql.SQLSyntaxErrorException: Error de sintaxis: Encountered "where" at line 1, column 64.

root cause

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [update fabricante set nombre=?,direccion=?,telefono=?, tipo=?, where id=? ]; nested exception is java.sql.SQLSyntaxErrorException: Error de sintaxis: Encountered "where" at line 1, column 64.

root cause

java.sql.SQLSyntaxErrorException: Error de sintaxis: Encountered "where" at line 1, column 64.

root cause

ERROR 42X01: Error de sintaxis: Encountered "where" at line 1, column 64.

答:
In your code in your question, you show:

```<code>    this.jdbcTemplate.update(
            "update fabricante "
        + "set nombre=?,"
        + "direccion=?,"
        + "telefono=? "
        + "tipo=? "
        + "where "
        + "id=? ",
</code>```

In the error message that you quote in your question, you show:

```<code>bad SQL grammar [update fabricante set nombre=?,direccion=?,telefono=?, tipo=?, where id=? ];
</code>```

Both of these look wrong to me.

In the code that you show, you are missing a comma after "telefono=? ".

In the error message that you show, you have an extra comma after tipo=?,

It is very confusing that these two things do not match up.

But I believe both are incorrect. You should have a comma in between each column=? expression, and no comma after the last column before the where.

I believe that if you very closely inspect your program, looking at the placement of the commas in your update statement, you will find the problem.

Body:
this is the FabricanteEditController:

package Controller;

import Modelo.Conectar;
import Modelo.Fabricante;
import Modelo.FabricanteValidar;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
*
* @author x2010s
*/

@Controller
@RequestMapping("fabricanteedit.htm")
public class FabricanteEditController {

FabricanteValidar fabricanteValidar;
private JdbcTemplate jdbcTemplate;

public FabricanteEditController()
{
   this.fabricanteValidar=new FabricanteValidar();
   Conectar con=new Conectar();
   this.jdbcTemplate=new JdbcTemplate(con.conectar() );
}

@RequestMapping(method=RequestMethod.GET)
public ModelAndView form(HttpServletRequest request)
{
    ModelAndView mav=new ModelAndView();
    int id=Integer.parseInt(request.getParameter("id"));
    Fabricante datos=this.selectFabricante(id);
    mav.setViewName("fabricanteedit");
    mav.addObject("fabricante",new  Fabricante(id,datos.getNombre(),datos.getDireccion(),datos.getTelefono(),datos.getTipo()));
    return mav;
}

 @RequestMapping(method=RequestMethod.POST)
 public ModelAndView form
    (
            @ModelAttribute("fabricante") Fabricante f,
            BindingResult result,
            SessionStatus status,
            HttpServletRequest request
    )
{
 this.fabricanteValidar.validate(f, result);
    if(result.hasErrors())
    {
         ModelAndView mav=new ModelAndView();
        int id=Integer.parseInt(request.getParameter("id"));
        Fabricante datos=this.selectFabricante(id);
        mav.setViewName("fabricanteedit");
        mav.addObject("fabricante",new Fabricante(id,datos.getNombre(),datos.getDireccion(),datos.getTelefono(),datos.getTipo()));
        return mav;
    }else
    {
        int id=Integer.parseInt(request.getParameter("id"));
    this.jdbcTemplate.update(
                "update fabricante "
            + "set nombre=?,"
            + "direccion=?,"
            + "telefono=? "
            + "tipo=? "
            + "where "
            + "id=? ",
     f.getNombre(),f.getDireccion(),f.getTelefono(),f.getTipo(),id);
     return new ModelAndView("redirect:/fabricante.htm");
    }

}
    public Fabricante selectFabricante(int id)
{
    final Fabricante maker = new Fabricante();
    String quer = "SELECT * FROM fabricante WHERE id="+id;
    return (Fabricante) jdbcTemplate.query
    (
            quer, new ResultSetExtractor<Fabricante>()
        {
            public Fabricante extractData(ResultSet rs) throws SQLException, DataAccessException {
                if (rs.next()) {
                    maker.setNombre(rs.getString("nombre"));
                    maker.setDireccion(rs.getString("direccion"));
                    maker.setTelefono(rs.getString("telefono"));
                    maker.setTipo(rs.getString("tipo"));

                }
                return maker;
            }

        }
    );
    }
}

this is the view fabricanteedit.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"   %>
<%@taglib  prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Editar Fabricante</title>
    <link href="css/estilos.css" rel="stylesheet">
    <link href="css/bootstrap.min.css" rel="stylesheet" >

<a href="<c:url value="/fabricante.htm" />">Listado de  fabricante

Editar

Editar

                    <form:form method="post" commandName="fabricante">

Complete el formulario

                        <form:errors path="*" element="div"  cssClass="alert alert-danger" />

                            <form:label path="nombre">Nombre:  </form:label>
                            <form:input path="nombre" cssClass="form-control" />

                            <form:label  path="direccion">Direccion</form:label>
                            <form:input path="direccion" cssClass="form-control" />

                            <form:label path="telefono">Telefono</form:label>
                            <form:input path="telefono" cssClass="form-control" />

                            <form:label path="tipo">Tipo</form:label>
                            <form:input path="tipo" cssClass="form-control" />

                        <input type="submit" value="Enviar" class="btn btn-danger" />
                    </form:form>

my database is derby.

when trying to edit a manufacturer, the following error occurs:

HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [update fabricante set nombre=?,direccion=?,telefono=?, tipo=?, where id=? ]; nested exception is java.sql.SQLSyntaxErrorException: Error de sintaxis: Encountered "where" at line 1, column 64.

root cause

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [update fabricante set nombre=?,direccion=?,telefono=?, tipo=?, where id=? ]; nested exception is java.sql.SQLSyntaxErrorException: Error de sintaxis: Encountered "where" at line 1, column 64.

root cause

java.sql.SQLSyntaxErrorException: Error de sintaxis: Encountered "where" at line 1, column 64.

root cause

ERROR 42X01: Error de sintaxis: Encountered "where" at line 1, column 64.

Body:
In your code in your question, you show:

    this.jdbcTemplate.update(
            "update fabricante "
        + "set nombre=?,"
        + "direccion=?,"
        + "telefono=? "
        + "tipo=? "
        + "where "
        + "id=? ",

In the error message that you quote in your question, you show:

bad SQL grammar [update fabricante set nombre=?,direccion=?,telefono=?, tipo=?, where id=? ];

Both of these look wrong to me.

In the code that you show, you are missing a comma after "telefono=? ".

In the error message that you show, you have an extra comma after tipo=?,

It is very confusing that these two things do not match up.

But I believe both are incorrect. You should have a comma in between each column=? expression, and no comma after the last column before the where.

I believe that if you very closely inspect your program, looking at the placement of the commas in your update statement, you will find the problem.


来源: stackexchange

问:
AWS DMS: Data not getting replicated to AWS Redshift
My source DB is AWS RDS and my target table is AWS Redshift. The data is loaded successfully but after that changes are not pushed to the target DB and there are no exceptions.

Configuration:
Migration type: Full Load, Ongoing Replication
Source DB: AWS RDS MariaDB
Target DB: AWS Redshit

Issue: After first upload there are no inserts, updates, deletes to the target DB.

Update: I restarted the DMS task, it duplicated the database records on target DB but now it is updating the target DB.
I drop and reloaded one table and it duplicated the record.

答:
I guess the problem was, I updated the Redshift Database name and that somehow created problems with my AWS DMS tasks.

Creating a fresh task worked for me.

ContentLicense: CC BY-SA 3.0


问:
Trying to pass multiple values from table view to another view controller
I want to pass the whole User info, I have a User class. I want to pass the username,name ,uid, image to another view controller.    </p>

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NewChatTableViewCell

        let user = usersarray[indexPath.row]
        let ColorView = UIView()
        ColorView.backgroundColor = UIColor(red: 0.05, green: 0.15, blue: 0.28, alpha: 0.7)
        cell.selectedBackgroundView = ColorView
        cell.backgroundColor = UIColor.clear
        cell.backgroundView?.backgroundColor = UIColor.clear
        cell.firstname.text = user.firstname! + " " + user.lastname!
        cell.username.text = "@" + user.username!
        cell.userimage?.layer.masksToBounds = true
        cell.userimage.layer.cornerRadius = 20
        cell.userimage.clipsToBounds = true
        if let profileimage = user.profilepic
        {cell.userimage.loadImageCache(urlString: profileimage)}
        return cell
    }

    func callmessage(){
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "message")
        self.present(controller, animated: true, completion: nil)
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let indexPath = tableView.indexPathForSelectedRow!
        callmessage(user: User!)
    }
</code>```

答: Subclass the UITableViewCell (create a new file of type UITableViewCell and call it something like UserTableViewCell. Add a property of type User (or whatever your user class is). On DidSelectRowAtIndexPath set the user property of the UIViewController equal to the User property of the UserTableViewCell, and then present the view controller.</p>

Body:
I want to pass the whole User info, I have a User class. I want to pass the username,name ,uid, image to another view controller.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NewChatTableViewCell

        let user = usersarray[indexPath.row]
        let ColorView = UIView()
        ColorView.backgroundColor = UIColor(red: 0.05, green: 0.15, blue: 0.28, alpha: 0.7)
        cell.selectedBackgroundView = ColorView
        cell.backgroundColor = UIColor.clear
        cell.backgroundView?.backgroundColor = UIColor.clear
        cell.firstname.text = user.firstname! + " " + user.lastname!
        cell.username.text = "@" + user.username!
        cell.userimage?.layer.masksToBounds = true
        cell.userimage.layer.cornerRadius = 20
        cell.userimage.clipsToBounds = true
        if let profileimage = user.profilepic
        {cell.userimage.loadImageCache(urlString: profileimage)}
        return cell
    }

    func callmessage(){
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "message")
        self.present(controller, animated: true, completion: nil)
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let indexPath = tableView.indexPathForSelectedRow!
        callmessage(user: User!)
    }


问:
Rails find records using an array of hashes
(Select Query by Pair of fields using an in clause)

I have an array of hashes that looks like this:

[ {product_id: 7629, group_id: 4}, {product_id: 8202, group_id: 3} ]

What I would like to return are all the records in the Items table that match the pair of fields in the array.

In SQL it would be retrieved like this:

```<code>SELECT *
FROM items
WHERE (product_id, group_id) IN (VALUES (7629,4), (8202,3))
</code>```

But I am having trouble doing this with a rails .where clause. Is this even possible?

答:
I can't think of any way to do this without resorting to SQL, even with Arel.

Since arrays can't be quoted, we have to do some silly stuff to still allow it to be sanitized. This isn't a great solution, but it is a working one.

```<code>your_hashes = [ {product_id: 7629, group_id: 4}, {product_id: 8202, group_id: 3} ]

# turn hashes into simple value array
conditions = your_hashes.map { |h| [ h[:product_id], h[:group_id] ] }
=> [[7629, 4], [8202, 3]]

# create a list of "(?)" values that will allow the conditions to be passed in
values = ("(?)," * conditions.length)[0..-2]
=> "(?),(?)"

# use it to look up the values
Model.where("(product_id, group_id) IN (VALUES #{values})", *conditions)

# this is the generated sql:
SELECT "models".* FROM "models" WHERE ((product_id, group_id) IN (VALUES (7629,4),(8202,3)))
</code>```

Body:
(Select Query by Pair of fields using an in clause)

I have an array of hashes that looks like this:

[ {product_id: 7629, group_id: 4}, {product_id: 8202, group_id: 3} ]

What I would like to return are all the records in the Items table that match the pair of fields in the array.

In SQL it would be retrieved like this:

SELECT *
FROM items
WHERE (product_id, group_id) IN (VALUES (7629,4), (8202,3))

But I am having trouble doing this with a rails .where clause. Is this even possible?

Body:
I can't think of any way to do this without resorting to SQL, even with Arel.

Since arrays can't be quoted, we have to do some silly stuff to still allow it to be sanitized. This isn't a great solution, but it is a working one.

your_hashes = [ {product_id: 7629, group_id: 4}, {product_id: 8202, group_id: 3} ]

# turn hashes into simple value array
conditions = your_hashes.map { |h| [ h[:product_id], h[:group_id] ] }
=> [[7629, 4], [8202, 3]]

# create a list of "(?)" values that will allow the conditions to be passed in
values = ("(?)," * conditions.length)[0..-2]
=> "(?),(?)"

# use it to look up the values
Model.where("(product_id, group_id) IN (VALUES #{values})", *conditions)

# this is the generated sql:
SELECT "models".* FROM "models" WHERE ((product_id, group_id) IN (VALUES (7629,4),(8202,3)))


问:
If a user inputs an invalid character how can I get my program to output a message to the user?
If the user enters the wrong character such as "E" or "A" in my program how can I output a message to the user? The line which I'm speaking about in my program is when the user has to choose to input one out of three characters P, M or D. However, if the user inputs another character which isn't listed I want the program to display a message.

As you can see if the user inputs "E" the program skips to the next step. However, I want the user to be notified and asked again to enter the correct value which is "P, M or D".

In order to do what I'm trying to achieve I believe I need to do an if statement so here what I have tried.

```<code>if((i = P,M,D) && (i < ?)) {
   System.out.println("ERROR, please input only P,M or D.");
}
</code>```

Screenshot of the program

JAVA CODE

```<code>String grade;
int yr2cred[] = new int[18];
char yr2grade[] = new char[18];
for (int i = 1; i <= 18; i++) {
    System.out.println("Please enter your grade for unit " + i +" "+(username) + ".");
    grade = userinput.next();
    yr2grade[i - 1] = grade.charAt(0);
    if (yr2grade[i - 1] == 'P' || yr2grade[i - 1] == 'p') {
        yr2cred[i - 1] = yr2cred[i - 1] + P;
    }
    if (yr2grade[i - 1] == 'M' || yr2grade[i - 1] == 'm') {
        yr2cred[i - 1] = yr2cred[i - 1] + M;
    }
    if (yr2grade[i - 1] == 'D' || yr2grade[i - 1] == 'd') {
        yr2cred[i - 1] = yr2cred[i - 1] + D;
    }
}
</code>```

答:
You can do this using a while loop within the for loop:

```<code>for (int i = 1; i <= 18; i++) {
    while (grade.equals("")) {
        System.out.println("Please enter your grade for unit " + i + " " + username + ".");
        grade = userinput.next().toLowerCase();
        yr2grade[i - 1] = grade.charAt(0);
        if (yr2grade[i - 1] == 'p') {
            yr2cred[i - 1] = yr2cred[i - 1] + P;
        } else if (yr2grade[i - 1] == 'm') {
            yr2cred[i - 1] = yr2cred[i - 1] + M;
        } else if (yr2grade[i - 1] == 'd') {
            yr2cred[i - 1] = yr2cred[i - 1] + D;
        } else {
            System.err.println("Invalid Grade Supplied! Try Again.\n");
            grade = "";
        }
    }
    grade = "";
}
</code>```

Body:
If the user enters the wrong character such as "E" or "A" in my program how can I output a message to the user? The line which I'm speaking about in my program is when the user has to choose to input one out of three characters P, M or D. However, if the user inputs another character which isn't listed I want the program to display a message.

As you can see if the user inputs "E" the program skips to the next step. However, I want the user to be notified and asked again to enter the correct value which is "P, M or D".

In order to do what I'm trying to achieve I believe I need to do an if statement so here what I have tried.

if((i = P,M,D) && (i < ?)) {
   System.out.println("ERROR, please input only P,M or D.");
}

Screenshot of the program

JAVA CODE

String grade;
int yr2cred[] = new int[18];
char yr2grade[] = new char[18];
for (int i = 1; i <= 18; i++) {
    System.out.println("Please enter your grade for unit " + i +" "+(username) + ".");
    grade = userinput.next();
    yr2grade[i - 1] = grade.charAt(0);
    if (yr2grade[i - 1] == 'P' || yr2grade[i - 1] == 'p') {
        yr2cred[i - 1] = yr2cred[i - 1] + P;
    }
    if (yr2grade[i - 1] == 'M' || yr2grade[i - 1] == 'm') {
        yr2cred[i - 1] = yr2cred[i - 1] + M;
    }
    if (yr2grade[i - 1] == 'D' || yr2grade[i - 1] == 'd') {
        yr2cred[i - 1] = yr2cred[i - 1] + D;
    }
}

Body:
You can do this using a while loop within the for loop:

for (int i = 1; i <= 18; i++) {
    while (grade.equals("")) {
        System.out.println("Please enter your grade for unit " + i + " " + username + ".");
        grade = userinput.next().toLowerCase();
        yr2grade[i - 1] = grade.charAt(0);
        if (yr2grade[i - 1] == 'p') {
            yr2cred[i - 1] = yr2cred[i - 1] + P;
        } else if (yr2grade[i - 1] == 'm') {
            yr2cred[i - 1] = yr2cred[i - 1] + M;
        } else if (yr2grade[i - 1] == 'd') {
            yr2cred[i - 1] = yr2cred[i - 1] + D;
        } else {
            System.err.println("Invalid Grade Supplied! Try Again.\n");
            grade = "";
        }
    }
    grade = "";
}


问:
Number of regex matches
I'm using the finditer function in the re module to match some things and everything is working.

Now I need to find out how many matches I've got. Is it possible without looping through the iterator twice? (one to find out the count and then the real iteration)

Some code:

```<code>imageMatches = re.finditer("<img src\=\"(?P<path>[-/\w\.]+)\"", response[2])
# <Here I need to get the number of matches>
for imageMatch in imageMatches:
    doStuff
</code>```

Everything works, I just need to get the number of matches before the loop.

答:
For those moments when you really want to avoid building lists:

import re
import operator
from functools import reduce
count = reduce(operator.add, (1 for _ in re.finditer(my_pattern, my_string)))
```

Sometimes you might need to operate on huge strings. This might help.

ContentLicense: CC BY-SA 4.0

Title: Number of regex matches

Body:
I'm using the finditer function in the re module to match some things and everything is working.

Now I need to find out how many matches I've got. Is it possible without looping through the iterator twice? (one to find out the count and then the real iteration)

Some code:

imageMatches = re.finditer("<img src\=\"(?P<path>[-/\w\.]+)\"", response[2])
# <Here I need to get the number of matches>
for imageMatch in imageMatches:
    doStuff

Everything works, I just need to get the number of matches before the loop.

Body:
For those moments when you really want to avoid building lists:

import re
import operator
from functools import reduce
count = reduce(operator.add, (1 for _ in re.finditer(my_pattern, my_string)))

Sometimes you might need to operate on huge strings. This might help.


问:
Need to cancel an actionscript command stop() and continue my project
I have an Actionscript on an invisible button in my Flash project and it is supposed to stop on a frame if it is clicked. This is the script on the button:

```<code>invisobutton.addEventListener(MouseEvent.CLICK,stopframe);
function stopframe(Event:MouseEvent):void{
stop();
}
</code>```

with invisobutton being the instance name of the button. It works if you click anywhere inside the invisible button the movie stops on that frame. My problem is that I do not know how to cancel the stop and continue where the movie paused. Is there a counter for the stop() command so that it can be like off and there was an on switch? I thought about using a second function for go to and play like this:

```<code>invisobutton.addEventListener(MouseEvent.MOUSE_OUT, restart);
                              function restart(Event:MouseEvent):void{
gotoAndPlay(*);
</code>```

but I am not sure how to know  what to put into the (*) so that it plays from right where it was stopped.

If someone could please advise me if there is a reverse command to stop() that can turn it off ans start again. I already tried play() but I got errors from Flash over it. I thought about start() but I had never heard of or seen such a command. Or if someone could tell me a way to correctly retrieve the frame number when the stop() command executes.

答:
Assuming that what you want is to use the same button to toggle between play and stop, you can use the following code:</p>

```<code>var lastFrame:int;
var isPlaying:Boolean = true;

invisobutton.addEventListener(MouseEvent.CLICK, toggleFrame);

function toggleFrame(Event:MouseEvent):void {
    if ( isPlaying ) {
        lastFrame = this.currentFrame;
        stop();
    } else {
        this.gotoAndPlay( lastFrame );
    }

    isPlaying = ! isPlaying;
}
</code>```

Body:
I have an Actionscript on an invisible button in my Flash project and it is supposed to stop on a frame if it is clicked. This is the script on the button:

invisobutton.addEventListener(MouseEvent.CLICK,stopframe);
function stopframe(Event:MouseEvent):void{
stop();
}

with invisobutton being the instance name of the button. It works if you click anywhere inside the invisible button the movie stops on that frame. My problem is that I do not know how to cancel the stop and continue where the movie paused. Is there a counter for the stop() command so that it can be like off and there was an on switch? I thought about using a second function for go to and play like this:

invisobutton.addEventListener(MouseEvent.MOUSE_OUT, restart);
                              function restart(Event:MouseEvent):void{
gotoAndPlay(*);

but I am not sure how to know  what to put into the (*) so that it plays from right where it was stopped.

If someone could please advise me if there is a reverse command to stop() that can turn it off ans start again. I already tried play() but I got errors from Flash over it. I thought about start() but I had never heard of or seen such a command. Or if someone could tell me a way to correctly retrieve the frame number when the stop() command executes.

Body:
Assuming that what you want is to use the same button to toggle between play and stop, you can use the following code:

var lastFrame:int;
var isPlaying:Boolean = true;

invisobutton.addEventListener(MouseEvent.CLICK, toggleFrame);

function toggleFrame(Event:MouseEvent):void {
    if ( isPlaying ) {
        lastFrame = this.currentFrame;
        stop();
    } else {
        this.gotoAndPlay( lastFrame );
    }

    isPlaying = ! isPlaying;
}

ContentLicense: CC BY-SA 2.5


问:
Using primary keys as index for active record reads, Rails
When I use users=User.where(...)
I can use users.find(id) to find by it's id

I want to use a hash such so that I can use users[id] as a means of searching, where the id becomes the index of the hash.

How do I do this?

I have tried:

```<code>users.to_a.map(&:serializable_hash)
users.map(&:attributes)
users.map { |r| r.attributes.symbolize_keys }
</code>```

None of these worked in turning the primary key into the index

答:
For the solution to your specific need

```<code>indexed_users = [] # holds users on index as id

users.each {|u| indexed_users[u.id] = u.attributes }
</code>```

Also converting id as index is not a good idea as the array size may go out of control if id become bigger like thousands or so and ids are not sequential. like
users = [<id: 1>, <id:200>] will result in array with size of 201.

Updated  to get hash is as key

```<code>users.map(&:attributes).group_by { |attr| attr[:id] }
</code>```

Body:
When I use users=User.where(...)
I can use users.find(id) to find by it's id

I want to use a hash such so that I can use users[id] as a means of searching, where the id becomes the index of the hash.

How do I do this?

I have tried:

users.to_a.map(&:serializable_hash)
users.map(&:attributes)
users.map { |r| r.attributes.symbolize_keys }

None of these worked in turning the primary key into the index

Body:
For the solution to your specific need

indexed_users = [] # holds users on index as id

users.each {|u| indexed_users[u.id] = u.attributes }

Also converting id as index is not a good idea as the array size may go out of control if id become bigger like thousands or so and ids are not sequential. like
users = [<id: 1>, <id:200>] will result in array with size of 201.

Updated  to get hash is as key

users.map(&:attributes).group_by { |attr| attr[:id] }


问:
Can't integrate INNER JOIN in my query
Hello I'm using the query below to select the latest message from each unique conversation. Everything works perfectly except when I try to integrate an INNER JOIN to try to link the user's user_id with their username in the users table.

I've tried pretty much every combination to integrate the INNER JOIN so I decided to separate it from the working query until I get help.

I made a Fiddle http://sqlfiddle.com/#!9/a9bbc/1   I just want user_id on the right to print the user's username

```<code>SELECT message_id,
       msg,
       user_id
FROM   messages
   JOIN (SELECT user_id,
                Max(dat) m
         FROM   ((SELECT message_id,
                         recipient_id user_id,
                         dat
                  FROM   messages
                  WHERE  owner_id = 1)
                 UNION
                 (SELECT message_id,
                         owner_id user_id,
                         dat
                  FROM   messages
                  WHERE  recipient_id = 1)) t1
         GROUP  BY user_id) t2
     ON ( ( owner_id = 1
            AND recipient_id = user_id )
           OR ( owner_id = user_id
                AND recipient_id = 1 ) )
        AND ( dat = m )
 ORDER  BY dat DESC
</code>```

.

```<code>users.username INNER JOIN users ON messages.user_id = users.user_id;
</code>```

答:
You need to join your final result with users table and get the value of users.username based on user_id. Try this:</p>

```<code>SELECT messages.message_id,
   messages.msg,
   users.user_id,
   users.username
FROM   users, messages
  JOIN (SELECT user_id,
            Max(dat) m
     FROM   ((SELECT message_id,
                     users.username,
                     recipient_id user_id,
                     dat
              FROM   messages
              INNER JOIN users ON messages.recipient_id = users.user_id
              WHERE  owner_id = 1)
             UNION
             (SELECT message_id,
                     users.username,
                     owner_id user_id,
                     dat
              FROM   messages
               INNER JOIN users ON messages.owner_id = users.user_id
              WHERE  recipient_id = 1)) t1
     GROUP  BY user_id) t2
 ON ( ( owner_id = 1
        AND recipient_id = user_id )
       OR ( owner_id = user_id
            AND recipient_id = 1 ) )
    AND ( dat = m )
WHERE users.user_id = messages.user_id
ORDER  BY dat DESC
</code>```

Title: Can't integrate INNER JOIN in my query

Body:
Hello I'm using the query below to select the latest message from each unique conversation. Everything works perfectly except when I try to integrate an INNER JOIN to try to link the user's user_id with their username in the users table.

I've tried pretty much every combination to integrate the INNER JOIN so I decided to separate it from the working query until I get help.

I made a Fiddle http://sqlfiddle.com/#!9/a9bbc/1   I just want user_id on the right to print the user's username

SELECT message_id,
       msg,
       user_id
FROM   messages
   JOIN (SELECT user_id,
                Max(dat) m
         FROM   ((SELECT message_id,
                         recipient_id user_id,
                         dat
                  FROM   messages
                  WHERE  owner_id = 1)
                 UNION
                 (SELECT message_id,
                         owner_id user_id,
                         dat
                  FROM   messages
                  WHERE  recipient_id = 1)) t1
         GROUP  BY user_id) t2
     ON ( ( owner_id = 1
            AND recipient_id = user_id )
           OR ( owner_id = user_id
                AND recipient_id = 1 ) )
        AND ( dat = m )
 ORDER  BY dat DESC

.

users.username INNER JOIN users ON messages.user_id = users.user_id;

Body:
You need to join your final result with users table and get the value of users.username based on user_id. Try this:

SELECT messages.message_id,
   messages.msg,
   users.user_id,
   users.username
FROM   users, messages
  JOIN (SELECT user_id,
            Max(dat) m
     FROM   ((SELECT message_id,
                     users.username,
                     recipient_id user_id,
                     dat
              FROM   messages
              INNER JOIN users ON messages.recipient_id = users.user_id
              WHERE  owner_id = 1)
             UNION
             (SELECT message_id,
                     users.username,
                     owner_id user_id,
                     dat
              FROM   messages
               INNER JOIN users ON messages.owner_id = users.user_id
              WHERE  recipient_id = 1)) t1
     GROUP  BY user_id) t2
 ON ( ( owner_id = 1
        AND recipient_id = user_id )
       OR ( owner_id = user_id
            AND recipient_id = 1 ) )
    AND ( dat = m )
WHERE users.user_id = messages.user_id
ORDER  BY dat DESC


问:
Return false within anchor tag gives error
I have the following statement

```<code><a href="javascript: return false;" id="addNew1">ADD NEW ROW</a>
</code>```

If I click on this I get the following error in my browser.

```<code>return not in function
</code>```

I use the following JQuery function

```<code>$('#addNew,#addNew1').click(function(){
</code>```

Do I need to include this in the function, the reason I do not add 'n # sign in is because the the page jumps to the top of the page.

答:
This works:

```<code><a href="#" id="addNew1">ADD NEW ROW</a>
</code>```

```<code>$('#addNew, #addNew1').click(function() {
    // do stuff
    return false;
}
</code>```

Another option would be this:

```<code>$('#addNew, #addNew1').click(function(e) {
    // do stuff
    e.preventDefault();
}
</code>```

Usually, if you want to prevent the default action, which in this case is the activation of the anchor, you do it inside the click handler.

Body:
I have the following statement

ADD NEW ROW

If I click on this I get the following error in my browser.

return not in function

I use the following JQuery function

$('#addNew,#addNew1').click(function(){

Do I need to include this in the function, the reason I do not add 'n # sign in is because the the page jumps to the top of the page.

Body:
This works:

<a href="#" id="addNew1">ADD NEW ROW</a>

$('#addNew, #addNew1').click(function() {
    // do stuff
    return false;
}

Another option would be this:

$('#addNew, #addNew1').click(function(e) {
    // do stuff
    e.preventDefault();
}

Usually, if you want to prevent the default action, which in this case is the activation of the anchor, you do it inside the click handler.


问:
Converting 2 strings to DateTime
I am getting 2 strings back from an API one for the date, and one for the time. I need to convert the 2 of them into a single DateTime object with the date and time in it. the 2 strings I get back are

```<code>Date: "2017-10-17"
Time: "8:00PM"
</code>```

Below is what I am trying to do and I can not get it to work. If I remove the time from it I can parse just the date, but I cant seem to figure out the pattern to add the time in it.

```<code>string date = "2017-10-17";
string time = "8:00PM"'

string startTime = $"{date} {time}";

DateTime date = DateTime.ParseExact(startTime, "yyyy-MM-dd hh:mmtt", System.Globalization.CultureInfo.CurrentCulture);
</code>```

How can I get those 2 strings to combine into a single DateTime object?

答:
```<code>string date = "2017-10-17";
string time = "8:00PM";

string startTime = $"{date} {time}";
DateTime myDate = DateTime.ParseExact(startTime, "yyyy-MM-dd h:mmtt",System.Globalization.CultureInfo.InvariantCulture);
</code>```

Title: Converting 2 strings to DateTime

Body:
I am getting 2 strings back from an API one for the date, and one for the time. I need to convert the 2 of them into a single DateTime object with the date and time in it. the 2 strings I get back are

Date: "2017-10-17"
Time: "8:00PM"

Below is what I am trying to do and I can not get it to work. If I remove the time from it I can parse just the date, but I cant seem to figure out the pattern to add the time in it.

string date = "2017-10-17";
string time = "8:00PM"'

string startTime = $"{date} {time}";

DateTime date = DateTime.ParseExact(startTime, "yyyy-MM-dd hh:mmtt", System.Globalization.CultureInfo.CurrentCulture);

How can I get those 2 strings to combine into a single DateTime object?


问:
Java - How do I check for a straight in a poker hand without sorting?
This is not a duplicate. I understand how easy this is if you can sort, but I am not allowed to use the sort method for arrays and I am not allowed to write my own. I can't find any help with this anywhere, including StackOverflow.

In this scenario, I have a method that is supposed to check whether or not a five card hand is a straight. I have a card object that holds a value (integer) and a suit (integer). I also have some rules about implementing this method.

There are no face cards besides the ace

The ace can count as either a 1 or a 10 but not both

A straight cannot wrap around

You cannot use the sorting method for arrays or write your own sorting method

That last rule is what is killing me. I have an array of cards. If I could just sort it, this would be so easy but I can't even write my own method to sort the array. For my other methods it simple to iterate through the hand and store the information about the hand in two separate arrays like this:

```<code>private static int[] cardValues = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private static int[] cardSuits = {0, 0, 0, 0, 0};

private static void evaluationHelper(Card[] cards) {
    for (int i = 0; i < cardValues.length; i++) {
        cardValues[i] = 0;
    }

    for (int i = 0; i <cardSuits.length; i++) {
        cardSuits[i] = 0;
    }

    for (int i = 0; i < 5; i++) {
        cardValues[cards[i].getValue() - 1]++;
        cardSuits[cards[i].getSuit()]++;

        if (cards[i].getValue() == 1) {
            cardValues[9]++;
        }
    }
}
</code>```

So in my first attempt to solve this issue I tried something like this:

```<code>public static boolean hasStraight(Card [] cards) {
    int sequenCounter = 0;
    evaluationHelper(cards);

    for (int i = 0; i < cardValues.length; i++) {
        if (sequenCounter != 5) {
            if (cardValues[i] != 0) {
                sequenCounter++;
            } else {
                sequenCounter = 0;
            }
        } else {
            return true;
        }
    }
    return false;
}
</code>```

That didn't work. So then I tried this:

```<code>public static boolean hasStraight(Card [] cards) {
    int min = 100, max = 0;
    boolean seenSix = false, seenAce = false;
    evaluationHelper(cards);

    for (int i = 0; i < cards.length; i++) {
        if (cards[i].getValue() > max) {
            max = cards[i].getValue();
        }

        if (cards[i].getValue() < min) {
            min = cards[i].getValue();
        }

        if (cards[i].getValue() == 6) {
            seenSix = true;
        }

        if (cards[i].getValue() == 1) {
            seenAce = true;
        }
    }

    if (seenSix && seenAce) {
        max = 10;
    }

    if (max - min == 4) {
        return true;
    }
    return false;
}
</code>```

That doesn't work either. I'm getting frustrated as both of these attempts went through many different changes over the course of overs and nothing has worked. I can't even figure out why they aren't working. The only information I have is that this method isn't spitting out the correct value. I don't know what values are being passed to the method. I don't know what the method is spitting out during the test. It could be spitting out false when it's supposed to be spitting true or vice versa. Please help!

答:
In your evaluationHelper you forgot to address when an ace is 10 adding:

```<code>if (cards[i].getValue() == 10) {
    cardValues[0]++;
}
</code>```

will make at least your first solution work (I haven't checked the second).

Note that what this method does is still a form of Radix sort so I'm not sure if it satisfies your requirement.

Body:
This is not a duplicate. I understand how easy this is if you can sort, but I am not allowed to use the sort method for arrays and I am not allowed to write my own. I can't find any help with this anywhere, including StackOverflow.

In this scenario, I have a method that is supposed to check whether or not a five card hand is a straight. I have a card object that holds a value (integer) and a suit (integer). I also have some rules about implementing this method.

There are no face cards besides the ace

The ace can count as either a 1 or a 10 but not both

A straight cannot wrap around

You cannot use the sorting method for arrays or write your own sorting method

That last rule is what is killing me. I have an array of cards. If I could just sort it, this would be so easy but I can't even write my own method to sort the array. For my other methods it simple to iterate through the hand and store the information about the hand in two separate arrays like this:

private static int[] cardValues = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private static int[] cardSuits = {0, 0, 0, 0, 0};

private static void evaluationHelper(Card[] cards) {
    for (int i = 0; i < cardValues.length; i++) {
        cardValues[i] = 0;
    }

    for (int i = 0; i <cardSuits.length; i++) {
        cardSuits[i] = 0;
    }

    for (int i = 0; i < 5; i++) {
        cardValues[cards[i].getValue() - 1]++;
        cardSuits[cards[i].getSuit()]++;

        if (cards[i].getValue() == 1) {
            cardValues[9]++;
        }
    }
}

So in my first attempt to solve this issue I tried something like this:

public static boolean hasStraight(Card [] cards) {
    int sequenCounter = 0;
    evaluationHelper(cards);

    for (int i = 0; i < cardValues.length; i++) {
        if (sequenCounter != 5) {
            if (cardValues[i] != 0) {
                sequenCounter++;
            } else {
                sequenCounter = 0;
            }
        } else {
            return true;
        }
    }
    return false;
}

That didn't work. So then I tried this:

public static boolean hasStraight(Card [] cards) {
    int min = 100, max = 0;
    boolean seenSix = false, seenAce = false;
    evaluationHelper(cards);

    for (int i = 0; i < cards.length; i++) {
        if (cards[i].getValue() > max) {
            max = cards[i].getValue();
        }

        if (cards[i].getValue() < min) {
            min = cards[i].getValue();
        }

        if (cards[i].getValue() == 6) {
            seenSix = true;
        }

        if (cards[i].getValue() == 1) {
            seenAce = true;
        }
    }

    if (seenSix && seenAce) {
        max = 10;
    }

    if (max - min == 4) {
        return true;
    }
    return false;
}

That doesn't work either. I'm getting frustrated as both of these attempts went through many different changes over the course of overs and nothing has worked. I can't even figure out why they aren't working. The only information I have is that this method isn't spitting out the correct value. I don't know what values are being passed to the method. I don't know what the method is spitting out during the test. It could be spitting out false when it's supposed to be spitting true or vice versa. Please help!

Body:
In your evaluationHelper you forgot to address when an ace is 10 adding:

if (cards[i].getValue() == 10) {
    cardValues[0]++;
}

will make at least your first solution work (I haven't checked the second).

Note that what this method does is still a form of Radix sort so I'm not sure if it satisfies your requirement.


问:
Does React DOM have to use className? Why am I not seeing any warnings?
I've been trying out React on a project for weeks now. And I just remembered that I should use className instead of class in regular DOM and SVG, because class is a reserved keyword in JS.

However, all my components are using classso far. For example:

```<code>export default class Header extends React.Component {
    render() {
        return (
            <div class="Header">
                <img class="Logo" src="./interface/images/ea-white.png"/>
                <h1 class="Title">{this.props.title}</h1>
            </div>
        );
    }
}
</code>```

Why haven't I got any syntax error? Does React DOM have to use className? What could happen if I keep it this way?

Edit: Yes, the CSS files worked normally all this time. There's no warning in my console (which is weird).

答:
React throws a warning when you use an unknown property such as class on an element.

It also points to the source line number, thanks to this pr https://github.com/facebook/react/pull/6398

Body:
I've been trying out React on a project for weeks now. And I just remembered that I should use className instead of class in regular DOM and SVG, because class is a reserved keyword in JS.

However, all my components are using classso far. For example:

export default class Header extends React.Component {
    render() {
        return (

{this.props.title}

        );
    }
}

Why haven't I got any syntax error? Does React DOM have to use className? What could happen if I keep it this way?

Edit: Yes, the CSS files worked normally all this time. There's no warning in my console (which is weird).


问:
CSS Animation Delay and Keyframe
I have a problem with animation delay on CSS Animation. I have 3 images and I want to make it slideshow. The illustrations is, image 1 to image 2 takes 15 seconds to change and image 2 to image 3 takes 15 seconds to change and image 3 back to image 1 it takes 30 seconds, after the first loop, I want to make the slideshow end in image 3 so image 1 to image 2 still 15 seconds and image 2 to image 3 still 15 seconds and when image 3 load it no need to back to image 1. I tried this code but it gives me 15 seconds delay to all images. This is my code :

ul {
      list-style: none;
      margin: 0;
      padding: 0;
      position: relative;
    }

    li {
      position: absolute;
      opacity:0;
    }

    li {
      animation: xfade 45s  infinite;
    }
    li:nth-child(2) {
      animation-delay:15s;
    }
    li:nth-child(3) {
      animation-delay:30s;
    }

    @keyframes xfade{
      3%{opacity:1}
      33% {opacity:1;}
      36%{opacity:0}
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <ul>
      <li><img width="500" height="500" src="http://lorempixel.com/500/500/sports" alt="pic1"></li>
      <li><img width="500" height="500" src="http://lorempixel.com/500/500/people" alt="pic2"></li>
      <li><img width="500" height="500" src="http://lorempixel.com/500/500/transport" alt="pic3"></li>
    </ul></code>```

I want to make delay in my animation according the illustrations above. Anyone could help me solve this problem ? Thank you before.

答:
Here's something that gave real food for thought :)

I had to apply 2 animations for opacity change: xfade-25pct and xfade-50pct. Both play only 2 times, fading out briefly after 25% and 50% of the animation. And an additional show animation to make the 3rd image stick after 2 animation loops, with the necessary rule animation-fill-mode: forwards;.

The trick to opacity is this: you have to split the animation in 4 quarters. If you want you can change the total animation duration from 60s to a multiple of 4, and adjust the delays. The 3rd animation delay is the double of the 2nd one.

```<code>----#----#----#----#----#----#----#----#----#----#
1st animation      | 1st animation     |
--------------------------------------------------
15s | 2nd animation     | 2nd animation     |
--------------------------------------------------
30s      | 3rd animation     |   3rd animation   |
----#----#----#----#----#----#----#----#----#----#
</code>```

Feel free to ask. Hope this helps you.

var s = 0,
  c = 1;
/* Code for displaying timer */
window.setInterval(function() {
  s++;
  document.querySelector('DIV').innerHTML = s;
  if (s == 15 && c <= 2 || s == 30) {
    if (s == 30) {
      c = 1;
    } else {
      c++;
    }
    s = 0;
  }
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  list-style: none;
  margin: 0;
  padding: 0;
  position: relative;
}

li {
  position: absolute;
  opacity: 0;
}

li {
  animation: xfade-25pct 60s 2;
}

li:nth-child(2) {
  animation-delay: 15s;
}

li:nth-child(3) {
  animation-delay: 30s, 120s;
  animation-name: xfade-50pct, show;
  animation-duration: 60s, 1s;
  animation-iteration-count: 2, 1;
  animation-fill-mode: forwards;
}

@keyframes xfade-25pct {
  0% {
    opacity: 0;
  }
  2%,
  25% {
    opacity: 1;
  }
  27% {
    opacity: 0;
  }
}

@keyframes xfade-50pct {
  0% {
    opacity: 0;
  }
  2%,
  50% {
    opacity: 1;
  }
  52% {
    opacity: 0;
  }
}

@keyframes show {
  0%,
  100% {
    opacity: 1;
  }
}</code>```

```

Title: CSS Animation Delay and Keyframe

Body:
I have a problem with animation delay on CSS Animation. I have 3 images and I want to make it slideshow. The illustrations is, image 1 to image 2 takes 15 seconds to change and image 2 to image 3 takes 15 seconds to change and image 3 back to image 1 it takes 30 seconds, after the first loop, I want to make the slideshow end in image 3 so image 1 to image 2 still 15 seconds and image 2 to image 3 still 15 seconds and when image 3 load it no need to back to image 1. I tried this code but it gives me 15 seconds delay to all images. This is my code :

ul {
      list-style: none;
      margin: 0;
      padding: 0;
      position: relative;
    }

    li {
      position: absolute;
      opacity:0;
    }

    li {
      animation: xfade 45s  infinite;
    }
    li:nth-child(2) {
      animation-delay:15s;
    }
    li:nth-child(3) {
      animation-delay:30s;
    }

    @keyframes xfade{
      3%{opacity:1}
      33% {opacity:1;}
      36%{opacity:0}
    }

I want to make delay in my animation according the illustrations above. Anyone could help me solve this problem ? Thank you before.

Body:
Here's something that gave real food for thought :)

I had to apply 2 animations for opacity change: xfade-25pct and xfade-50pct. Both play only 2 times, fading out briefly after 25% and 50% of the animation. And an additional show animation to make the 3rd image stick after 2 animation loops, with the necessary rule animation-fill-mode: forwards;.

The trick to opacity is this: you have to split the animation in 4 quarters. If you want you can change the total animation duration from 60s to a multiple of 4, and adjust the delays. The 3rd animation delay is the double of the 2nd one.

----#----#----#----#----#----#----#----#----#----#
1st animation      | 1st animation     |
--------------------------------------------------
15s | 2nd animation     | 2nd animation     |
--------------------------------------------------
30s      | 3rd animation     |   3rd animation   |
----#----#----#----#----#----#----#----#----#----#

Feel free to ask. Hope this helps you.

var s = 0,
  c = 1;
/* Code for displaying timer */
window.setInterval(function() {
  s++;
  document.querySelector('DIV').innerHTML = s;
  if (s == 15 && c <= 2 || s == 30) {
    if (s == 30) {
      c = 1;
    } else {
      c++;
    }
    s = 0;
  }
}, 1000);

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  position: relative;
}

li {
  position: absolute;
  opacity: 0;
}

li {
  animation: xfade-25pct 60s 2;
}

li:nth-child(2) {
  animation-delay: 15s;
}

li:nth-child(3) {
  animation-delay: 30s, 120s;
  animation-name: xfade-50pct, show;
  animation-duration: 60s, 1s;
  animation-iteration-count: 2, 1;
  animation-fill-mode: forwards;
}

@keyframes xfade-25pct {
  0% {
    opacity: 0;
  }
  2%,
  25% {
    opacity: 1;
  }
  27% {
    opacity: 0;
  }
}

@keyframes xfade-50pct {
  0% {
    opacity: 0;
  }
  2%,
  50% {
    opacity: 1;
  }
  52% {
    opacity: 0;
  }
}

@keyframes show {
  0%,
  100% {
    opacity: 1;
  }
}

<DIV></DIV>
<ul>
  <li><img width="500" height="500" src="https://www.noao.edu/image_gallery/images/d2/pelican_500.jpg" alt="pic1"></li>
  <li><img width="500" height="500" src="http://whc.unesco.org/uploads/thumbs/news_920-500-500-20151015155516.jpg" alt="pic2"></li>
  <li><img width="500" height="500" src="https://i.pinimg.com/736x/4c/17/65/4c176537aee906de294138c3bac5b8f5--merry-christmas-love-coffee-aroma.jpg" alt="pic3"></li>
</ul>


问:
Why function if/else not work in Datatables CI (use Ignited)
I get this library datatbles on git hub, this is ignited datatbles.

Ok, i've code in my Controller,

```<code>function json_survey(){
        header('Content-Type: application/json');
        $this->load->library('Datatables');
        $this->load->helper('datatables_helper');
        $this->datatables->SELECT('id_survey,judul_survey,status_survey,responden,detail_target,judul_kategori,judul_target');
        $dataids = array('id_survey'=> '$1','status_survey'=> '$2');
        $this->datatables->add_column('action',tombol_survey($dataids), 'id_survey,status_survey');
        $this->datatables->FROM('survey');
        $this->datatables->JOIN('kategori','survey.id_kategori=kategori.id_kategori');
        $this->datatables->JOIN('target','survey.id_target=target.id_target');

        return print_r($this->datatables->generate('json',''));
    }
</code>```

And i have code in muy Helper to create button with function if/else

```<code>function tombol_survey($ids)
    {
        $ci = & get_instance();
        if(!empty($ids)){
            $html = '<span class="actions">';
            if($ids['status_survey']=='terbit'){
                $html .= '<a href="' . base_url() . 'survey/edit/'.$ids['id_survey'].'">Tutup</a>';
            }
            if($ids['status_survey']=='tertunda'){
                $html .= '<a href="' . base_url() . 'pertanyaan/tambah/'.$ids['id_survey'].'">Tambah</a>';
            }
            if($ids['status_survey']=='tutup'){
                $html .= 'Hapus | ';
            }
            $html .= '<a href="' . base_url() . 'pertanyaan/tambah/' .$ids['id_survey']. '">Test</a>';
            $html .= '</span>';

            return $html;
        }
    }
</code>```

my problem, function if not work but 2 parameter (id_survey & status_survey) was inclued.
Please help me sir

Look my picture

答:
You need to perform some simple debugging...

You have this line

```<code>$dataids = array('id_survey'=> '$1','status_survey'=> '$2');
</code>```

If you perform a var_dump on this like...

```<code>$dataids = array('id_survey'=> '$1','status_survey'=> '$2');
var_dump($dataids);
</code>```

you will get

```<code>array (size=2)
  'id_survey' => string '$1' (length=2)
  'status_survey' => string '$2' (length=2)
</code>```

These are NOT in any of your If/Else tests so they none of them will evaluate.

Your HTML will evaluate to be

```<code>```Test
```

<p>So first thing is to change your code by removing the quotes from that line so it becomes...</p>

```$dataids = array('id_survey'=> $1,'status_survey'=> $2);
```

BUT I cannot see where you are setting the values for $1 and $2.

So for starters remove the quotes around $1 and $2... They are Variables - Not Strings...

Body:
I get this library datatbles on git hub, this is ignited datatbles.

Ok, i've code in my Controller,

function json_survey(){
        header('Content-Type: application/json');
        $this->load->library('Datatables');
        $this->load->helper('datatables_helper');
        $this->datatables->SELECT('id_survey,judul_survey,status_survey,responden,detail_target,judul_kategori,judul_target');
        $dataids = array('id_survey'=> '$1','status_survey'=> '$2');
        $this->datatables->add_column('action',tombol_survey($dataids), 'id_survey,status_survey');
        $this->datatables->FROM('survey');
        $this->datatables->JOIN('kategori','survey.id_kategori=kategori.id_kategori');
        $this->datatables->JOIN('target','survey.id_target=target.id_target');

        return print_r($this->datatables->generate('json',''));
    }

And i have code in muy Helper to create button with function if/else

function tombol_survey($ids)
    {
        $ci = & get_instance();
        if(!empty($ids)){
            $html = '';
            if($ids['status_survey']=='terbit'){
                $html .= 'Tutup';
            }
            if($ids['status_survey']=='tertunda'){
                $html .= 'Tambah';
            }
            if($ids['status_survey']=='tutup'){
                $html .= 'Hapus | ';
            }
            $html .= 'Test';
            $html .= '';

            return $html;
        }
    }

my problem, function if not work but 2 parameter (id_survey & status_survey) was inclued.
Please help me sir

Look my picture

Body:
You need to perform some simple debugging...

You have this line

$dataids = array('id_survey'=> '$1','status_survey'=> '$2');

If you perform a var_dump on this like...

$dataids = array('id_survey'=> '$1','status_survey'=> '$2');
var_dump($dataids);

you will get

array (size=2)
  'id_survey' => string '$1' (length=2)
  'status_survey' => string '$2' (length=2)

These are NOT in any of your If/Else tests so they none of them will evaluate.

Your HTML will evaluate to be

</pre><span class="actions"><a href="http://cidev315.com/pertanyaan/tambah/$1">Test</a></span>

So first thing is to change your code by removing the quotes from that line so it becomes...

$dataids = array('id_survey'=> $1,'status_survey'=> $2);

BUT I cannot see where you are setting the values for $1 and $2.

So for starters remove the quotes around $1 and $2... They are Variables - Not Strings...


问:
PHP count of occurrences of characters of a string within another string
Let's say I have two strings.

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

答:
You can calculate the length of the original string and the length of the string without these characters. The differences between them is the number of matches.

Basically,

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

Here is the part that does the work. In one line.

```<code>$count = strlen($haystack) - strlen(str_replace(str_split($needle), '', $haystack));
</code>```

Explanation: The first part is self-explanatory. The second part is the length of the string without the characters in the $needle string. This is done by replacing each occurrences of any characters inside the $needle with a blank string.

To do this, we split $needle into an array, once character for each item, using str_split. Then pass it to str_replace. It replaces each occurence of any items in the $search array with a blank string.

Echo it out,

```<code>echo "Count = $count\n";
</code>```

you get:

Count = 5

Body:
Let's say I have two strings.

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

Body:
You can calculate the length of the original string and the length of the string without these characters. The differences between them is the number of matches.

Basically,

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

Here is the part that does the work. In one line.

$count = strlen($haystack) - strlen(str_replace(str_split($needle), '', $haystack));

Explanation: The first part is self-explanatory. The second part is the length of the string without the characters in the $needle string. This is done by replacing each occurrences of any characters inside the $needle with a blank string.

To do this, we split $needle into an array, once character for each item, using str_split. Then pass it to str_replace. It replaces each occurence of any items in the $search array with a blank string.

Echo it out,

echo "Count = $count\n";

you get:

Count = 5


问:
Numerical Stability of Forward Substitution in Python
I am implementing some basic linear equation solvers in Python.

I have currently implemented forward and backward substitution for triangular systems of equations (so very straightforward to solve!), but the precision of the solutions becomes very poor even with systems of about 50 equations (50x50 coefficient matrix).

The following code performs the forward/backward substitution:

```<code>FORWARD_SUBSTITUTION = 1
BACKWARD_SUBSTITUTION = 2
def solve_triang_subst(A: np.ndarray, b: np.ndarray,
                       substitution=FORWARD_SUBSTITUTION) -> np.ndarray:
    """Solves a triangular system via
    forward or backward substitution.

    A must be triangular. FORWARD_SUBSTITUTION means A should be
    lower-triangular, BACKWARD_SUBSTITUTION means A should be upper-triangular.
    """
    rows = len(A)
    x = np.zeros(rows, dtype=A.dtype)
    row_sequence = reversed(range(rows)) if substitution == BACKWARD_SUBSTITUTION else range(rows)

    for row in row_sequence:
        delta = b[row] - np.dot(A[row], x)
        cur_x = delta / A[row][row]
        x[row] = cur_x

    return x
</code>```

I am using numpy and 64-bit floats.

Simple Testing Tool

I have set up a simple test suite which generates coefficient matrices and x vectors, computes the b, and then uses forward or backward substitution to recover the x, comparing it to the its known value for validity.

The following code performs these checks:

```<code>import numpy as np
import scipy.linalg as sp_la

RANDOM_SEED = 1984
np.random.seed(RANDOM_SEED)

def check(sol: np.ndarray, x_gt: np.ndarray, description: str) -> None:
    if not np.allclose(sol, x_gt, rtol=0.1):
        print("Found inaccurate solution:")
        print(sol)
        print("Ground truth (not achieved...):")
        print(x_gt)
        raise ValueError("{} did not work!".format(description))

def fuzz_test_solving():
    N_ITERATIONS = 100
    refine_result = True
    for mode in [FORWARD_SUBSTITUTION, BACKWARD_SUBSTITUTION]:
        print("Starting mode {}".format(mode))
        for iteration in range(N_ITERATIONS):
            N = np.random.randint(3, 50)
            A = np.random.uniform(0.0, 1.0, [N, N]).astype(np.float64)

            if mode == BACKWARD_SUBSTITUTION:
                A = np.triu(A)
            elif mode == FORWARD_SUBSTITUTION:
                A = np.tril(A)
            else:
                raise ValueError()

            x_gt = np.random.uniform(0.0, 1.0, N).astype(np.float64)
            b = np.dot(A, x_gt)

            x_est = solve_triang_subst(A, b, substitution=mode,
                                       refine_result=refine_result)
            # TODO report error and count, don't throw!
            # Keep track of error norm!!
            check(x_est, x_gt,
                  "Mode {} custom triang iteration {}".format(mode, iteration))

if __name__ == '__main__':
    fuzz_test_solving()
</code>```

Note that the maximum size of a test matrix is 49x49. Even in this case, the system cannot always compute decent solutions, and fails by more than a margin of 0.1. Here's an example of such a failure (this is doing backward substitution, so the biggest error is in the 0th coefficient; all the test data are sampled uniformly from [0, 1[):

```<code>Solution found with Mode 2 custom triang iteration 24:
[ 0.27876067  0.55200497  0.49499509  0.3259397   0.62420183  0.47041149
  0.63557676  0.41155446  0.47191956  0.74385864  0.03002819  0.4700286
  0.37989592  0.56527691  0.15072607  0.05659282  0.52587574  0.82252197
  0.65662833  0.50250729  0.74139748  0.10852731  0.27864265  0.42981232
  0.16327331  0.74097937  0.24411709  0.96934199  0.890266    0.9183985
  0.14842446  0.51806495  0.36966843  0.18227989  0.85399593  0.89615663
  0.39819336  0.90445931  0.21430972  0.61212349  0.85205597  0.66758689
  0.1793689   0.38067267  0.39104614  0.6765885   0.4118123 ]
Ground truth (not achieved...)
[ 0.20881608  0.71009766  0.44735271  0.31169033  0.63982328  0.49075813
  0.59669585  0.43844108  0.47764942  0.72222069  0.03497499  0.4707452
  0.37679884  0.56439738  0.15120397  0.05635977  0.52616387  0.82230625
  0.65670245  0.50251426  0.74139956  0.10845974  0.27864289  0.42981226
  0.1632732   0.74097939  0.24411707  0.96934199  0.89026601  0.91839849
  0.14842446  0.51806495  0.36966843  0.18227989  0.85399593  0.89615663
  0.39819336  0.90445931  0.21430972  0.61212349  0.85205597  0.66758689
  0.1793689   0.38067267  0.39104614  0.6765885   0.4118123 ]
</code>```

I have also implemented the iterative refinement method described in Section 2.5 of [0], and while it did help a little, the results are still poor for larger matrices.

MATLAB Sanity Check

I also did this experiment in MATLAB, and even there, once there are more than 100 equations, the estimation error shoots up exponentially.

Here is the MATLAB code I used for this experiment:

```<code>err_norms = [];
range = 1:3:120;
for size=range

  A = rand(size, size);
  A = tril(A);
  x_gt = rand(size, 1);

  b = A * x_gt;
  x_sol = A\b;

  err_norms = [err_norms, norm(x_gt - x_sol)];
end

plot(range, err_norms);
set(gca, 'YScale', 'log')
</code>```

And here is the resulting plot:

Main Question

My question is: Is this normal behavior, seeing as there is essentially no structure in the problem, given that I randomly generate the A matrix and x?

What about solving linear systems of 100s of equations for various practical applications? Are these limitations simply an accepted fact, and e.g., optimization algorithms are just naturally robust to these issues? Or am I missing some important facets of this problem?

[0]: Press, William H. Numerical recipes 3rd edition: The art of scientific computing. Cambridge university press, 2007.

答:
There are no limitations. This is a very fruitful exercise that we all came to realize; writing linear solvers are not that easy and that's why almost always LAPACK or its cousins in other languages are used with full confidence.

You are hit by almost singular matrices and because you are using matlab's backslash you don't see that matlab is switching to least squares solutions behind the scenes when near singularity is hit. If you just change A\b to linsolve(A,b) hence you restrict the solver to solve square systems you'll probably see lots of warnings on your console.

I didn't test it because I don't have a license anymore but if I write blindly this should show you the condition numbers of the matrices at each step.

```<code>err_norms = [];
range = 1:3:120;
for i=1:40
  size = range(i);
  A = rand(size, size);
  A = tril(A);
  x_gt = rand(size, 1);

  b = A * x_gt;
  x_sol = linsolve(A,b);

  err_norms = [err_norms, norm(x_gt - x_sol)];
  zzz(i) = rcond(A);
end

semilogy(range, err_norms);
figure,semilogy(range,zzz);
</code>```

Note that because you are picking up numbers from a uniform distribution it becomes more and more likely to hit ill-conditioned matrices (wrt to inversion) as the rows have more probability to have rank deficiency. That's why the error becomes bigger and bigger. Sprinkle some identity matrix times a scalar and all errors should come back to eps*n levels.

But best, leave this to expert algorithms which have been tested through decades. It is really not that trivial to write any of these. You can read the Fortran codes, for example, dtrsm solves the triangular system.

On the Python side, you can use scipy.linalg.solve_triangular which uses ?trtrs routines from LAPACK.

Body:
I am implementing some basic linear equation solvers in Python.

I have currently implemented forward and backward substitution for triangular systems of equations (so very straightforward to solve!), but the precision of the solutions becomes very poor even with systems of about 50 equations (50x50 coefficient matrix).

The following code performs the forward/backward substitution:

FORWARD_SUBSTITUTION = 1
BACKWARD_SUBSTITUTION = 2
def solve_triang_subst(A: np.ndarray, b: np.ndarray,
                       substitution=FORWARD_SUBSTITUTION) -> np.ndarray:
    """Solves a triangular system via
    forward or backward substitution.

    A must be triangular. FORWARD_SUBSTITUTION means A should be
    lower-triangular, BACKWARD_SUBSTITUTION means A should be upper-triangular.
    """
    rows = len(A)
    x = np.zeros(rows, dtype=A.dtype)
    row_sequence = reversed(range(rows)) if substitution == BACKWARD_SUBSTITUTION else range(rows)

    for row in row_sequence:
        delta = b[row] - np.dot(A[row], x)
        cur_x = delta / A[row][row]
        x[row] = cur_x

    return x

I am using numpy and 64-bit floats.

Simple Testing Tool

I have set up a simple test suite which generates coefficient matrices and x vectors, computes the b, and then uses forward or backward substitution to recover the x, comparing it to the its known value for validity.

The following code performs these checks:

import numpy as np
import scipy.linalg as sp_la

RANDOM_SEED = 1984
np.random.seed(RANDOM_SEED)

def check(sol: np.ndarray, x_gt: np.ndarray, description: str) -> None:
    if not np.allclose(sol, x_gt, rtol=0.1):
        print("Found inaccurate solution:")
        print(sol)
        print("Ground truth (not achieved...):")
        print(x_gt)
        raise ValueError("{} did not work!".format(description))

def fuzz_test_solving():
    N_ITERATIONS = 100
    refine_result = True
    for mode in [FORWARD_SUBSTITUTION, BACKWARD_SUBSTITUTION]:
        print("Starting mode {}".format(mode))
        for iteration in range(N_ITERATIONS):
            N = np.random.randint(3, 50)
            A = np.random.uniform(0.0, 1.0, [N, N]).astype(np.float64)

            if mode == BACKWARD_SUBSTITUTION:
                A = np.triu(A)
            elif mode == FORWARD_SUBSTITUTION:
                A = np.tril(A)
            else:
                raise ValueError()

            x_gt = np.random.uniform(0.0, 1.0, N).astype(np.float64)
            b = np.dot(A, x_gt)

            x_est = solve_triang_subst(A, b, substitution=mode,
                                       refine_result=refine_result)
            # TODO report error and count, don't throw!
            # Keep track of error norm!!
            check(x_est, x_gt,
                  "Mode {} custom triang iteration {}".format(mode, iteration))

if __name__ == '__main__':
    fuzz_test_solving()

Note that the maximum size of a test matrix is 49x49. Even in this case, the system cannot always compute decent solutions, and fails by more than a margin of 0.1. Here's an example of such a failure (this is doing backward substitution, so the biggest error is in the 0th coefficient; all the test data are sampled uniformly from [0, 1[):

Solution found with Mode 2 custom triang iteration 24:
[ 0.27876067  0.55200497  0.49499509  0.3259397   0.62420183  0.47041149
  0.63557676  0.41155446  0.47191956  0.74385864  0.03002819  0.4700286
  0.37989592  0.56527691  0.15072607  0.05659282  0.52587574  0.82252197
  0.65662833  0.50250729  0.74139748  0.10852731  0.27864265  0.42981232
  0.16327331  0.74097937  0.24411709  0.96934199  0.890266    0.9183985
  0.14842446  0.51806495  0.36966843  0.18227989  0.85399593  0.89615663
  0.39819336  0.90445931  0.21430972  0.61212349  0.85205597  0.66758689
  0.1793689   0.38067267  0.39104614  0.6765885   0.4118123 ]
Ground truth (not achieved...)
[ 0.20881608  0.71009766  0.44735271  0.31169033  0.63982328  0.49075813
  0.59669585  0.43844108  0.47764942  0.72222069  0.03497499  0.4707452
  0.37679884  0.56439738  0.15120397  0.05635977  0.52616387  0.82230625
  0.65670245  0.50251426  0.74139956  0.10845974  0.27864289  0.42981226
  0.1632732   0.74097939  0.24411707  0.96934199  0.89026601  0.91839849
  0.14842446  0.51806495  0.36966843  0.18227989  0.85399593  0.89615663
  0.39819336  0.90445931  0.21430972  0.61212349  0.85205597  0.66758689
  0.1793689   0.38067267  0.39104614  0.6765885   0.4118123 ]

I have also implemented the iterative refinement method described in Section 2.5 of [0], and while it did help a little, the results are still poor for larger matrices.

MATLAB Sanity Check

I also did this experiment in MATLAB, and even there, once there are more than 100 equations, the estimation error shoots up exponentially.

Here is the MATLAB code I used for this experiment:

err_norms = [];
range = 1:3:120;
for size=range

  A = rand(size, size);
  A = tril(A);
  x_gt = rand(size, 1);

  b = A * x_gt;
  x_sol = A\b;

  err_norms = [err_norms, norm(x_gt - x_sol)];
end

plot(range, err_norms);
set(gca, 'YScale', 'log')

And here is the resulting plot:

Main Question

My question is: Is this normal behavior, seeing as there is essentially no structure in the problem, given that I randomly generate the A matrix and x?

What about solving linear systems of 100s of equations for various practical applications? Are these limitations simply an accepted fact, and e.g., optimization algorithms are just naturally robust to these issues? Or am I missing some important facets of this problem?

[0]: Press, William H. Numerical recipes 3rd edition: The art of scientific computing. Cambridge university press, 2007.

Body:
There are no limitations. This is a very fruitful exercise that we all came to realize; writing linear solvers are not that easy and that's why almost always LAPACK or its cousins in other languages are used with full confidence.

You are hit by almost singular matrices and because you are using matlab's backslash you don't see that matlab is switching to least squares solutions behind the scenes when near singularity is hit. If you just change A\b to linsolve(A,b) hence you restrict the solver to solve square systems you'll probably see lots of warnings on your console.

I didn't test it because I don't have a license anymore but if I write blindly this should show you the condition numbers of the matrices at each step.

err_norms = [];
range = 1:3:120;
for i=1:40
  size = range(i);
  A = rand(size, size);
  A = tril(A);
  x_gt = rand(size, 1);

  b = A * x_gt;
  x_sol = linsolve(A,b);

  err_norms = [err_norms, norm(x_gt - x_sol)];
  zzz(i) = rcond(A);
end

semilogy(range, err_norms);
figure,semilogy(range,zzz);

Note that because you are picking up numbers from a uniform distribution it becomes more and more likely to hit ill-conditioned matrices (wrt to inversion) as the rows have more probability to have rank deficiency. That's why the error becomes bigger and bigger. Sprinkle some identity matrix times a scalar and all errors should come back to eps*n levels.

But best, leave this to expert algorithms which have been tested through decades. It is really not that trivial to write any of these. You can read the Fortran codes, for example, dtrsm solves the triangular system.

On the Python side, you can use scipy.linalg.solve_triangular which uses ?trtrs routines from LAPACK.


问:
Changing an encoding while change Content-Type
I have a server, which should response for some requests. Requests contain "Content-Type" is equal to "application/x-protobuf", so I need to response a set of bytes (serialised proto object). When I tried to send this bytes with Content-Type "text/plain" - each byte was successfully delivered to users, but when I tried to change this value to "application/x-protobuf" - every byte with value more than 128 was replaced by \uFFF8.

I use cherrypy framework for my server.

Anybody have some ideas, why this happens? And how to know which encoding were used in case "text/plain".

Thank you for your answers.

答:
Google Protocol Buffers code generator for nginx module developers
https://github.com/dbcode/protobuf-nginx


问:
Changing time zone in Highchart
I am plotting a chart using  highcharter function. You can notice the timestamp starts from June 29th. But i when plot it , the graph shows data  plotting from June 28,18.30. How do i change this time zone??

```<code>> head(d)
                   timestamps  x1  x2  x3  x4  x5  x6  x7  x8  x9 x10  x11     x12
    47948 2017-06-29 00:00:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 48.5 1210.87
    47949 2017-06-29 00:01:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 49.2 1213.91
    47950 2017-06-29 00:02:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 49.0 1213.59
    47951 2017-06-29 00:03:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 50.0 1214.28
    47952 2017-06-29 00:04:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 50.0 1212.13
    47953 2017-06-29 00:05:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 49.8 1216.06
</code>```

```<code>library(highcharter)
highchart() %>%
  hc_title(text = "A nice chart") %>%
  hc_add_series_times_values(d$timestamps,
                             d$x12, name = "x12")
</code>```

Any help is appreciated. Thank you.

答:
This is how I managed to deactivate UTC in highcharter.

```<code>hcGopts <- getOption("highcharter.global")
hcGopts$useUTC <- FALSE
options(highcharter.global = hcGopts)
</code>```

The global options are not directly accessible from R. From JavaScript, it would be like this:

```<code>Highcharts.setOptions({
    global: {
        useUTC: false
    }
});
</code>```

Title: Changing time zone in Highchart

Body:
I am plotting a chart using  highcharter function. You can notice the timestamp starts from June 29th. But i when plot it , the graph shows data  plotting from June 28,18.30. How do i change this time zone??

> head(d)
                   timestamps  x1  x2  x3  x4  x5  x6  x7  x8  x9 x10  x11     x12
    47948 2017-06-29 00:00:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 48.5 1210.87
    47949 2017-06-29 00:01:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 49.2 1213.91
    47950 2017-06-29 00:02:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 49.0 1213.59
    47951 2017-06-29 00:03:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 50.0 1214.28
    47952 2017-06-29 00:04:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 50.0 1212.13
    47953 2017-06-29 00:05:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 49.8 1216.06

library(highcharter)
highchart() %>%
  hc_title(text = "A nice chart") %>%
  hc_add_series_times_values(d$timestamps,
                             d$x12, name = "x12")

Any help is appreciated. Thank you.

Body:
This is how I managed to deactivate UTC in highcharter.

hcGopts <- getOption("highcharter.global")
hcGopts$useUTC <- FALSE
options(highcharter.global = hcGopts)

The global options are not directly accessible from R. From JavaScript, it would be like this:

Highcharts.setOptions({
    global: {
        useUTC: false
    }
});


答: It currently works, but React will throw a warning in your console. I would recommend using className considering this is what React wants you to do. If you continue to use class, there may be a time when React stops supporting this.

Title: Does React DOM have to use className? Why am I not seeing any warnings?


问:
How to find the index of a missing element?
Let's say you have the following lists:

```<code>fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
</code>```

How would I write a loop that identifies that the "pear" element is missing in the
"fruits" list's 2nd index?

I do know the first step begins with:

```<code>for element in fruit_types:
    if element not in fruits:
</code>```

But I am completely lost where else to go from here.

答:
You can use difference operation on set to find this.

```<code>fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

missings = list(set(fruits_types) - set(fruit))
print missings
</code>```

If this is cool, then why use loops?

Then to get index of the missing item:

```<code>for missing in missings:
    print fruit_types.index(missing)
</code>```

Body:
Let's say you have the following lists:

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

How would I write a loop that identifies that the "pear" element is missing in the
"fruits" list's 2nd index?

I do know the first step begins with:

for element in fruit_types:
    if element not in fruits:

But I am completely lost where else to go from here.

Body:
You can use difference operation on set to find this.

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

missings = list(set(fruits_types) - set(fruit))
print missings

If this is cool, then why use loops?

Then to get index of the missing item:

for missing in missings:
    print fruit_types.index(missing)


问:
How do I display rows individually at a set interval?
Here is the issue .... I have a PHP program reading and displaying the contents (4 text fields) of a MySQL database. These records are displayed sequentially down the page. What I hope to do is read a record and display the text, have a little timer to pause and then display the next record in the same location on the page. Like a slide show of text.

If I use the CSS position command the text is positioned in the same place but it just writes right over the previous record.  Is there a way to clear/delete content at a specific position on a page ....  or some other way of doing this?

答:
You want the display properties; specifically, display:none and display:block.  Start with the first row having display:block and the rest having display:none, then when the timer advances, switch the first to display:none and the second to display:block.

You probably want to handle this purely through a class.  Set all of the rows to display:none in CSS, then have a single row at a time use an "active" class or something similar which has display:block.

OwnerDisplayName: martinb

OwnerDisplayName: Xanthir


问:
PHP: Cast variable to null
I just stumbled upon a thing in the PHP manual that is new to me...

Casting a variable to null will remove the variable and unset its value. (Source)

Now I wonder how this can be done... I tried (null) and (NULL) but it seems to be interpreted as the value null, not the type null.
I know this question must sound ridiculous, but does somebody know how to cast to null?

答:
According to the Type casting section of the Type Juggling manual page, you can achieve this via...</p>

```<code>$varName = (unset)$varName;
</code>```

Title: PHP: Cast variable to null

Body:
According to the Type casting section of the Type Juggling manual page, you can achieve this via...

$varName = (unset)$varName;


答:
Using sets difference, and finding the index:

```<code>fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

missings = set(fruit_types) - set(fruits)
for missing in missings:
    print(fruit_types.index(missing))
</code>```

output:

```<code>1  # which is the index of the missing element in fruit_types
</code>```

Title: How to find the index of a missing element?

Body:
Using sets difference, and finding the index:

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

missings = set(fruit_types) - set(fruits)
for missing in missings:
    print(fruit_types.index(missing))

output:

1  # which is the index of the missing element in fruit_types


问:
Sails.js server request timeout
I am using sails.js  v0.10.5.

I have long processing controller action which takes more than 2 minutes to complete which causes the sails server to timeout. How can I overwrite this timeout duration and set it to my value say 10 minutes.Please specify in which file and what changes I need to make to increase the sails server timeout.

答:
My answer is pretty similar to the provided by Ryan, but I'll expand the example a bit more for clarity. Also I don't see the need for the dependency installation there.

TL;DR Add a custom middleware that amends req to increase the timeout

In /config/http.js

```<code>order: [
  'startRequestTimer',
  'cookieParser',
  'session',
  'myRequestLogger',
  'contentTypeCheck',
  'extendTimeout', // <--- The order is somewhat important, added it before the body is parsed without issue
  'bodyParser',
  'handleBodyParserError',
  'compress',
  'methodOverride',
  'poweredBy',
  '$custom',
  'router',
  'www',
  'favicon',
  '404',
  '500'
],

extendTimeout: function(req, res, next) {
  req.setTimeout(300 * 1000); // Increase the request timeout to 5 minutes

  return next();
},
// Other custom middleware
</code>```

Can also set req.setTimeout(0) if you don't want any timeout at all, but could be a bit risky.

This will set the timeout for all routes keep in mind. This can be overridden on a per route basis by simply setting req.setTimeout(<some timeout>) as the first line in the controller handling the route

Title: Sails.js server request timeout

Body:
My answer is pretty similar to the provided by Ryan, but I'll expand the example a bit more for clarity. Also I don't see the need for the dependency installation there.

TL;DR Add a custom middleware that amends req to increase the timeout

In /config/http.js

order: [
  'startRequestTimer',
  'cookieParser',
  'session',
  'myRequestLogger',
  'contentTypeCheck',
  'extendTimeout', // <--- The order is somewhat important, added it before the body is parsed without issue
  'bodyParser',
  'handleBodyParserError',
  'compress',
  'methodOverride',
  'poweredBy',
  '$custom',
  'router',
  'www',
  'favicon',
  '404',
  '500'
],

extendTimeout: function(req, res, next) {
  req.setTimeout(300 * 1000); // Increase the request timeout to 5 minutes

  return next();
},
// Other custom middleware

Can also set req.setTimeout(0) if you don't want any timeout at all, but could be a bit risky.

This will set the timeout for all routes keep in mind. This can be overridden on a per route basis by simply setting req.setTimeout(<some timeout>) as the first line in the controller handling the route


问:
How to eliminate Warning LNK4221?
I am working on a project using c++/windows forms (visual studio 2010), we have 4 projects:

1 project containing GUI windows forms {managed code} and this is the exe project

other 3 projects {non-managed code} and all are static libraries.

in the 4 projects we don`t use precompilied headers stdafx.h , and common language runtime support is the Pure MSIL Common Language Runtime Support (/clr:pure).

every project include the other 3 projects as additional include directories , and link library dependencies set to yes.

We have:

Warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library

This warning appeared for the 3 static libraries projects in the same object files (.NETFramework,Version=v4.0.AssemblyAttributes.obj).

We want to eliminate it, but after some search, most topics speak about the precompiled headers to be a reason while we don not use it.

Any new ideas about why this warning exist and how to eliminate it?

答: This was kind of just my particular problem but if your .cpp doesn't define any new functions or has empty bodies for constructor functions, you will get this warning. I used an initialization list for my constructor so the body was empty.</p>

Title: How to eliminate Warning LNK4221?


问:
Cannot change width and height of custom component in React-native?
I have a minimal custom stateless component like this:

```<code>const ViewBox = (props) => (
    <View style={ mainStyle : {backgroundColor: 'beige'} }>
        {props.children}
    </View>
)
export default ViewBox;
</code>```

so I want to import and use it inside another component.

```<code>export default class Test extends React.Component {

render() {
    return (
        <View style={styles.containerView} >
            <ViewBox style={styles.mainBox}>
              <Text style={[styles.boxTitle, {color: '#8F468C'}]}>Lorem ipsum...</Text>
            </ViewBox>
        </View>
    );
    }
}

const styles = {
  containerView: {
    flex: 1,
    marginTop: 50,
    alignItems: 'center',
    backgroundColor: 'brown',
  },
  mainBox: {
    flex: 1,
    width: 250,  //No effect ! ! !
    height: 250  //No effect ! ! !
  },
  boxTitle: {
    backgroundColor: 'pink',
    fontSize: 17,
    marginTop: 20
  }
};
</code>```

Here we have at least 2 inexplicable facts:

1) and more important the width and height of the ViewBox (or every custom component you want to use here) is totally out of control! Assigning numeric size or Flex values has no effect and ViewBox keeps the minimum width/height needed to render the inner Text.

2) Removing the root View (so the ViewBox became the root) ViewBox continue ignoring any size, but now it fills all the space available.... WHY???

All mentioned behavoirs occurs using a custom View (ViewBox in this case), instead if replace it with a normal View all works as expected.

I guess to know enough flex and UI best practices for React-native, but such two cases are not well covered by docs. Hope somebody can surprise me!

答:
This is actually how flexbox works:

Flex containers come with flexShrink: 1 by default meaning that they will shrink to their contents. Adding flexShrink: 0 changes that. You may need to use minWidth and minHeight with that instead.

The reason why it stretches is because there's nothing to tell it otherwise. Your container has the default alignItems: 'stretch' overwritten with alignItems: 'center' which shrinks its contents.

Have a look at the example code on Snack: https://snack.expo.io/B1VdUma1M

There's a really nice flexbox cheatsheet/playground that shows the behaviour at: https://yoksel.github.io/flex-cheatsheet/

Bear in mind React Native's implementation is slightly different.

Body:
I have a minimal custom stateless component like this:

const ViewBox = (props) => (
    <View style={ mainStyle : {backgroundColor: 'beige'} }>
        {props.children}
    </View>
)
export default ViewBox;

so I want to import and use it inside another component.

export default class Test extends React.Component {

render() {
    return (
        <View style={styles.containerView} >
            <ViewBox style={styles.mainBox}>
              <Text style={[styles.boxTitle, {color: '#8F468C'}]}>Lorem ipsum...</Text>
            </ViewBox>
        </View>
    );
    }
}

const styles = {
  containerView: {
    flex: 1,
    marginTop: 50,
    alignItems: 'center',
    backgroundColor: 'brown',
  },
  mainBox: {
    flex: 1,
    width: 250,  //No effect ! ! !
    height: 250  //No effect ! ! !
  },
  boxTitle: {
    backgroundColor: 'pink',
    fontSize: 17,
    marginTop: 20
  }
};

Here we have at least 2 inexplicable facts:

1) and more important the width and height of the ViewBox (or every custom component you want to use here) is totally out of control! Assigning numeric size or Flex values has no effect and ViewBox keeps the minimum width/height needed to render the inner Text.

2) Removing the root View (so the ViewBox became the root) ViewBox continue ignoring any size, but now it fills all the space available.... WHY???

All mentioned behavoirs occurs using a custom View (ViewBox in this case), instead if replace it with a normal View all works as expected.

I guess to know enough flex and UI best practices for React-native, but such two cases are not well covered by docs. Hope somebody can surprise me!