问:
Minimum bounding rectangle of polygon
Let's say we have a class/struct Point

```<code>class Point
{
 int x;
int y;
}
</code>```

and a class Polygon that contains list of Points

```<code>class Polygon
{
  List<Point> points;

  Path(List<Point> points)
  {
  //some implementation
  }
}
</code>```

I am interested in finding the Minimal bounding rectangle points of the Polygon(https://en.wikipedia.org/wiki/Minimum_bounding_rectangle).  The found minimal bounding rectangle sides might not be parallel to both axis , so I am trying to find an algorithm written in Java,C#,C++ .Can anyone propose or link such a solution, thanks!

答:
You can do this as follows:

Find the convex hull of the polygon points. A popular method is the Graham scan.

For each edge of the convex hull, find the minimum bounding rectangle that must have one side overlapping with that edge, so that the convex hull's edge is a subsegment of that rectangle's side.

Find the two perpendicular sides of the rectangle by walking along the convex hull vertices, and projecting the vertex to the first side, retaining the two that have all other projections between them. The final opposite side can be found in a similar manner. The vertices that lie on the rectangle, should be the starting point for when this step is executed again for the next edge on the convex hull (step 2).

Calculate the size of these rectangles, and retain the minimal one.

The complexity of this algorithm is determined by the first step, which is O(nlogn). The second step is O(n), as you have a selection of one edge and 3 vertices that rotates around the convex hull, visiting each edge once, and each vertex 3 times.

Title: Minimum bounding rectangle of polygon

Body:
Let's say we have a class/struct Point

class Point
{
 int x;
int y;
}

and a class Polygon that contains list of Points

class Polygon
{
  List<Point> points;

  Path(List<Point> points)
  {
  //some implementation
  }
}

I am interested in finding the Minimal bounding rectangle points of the Polygon(https://en.wikipedia.org/wiki/Minimum_bounding_rectangle).  The found minimal bounding rectangle sides might not be parallel to both axis , so I am trying to find an algorithm written in Java,C#,C++ .Can anyone propose or link such a solution, thanks!


来源: stackexchange

问:
How to map Postgres JSON data type in DTO and Aggentity class using Springboot and Hibernate
I have a ResponseDto class which looks like as below:

```<code>public static class HealthGoalsHighlight {

    @ApiModelProperty(value = "Total number of eligible users")
    private Long totalEligibleUsers;
    @ApiModelProperty(value = "Total number of registered users")
    private Long totalRegisteredUsers;
    @ApiModelProperty(value = "Total number of users with atleast one goal count")
    private Long totalUsersWithGoal;
    @ApiModelProperty(value = "Top goal name selected by user")
    private String topGoal;
    @ApiModelProperty(value = "Bottom goal name selected by user")
    private String bottomGoal;
  }
</code>```

This DTO was made based upon below table structure:

```<code>health_goals
(
  uid BIGSERIAL NOT NULL CONSTRAINT health_goals_pkey primary key,
  employer_key bigint not null,
  total_eligible_users bigint not null,
  total_registered_users bigint not null,
  total_users_with_goal bigint not null,
  top_goal_name varchar(255),
  bottom_goal_name varchar(255),
  created_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  created_by varchar(255),
  updated_by varchar(255)
);
</code>```

Now the table structure has been changed to as below:

```<code>health_goals
(
  uid BIGSERIAL NOT NULL CONSTRAINT health_goals_pkey primary key,
  employer_key bigint not null,
  health_goals_metric_value json null,
  created_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  created_by varchar(255),
  updated_by varchar(255)
);
</code>```

Basically now all these columns like total_eligible_users, total_registered_users, total_users_with_goal, top_goal_name, bottom_goal_name wil be consolidated to single columnhealth_goals_metric_value as a JSON data type.

How can I write the response DTO for JSON data type column. Also what changes needs to be done in my AggMapper class.

答:
Well one way is by using converter function. You can use the converter function to get values in same format.

Change your orm.xml something like below on your column definition

```<code><basic name="healthGoalsMetricValue">
                <column name="health_goals_metric_value" nullable="true"/>
                <convert converter="path.to.your.HealthGoalsMetricValueConverter"/>
            </basic>
</code>```

Or if you have java file

aggentity will have following entry

```<code>  @Convert(converter = HealthGoalsMetricValueConverter.class)
    private HealthGoalsHighlight healthGoalsHighlight ;
</code>```

and your class HealthGoalsMetricValue will look something like

//////////////////Edited converter class after comments

```<code>       import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;

@Converter
public class HealthGoalsMetricValueConverter implements AttributeConverter<HealthGoalsMetricValue, String> {

private final ObjectMapper mapper = new ObjectMapper();

//And then override like that
@Override
        public String convertToDatabaseColumn(HealthGoalsHighlight healthGoalsMetricValue) {

            try {
                json = mapper.writeValueAsString(healthGoalsMetricValue);
            } catch (JsonProcessingException exception) {
                throw new JsonProcessingException("Error occurred while object serialization", exception);
            }
            return json;
    }

 //And then override again
@Override
public HealthGoalsMetricValue  convertToEntityAttribute(String healthGoalsMetricValuestr ) {
    HealthGoalsMetricValue  healthGoalsMetricValue  = null;
    try {
        if (healthGoalsMetricValue != null) {
            healthGoalsMetricValue = mapper.readValue(healthGoalsMetricValuestr, HealthGoalsMetricValue.class);
        }
    } catch (Exception exception) {
        throw new Exception("Error occurred while object Deserialization", exception);
    }
    return healthGoalsMetricValue;
}
</code>```

This all will do the job for you.

ContentLicense: CC BY-SA 4.0

Body:
I have a ResponseDto class which looks like as below:

public static class HealthGoalsHighlight {

    @ApiModelProperty(value = "Total number of eligible users")
    private Long totalEligibleUsers;
    @ApiModelProperty(value = "Total number of registered users")
    private Long totalRegisteredUsers;
    @ApiModelProperty(value = "Total number of users with atleast one goal count")
    private Long totalUsersWithGoal;
    @ApiModelProperty(value = "Top goal name selected by user")
    private String topGoal;
    @ApiModelProperty(value = "Bottom goal name selected by user")
    private String bottomGoal;
  }

This DTO was made based upon below table structure:

health_goals
(
  uid BIGSERIAL NOT NULL CONSTRAINT health_goals_pkey primary key,
  employer_key bigint not null,
  total_eligible_users bigint not null,
  total_registered_users bigint not null,
  total_users_with_goal bigint not null,
  top_goal_name varchar(255),
  bottom_goal_name varchar(255),
  created_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  created_by varchar(255),
  updated_by varchar(255)
);

Now the table structure has been changed to as below:

health_goals
(
  uid BIGSERIAL NOT NULL CONSTRAINT health_goals_pkey primary key,
  employer_key bigint not null,
  health_goals_metric_value json null,
  created_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  created_by varchar(255),
  updated_by varchar(255)
);

Basically now all these columns like total_eligible_users, total_registered_users, total_users_with_goal, top_goal_name, bottom_goal_name wil be consolidated to single columnhealth_goals_metric_value as a JSON data type.

How can I write the response DTO for JSON data type column. Also what changes needs to be done in my AggMapper class.

Body:
Well one way is by using converter function. You can use the converter function to get values in same format.

Change your orm.xml something like below on your column definition

<basic name="healthGoalsMetricValue">
                <column name="health_goals_metric_value" nullable="true"/>
                <convert converter="path.to.your.HealthGoalsMetricValueConverter"/>
            </basic>

Or if you have java file

aggentity will have following entry

  @Convert(converter = HealthGoalsMetricValueConverter.class)
    private HealthGoalsHighlight healthGoalsHighlight ;

and your class HealthGoalsMetricValue will look something like

//////////////////Edited converter class after comments

       import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;

@Converter
public class HealthGoalsMetricValueConverter implements AttributeConverter<HealthGoalsMetricValue, String> {

private final ObjectMapper mapper = new ObjectMapper();

//And then override like that
@Override
        public String convertToDatabaseColumn(HealthGoalsHighlight healthGoalsMetricValue) {

            try {
                json = mapper.writeValueAsString(healthGoalsMetricValue);
            } catch (JsonProcessingException exception) {
                throw new JsonProcessingException("Error occurred while object serialization", exception);
            }
            return json;
    }

 //And then override again
@Override
public HealthGoalsMetricValue  convertToEntityAttribute(String healthGoalsMetricValuestr ) {
    HealthGoalsMetricValue  healthGoalsMetricValue  = null;
    try {
        if (healthGoalsMetricValue != null) {
            healthGoalsMetricValue = mapper.readValue(healthGoalsMetricValuestr, HealthGoalsMetricValue.class);
        }
    } catch (Exception exception) {
        throw new Exception("Error occurred while object Deserialization", exception);
    }
    return healthGoalsMetricValue;
}

This all will do the job for you.


问:
Show success or fail alert in AJAX JSP after insert statement
I'd need some help displaying a status msg to the user, when an insert is successful or not.

my ajax is like this

```<code><script>
function insertData(){
$.ajax({
url: "add.jsp",
type: "post",
dataType: "text",
data: {
userid:$('#userid').val(),
smeid:$('#smeid').val(),
weeks:$('#weeks').val(),
worktype:$('#worktype').val(),
comments1:$('#comments1').val(),
comments2:$('#comments2').val(),
comments3:$('#comments3').val(),
managerID:$('#managerID').val(),
success: function() {
    alert("success");
}
}
});
}
</script>
</code>```

My jsp page where the insertion happens is like this

```<code>// variables

try
{

// establish connection
Statement st=conn.createStatement();
int x=st.executeUpdate( // query );
if (x<1)
{
    out.println("false");
}
else
{
    out.println("true");
}
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
</code>```

I'd want to show alert when the insert has failed. How to return that from the jsp to ajax.

EDIT 1:

Tried the below addition for JSP:

```<code>String msg;
if (x > 0)
{
   msg ="true";//inserted
}
else
{
    msg = "false";//not inserted
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(msg);//this send back to ajax success function
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
</code>```

and below for ajax:

```<code><script>
function insertData(){
$.ajax({
url: "add.jsp",
type: "post",
dataType: "text",

data: {
userid:$('#userid').val(),
smeid:$('#smeid').val(),
weeks:$('#weeks').val(),
worktype:$('#worktype').val(),
comments1:$('#comments1').val(),
comments2:$('#comments2').val(),
comments3:$('#comments3').val(),
managerID:$('#managerID').val(),
success: function(data) {
    var values = $.trim(data); //triming value if there is any whitespaces
    alert(values);
        if (values == "true") {
      alert("Done inserted"); //show alert
    } else {
      alert("Sorry not inserted");
    }
  }

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

答:
You can just send some values back to ajax success and check that value against some condition depending on this show your alert.

So , your jsp will look like below :

```<code>String msg="";
if (x > 0)
{
   msg ="true";//inserted
}
else
{
    msg = "false";//not inserted
}
response.getWriter().write(msg);//this send back to ajax success function
</code>```

And your ajax success function will look like below :

```<code>function insertData() {
   $.ajax({
     url: "add.jsp",
     type: "post",
     dataType: "text",
     data: {
          userid: $('#userid').val(),
          smeid: $('#smeid').val(),
          weeks: $('#weeks').val(),
          worktype: $('#worktype').val(),
          comments1: $('#comments1').val(),
          comments2: $('#comments2').val(),
          comments3: $('#comments3').val(),
          managerID: $('#managerID').val()
        }, //close here
     success: function(data) {
          var values = $.trim(data); //triming value if there is any whitespaces
          alert(values);
          if (values == "true") {
            alert("Done inserted"); //show alert
          } else {
            alert("Sorry not inserted");
          }
        }
      });
    }
</code>```

Body:
I'd need some help displaying a status msg to the user, when an insert is successful or not.

my ajax is like this

My jsp page where the insertion happens is like this

// variables

try
{

// establish connection
Statement st=conn.createStatement();
int x=st.executeUpdate( // query );
if (x<1)
{
    out.println("false");
}
else
{
    out.println("true");
}
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}

I'd want to show alert when the insert has failed. How to return that from the jsp to ajax.

EDIT 1:

Tried the below addition for JSP:

String msg;
if (x > 0)
{
   msg ="true";//inserted
}
else
{
    msg = "false";//not inserted
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(msg);//this send back to ajax success function
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}

and below for ajax:

Body:
You can just send some values back to ajax success and check that value against some condition depending on this show your alert.

So , your jsp will look like below :

String msg="";
if (x > 0)
{
   msg ="true";//inserted
}
else
{
    msg = "false";//not inserted
}
response.getWriter().write(msg);//this send back to ajax success function

And your ajax success function will look like below :

function insertData() {
   $.ajax({
     url: "add.jsp",
     type: "post",
     dataType: "text",
     data: {
          userid: $('#userid').val(),
          smeid: $('#smeid').val(),
          weeks: $('#weeks').val(),
          worktype: $('#worktype').val(),
          comments1: $('#comments1').val(),
          comments2: $('#comments2').val(),
          comments3: $('#comments3').val(),
          managerID: $('#managerID').val()
        }, //close here
     success: function(data) {
          var values = $.trim(data); //triming value if there is any whitespaces
          alert(values);
          if (values == "true") {
            alert("Done inserted"); //show alert
          } else {
            alert("Sorry not inserted");
          }
        }
      });
    }


问:
Test an API Controller Symfony 4 || that was not configured to cascade persist operations for entity:
First of all, i'm worry about my english. I'm really sorry if you don't understand.

I work on a API Project to improve my skills in React and Symfony.

So I work with a Test Driven Developpement. My problem is that i use some Fixture to test.

My first route to get result is ok. But when i want POST , it's an other thing because i got 2 ManyTo Relation.

I use Liip\TestFixturesBundle\ for my fixtures;

This is my test function:

```<code>    public function testAPIProjectPOST(){
        $client = static::createClient();
        $fixtures = $this->loadFixtureFiles([
            __DIR__ . '/../Fixtures/DataBaseFixture.yaml'
        ]);
        $parameters = [
            'name' => "ProjectTestAPI",
            'description' => "First Project in POST",
            'difficulty' => 4,
            'skills' => [1],
            'owner' => 1
        ];
        $client->request('POST','/api/project',[],[],['CONTENT_TYPE'=>'application/json'],json_encode($parameters));
        $content = $client->getResponse();
        $this->assertResponseStatusCodeSame(Response::HTTP_CREATED);

    }
</code>```

I got these error :

```<code>A new entity was found through the relationship 'App\Entity\Project#skills' that was not configured to cascade persist operations for entity: App\Entity\Skill@00000000726fccc80000000059a1c5e2. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'App\Entity\Skill#__toString()' to get a clue.
 * A new entity was found through the relationship 'App\Entity\Project#owner' that was not configured to cascade persist operations for entity: App\Entity\User@00000000726fcd310000000059a1c5e2. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'App\Entity\User#__toString()' to get a clue. (500 Internal Server Error) -->
</code>```

Thank you a lot for your answers !

UPDATE : More code

Datafixture.yaml :

```<code>App\Entity\User:
  user{1..10}:
    username: user<current()>
    email: user<current()>\@domain.fr
    password: '0000'

App\Entity\Skill:
  skill{1..3}:
    name: skill<current()>

App\Entity\Project:
  project{1..10}:
    name: project<current()>
    description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean egestas id eros sit amet maximus. Donec fringilla diam et elementum ultricies.
    owner: '@user<current()>'
    difficulty: <numberBetween(1,5)>
    skills: ['@skill<numberBetween(1,3)>']

</code>```

PageController.php

```<code><?php

namespace App\Controller;

use App\Entity\Project;
use App\Repository\ProjectRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class ApiProjectController extends AbstractController
{
    /**
     * @Route("/api/project", name="api_project", methods={"GET"})
     */
    public function index(ProjectRepository $projectRepository)
    {
        return $this->json($projectRepository->findAll(),200,[],['groups'=>'project:read']);
    }

    /**
     * @Route("/api/project", name="api_project_store", methods={"POST"})
     */
    public function store(Request $request,SerializerInterface $serializer,EntityManagerInterface $em,ValidatorInterface $validator){
        $json = $request->getContent();
        try{
            $post = $serializer->deserialize($json, Project::class,'json');

            $errors = $validator->validate($post);

            if (count($errors)>0){
                return $this->json($errors,400);
            }

            $em->persist($post);
            $em->flush();

            return $this->json($post,201,[],['groups'=>'read']);
        }
        catch(NotEncodableValueException $e){
            return $this->json([
                'status'=>400,
                'message'=> $e->getMessage()
            ],400);
        }
    }
}

</code>```

答: I search again, but i don't know why my fixtures is'nt considered :/ If someone had a response ?</p>

Body:
First of all, i'm worry about my english. I'm really sorry if you don't understand.

I work on a API Project to improve my skills in React and Symfony.

So I work with a Test Driven Developpement. My problem is that i use some Fixture to test.

My first route to get result is ok. But when i want POST , it's an other thing because i got 2 ManyTo Relation.

I use Liip\TestFixturesBundle\ for my fixtures;

This is my test function:

    public function testAPIProjectPOST(){
        $client = static::createClient();
        $fixtures = $this->loadFixtureFiles([
            __DIR__ . '/../Fixtures/DataBaseFixture.yaml'
        ]);
        $parameters = [
            'name' => "ProjectTestAPI",
            'description' => "First Project in POST",
            'difficulty' => 4,
            'skills' => [1],
            'owner' => 1
        ];
        $client->request('POST','/api/project',[],[],['CONTENT_TYPE'=>'application/json'],json_encode($parameters));
        $content = $client->getResponse();
        $this->assertResponseStatusCodeSame(Response::HTTP_CREATED);

    }

I got these error :

A new entity was found through the relationship 'App\Entity\Project#skills' that was not configured to cascade persist operations for entity: App\Entity\Skill@00000000726fccc80000000059a1c5e2. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'App\Entity\Skill#__toString()' to get a clue.
 * A new entity was found through the relationship 'App\Entity\Project#owner' that was not configured to cascade persist operations for entity: App\Entity\User@00000000726fcd310000000059a1c5e2. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'App\Entity\User#__toString()' to get a clue. (500 Internal Server Error) -->

Thank you a lot for your answers !

UPDATE : More code

Datafixture.yaml :

App\Entity\User:
  user{1..10}:
    username: user<current()>
    email: user<current()>\@domain.fr
    password: '0000'

App\Entity\Skill:
  skill{1..3}:
    name: skill<current()>

App\Entity\Project:
  project{1..10}:
    name: project<current()>
    description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean egestas id eros sit amet maximus. Donec fringilla diam et elementum ultricies.
    owner: '@user<current()>'
    difficulty: <numberBetween(1,5)>
    skills: ['@skill<numberBetween(1,3)>']

PageController.php

<?php

namespace App\Controller;

use App\Entity\Project;
use App\Repository\ProjectRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class ApiProjectController extends AbstractController
{
    /**
     * @Route("/api/project", name="api_project", methods={"GET"})
     */
    public function index(ProjectRepository $projectRepository)
    {
        return $this->json($projectRepository->findAll(),200,[],['groups'=>'project:read']);
    }

    /**
     * @Route("/api/project", name="api_project_store", methods={"POST"})
     */
    public function store(Request $request,SerializerInterface $serializer,EntityManagerInterface $em,ValidatorInterface $validator){
        $json = $request->getContent();
        try{
            $post = $serializer->deserialize($json, Project::class,'json');

            $errors = $validator->validate($post);

            if (count($errors)>0){
                return $this->json($errors,400);
            }

            $em->persist($post);
            $em->flush();

            return $this->json($post,201,[],['groups'=>'read']);
        }
        catch(NotEncodableValueException $e){
            return $this->json([
                'status'=>400,
                'message'=> $e->getMessage()
            ],400);
        }
    }
}


问:
How to find the highest number of passenger of all round?
im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.</p>

```<code>#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int(turn);
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=get_on-get_off;
        stops[i]=total_passenger;
    }
    for(int i=0;i<turn;i++){
        if(stops[i]>stops[i+1]){
            highest_total=stops[i];
        }
    }
    cout<<highest_total<<endl;
    return 0;
}
</code>```

答:
The issue seems to be with int *stops = new int(turn). It will allocate memory for 1 integer.
Use int stops[turn] and your algorithm need to be modified.
stop[i] += total_passenger need to be used with some if-else.

Body:
im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.

#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int(turn);
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=get_on-get_off;
        stops[i]=total_passenger;
    }
    for(int i=0;i<turn;i++){
        if(stops[i]>stops[i+1]){
            highest_total=stops[i];
        }
    }
    cout<<highest_total<<endl;
    return 0;
}


问:
Function-wide exception handling in c++ - is it a bad style?
There is a try-catch thing about functions, which I think sometimes may be quite useful:

```<code>bool function()
try
{
    //do something
}
catch(exception_type & t)
{
   //do something
}
</code>```

So the first part of the question: is this style considered bad in general case?

And the concrete example I used this approach in:

We had project with quite a lot of code in c and c++. And there we had custom exception types (not std::exception derived). I needed to integrate XML library and cast all exception to our types. So, basically, the last step was to catch all exceptions from XML library and convert them.

Function before:

```<code>bool readEntity(...)
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
</code>```

after:

```<code>bool readEntity(...)
try
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
catch(XMLBaseException & ex)
{
    //create our exception and throw
}
</code>```

My thoughts went something like this: I clearly state my intentions to convert all exception derived from one type into custom type AND we keep our screen without horizontal scroll bar (cause horizontal scroll bars are bad).

Well, I actually was quite criticized for this approach as for non-clear one during code review.

So I'd like to hear you thoughts.

UPDATE: just to be clear: refactoring the function wasn't an option. And actually it was good written one.

答: There is a good discussion about the general uselessness of constructor/function try blocks at Herb Sutters GotW site.</p>

ContentLicense: CC BY-SA 2.5

Body:
There is a try-catch thing about functions, which I think sometimes may be quite useful:

bool function()
try
{
    //do something
}
catch(exception_type & t)
{
   //do something
}

So the first part of the question: is this style considered bad in general case?

And the concrete example I used this approach in:

We had project with quite a lot of code in c and c++. And there we had custom exception types (not std::exception derived). I needed to integrate XML library and cast all exception to our types. So, basically, the last step was to catch all exceptions from XML library and convert them.

Function before:

bool readEntity(...)
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}

after:

bool readEntity(...)
try
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
catch(XMLBaseException & ex)
{
    //create our exception and throw
}

My thoughts went something like this: I clearly state my intentions to convert all exception derived from one type into custom type AND we keep our screen without horizontal scroll bar (cause horizontal scroll bars are bad).

Well, I actually was quite criticized for this approach as for non-clear one during code review.

So I'd like to hear you thoughts.

UPDATE: just to be clear: refactoring the function wasn't an option. And actually it was good written one.

OwnerDisplayName: anon


问:
Check if a process is running or not on Windows?
I am trying to create a python script which I will later run as a service. Now I want to run a particular part of the code only when iTunes is running. I understand from some research that polling the entire command list and then searching for the application for that list is expensive.

I found out that processes on UNIX-based operating systems create a lock file to notify that a program is currently running, at which point we can use os.stat(location_of_file) to check if the file exists to determine if a program is running or not.

Is there a similar lock file created on Windows?

If not what are the various ways in Python by which we can determine if a process is running or not?

I am using python 2.7 and iTunes COM interface.

答:
According to the ewerybody post: https://stackoverflow.com/a/29275361/7530957

Multiple problems can arise:

Multiple processes with the same name

Name of the long process

The 'ewerybody's' code will not work if the process name is long. So there is a problem with this line:

```<code>last_line.lower().startswith(process_name.lower())
</code>```

Because last_line will be shorter than the process name.

So if you just want to know if a process/processes is/are active:

```<code>from subprocess import check_output

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    if check_output(call).splitlines()[3:]:
        return True
</code>```

Instead for all the information of a process/processes

```<code>from subprocess import check_output

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    processes = []
    for process in check_output(call).splitlines()[3:]:
        process = process.decode()
        processes.append(process.split())
    return processes
</code>```

Body:
According to the ewerybody post: https://stackoverflow.com/a/29275361/7530957

Multiple problems can arise:

Multiple processes with the same name

Name of the long process

The 'ewerybody's' code will not work if the process name is long. So there is a problem with this line:

last_line.lower().startswith(process_name.lower())

Because last_line will be shorter than the process name.

So if you just want to know if a process/processes is/are active:

from subprocess import check_output

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    if check_output(call).splitlines()[3:]:
        return True

Instead for all the information of a process/processes

from subprocess import check_output

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    processes = []
    for process in check_output(call).splitlines()[3:]:
        process = process.decode()
        processes.append(process.split())
    return processes


问:
RegEx to match stuff between parentheses
I'm having a tough time getting this to work. I have a string like:

```<code>something/([0-9])/([a-z])
</code>```

And I need regex or a method of getting each match between the parentheses and return an array of matches like:

```<code>[
  [0-9],
  [a-z]
]
</code>```

The regex I'm using is /\((.+)\)/ which does seem to match the right thing if there is only one set of parenthesis.

How can I get an array like above using any RegExp method in JavaScript? I need to return just that array because the returned items in the array will be looped through to create a URL routing scheme.

答:
If s is your string:</p>

```<code>s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
 .replace(/\)[^(]*$/, "") // trim everything after last parenthesis
 .split(/\)[^(]*\(/);      // split between parenthesis
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having a tough time getting this to work. I have a string like:

something/([0-9])/([a-z])

And I need regex or a method of getting each match between the parentheses and return an array of matches like:

[
  [0-9],
  [a-z]
]

The regex I'm using is /\((.+)\)/ which does seem to match the right thing if there is only one set of parenthesis.

How can I get an array like above using any RegExp method in JavaScript? I need to return just that array because the returned items in the array will be looped through to create a URL routing scheme.

Body:
If s is your string:

s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
 .replace(/\)[^(]*$/, "") // trim everything after last parenthesis
 .split(/\)[^(]*\(/);      // split between parenthesis


问:
JavaScript output of a string instead of undefined?
I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?</p>

```<code>var greet = function(name) {
   let  first = String(name. charAt(0). toUpperCase());
    let second = String(name.slice(1));

    console.log('Hello ' + first + second + '!');
    }
</code>```

答:
The console will print the result of evaluating an expression. You can notice if you set

let name = 'john'

it will print undefined in the very next line.
That is also happening here. First it is printing your value, then it print undefined.

Body:
I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?

var greet = function(name) {
   let  first = String(name. charAt(0). toUpperCase());
    let second = String(name.slice(1));

    console.log('Hello ' + first + second + '!');
    }


问:
Mockito in spring boot does not mock object
I have a simple test case for which I am using Mockito in spring boot application.

userOperation.java

```<code>...
@Autowired
Validator nameValidator;

private boolean userOperation(String name) {
    NameStats nameStats = nameValidator.validate(name);
    if (!nameStats.isSuccess()) {
        throw new Exception();
    }
    return true;
}
...
</code>```

Validator.java

```<code>public NameStats validate(String name)
{
    NameStats nameStats = new NameStats();
    // code goes here
    return nameStats;
}
</code>```

testCase.java

```<code>...
@SpringBootTest
@RunWith(SpringRunner.class)
public class ImportFileOperationTest {

    @Mock
    Validator nameValidator;

    @Mock
    NameStats nameStats;

    @InjectMocks
    UserOperation operation;

    @Test
    public void  ConnectorDelegate0Test() {
        Mockito.when(nameValidator.validate(any(String.class))).thenReturn(nameStats);
        Mockito.when(nameStats.isSuccess()).thenReturn(true);
        operation.userOperation(restConsumerRequest);
    }

}
...
</code>```

Error :

For the above test case, I am getting NullPointerException.
While tracing I found out that below line of code in test returns the null value.

```<code>Mockito.when(nameValidator.validate(any(String.class))).thenReturn(nameStats);
</code>```

Because of the null value, when it tries to call nameStats.isSuccess() it is throwing nullpointexception even I have mocked the response to this function as true.

Question :
1. Am I mocking the response right way?
2. Why the mocking function returns the null object?

Update :

testCase.java

```<code>@SpringBootTest
@RunWith(SpringRunner.class)
public class ImportFileOperationTest {

    @MockBean
    Validator nameValidator;

    NameStats nameStats;

    @InjectMocks
    @Resource
    UserOperation operation;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void  ConnectorDelegate0Test() {
        nameStats = new nameStats();
        Mockito.when(nameValidator.validate(any(String.class))).thenReturn(nameStats);
        Mockito.when(nameStats.isSuccess()).thenReturn(true);
        operation.userOperation(restConsumerRequest);
    }

}
</code>```

I tried to create the object nameStats manually and expected validate function to return that object but still, it returns null.

Any help would be appreciated.

答:
Had a similar problem after upgrade to Spring Boot 2.
The reason is explained here https://javadoc.io/static/org.mockito/mockito-core/3.3.3/org/mockito/ArgumentMatchers.html#any-java.lang.Class-

Since Mockito 2.1.0, only allow non-null instance of , thus null is not anymore a valid value.

So mock returns null, or empty list, because calls were set with anyString(), and object passed was null. To match value or null, use matcher any().

Body:
I have a simple test case for which I am using Mockito in spring boot application.

userOperation.java

...
@Autowired
Validator nameValidator;

private boolean userOperation(String name) {
    NameStats nameStats = nameValidator.validate(name);
    if (!nameStats.isSuccess()) {
        throw new Exception();
    }
    return true;
}
...

Validator.java

public NameStats validate(String name)
{
    NameStats nameStats = new NameStats();
    // code goes here
    return nameStats;
}

testCase.java

...
@SpringBootTest
@RunWith(SpringRunner.class)
public class ImportFileOperationTest {

    @Mock
    Validator nameValidator;

    @Mock
    NameStats nameStats;

    @InjectMocks
    UserOperation operation;

    @Test
    public void  ConnectorDelegate0Test() {
        Mockito.when(nameValidator.validate(any(String.class))).thenReturn(nameStats);
        Mockito.when(nameStats.isSuccess()).thenReturn(true);
        operation.userOperation(restConsumerRequest);
    }

}
...

Error :

For the above test case, I am getting NullPointerException.
While tracing I found out that below line of code in test returns the null value.

Mockito.when(nameValidator.validate(any(String.class))).thenReturn(nameStats);

Because of the null value, when it tries to call nameStats.isSuccess() it is throwing nullpointexception even I have mocked the response to this function as true.

Question :
1. Am I mocking the response right way?
2. Why the mocking function returns the null object?

Update :

testCase.java

@SpringBootTest
@RunWith(SpringRunner.class)
public class ImportFileOperationTest {

    @MockBean
    Validator nameValidator;

    NameStats nameStats;

    @InjectMocks
    @Resource
    UserOperation operation;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void  ConnectorDelegate0Test() {
        nameStats = new nameStats();
        Mockito.when(nameValidator.validate(any(String.class))).thenReturn(nameStats);
        Mockito.when(nameStats.isSuccess()).thenReturn(true);
        operation.userOperation(restConsumerRequest);
    }

}

I tried to create the object nameStats manually and expected validate function to return that object but still, it returns null.

Any help would be appreciated.


问:
How to only close TopLevel window in Python Tkinter?
Use the Python Tkinter , create a sub-panel (TopLevel) to show something and get user input, after user inputed, clicked the "EXIT" found the whole GUI (main panel) also destory.
How to only close the toplevel window?</p>

```<code>from tkinter import *

lay=[]
root = Tk()
root.geometry('300x400+100+50')

def exit_btn():
    top = lay[0]
    top.quit()
    top.destroy()

def create():
    top = Toplevel()
    lay.append(top)

    top.title("Main Panel")
    top.geometry('500x500+100+450')
    msg = Message(top, text="Show on Sub-panel",width=100)
    msg.pack()

    btn = Button(top,text='EXIT',command=exit_btn)
    btn.pack()

Button(root, text="Click me,Create a sub-panel", command=create).pack()
mainloop()
</code>```

答:
you can use lambda function with the command it's better than the normal function for your work

ex)

btn = Button(top,text='EXIT',command=exit_btn)

change the exit_btn to lambda :top.destroy()

Body:
Use the Python Tkinter , create a sub-panel (TopLevel) to show something and get user input, after user inputed, clicked the "EXIT" found the whole GUI (main panel) also destory.
How to only close the toplevel window?

from tkinter import *

lay=[]
root = Tk()
root.geometry('300x400+100+50')

def exit_btn():
    top = lay[0]
    top.quit()
    top.destroy()

def create():
    top = Toplevel()
    lay.append(top)

    top.title("Main Panel")
    top.geometry('500x500+100+450')
    msg = Message(top, text="Show on Sub-panel",width=100)
    msg.pack()

    btn = Button(top,text='EXIT',command=exit_btn)
    btn.pack()

Button(root, text="Click me,Create a sub-panel", command=create).pack()
mainloop()


问:
Python: words replacing in huge text
I have a huge text and a list of words ~10K.
What is the fastest way in Python to replace all this words in text with some other word?

EDIT:
Text size >1Gb, text is human written, and "extremely tokenized" (any runs of alphanumeric characters and any other single symbols was splitted into new tokens)

a number of words >10K, each word frequency in text is 1
the replacement word is same in all replacements.
Python 2.5-2.7

答:
The fastest method, if you have enough memory, may be to read the text as a string and use regex to search for and perform the replacements:

```<code>def replace(matched):
    # Matched.group(0) is the word that was found
    # Return the replacement
    return "REPLACEMENT"

# The \b ensure that only whole words are matched.
text = re.sub(r"\b(%s)\b" % "|".join(words), replace, text)
</code>```

If you don't have the memory, try doing it in chunks, perhaps:

```<code># Read a chunk and a line to ensure that you're not truncating a word.
chunk = text_file.read(1024 ** 2) + text_file.readline()
</code>```

Title: Python: words replacing in huge text

Body:
The fastest method, if you have enough memory, may be to read the text as a string and use regex to search for and perform the replacements:

def replace(matched):
    # Matched.group(0) is the word that was found
    # Return the replacement
    return "REPLACEMENT"

# The \b ensure that only whole words are matched.
text = re.sub(r"\b(%s)\b" % "|".join(words), replace, text)

If you don't have the memory, try doing it in chunks, perhaps:

# Read a chunk and a line to ensure that you're not truncating a word.
chunk = text_file.read(1024 ** 2) + text_file.readline()


问:
Boost variant with custom type failing when using custom visitor (derived from boost::static_visitor)
I am experimenting with boost::variant and printing with standard types like the below, works.

```<code>typedef boost::variant<int, std::string> myVariant;

myVariant my;
my = "Hello";
std::cout << my << endl;
</code>```

But when I introduced custom type

```<code>struct MyStructTag
{
   uint32_t ver;
   double kind;
   std::string type;
};

typedef boost::variant<MyStructTag, std::string> myVariant;
</code>```

It threw the following error but couldn't understand it completely.

```<code>main.cpp: In instantiation of ‘std::ostream& test_variant::custom_ostream::operator()(const T&) const [with T = test_variant::MyStructTag; std::ostream = std::basic_ostream<char>]’:
v_1_55_0/boost/variant/variant.hpp:938:32:   required from ‘boost::detail::variant::invoke_visitor<Visitor>::result_type boost::detail::variant::invoke_visitor<Visitor>::internal_visit(T&, int) [with T = const test_variant::MyStructTag; Visitor = const test_variant::custom_ostream; boost::detail::variant::invoke_visitor<Visitor>::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:113:9:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl_invoke_impl(int, Visitor&, VoidPtrCV, T*, mpl_::true_) [with Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; VoidPtrCV = const void*; T = test_variant::MyStructTag; typename Visitor::result_type = std::basic_ostream<char>&; mpl_::true_ = mpl_::bool_<true>]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:156:9:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl_invoke(int, Visitor&, VoidPtrCV, T*, NoBackupFlag, int) [with Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; VoidPtrCV = const void*; T = test_variant::MyStructTag; NoBackupFlag = boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::has_fallback_type_; typename Visitor::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:237:5:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl(int, int, Visitor&, VoidPtrCV, mpl_::false_, NoBackupFlag, Which*, step0*) [with Which = mpl_::int_<0>; step0 = boost::detail::variant::visitation_impl_step<boost::mpl::l_iter<boost::mpl::l_item<mpl_::long_<2l>, test_variant::MyStructTag, boost::mpl::l_item<mpl_::long_<1l>, std::basic_string<char>, boost::mpl::l_end> > >, boost::mpl::l_iter<boost::mpl::l_end> >; Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; VoidPtrCV = const void*; NoBackupFlag = boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::has_fallback_type_; typename Visitor::result_type = std::basic_ostream<char>&; mpl_::false_ = mpl_::bool_<false>]’
v_1_55_0/boost/variant/variant.hpp:2237:13:   required from ‘static typename Visitor::result_type boost::variant<T0, TN>::internal_apply_visitor_impl(int, int, Visitor&, VoidPtrCV) [with Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; VoidPtrCV = const void*; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/variant.hpp:2259:13:   required from ‘typename Visitor::result_type boost::variant<T0, TN>::internal_apply_visitor(Visitor&) const [with Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/variant.hpp:2281:52:   required from ‘typename Visitor::result_type boost::variant<T0, TN>::apply_visitor(Visitor&) const [with Visitor = const test_variant::custom_ostream; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/detail/apply_visitor_unary.hpp:74:43:   required from ‘typename Visitor::result_type boost::apply_visitor(const Visitor&, Visitable&) [with Visitor = test_variant::custom_ostream; Visitable = const boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >; typename Visitor::result_type = std::basic_ostream<char>&]’
main.cpp:34:59:   required from here
main.cpp:23:21: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
          return os_ << val;
                     ^
In file included from /usr/include/c++/4.8.2/iostream:39:0,
                 from main.cpp:1:
/usr/include/c++/4.8.2/ostream:602:5: error:   initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = test_variant::MyStructTag]’
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
     ^
In file included from v_1_55_0/boost/variant/variant.hpp:2325:0,
                 from v_1_55_0/boost/variant.hpp:17,
                 from main.cpp:2:
v_1_55_0/boost/variant/detail/variant_io.hpp: In instantiation of ‘void boost::detail::variant::printer<OStream>::operator()(const T&) const [with T = test_variant::MyStructTag; OStream = std::basic_ostream<char>]’:
v_1_55_0/boost/variant/variant.hpp:938:32:   required from ‘boost::detail::variant::invoke_visitor<Visitor>::result_type boost::detail::variant::invoke_visitor<Visitor>::internal_visit(T&, int) [with T = const test_variant::MyStructTag; Visitor = boost::detail::variant::printer<std::basic_ostream<char> >; boost::detail::variant::invoke_visitor<Visitor>::result_type = void]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:113:9:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl_invoke_impl(int, Visitor&, VoidPtrCV, T*, mpl_::true_) [with Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; VoidPtrCV = const void*; T = test_variant::MyStructTag; typename Visitor::result_type = void; mpl_::true_ = mpl_::bool_<true>]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:156:9:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl_invoke(int, Visitor&, VoidPtrCV, T*, NoBackupFlag, int) [with Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; VoidPtrCV = const void*; T = test_variant::MyStructTag; NoBackupFlag = boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::has_fallback_type_; typename Visitor::result_type = void]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:237:5:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl(int, int, Visitor&, VoidPtrCV, mpl_::false_, NoBackupFlag, Which*, step0*) [with Which = mpl_::int_<0>; step0 = boost::detail::variant::visitation_impl_step<boost::mpl::l_iter<boost::mpl::l_item<mpl_::long_<2l>, test_variant::MyStructTag, boost::mpl::l_item<mpl_::long_<1l>, std::basic_string<char>, boost::mpl::l_end> > >, boost::mpl::l_iter<boost::mpl::l_end> >; Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; VoidPtrCV = const void*; NoBackupFlag = boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::has_fallback_type_; typename Visitor::result_type = void; mpl_::false_ = mpl_::bool_<false>]’
v_1_55_0/boost/variant/variant.hpp:2237:13:   required from ‘static typename Visitor::result_type boost::variant<T0, TN>::internal_apply_visitor_impl(int, int, Visitor&, VoidPtrCV) [with Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; VoidPtrCV = const void*; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = void]’
v_1_55_0/boost/variant/variant.hpp:2259:13:   required from ‘typename Visitor::result_type boost::variant<T0, TN>::internal_apply_visitor(Visitor&) const [with Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = void]’
v_1_55_0/boost/variant/variant.hpp:2281:52:   required from ‘typename Visitor::result_type boost::variant<T0, TN>::apply_visitor(Visitor&) const [with Visitor = boost::detail::variant::printer<std::basic_ostream<char> >; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = void]’
v_1_55_0/boost/variant/detail/variant_io.hpp:88:5:   required from ‘std::basic_ostream<_CharT, _Traits>& boost::operator<<(std::basic_ostream<_CharT, _Traits>&, const boost::variant<U0, UN ...>&) [with E = char; T = std::char_traits<char>; U0 = test_variant::MyStructTag; UN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}]’
main.cpp:47:17:   required from here
v_1_55_0/boost/variant/detail/variant_io.hpp:64:14: error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’
         out_ << operand;
</code>```

Full code

```<code>#include <iostream>
#include <boost/variant.hpp>
#include <cstdint>
namespace test_variant {
   struct MyStructTag
   {
     uint32_t ver;
     double kind;
     std::string type;
   };

   typedef boost::variant<MyStructTag, std::string> myVariant;

   struct custom_ostream : public boost::static_visitor<std::ostream&>
   {
      std::ostream& os_;

      custom_ostream(std::ostream& os) : os_(os) {}
#if 1
      template <typename T>
      std::ostream& operator()(T const& val) const
      {
         return os_ << val;
      }
#else
      std::ostream& operator()(MyStructTag const& val) const
      {
         return os_ << val.type;
      }
#endif

      friend std::ostream& operator<<(std::ostream& os, myVariant const& v)
      {
         return boost::apply_visitor(custom_ostream{os}, v);
      }
  };

using namespace test_variant;

int main(int argc, char* agrv[])
{
   myVariant my;

   my = "test";
   std::cout << my << std::endl;

   return 0;
}
</code>```

Code is compiled with :

```<code>g++ --std=c++11 -o main -Iv_1_55_0/ main.cpp
</code>```

Tried singling out visiting custom boundedtype with no luck.

Any inputs will be helpful.

答:
The reason for the error is that operator<<(std::ostream& os, myVariant const& v) is not found via ADL.

Argument-dependent lookup is a procedure that involves extending the set of namespaces that are examined in the name lookup for an unqualified function call, that std::cout << my is an example of. That is, you don't spell std::cout.operator<<(my), nor std::operator<<(std::cout, my).

ADL builds a set of associated namespaces, where the name of the function (here operator<<) can potentially be found. These namespaces could be, e.g.:

the namespace of the type of an argument,

the namespace of the type of a template argument of the type of an argument.

The arguments to operator<< are:

std::cout, which lives in the std namespace,

boost::variant, which lives in the boost namespace.

In addition to these namespaces, also the namespaces of template arguments are considered, and these are:

MyStructTag, which lives in the test_variant namespace,

std::string, which lives in the std namespace.

On top of that, ADL considers associated classes for arguments that are instantiations of class templates, and here these are:

std::string,

MyStructTag.

At this point, operator<<(std::ostream& os, myVariant const& v) could be found via ADL, if it were declared inside, e.g., the test_variant namespace itself. However, that function is declared and defined inside custom_ostream, and for friend functions declared in classes, they are not visible to ADL unless that class is an associated class. Since custom_ostream is not in the set of associated classes, the lookup fails to find operator<< overload matching the call arguments.

In order to fix that, define operator<< in the test_variant namespace itself, and inside custom_ostream just leave a friend declaration alone.

DEMO

Body:
I am experimenting with boost::variant and printing with standard types like the below, works.

typedef boost::variant<int, std::string> myVariant;

myVariant my;
my = "Hello";
std::cout << my << endl;

But when I introduced custom type

struct MyStructTag
{
   uint32_t ver;
   double kind;
   std::string type;
};

typedef boost::variant<MyStructTag, std::string> myVariant;

It threw the following error but couldn't understand it completely.

main.cpp: In instantiation of ‘std::ostream& test_variant::custom_ostream::operator()(const T&) const [with T = test_variant::MyStructTag; std::ostream = std::basic_ostream<char>]’:
v_1_55_0/boost/variant/variant.hpp:938:32:   required from ‘boost::detail::variant::invoke_visitor<Visitor>::result_type boost::detail::variant::invoke_visitor<Visitor>::internal_visit(T&, int) [with T = const test_variant::MyStructTag; Visitor = const test_variant::custom_ostream; boost::detail::variant::invoke_visitor<Visitor>::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:113:9:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl_invoke_impl(int, Visitor&, VoidPtrCV, T*, mpl_::true_) [with Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; VoidPtrCV = const void*; T = test_variant::MyStructTag; typename Visitor::result_type = std::basic_ostream<char>&; mpl_::true_ = mpl_::bool_<true>]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:156:9:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl_invoke(int, Visitor&, VoidPtrCV, T*, NoBackupFlag, int) [with Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; VoidPtrCV = const void*; T = test_variant::MyStructTag; NoBackupFlag = boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::has_fallback_type_; typename Visitor::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:237:5:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl(int, int, Visitor&, VoidPtrCV, mpl_::false_, NoBackupFlag, Which*, step0*) [with Which = mpl_::int_<0>; step0 = boost::detail::variant::visitation_impl_step<boost::mpl::l_iter<boost::mpl::l_item<mpl_::long_<2l>, test_variant::MyStructTag, boost::mpl::l_item<mpl_::long_<1l>, std::basic_string<char>, boost::mpl::l_end> > >, boost::mpl::l_iter<boost::mpl::l_end> >; Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; VoidPtrCV = const void*; NoBackupFlag = boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::has_fallback_type_; typename Visitor::result_type = std::basic_ostream<char>&; mpl_::false_ = mpl_::bool_<false>]’
v_1_55_0/boost/variant/variant.hpp:2237:13:   required from ‘static typename Visitor::result_type boost::variant<T0, TN>::internal_apply_visitor_impl(int, int, Visitor&, VoidPtrCV) [with Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; VoidPtrCV = const void*; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/variant.hpp:2259:13:   required from ‘typename Visitor::result_type boost::variant<T0, TN>::internal_apply_visitor(Visitor&) const [with Visitor = boost::detail::variant::invoke_visitor<const test_variant::custom_ostream>; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/variant.hpp:2281:52:   required from ‘typename Visitor::result_type boost::variant<T0, TN>::apply_visitor(Visitor&) const [with Visitor = const test_variant::custom_ostream; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = std::basic_ostream<char>&]’
v_1_55_0/boost/variant/detail/apply_visitor_unary.hpp:74:43:   required from ‘typename Visitor::result_type boost::apply_visitor(const Visitor&, Visitable&) [with Visitor = test_variant::custom_ostream; Visitable = const boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >; typename Visitor::result_type = std::basic_ostream<char>&]’
main.cpp:34:59:   required from here
main.cpp:23:21: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
          return os_ << val;
                     ^
In file included from /usr/include/c++/4.8.2/iostream:39:0,
                 from main.cpp:1:
/usr/include/c++/4.8.2/ostream:602:5: error:   initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = test_variant::MyStructTag]’
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
     ^
In file included from v_1_55_0/boost/variant/variant.hpp:2325:0,
                 from v_1_55_0/boost/variant.hpp:17,
                 from main.cpp:2:
v_1_55_0/boost/variant/detail/variant_io.hpp: In instantiation of ‘void boost::detail::variant::printer<OStream>::operator()(const T&) const [with T = test_variant::MyStructTag; OStream = std::basic_ostream<char>]’:
v_1_55_0/boost/variant/variant.hpp:938:32:   required from ‘boost::detail::variant::invoke_visitor<Visitor>::result_type boost::detail::variant::invoke_visitor<Visitor>::internal_visit(T&, int) [with T = const test_variant::MyStructTag; Visitor = boost::detail::variant::printer<std::basic_ostream<char> >; boost::detail::variant::invoke_visitor<Visitor>::result_type = void]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:113:9:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl_invoke_impl(int, Visitor&, VoidPtrCV, T*, mpl_::true_) [with Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; VoidPtrCV = const void*; T = test_variant::MyStructTag; typename Visitor::result_type = void; mpl_::true_ = mpl_::bool_<true>]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:156:9:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl_invoke(int, Visitor&, VoidPtrCV, T*, NoBackupFlag, int) [with Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; VoidPtrCV = const void*; T = test_variant::MyStructTag; NoBackupFlag = boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::has_fallback_type_; typename Visitor::result_type = void]’
v_1_55_0/boost/variant/detail/visitation_impl.hpp:237:5:   required from ‘typename Visitor::result_type boost::detail::variant::visitation_impl(int, int, Visitor&, VoidPtrCV, mpl_::false_, NoBackupFlag, Which*, step0*) [with Which = mpl_::int_<0>; step0 = boost::detail::variant::visitation_impl_step<boost::mpl::l_iter<boost::mpl::l_item<mpl_::long_<2l>, test_variant::MyStructTag, boost::mpl::l_item<mpl_::long_<1l>, std::basic_string<char>, boost::mpl::l_end> > >, boost::mpl::l_iter<boost::mpl::l_end> >; Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; VoidPtrCV = const void*; NoBackupFlag = boost::variant<test_variant::MyStructTag, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::has_fallback_type_; typename Visitor::result_type = void; mpl_::false_ = mpl_::bool_<false>]’
v_1_55_0/boost/variant/variant.hpp:2237:13:   required from ‘static typename Visitor::result_type boost::variant<T0, TN>::internal_apply_visitor_impl(int, int, Visitor&, VoidPtrCV) [with Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; VoidPtrCV = const void*; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = void]’
v_1_55_0/boost/variant/variant.hpp:2259:13:   required from ‘typename Visitor::result_type boost::variant<T0, TN>::internal_apply_visitor(Visitor&) const [with Visitor = boost::detail::variant::invoke_visitor<boost::detail::variant::printer<std::basic_ostream<char> > >; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = void]’
v_1_55_0/boost/variant/variant.hpp:2281:52:   required from ‘typename Visitor::result_type boost::variant<T0, TN>::apply_visitor(Visitor&) const [with Visitor = boost::detail::variant::printer<std::basic_ostream<char> >; T0_ = test_variant::MyStructTag; TN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; typename Visitor::result_type = void]’
v_1_55_0/boost/variant/detail/variant_io.hpp:88:5:   required from ‘std::basic_ostream<_CharT, _Traits>& boost::operator<<(std::basic_ostream<_CharT, _Traits>&, const boost::variant<U0, UN ...>&) [with E = char; T = std::char_traits<char>; U0 = test_variant::MyStructTag; UN = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}]’
main.cpp:47:17:   required from here
v_1_55_0/boost/variant/detail/variant_io.hpp:64:14: error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’
         out_ << operand;

Full code

#include <iostream>
#include <boost/variant.hpp>
#include <cstdint>
namespace test_variant {
   struct MyStructTag
   {
     uint32_t ver;
     double kind;
     std::string type;
   };

   typedef boost::variant<MyStructTag, std::string> myVariant;

   struct custom_ostream : public boost::static_visitor<std::ostream&>
   {
      std::ostream& os_;

      custom_ostream(std::ostream& os) : os_(os) {}
#if 1
      template <typename T>
      std::ostream& operator()(T const& val) const
      {
         return os_ << val;
      }
#else
      std::ostream& operator()(MyStructTag const& val) const
      {
         return os_ << val.type;
      }
#endif

      friend std::ostream& operator<<(std::ostream& os, myVariant const& v)
      {
         return boost::apply_visitor(custom_ostream{os}, v);
      }
  };

using namespace test_variant;

int main(int argc, char* agrv[])
{
   myVariant my;

   my = "test";
   std::cout << my << std::endl;

   return 0;
}

Code is compiled with :

g++ --std=c++11 -o main -Iv_1_55_0/ main.cpp

Tried singling out visiting custom boundedtype with no luck.

Any inputs will be helpful.


问:
Find whether Esc key is pressed in resizing operation (MouseLeftButtonDown+MouseMove)
In my WPF application, I have to find whether "Esc" key is pressed or not in MouseDown and MouseMove event (i.e. resizing operation).

I have tried below code in MouseMove event:

```<code>isEscapePressed = Keyboard.IsKeyDown(Key.Escape);
</code>```

but isEscapePressed is true, when "Esc" key is in still holding state only. otherwise it is false.

I have tried to use OnKeyDown and OnPreviewKeyDown events also. but these are not triggered when mouse left button is in pressed state.

in my app, I am using ContentControl inside the Border and using MouseMove and MouseLeftButtonDown events of Border for resizing.

```<code><Border>
   <ContentControl></ContentControl>
</Border>
</code>```

Please give any idea for this case.

答:
Maybe you can used following:</p>

```<code>  private bool _isEscapePressed = false;
  private void MouseMoveEventHandler(object sender, System.Windows.Input.MouseEventArgs e)
  {

     if (!_isEscapePressed && Keyboard.IsKeyDown(Key.Escape))
     {
        _isEscapePressed = true;

        // Code for Esc pressed down

     }
     else if (_isEscapePressed && !Keyboard.IsKeyDown(Key.Escape))
     {
        _isEscapePressed = false;

        // Code for Esc released

     }

     // Mouse move code

  }
</code>```

Body:
In my WPF application, I have to find whether "Esc" key is pressed or not in MouseDown and MouseMove event (i.e. resizing operation).

I have tried below code in MouseMove event:

isEscapePressed = Keyboard.IsKeyDown(Key.Escape);

but isEscapePressed is true, when "Esc" key is in still holding state only. otherwise it is false.

I have tried to use OnKeyDown and OnPreviewKeyDown events also. but these are not triggered when mouse left button is in pressed state.

in my app, I am using ContentControl inside the Border and using MouseMove and MouseLeftButtonDown events of Border for resizing.

<Border>
   <ContentControl></ContentControl>
</Border>

Please give any idea for this case.

Body:
Maybe you can used following:

  private bool _isEscapePressed = false;
  private void MouseMoveEventHandler(object sender, System.Windows.Input.MouseEventArgs e)
  {

     if (!_isEscapePressed && Keyboard.IsKeyDown(Key.Escape))
     {
        _isEscapePressed = true;

        // Code for Esc pressed down

     }
     else if (_isEscapePressed && !Keyboard.IsKeyDown(Key.Escape))
     {
        _isEscapePressed = false;

        // Code for Esc released

     }

     // Mouse move code

  }


问:
Make CSS Drop Down Menu 2 Columns
I currently have a CSS

 dropdown menu that uses the following code.  Unfortunately I want the sub menus to display in 2 columns as there are about 16 items in that submenu.  Does anyone know how to use the following code to make this drop down menu 2 columns?

.menu {
  border: none;
  border: 0px;
  margin: 0px;
  padding: 0px;
  font: 67.5% "Lucida Sans Unicode", "Bitstream Vera Sans", "Trebuchet Unicode MS", "Lucida Grande", Verdana, Helvetica, sans-serif;
  font-size: 18px;
  font-weight: bold;
}

.menu ul {
  background: #006633;
  height: 35px;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  float: left;
  padding: 0px;
}

.menu li a {
  background: #006633 url("../images/seperator.gif") bottom right no-repeat;
  color: #ffffff;
  display: block;
  font-weight: normal;
  line-height: 35px;
  margin: 0px;
  padding: 0px 25px;
  text-align: center;
  text-decoration: none;
}

.menu li a:hover,
.menu ul li:hover a {
  background: #003f20 url("../images/hover.gif") bottom center no-repeat;
  color: #FFFFFF;
  text-decoration: none;
}

.menu li ul {
  background: #006633;
  display: none;
  height: auto;
  padding: 0px;
  margin: 0px;
  border: 0px;
  position: absolute;
  width: 225px;
  z-index: 200;
  /*top:1em;
    /*left:0;*/
}

.menu li:hover ul {
  display: block;
}

.menu li li {
  background: url('../images/sub_sep.gif') bottom left no-repeat;
  display: block;
  float: none;
  margin: 0px;
  padding: 0px;
  width: 225px;
}

.menu li:hover li a {
  background: none;
}

.menu li ul a {
  display: block;
  height: 30px;
  font-size: 12px;
  font-style: normal;
  margin: 0px;
  padding: 0px 10px 0px 15px;
  text-align: left;
}

.menu li ul a:hover,
.menu li ul li:hover a {
  background: #003f20 url('../images/hover_sub.gif') center left no-repeat;
  border: 0px;
  color: #ffffff;
  text-decoration: none;
}

.menu p {
  clear: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
  <ul>
    <li>Main Item 1</li>
    <li>Main Item 2
      <ul>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
      </ul>
    </li>
    <li>Main Item 3</li>
    <li>Main Item 4</li>
    <li>Main Item 5</li>
    <li>Main Item 6
      <ul>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
        <li>Test Sub Item</li>
      </ul>
    </li>
  </ul>
</div></code>```

答:
2018 edit

Hey, 7 years later the columns css property is well supported

ul{
  columns: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
  <li>fourth item</li>
  <li>fifth item</li>
</ul></code>```

You could probably get a similar effect with the very robust grid

2011 original answer

Make the ul twice as wide as the li's and float the li's left

http://www.behemothdan.com/2011/05/faux-mega-menu-in-wordpress/

Title: Make CSS Drop Down Menu 2 Columns

Body:
I currently have a CSS

 dropdown menu that uses the following code.  Unfortunately I want the sub menus to display in 2 columns as there are about 16 items in that submenu.  Does anyone know how to use the following code to make this drop down menu 2 columns?

.menu {
  border: none;
  border: 0px;
  margin: 0px;
  padding: 0px;
  font: 67.5% "Lucida Sans Unicode", "Bitstream Vera Sans", "Trebuchet Unicode MS", "Lucida Grande", Verdana, Helvetica, sans-serif;
  font-size: 18px;
  font-weight: bold;
}

.menu ul {
  background: #006633;
  height: 35px;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  float: left;
  padding: 0px;
}

.menu li a {
  background: #006633 url("../images/seperator.gif") bottom right no-repeat;
  color: #ffffff;
  display: block;
  font-weight: normal;
  line-height: 35px;
  margin: 0px;
  padding: 0px 25px;
  text-align: center;
  text-decoration: none;
}

.menu li a:hover,
.menu ul li:hover a {
  background: #003f20 url("../images/hover.gif") bottom center no-repeat;
  color: #FFFFFF;
  text-decoration: none;
}

.menu li ul {
  background: #006633;
  display: none;
  height: auto;
  padding: 0px;
  margin: 0px;
  border: 0px;
  position: absolute;
  width: 225px;
  z-index: 200;
  /*top:1em;
    /*left:0;*/
}

.menu li:hover ul {
  display: block;
}

.menu li li {
  background: url('../images/sub_sep.gif') bottom left no-repeat;
  display: block;
  float: none;
  margin: 0px;
  padding: 0px;
  width: 225px;
}

.menu li:hover li a {
  background: none;
}

.menu li ul a {
  display: block;
  height: 30px;
  font-size: 12px;
  font-style: normal;
  margin: 0px;
  padding: 0px 10px 0px 15px;
  text-align: left;
}

.menu li ul a:hover,
.menu li ul li:hover a {
  background: #003f20 url('../images/hover_sub.gif') center left no-repeat;
  border: 0px;
  color: #ffffff;
  text-decoration: none;
}

.menu p {
  clear: left;
}

Main Item 1

Main Item 2

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Main Item 3

Main Item 4

Main Item 5

Main Item 6

Test Sub Item

Test Sub Item

Test Sub Item

Body:
2018 edit

Hey, 7 years later the columns css property is well supported

ul{
  columns: 2;
}

<ul>
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
  <li>fourth item</li>
  <li>fifth item</li>
</ul>

You could probably get a similar effect with the very robust grid

2011 original answer

Make the ul twice as wide as the li's and float the li's left

http://www.behemothdan.com/2011/05/faux-mega-menu-in-wordpress/


问:
Node.js: mongoose.once('open') doesn't execute callback function
I'm trying to save some json files inside my database using a custom function I've wrote. To achieve that I must connect to the database which I'm trying to do using this piece of code at the start of the function:

```<code>let url = "mongodb://localhost:27017/database";

(async () => {
    const directory = await fs.promises.readdir(__dirname + '/files')
    let database = await mongoose.createConnection(url, {useNewUrlParser:true, useUnifiedTopology:true});
    database.on('error', error => {
        throw console.log("Couldn't Connect To The Database");
    });
    database.once('open', function() {
        //Saving the data using Schema and save();
</code>```

Weirdly enough, when executing database.once('open', function()) the callback function isn't being called at all and the program just skips the whole saving part and gets right to the end of the function.

I've searched the web for a solution, and one solution suggested to use mongoose.createConnection instant of mongoose.connect.
As you can see it didn't really fixed the issue and the callback function is still not being called.

How can I fix it, and why it happens?

Thanks!

答:
mongoose.createConnection creates a connection instance and allows you to manage multiple db connections as the documentation states. In your case using connect() should be sufficient (connect will create one default connection which is accessible under mongoose.connection).

By awaiting the connect-promise you don't actually need to listen for the open event, you can simply do:

```<code>...
await mongoose.connect(url, {useNewUrlParser:true, useUnifiedTopology:true});
mongoose.model('YourModel', YourModelSchema);
...
</code>```

Body:
I'm trying to save some json files inside my database using a custom function I've wrote. To achieve that I must connect to the database which I'm trying to do using this piece of code at the start of the function:

let url = "mongodb://localhost:27017/database";

(async () => {
    const directory = await fs.promises.readdir(__dirname + '/files')
    let database = await mongoose.createConnection(url, {useNewUrlParser:true, useUnifiedTopology:true});
    database.on('error', error => {
        throw console.log("Couldn't Connect To The Database");
    });
    database.once('open', function() {
        //Saving the data using Schema and save();

Weirdly enough, when executing database.once('open', function()) the callback function isn't being called at all and the program just skips the whole saving part and gets right to the end of the function.

I've searched the web for a solution, and one solution suggested to use mongoose.createConnection instant of mongoose.connect.
As you can see it didn't really fixed the issue and the callback function is still not being called.

How can I fix it, and why it happens?

Thanks!

Body:
mongoose.createConnection creates a connection instance and allows you to manage multiple db connections as the documentation states. In your case using connect() should be sufficient (connect will create one default connection which is accessible under mongoose.connection).

By awaiting the connect-promise you don't actually need to listen for the open event, you can simply do:

...
await mongoose.connect(url, {useNewUrlParser:true, useUnifiedTopology:true});
mongoose.model('YourModel', YourModelSchema);
...


问:
'pageshow' is not received when pressing "back" button on Safari on *IPad"
I have the following handler:

```<code>        $(window).bind('pageshow', function() { alert("back to page"); });
</code>```

When I navigate away from the page (by pressing on a link) and return back to the page (by pressing the "back" button), the alert() is not called (IPad 2, iOS 5.1).

What am I doing wrong please? Any other event I need to bind to?

PS: interesting that pagehide is received properly when navigating away from the page.

答: you should checkout you page is has iFrame component? i dont know why , but i delete iFrame component to solve this question</p>

Body:
I have the following handler:

        $(window).bind('pageshow', function() { alert("back to page"); });

When I navigate away from the page (by pressing on a link) and return back to the page (by pressing the "back" button), the alert() is not called (IPad 2, iOS 5.1).

What am I doing wrong please? Any other event I need to bind to?

PS: interesting that pagehide is received properly when navigating away from the page.


问:
Access Query Limit From Another Query
I am trying to get a query to populate claims that are above an upper limit that is specified in another query. The claims from query 1 and the upper limit in query 2 are related by part numbers. the below pictures will give a better visual rep.

Edit:If the claim field for month is less than the upper limit then I don't want it show in the query, but each upper limit is different for each part number.

答:
Here is the sql:

```<code>SELECT Claims.PartNo, Month([Claims].[ProdYM]) AS [Month], Year([Claims].[ProdYM]) AS [Year], Sum(Claims.Claims) AS SumOfClaims
FROM UpperLimits INNER JOIN Claims ON UpperLimits.PartNO = Claims.PartNo
GROUP BY Claims.PartNo, Month([Claims].[ProdYM]), Year([Claims].[ProdYM])
HAVING (((Sum(Claims.Claims))>=Max([UpperLimits].[UpperLimit])));
</code>```

Result:

this is a totals query so upper limit needs to have a summary function.  Max was easiest to find but first and last will work if you find them.

Title: Access Query Limit From Another Query

Body:
Here is the sql:

SELECT Claims.PartNo, Month([Claims].[ProdYM]) AS [Month], Year([Claims].[ProdYM]) AS [Year], Sum(Claims.Claims) AS SumOfClaims
FROM UpperLimits INNER JOIN Claims ON UpperLimits.PartNO = Claims.PartNo
GROUP BY Claims.PartNo, Month([Claims].[ProdYM]), Year([Claims].[ProdYM])
HAVING (((Sum(Claims.Claims))>=Max([UpperLimits].[UpperLimit])));

Result:

this is a totals query so upper limit needs to have a summary function.  Max was easiest to find but first and last will work if you find them.


问:
OSB transform String to DateTime (xsl or xquery)
I'm working with Oracle OSB and I have the following incoming xml message:

```<code><db:InputParameters>
    <db:DETAILS>
        <db:DETAILS_ITEM>
            <db:Mutate>W</db:Mutate>
            <db:Date>2020-04-06T14:43</db:Date>
            <db:Account>T</db:Account>
        </db:DETAILS_ITEM>
        <db:DETAILS_ITEM>
            <db:Mutate>W</db:Mutate>
            <db:Date>2020-04-06T14:43</db:Date>
            <db:Account>T</db:Account>
        </db:DETAILS_ITEM>
    </db:DETAILS>
</db:InputParameters>
</code>```

The element "Date" is a "string" -> according to the xsd. But the application that I'm sending this message to, expects a "DateTime" type. So I need to transform the element "Date" from type "String" to type "DateTime". Keep in mind that the incoming message has more than one element called "Date". I tried a For Each stage with a replace action but I couldn't get it to work.

Also, I tried to concat ":00" to the "Date" element with the expression: fn:concat($body/*:inputparameters/*:DETAILS/*:DETAILS_ITEM/*:Date,':00')
This didn't seem to work either.

What would be the most simple solution to this?

Thanks for the help.

答:
With XSLT you can change the value of the element as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:db="http://example.com/db"
    version="1.0">

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="db:DETAILS_ITEM/db:Date">
      <xsl:copy>
          <xsl:value-of select="concat(., ':00')"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

https://xsltfiddle.liberty-development.net/pNmCzsv

Note that this is simply changing the contents of that element to a value which can be parsed as an xs:dateTime. There is no schema involved or any validation done. You will need to adapt the namespace declaration xmlns:db="http://example.com/db" to the one of the input document.

Body:
I'm working with Oracle OSB and I have the following incoming xml message:

<db:InputParameters>
    <db:DETAILS>
        <db:DETAILS_ITEM>
            <db:Mutate>W</db:Mutate>
            <db:Date>2020-04-06T14:43</db:Date>
            <db:Account>T</db:Account>
        </db:DETAILS_ITEM>
        <db:DETAILS_ITEM>
            <db:Mutate>W</db:Mutate>
            <db:Date>2020-04-06T14:43</db:Date>
            <db:Account>T</db:Account>
        </db:DETAILS_ITEM>
    </db:DETAILS>
</db:InputParameters>

The element "Date" is a "string" -> according to the xsd. But the application that I'm sending this message to, expects a "DateTime" type. So I need to transform the element "Date" from type "String" to type "DateTime". Keep in mind that the incoming message has more than one element called "Date". I tried a For Each stage with a replace action but I couldn't get it to work.

Also, I tried to concat ":00" to the "Date" element with the expression: fn:concat($body/*:inputparameters/*:DETAILS/*:DETAILS_ITEM/*:Date,':00')
This didn't seem to work either.

What would be the most simple solution to this?

Thanks for the help.

Body:
With XSLT you can change the value of the element as follows:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:db="http://example.com/db"
    version="1.0">

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="db:DETAILS_ITEM/db:Date">
      <xsl:copy>
          <xsl:value-of select="concat(., ':00')"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/pNmCzsv

Note that this is simply changing the contents of that element to a value which can be parsed as an xs:dateTime. There is no schema involved or any validation done. You will need to adapt the namespace declaration xmlns:db="http://example.com/db" to the one of the input document.


问:
How to store day wise timetable in database?
I am working on a school management system
I want to store time table based on day, class, section, subjects, teacher and time.
I am confused about how to design table and how to store data.
time table image</p>

答:
It seems you are new in this community. Your question does not provide proper information. Guessing you are trying to create a table named 'time' with attributes day, class, section, subjects, teacher and time.

In phpmyadmin you can do this easily by create table option. In case of laravel you need to create migrations and use 'php artisan migrate' command. you can follow below link for further clarification- https://laravel.com/docs/7.x/migrations


问:
Positioning children widgets at the center and at the end of a Column parent widget
I have to position 2 children widgets inside a Column parent widget. I want one of them to be positioned in the center and the other at the end of the column. What is the best way to do that?

import 'package:flutter/material.dart';

class Screen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Screen'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center, // this is wrong, it positions both the widgets in the center
        children: <Widget>[
          Text('This text should be at the center of the column'),
          Text('This text should be at the end of the column'),
        ],
      ),
    );
  }
}
```

答:
Another way is to use an empty SizedBox at the start and the mainAxisAlignment: MainAxisAlignment.spaceBetween,

```<code>class Screen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Screen'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          SizedBox(
            height: 0.0,
            width: 0.0,
          ),
          Text('This text should be at the center of the column'),
          Text('This text should be at the end of the column'),
        ],
      ),
    );
  }
}
</code>```

Body:
Another way is to use an empty SizedBox at the start and the mainAxisAlignment: MainAxisAlignment.spaceBetween,

class Screen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Screen'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          SizedBox(
            height: 0.0,
            width: 0.0,
          ),
          Text('This text should be at the center of the column'),
          Text('This text should be at the end of the column'),
        ],
      ),
    );
  }
}


问:
How to increase plt.title font size?
I'm using Pythons matplotlib and this is my code:

```<code>  plt.title('Temperature \n Humidity')
</code>```

How can I just increase the font size of temperature instead of both the temperature & the humdity?

This does NOT work:

```<code> plt.title('Temperature \n Humidity', fontsize=100)
</code>```

答:
I don't want to go into this chart exactly
Universal method:
step one - make a distance between the main title and the chart:

```<code>from matplotlib import rcParams
rcParams['axes.titlepad'] = 20
</code>```

then insert subtitle by setting coordinates:

```<code>ax.text(0.3, -0.56, 'subtitle',fontsize=12)
</code>```

Title: How to increase plt.title font size?

Body:
I'm using Pythons matplotlib and this is my code:

  plt.title('Temperature \n Humidity')

How can I just increase the font size of temperature instead of both the temperature & the humdity?

This does NOT work:

 plt.title('Temperature \n Humidity', fontsize=100)

Body:
I don't want to go into this chart exactly
Universal method:
step one - make a distance between the main title and the chart:

from matplotlib import rcParams
rcParams['axes.titlepad'] = 20

then insert subtitle by setting coordinates:

ax.text(0.3, -0.56, 'subtitle',fontsize=12)


问:
bash script to find unique value in a file with index
I have a text file ,test.txt, like

```<code>shekhar cbv
ravi cbv
ravi sdf
asd df
ravi Df
ravi dfg
ravi df
ravi dfg
ravi df
afas cvb
sdf hgh
sasdg cfg
</code>```

I want to sort based on 2nd field and want to write 2nd field only on "result.txt"
 Currently I am doing following:

sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

which is writing 2n field i.e.

```<code>cbv
cfg
cvb
df
dfg
hgh
sdf
</code>```

Corresponding to every unique 2nd field value I want its,all, index in original file.
How this is possible ?

Desired Output:

```<code>cbv 1 2
cfg 12
cvb 10
df 4 5 7 9
dfg 6 8
hgh 11
sdf 3
</code>```

One more thing if say there is 3rd field also. How to achieve the above only mean while sorting and finding uniqueness only 2nd field is used.

input With 3rd field

```<code>    shekhar cbv rg
    ravi cbv fdf
    ravi sdf dfh
    asd df dfhdfh
    ravi Df fgh
    ravi dfg dfh
    ravi df dfgh
    ravi dfg dfgh
    ravi df dfhg
    afas cvb fhfg
    sdf hgh cgfhfg
    sasdg cfg fgh
</code>```

Desired o/p same .
Thanks,
Ravi

答:
For fun - perl:

```<code>perl -anle 'push(@{$s{$F[1]}},++$n);END{map{print "$_: @{$s{$_}}"} sort keys %s}'
</code>```

or case insensitive

```<code>perl -anle 'push(@{$s{lc($F[1])}},++$n);END{map{print "$_: @{$s{$_}}"} sort keys %s}'
</code>```

Body:
I have a text file ,test.txt, like

shekhar cbv
ravi cbv
ravi sdf
asd df
ravi Df
ravi dfg
ravi df
ravi dfg
ravi df
afas cvb
sdf hgh
sasdg cfg

I want to sort based on 2nd field and want to write 2nd field only on "result.txt"
 Currently I am doing following:

sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

which is writing 2n field i.e.

cbv
cfg
cvb
df
dfg
hgh
sdf

Corresponding to every unique 2nd field value I want its,all, index in original file.
How this is possible ?

Desired Output:

cbv 1 2
cfg 12
cvb 10
df 4 5 7 9
dfg 6 8
hgh 11
sdf 3

One more thing if say there is 3rd field also. How to achieve the above only mean while sorting and finding uniqueness only 2nd field is used.

input With 3rd field

    shekhar cbv rg
    ravi cbv fdf
    ravi sdf dfh
    asd df dfhdfh
    ravi Df fgh
    ravi dfg dfh
    ravi df dfgh
    ravi dfg dfgh
    ravi df dfhg
    afas cvb fhfg
    sdf hgh cgfhfg
    sasdg cfg fgh

Desired o/p same .
Thanks,
Ravi

Body:
For fun - perl:

perl -anle 'push(@{$s{$F[1]}},++$n);END{map{print "$_: @{$s{$_}}"} sort keys %s}'

or case insensitive

perl -anle 'push(@{$s{lc($F[1])}},++$n);END{map{print "$_: @{$s{$_}}"} sort keys %s}'


问:
How does GCP iot-device-sdk-embedded-c work on MIPS(uclibc)?
I download source code iot-device-sdk-embedded-c from github.

I only change config for tool-chain and then compiler it successfully. But it stop in connect step(iotc_connect_to), when I run example "iot_core_mqtt_client" in my device(MIPS+uclibc). This example work in google shell, x86_64 linux and ARM linux.

My Device:

CPU: MIPS

OS: Linux 3.10.14

tool-chain : CC=mips-linux-uclibc-gnu-gcc-4.7.2 AR=mips-linux-uclibc-gnu-gcc-ar

Can iot-device-sdk-embedded-c run in MIPS+uclibc?

What do I need to change?

答:
I think I got the answer....
"SOCK_STREAM" is defined to 1 for any other architectures, but it is defined to 2 for MIPS.
And then iotc_bsp_io_net_posix.c didn't use socket.h file from MIPS include folder.
That's reason why my device can't send data to server.</p>