问:
Algorithm for fairly assigning tasks to workers based on skills
(Before anyone asks, this is not homework.)

I have a set of workers with interests, i.e.:

Bob: Java, XML, Ruby

Susan: Java, HTML, Python

Fred: Python, Ruby

Sam: Java, Ruby

etc.

(There are actually somewhere in the range of 10-25 "interests" for each worker, and I have around 40-50 workers)

At the same time, I have a very large set of tasks that need to be distributed among the workers. Each task has to be assigned to at least 3 workers, and the workers must match at least one of the tasks' interests:

Task 1: Ruby, XML
Task 2: XHTML, Python

and so on. So Bob, Fred, or Sam could get Task 1; Susan or Fred could get Task 2.

This is all stored in a database thusly:

```<code>Task
    id integer primary key
    name varchar

TaskInterests
    task_id integer
    interest_id integer

Workers
    id integer primary key
    name varchar
    max_assignments integer

WorkerInterests
    worker_id
    interest_id

Assignments
    task_id
    worker_id
    date_assigned
</code>```

Each worker has a maximum number of assignments they will do, around 10. Some interests are more rare than others (i.e. only 1 or 2 workers have listed them as a interest), some interests are more common (i.e. half of the workers list them).

The algorithm must:

Assign every task to 3 workers (it is
assumed that at least 3 of the
workers are interested in one of the
interests of the task).

Assign every worker 1 or more tasks

Ideally, the algorithm will:

Assign each worker a number of tasks proportional to their maximum assignments and the total number of tasks. For example, if Susan says she will do 20 tasks and most people will only do 10 tasks and there are 50 workers and 300 tasks, she should be assigned 12 tasks (20/10*(300/50)).

Assign a variety of tasks to each worker, so if Susan lists 4 interests she gets tasks that include 4 interests (rather than getting 10 tasks all with the same interest)

The most difficult aspect so far has been dealing with theses issues:

tasks having interests with few corresponding workers

workers who have few interests, especially

workers who have a few interests, for which there are relatively few tasks

答:
This problem can be modeled as a
Maximum Flow Problem.

In a max-flow problem, you have a directed graph with two special nodes, the source and the sink. The edges in the graph have capacities, and your goal is to assign a flow through the graph from the source to the sink without exceeding any of the edge capacities.

With a (very) carefully crafted graph, we can find an assignment meeting your requirements from the maximum flow.

Let me number the requirements.

Required:

```<code>1. Workers are assigned no more than their maximum assignments.
2. Tasks can only be assigned to workers that match one of the task's interests.
3. Every task must be assigned to 3 workers.
4. Every worker must be assigned to at least 1 task.
</code>```

Optional:

```<code>5. Each worker should be assigned a number of tasks proportional to that worker's maximum assignments
6. Each worker should be assigned a variety of tasks.
</code>```

I will assume that the maximum flow is found using the
Edmonds-Karp Algorithm.

Let's first find a graph that meets requirements 1-3.

Picture the graph as 4 columns of nodes, where edges only go from nodes in a column to nodes in the neighboring column to the right.

In the first column we have the source node. In the next column we will have nodes for each of the workers. From the source, there is an edge to each worker with capacity equal to that worker's maximum assignments. This will enforce requirement 1.

In the third column, there is a node for each task. From each worker in the second column there is an edge to each task that that worker is interested in with a capacity of 1 (a worker is interested in a task if the intersection of their interests is non-empty). This will enforce requirement 2. The capacity of 1 will ensure that each worker takes only 1 of the 3 slots for each task.

In the fourth column we have the sink. There is an edge from each task to the sink with capacity 3. This will enforce requirement 3.

Now, we find a maximum flow in this graph using the Edmonds-Karp Algorithm. If this maximum flow is less than 3 * (# of tasks) then there is no assignment meeting requirements 1-3. If not, there is such an assignment and we can find it by examining the final augmented graph. In the augmented graph, if there is an edge from a task to a worker with capacity 1, then that worker is assigned to that task.

Now, we will modify our graph and algorithm to meet the rest of the requirements.

First, let's meet requirement 4. This will require a small change to the algorithm. Initially, set all the capacities from the source to the workers to 1. Find the max-flow in this graph. If the flow is not equal to the number of workers, then there is no assignment meeting requirement 4. Now, in your final residual graph, for each worker the edge from the source to that worker has capacity 0 and the reverse edge has capacity 1. Change these to that worker's maximum assignments - 1 and 0, respectively. Now continue Edmonds-Karp algorithm as before. Basically what we have done is first find an assignment such that each worker is assigned to exactly one task. Then delete the reverse edge from that task so that the worker will always be assigned to at least one task(though it may not be the one assigned to in the first pass).

Now let's meet requirement 5. Strictly speaking, this requirement just means that we divide each worker's maximum assignments by sum of all worker's maximum assignments / number of tasks. This will quite possibly not have a satisfying assignment. But that's ok. Initialize our graph with these new maximum assignments. Run Edmonds-Karp. If it finds a flow that saturates the edges from tasks to sink, we are done. Otherwise we can increment the capacities from sink to workers in the residual graph and continue running Edmonds-Karp. Repeat until we saturate the edges into the sink. Don't increment the capacities so much that a worker is assigned too many tasks. Also, technically, the increment for each worker should be proportional to that worker's maximum assignments. These are both easy to do.

Finally let's meet requirement 6. This one is a bit tricky. First, add a column between workers and tasks and remove all edges from workers to tasks. In this new column, for each worker add a node for each of that workers interests. From each of these new nodes, add an edge to each task with a matching interest with capacity 1. Add an edge from each worker to each of its interest nodes with capacity 1. Now, a flow in this graph would enforce that if a worker is assigned to n tasks, then the intersection of the union of those task's interests with that worker's interests has size at least n. Again, it is possible that there is a satisfying assignment without this assignment, but there is not one with it. We can handle this the same as requirement 5: run Edmonds-Karp to completion, if no satisfying assignment, increment the capacities from workers to their interest nodes and repeat.

Note that in this modified graph we no longer satisfy requirement 3, as a single worker may be assigned to multiple/all slots of a task if the intersection of their interests has size greater than 1. We can fix that. Add a new column of nodes between the interest nodes and the task nodes and delete the edges between those nodes. For each employee, in the new column insert a node for each task (so each employee has its own node for each task). From these new nodes, to their corresponding task to the right, add an edge with capacity 1. From each worker's interests node to that worker's task nodes, add an edge with capacity 1 from each interest to each task that matches.

-

EDIT: Let me try to clarify this a little. Let -(n)-> be an edge with n capacity.

Previously we had worker-(1)->task for each worker-task pair with a matching interest. Now we have worker-(k)->local interest-(1)->local task-(1)->global task. Now, you can think of a task being matched to a worker-interest pair. The first edge says that for a worker, each of its interests can be matched to k tasks. The second edge says that each of a worker's interests can only be matched once to each job. The third edge says that each task can only be assigned once to each worker. Note that you could push multiple flow from the worker to a local task (equal to the size of the intersection of their interests) but only 1 flow from the worker to the global task node due to the third edge.

-

Also note that we can't really mix this incrementing with the one for requirement 5 correctly. However, we can run the whole algorithm once for each capacity {1,2,...,r} for worker->interest edges. We then need a way to rank the assignments. That is, as we relax requirement 5 we can better meet requirement 6 and vice versa. However, there is another approach that I prefer for relaxing these constraints.

A better approach to requirement relaxation (inspired-by/taken-from templatetypedef)

When we want to be able to relax multiple requirements (e.g. 5 and 6), we can model it as a min-cost max-flow problem. This may be simpler than the incremental search that I described above.

For example, for requirement 5, set all the edge costs to 0. We have the initial edge from the source to the worker with the capacity equal to worker's maximum assignments / (sum of all worker's maximum assignments / number of tasks) and with cost 0. Then you can add another edge with the remaining capacity for that worker and cost 1. Another possibility would be to use some sort of progressive cost such that as you add tasks to a worker the cost to add another task to that user goes up. E.g. you could instead split a worker's remaining capacity up into individual edges with costs 1,2,3,4,....

A similar thing could then be done between the worker nodes and the local-interest nodes for requirement 6. The weighting would need to be balanced to reflect the relative importance of the different requirements.

This method is also sufficient to enforce requirement 4. Also, the costs for requirement 5 should probably be made such that they are proportional to a worker's maximum assignments. Then assigning 1 extra task to a worker with max 100 would not cost as much as assigning an extra to a worker with max 2.

Complexity Analysis

Let n = # of employees, m = # of tasks, k = max interests for a single task/worker, l = # of interests, j = maximum of maximum assignments.

Requirement 3 implies that n = O(m). Let's also assume that l = O(m) and j = O(m).

In the smaller graph (before the change for req. 6), the graph has n + m + 2 = O(m) vertices and at most n + m + k*min(n, m) = O(km) edges.

After the change it has 2 + n + n * l + n * m + m = O(nm) vertices and n + k * n + k * m * n + n * m + m = O(kmn) edges (technically we may need j * n + j * l more nodes and edges so that there are not multiple edges from one node to another, but this wouldn't change the asymptotic bound). Also note that no edge need have capacity > j.

Using the min-cost max-flow formulation, we can find a solution in O(VEBlogV) where V = # vertices, E = # edges, and B = max capacity on a single edge. In our case this gives O(kjn^2m^2log(nm)).

Body:
(Before anyone asks, this is not homework.)

I have a set of workers with interests, i.e.:

Bob: Java, XML, Ruby

Susan: Java, HTML, Python

Fred: Python, Ruby

Sam: Java, Ruby

etc.

(There are actually somewhere in the range of 10-25 "interests" for each worker, and I have around 40-50 workers)

At the same time, I have a very large set of tasks that need to be distributed among the workers. Each task has to be assigned to at least 3 workers, and the workers must match at least one of the tasks' interests:

Task 1: Ruby, XML
Task 2: XHTML, Python

and so on. So Bob, Fred, or Sam could get Task 1; Susan or Fred could get Task 2.

This is all stored in a database thusly:

Task
    id integer primary key
    name varchar

TaskInterests
    task_id integer
    interest_id integer

Workers
    id integer primary key
    name varchar
    max_assignments integer

WorkerInterests
    worker_id
    interest_id

Assignments
    task_id
    worker_id
    date_assigned

Each worker has a maximum number of assignments they will do, around 10. Some interests are more rare than others (i.e. only 1 or 2 workers have listed them as a interest), some interests are more common (i.e. half of the workers list them).

The algorithm must:

Assign every task to 3 workers (it is
assumed that at least 3 of the
workers are interested in one of the
interests of the task).

Assign every worker 1 or more tasks

Ideally, the algorithm will:

Assign each worker a number of tasks proportional to their maximum assignments and the total number of tasks. For example, if Susan says she will do 20 tasks and most people will only do 10 tasks and there are 50 workers and 300 tasks, she should be assigned 12 tasks (20/10*(300/50)).

Assign a variety of tasks to each worker, so if Susan lists 4 interests she gets tasks that include 4 interests (rather than getting 10 tasks all with the same interest)

The most difficult aspect so far has been dealing with theses issues:

tasks having interests with few corresponding workers

workers who have few interests, especially

workers who have a few interests, for which there are relatively few tasks

Body:
This problem can be modeled as a
Maximum Flow Problem.

In a max-flow problem, you have a directed graph with two special nodes, the source and the sink. The edges in the graph have capacities, and your goal is to assign a flow through the graph from the source to the sink without exceeding any of the edge capacities.

With a (very) carefully crafted graph, we can find an assignment meeting your requirements from the maximum flow.

Let me number the requirements.

Required:

1. Workers are assigned no more than their maximum assignments.
2. Tasks can only be assigned to workers that match one of the task's interests.
3. Every task must be assigned to 3 workers.
4. Every worker must be assigned to at least 1 task.

Optional:

5. Each worker should be assigned a number of tasks proportional to that worker's maximum assignments
6. Each worker should be assigned a variety of tasks.

I will assume that the maximum flow is found using the
Edmonds-Karp Algorithm.

Let's first find a graph that meets requirements 1-3.

Picture the graph as 4 columns of nodes, where edges only go from nodes in a column to nodes in the neighboring column to the right.

In the first column we have the source node. In the next column we will have nodes for each of the workers. From the source, there is an edge to each worker with capacity equal to that worker's maximum assignments. This will enforce requirement 1.

In the third column, there is a node for each task. From each worker in the second column there is an edge to each task that that worker is interested in with a capacity of 1 (a worker is interested in a task if the intersection of their interests is non-empty). This will enforce requirement 2. The capacity of 1 will ensure that each worker takes only 1 of the 3 slots for each task.

In the fourth column we have the sink. There is an edge from each task to the sink with capacity 3. This will enforce requirement 3.

Now, we find a maximum flow in this graph using the Edmonds-Karp Algorithm. If this maximum flow is less than 3 * (# of tasks) then there is no assignment meeting requirements 1-3. If not, there is such an assignment and we can find it by examining the final augmented graph. In the augmented graph, if there is an edge from a task to a worker with capacity 1, then that worker is assigned to that task.

Now, we will modify our graph and algorithm to meet the rest of the requirements.

First, let's meet requirement 4. This will require a small change to the algorithm. Initially, set all the capacities from the source to the workers to 1. Find the max-flow in this graph. If the flow is not equal to the number of workers, then there is no assignment meeting requirement 4. Now, in your final residual graph, for each worker the edge from the source to that worker has capacity 0 and the reverse edge has capacity 1. Change these to that worker's maximum assignments - 1 and 0, respectively. Now continue Edmonds-Karp algorithm as before. Basically what we have done is first find an assignment such that each worker is assigned to exactly one task. Then delete the reverse edge from that task so that the worker will always be assigned to at least one task(though it may not be the one assigned to in the first pass).

Now let's meet requirement 5. Strictly speaking, this requirement just means that we divide each worker's maximum assignments by sum of all worker's maximum assignments / number of tasks. This will quite possibly not have a satisfying assignment. But that's ok. Initialize our graph with these new maximum assignments. Run Edmonds-Karp. If it finds a flow that saturates the edges from tasks to sink, we are done. Otherwise we can increment the capacities from sink to workers in the residual graph and continue running Edmonds-Karp. Repeat until we saturate the edges into the sink. Don't increment the capacities so much that a worker is assigned too many tasks. Also, technically, the increment for each worker should be proportional to that worker's maximum assignments. These are both easy to do.

Finally let's meet requirement 6. This one is a bit tricky. First, add a column between workers and tasks and remove all edges from workers to tasks. In this new column, for each worker add a node for each of that workers interests. From each of these new nodes, add an edge to each task with a matching interest with capacity 1. Add an edge from each worker to each of its interest nodes with capacity 1. Now, a flow in this graph would enforce that if a worker is assigned to n tasks, then the intersection of the union of those task's interests with that worker's interests has size at least n. Again, it is possible that there is a satisfying assignment without this assignment, but there is not one with it. We can handle this the same as requirement 5: run Edmonds-Karp to completion, if no satisfying assignment, increment the capacities from workers to their interest nodes and repeat.

Note that in this modified graph we no longer satisfy requirement 3, as a single worker may be assigned to multiple/all slots of a task if the intersection of their interests has size greater than 1. We can fix that. Add a new column of nodes between the interest nodes and the task nodes and delete the edges between those nodes. For each employee, in the new column insert a node for each task (so each employee has its own node for each task). From these new nodes, to their corresponding task to the right, add an edge with capacity 1. From each worker's interests node to that worker's task nodes, add an edge with capacity 1 from each interest to each task that matches.

-

EDIT: Let me try to clarify this a little. Let -(n)-> be an edge with n capacity.

Previously we had worker-(1)->task for each worker-task pair with a matching interest. Now we have worker-(k)->local interest-(1)->local task-(1)->global task. Now, you can think of a task being matched to a worker-interest pair. The first edge says that for a worker, each of its interests can be matched to k tasks. The second edge says that each of a worker's interests can only be matched once to each job. The third edge says that each task can only be assigned once to each worker. Note that you could push multiple flow from the worker to a local task (equal to the size of the intersection of their interests) but only 1 flow from the worker to the global task node due to the third edge.

-

Also note that we can't really mix this incrementing with the one for requirement 5 correctly. However, we can run the whole algorithm once for each capacity {1,2,...,r} for worker->interest edges. We then need a way to rank the assignments. That is, as we relax requirement 5 we can better meet requirement 6 and vice versa. However, there is another approach that I prefer for relaxing these constraints.

A better approach to requirement relaxation (inspired-by/taken-from templatetypedef)

When we want to be able to relax multiple requirements (e.g. 5 and 6), we can model it as a min-cost max-flow problem. This may be simpler than the incremental search that I described above.

For example, for requirement 5, set all the edge costs to 0. We have the initial edge from the source to the worker with the capacity equal to worker's maximum assignments / (sum of all worker's maximum assignments / number of tasks) and with cost 0. Then you can add another edge with the remaining capacity for that worker and cost 1. Another possibility would be to use some sort of progressive cost such that as you add tasks to a worker the cost to add another task to that user goes up. E.g. you could instead split a worker's remaining capacity up into individual edges with costs 1,2,3,4,....

A similar thing could then be done between the worker nodes and the local-interest nodes for requirement 6. The weighting would need to be balanced to reflect the relative importance of the different requirements.

This method is also sufficient to enforce requirement 4. Also, the costs for requirement 5 should probably be made such that they are proportional to a worker's maximum assignments. Then assigning 1 extra task to a worker with max 100 would not cost as much as assigning an extra to a worker with max 2.

Complexity Analysis

Let n = # of employees, m = # of tasks, k = max interests for a single task/worker, l = # of interests, j = maximum of maximum assignments.

Requirement 3 implies that n = O(m). Let's also assume that l = O(m) and j = O(m).

In the smaller graph (before the change for req. 6), the graph has n + m + 2 = O(m) vertices and at most n + m + k*min(n, m) = O(km) edges.

After the change it has 2 + n + n * l + n * m + m = O(nm) vertices and n + k * n + k * m * n + n * m + m = O(kmn) edges (technically we may need j * n + j * l more nodes and edges so that there are not multiple edges from one node to another, but this wouldn't change the asymptotic bound). Also note that no edge need have capacity > j.

Using the min-cost max-flow formulation, we can find a solution in O(VEBlogV) where V = # vertices, E = # edges, and B = max capacity on a single edge. In our case this gives O(kjn^2m^2log(nm)).


来源: stackexchange

问:
Showing custom error message on web browser
I have created an ASP.NET Web API which calls a java web server to retrieve data. When the java web server is down, i want the Web API to show an error message: {"ErrorMessage:" Server is down} What are the codes that i should add to achieve the custom error message to be shown on the browser?

Here are my codes:

RestfulClient.cs

```<code>public class RestfulClient
{
    private static HttpClient client;
    private static string BASE_URL = "http://localhost:8080/";

    static RestfulClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> addition(int firstNumber, int secondNumber)
    {

        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
        }
        catch (Exception e)
        {
            //What do i have to code here?
        }
        return null;
    }

}
</code>```

AdditionController.cs

```<code>public class Temp
{
    public string firstNumber { get; set; }
    public string secondNumber { get; set; }
    public string sum { get; set; }
}

public class AdditionController : ApiController
{
    private RestfulClient restfulClient = new RestfulClient();
    public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
    {
        var result = await restfulClient.addition(firstNumber, secondNumber);
        var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
        return Json(resultDTO);
    }
}
</code>```

Someone please do help me, thank you so much.

答:
If you catch an exception of type Exception and then decide the server you called is down, that would not be true. Something may go wrong within your own code before you call the other service or after the other service has returned successfully. Therefore, you need to be careful how you make that decision.

Having said that it is still hard to say when you can make that decision with confidence: Is the calling service returning the correct message etc.

Anyhow, you can do something similar to this:

```<code>try
{
    // ...
}
catch (System.Net.WebException ex)
{
    if (ex.Status == System.Net.WebExceptionStatus.ConnectFailure)
    {
        // To use these 2 commented out returns, you need to change
        // your method's return type to Task<IHttpActionResult>
        // return Content(System.Net.HttpStatusCode.ServiceUnavailable, "Unavilable.");
        // return StatusCode(System.Net.HttpStatusCode.ServiceUnavailable);
        return "Unavailable"
    }
}
catch(Exception ex)
{
    // You could be here because something went wrong in your server,
    // or the server you called which was not caught by the catch above
    // because it was not WebException. Make sure to give it some
    // thought.
    // You need to change
    // your method's return type to Task<IHttpActionResult> or
    // just return a string.
    return StatusCode(System.Net.HttpStatusCode.InternalServerError);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created an ASP.NET Web API which calls a java web server to retrieve data. When the java web server is down, i want the Web API to show an error message: {"ErrorMessage:" Server is down} What are the codes that i should add to achieve the custom error message to be shown on the browser?

Here are my codes:

RestfulClient.cs

public class RestfulClient
{
    private static HttpClient client;
    private static string BASE_URL = "http://localhost:8080/";

    static RestfulClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> addition(int firstNumber, int secondNumber)
    {

        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
        }
        catch (Exception e)
        {
            //What do i have to code here?
        }
        return null;
    }

}

AdditionController.cs

public class Temp
{
    public string firstNumber { get; set; }
    public string secondNumber { get; set; }
    public string sum { get; set; }
}

public class AdditionController : ApiController
{
    private RestfulClient restfulClient = new RestfulClient();
    public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
    {
        var result = await restfulClient.addition(firstNumber, secondNumber);
        var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
        return Json(resultDTO);
    }
}

Someone please do help me, thank you so much.

Body:
If you catch an exception of type Exception and then decide the server you called is down, that would not be true. Something may go wrong within your own code before you call the other service or after the other service has returned successfully. Therefore, you need to be careful how you make that decision.

Having said that it is still hard to say when you can make that decision with confidence: Is the calling service returning the correct message etc.

Anyhow, you can do something similar to this:

try
{
    // ...
}
catch (System.Net.WebException ex)
{
    if (ex.Status == System.Net.WebExceptionStatus.ConnectFailure)
    {
        // To use these 2 commented out returns, you need to change
        // your method's return type to Task<IHttpActionResult>
        // return Content(System.Net.HttpStatusCode.ServiceUnavailable, "Unavilable.");
        // return StatusCode(System.Net.HttpStatusCode.ServiceUnavailable);
        return "Unavailable"
    }
}
catch(Exception ex)
{
    // You could be here because something went wrong in your server,
    // or the server you called which was not caught by the catch above
    // because it was not WebException. Make sure to give it some
    // thought.
    // You need to change
    // your method's return type to Task<IHttpActionResult> or
    // just return a string.
    return StatusCode(System.Net.HttpStatusCode.InternalServerError);
}


问:
Why does the chart image generated by zk does not shows the y numbers?
I am using ZK Framework in a project and i need to build this chart and export it as an image.

This is my chart:

And this is the image that is being generated:

As you can see, whenever the image is generated the numbers on the Y axis disappear and its range also changes. Does anyone knows why this is happening?

zul

```<code><charts id="chrtConsumoFaturado" type="line" title="Gráfico dos últimos 12 meses" />
</code>```

controller

```<code>this.chrtConsumoFaturado.setHeight(222);
this.chrtConsumoFaturado.getYAxis().setTitle("Valores");
this.chrtConsumoFaturado.getYAxis().getLabels().setFormat("R$ {value},00");
this.chrtConsumoFaturado.getExporting().getButtons().setEnabled(true);

this.chrtConsumoFaturado.getTooltip().setValuePrefix("R$ ");
this.chrtConsumoFaturado.getTooltip().setValueSuffix(",00");

this.chrtConsumoFaturado.setModel(new DefaultCategoryModel());
</code>```

Some observations: the exporting button is enabled; the other values are correct and I am using zk 7.0.0

答:
Since you don't specify the axis tick interval, zkcharts exports the axis tick according to its size. But the exporting image size is not as the same as what you see on a browser screen. It's 600px width * 400px height, if you don't specify a chart's width/height.

Since you don't specify the width, so zk charts export the chart by default width (600px) with default scale. Therefore, the result image is 1200 * 444. The height 444 is from the specified height multiplying the default scale which is 222 * 2.

If you try to shrink your chart's size to 600px in your browser, you will see the y axis tick changes, too. And this changed result matches your current exporting image.
For example:

original on the browser screen, wider

narrower

Because the rotated x axis label consumes more space of height, the height shrinks, so the number of y axis label becomes fewer.

I think there are at least 2 solutions:

enlarge exporting source width
set exporting source width as close as your screen width e.g.

chart.getExporting().setSourceWidth(1200);

https://api.highcharts.com/highcharts/exporting.sourceWidth

specify y axis tick interval
enforce tick interval

chart.getYAxis().setTickInterval(20);

Body:
I am using ZK Framework in a project and i need to build this chart and export it as an image.

This is my chart:

And this is the image that is being generated:

As you can see, whenever the image is generated the numbers on the Y axis disappear and its range also changes. Does anyone knows why this is happening?

zul

<charts id="chrtConsumoFaturado" type="line" title="Gráfico dos últimos 12 meses" />

controller

this.chrtConsumoFaturado.setHeight(222);
this.chrtConsumoFaturado.getYAxis().setTitle("Valores");
this.chrtConsumoFaturado.getYAxis().getLabels().setFormat("R$ {value},00");
this.chrtConsumoFaturado.getExporting().getButtons().setEnabled(true);

this.chrtConsumoFaturado.getTooltip().setValuePrefix("R$ ");
this.chrtConsumoFaturado.getTooltip().setValueSuffix(",00");

this.chrtConsumoFaturado.setModel(new DefaultCategoryModel());

Some observations: the exporting button is enabled; the other values are correct and I am using zk 7.0.0


问:
How to use headers common for all api requests using service in angular?
Iam working in angular4 ecommerce project.Here I need different api calls from backend having common headers with key and secret key.I have kept all the api urls in a service and whenever there is a api call,I am using that service.Here Iam declaring headers every time of api call.But I want to place those headers as global in that same service,so that I can use the headers too using that service.My problem is Iam unable use the headers in the service that are common to all api requests.How can I implement this one in angular?Please help me.Here is my code:
//service...</p>

```<code>import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import {Http, Headers} from '@angular/http';

@Injectable()
export class SharedServiceService {
public static headers = new Headers();
    public static baseUrl='https://www.t3stores.com/mystores/wordpress/';
    public static baseUrl2='https://colourssoftware.com/T3Liquors/';
    public static newCollections=SharedServiceService.baseUrl+'wp-json/wc/v2/products?tag=882';
public static productsApi=SharedServiceService.baseUrl+'wp-json/wc/v2/products?page=1&per_page=100';
    public static products=SharedServiceService.baseUrl;
    }

    //headers:
      createAuthorizationHeader(headers: Headers) {
        headers.append('Authorization', 'Basic ' +
            btoa('ck_543700d9f8c08268d75d3efefb302df4fad70a8f:cs_f1514261bbe154d662eb5053880d40518367c901'));
        headers.append("Content-Type", "application/json");
    }
     let headers = new Headers();
        this.createAuthorizationHeader(headers);
</code>```

答:
I think you are looking for Interceptors in Angular .

of Interceptors

```<code>import { Observable } from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { HttpErrorResponse } from "@angular/common/http";

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
            // instead of handling error you can add headers
        }
    });
  }
}
</code>```

To activate the interceptor

```<code>@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule
    ],
    providers: [
        [ { provide: HTTP_INTERCEPTORS, useClass:
              AngularInterceptor, multi: true } ]
    ],
    bootstrap: [AppComponent]
})
</code>```

More on Interceptors

Body:
Iam working in angular4 ecommerce project.Here I need different api calls from backend having common headers with key and secret key.I have kept all the api urls in a service and whenever there is a api call,I am using that service.Here Iam declaring headers every time of api call.But I want to place those headers as global in that same service,so that I can use the headers too using that service.My problem is Iam unable use the headers in the service that are common to all api requests.How can I implement this one in angular?Please help me.Here is my code:
//service...

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import {Http, Headers} from '@angular/http';

@Injectable()
export class SharedServiceService {
public static headers = new Headers();
    public static baseUrl='https://www.t3stores.com/mystores/wordpress/';
    public static baseUrl2='https://colourssoftware.com/T3Liquors/';
    public static newCollections=SharedServiceService.baseUrl+'wp-json/wc/v2/products?tag=882';
public static productsApi=SharedServiceService.baseUrl+'wp-json/wc/v2/products?page=1&per_page=100';
    public static products=SharedServiceService.baseUrl;
    }

    //headers:
      createAuthorizationHeader(headers: Headers) {
        headers.append('Authorization', 'Basic ' +
            btoa('ck_543700d9f8c08268d75d3efefb302df4fad70a8f:cs_f1514261bbe154d662eb5053880d40518367c901'));
        headers.append("Content-Type", "application/json");
    }
     let headers = new Headers();
        this.createAuthorizationHeader(headers);

Body:
I think you are looking for Interceptors in Angular .

of Interceptors

import { Observable } from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { HttpErrorResponse } from "@angular/common/http";

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
            // instead of handling error you can add headers
        }
    });
  }
}

To activate the interceptor

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule
    ],
    providers: [
        [ { provide: HTTP_INTERCEPTORS, useClass:
              AngularInterceptor, multi: true } ]
    ],
    bootstrap: [AppComponent]
})

More on Interceptors


问:
MPI Scattering 3D array to tetragonal prismas

Hello everyone, I am trying to scatter 3d array in tetragonal prisma format. I hope this picture will clarify what I mean.

Think of the big cube is 3d array(lets say 4x4x4 dimensions) and P0..3 is processors. (P0 will take [0..1][0..1][0..3] part of big array). I am using datatypes in order to do this, I created 2 datatypes;

```<code>MPI_Datatype dtype1, surface,dtype2,tetragonal;

MPI_Type_vector((N)/sqrt(size),
            (N),
           (N),
           MPI_FLOAT,
           &dtype1);

 MPI_Type_commit(&dtype1);
 MPI_Type_create_resized(dtype1, 0, 1*sizeof(float), &surface);

 MPI_Type_commit(&surface);

 MPI_Type_vector(N/sqrt(size),
           1,
           sqrt(size),
           surface,
           &dtype2);

 MPI_Type_commit(&dtype2);
 MPI_Type_create_resized(dtype2, 0, 1*sizeof(float), &tetragonal);
 MPI_Type_commit(&tetragonal);
</code>```

However, I am getting very strange results, I am new on MPI environment so I need some help on this issue to understand how datatypes actually work.
Thank you.

(Assume processor size is squared number and N is evenly divisible by sqrt(size) )

答: You cannot use MPI_Scatter() with this derived datatype, but you can use MPI_Scatterv() (all the counts are equal, but you need to manually calculate the displacements).

Body:
Hello everyone, I am trying to scatter 3d array in tetragonal prisma format. I hope this picture will clarify what I mean.

Think of the big cube is 3d array(lets say 4x4x4 dimensions) and P0..3 is processors. (P0 will take [0..1][0..1][0..3] part of big array). I am using datatypes in order to do this, I created 2 datatypes;

MPI_Datatype dtype1, surface,dtype2,tetragonal;

MPI_Type_vector((N)/sqrt(size),
            (N),
           (N),
           MPI_FLOAT,
           &dtype1);

 MPI_Type_commit(&dtype1);
 MPI_Type_create_resized(dtype1, 0, 1*sizeof(float), &surface);

 MPI_Type_commit(&surface);

 MPI_Type_vector(N/sqrt(size),
           1,
           sqrt(size),
           surface,
           &dtype2);

 MPI_Type_commit(&dtype2);
 MPI_Type_create_resized(dtype2, 0, 1*sizeof(float), &tetragonal);
 MPI_Type_commit(&tetragonal);

However, I am getting very strange results, I am new on MPI environment so I need some help on this issue to understand how datatypes actually work.
Thank you.

(Assume processor size is squared number and N is evenly divisible by sqrt(size) )


问:
Ajax send data Json type error
I want to submit Form ajax with jsontype

Let say I have 5 Field in that text box out of 5, 4 textbox normal Text one field value itself json so that ajax throw the error. How i can send

[![enter image description here][1]][1]

my.js

```<code>function _getTest(){
                var data = JSON.stringify($("#formId").serialize());
               //alert(data);
                $.ajax({
                url: "domain.com",
                datatype: 'json',
                type: "POST",
                contentType: 'application/json',
                data: data,
                    success: function(data) {
                        console.log(data);
                    },
                    error: function(result) {
                        alert(result.responseText);
                    }
                });
            }
</code>```

After Submit form i got status this Status Code:400 Bad Request

General Tab
Request URL:http://mycustomurl/com
Request Method:POST
Status Code:400 Bad Request
Remote Address:35.154.113.130:8080
Referrer Policy:no-referrer-when-downgrade

[![enter image description here][2]][2]

Expected Payload

```<code>{
    "name": "user",
    "mobile": "1234567890",
    "email": "my@gmail.com",
    "address": "test",
    "localityID": 1,
    "cityID": 1,
    "bookingDate": "2017-12-20",
    "timingID": "1",
    "paymentType": 1,
    "affiliateID": 15,
    "key": "test",
    "password": "test",
    "orderItems": [{
        "id": 3,
        "quantity": 2
           }, {
        "id": 4,
        "quantity": 5
    }]
}
</code>```

答:
Based on my understanding I have created below logic to create your payload. This code create exact structure you want to send as payload. In my code I have created mainData array to create payload. In your case you need to pass this mainData  as your ajax payload data. Hopefully this will solve your problem

var mainData={};

$(document).ready(function(){

   $("#submit").click(function(){

    mainData='{'+'\n'+
    '"name":'+ $("#name").val()+',\n'+
    '"mobile": '+$("#mobile").val()+',\n'+
    '"email": '+$("#email").val()+',\n'+
    '"address": '+$("#address").val()+',\n'+
    '"localityID": '+$("#localityID").val()+',\n'+
    '"cityID": '+$("#cityID").val()+',\n'+
    '"bookingDate":'+$("#bookingDate").val()+',\n'+
    '"timingID": '+$("#timingID").val()+',\n'+
    '"paymentType":'+$("#paymentType").val()+',\n'+
    '"affiliateID": '+$("#affiliateID").val()+',\n'+
    '"key": '+$("#key").val()+',\n'+
    '"password":'+$("#password").val()+',\n'+
    '"orderItems": '+$("#orderItems").val()+'\n'+
   ' });';
   console.log("mainData=");
   console.log(mainData);

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<input type="text" id="name" placeholder="Name"/>
<input type="number" id="mobile" placeholder="Mobile"/>
<input type="text" id="email" placeholder="Email"/>
<input type="text" id="address" placeholder="address"/>
<input type="text" id="cityID" placeholder="City ID"/>
<input type="text" id="localityID" placeholder="Locality ID"/>
<input type="date" id="bookingDate" placeholder="Booking Date"/>
<input type="text" id="timingID" placeholder="Timing ID"/>
<input type="text" id="paymentType" placeholder="Payment Type"/>
<input type="text" id="affiliateID" placeholder="Affiliate ID"/>
<input type="text" id="key" placeholder="Key"/>
<input type="password" id="password" placeholder="Password"/>
<textarea type="text" id="orderItems" placeholder="order Items"></textarea>
<input type="submit" id="submit" /></code>```

After created payload from above code you can pass payload in your ajax as follows

```<code>function _getTest(){
                $.ajax({
                url: "domain.com",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(mainData),
                    success: function(data) {
                        console.log(data);
                    },
                    error: function(result) {
                        alert(result.responseText);
                    }
                });
            }
</code>```

I am also attaching output screenshot for the same

Title: Ajax send data Json type error

Body:
I want to submit Form ajax with jsontype

Let say I have 5 Field in that text box out of 5, 4 textbox normal Text one field value itself json so that ajax throw the error. How i can send

[![enter image description here][1]][1]

my.js

function _getTest(){
                var data = JSON.stringify($("#formId").serialize());
               //alert(data);
                $.ajax({
                url: "domain.com",
                datatype: 'json',
                type: "POST",
                contentType: 'application/json',
                data: data,
                    success: function(data) {
                        console.log(data);
                    },
                    error: function(result) {
                        alert(result.responseText);
                    }
                });
            }

After Submit form i got status this Status Code:400 Bad Request

General Tab
Request URL:http://mycustomurl/com
Request Method:POST
Status Code:400 Bad Request
Remote Address:35.154.113.130:8080
Referrer Policy:no-referrer-when-downgrade

[![enter image description here][2]][2]

Expected Payload

{
    "name": "user",
    "mobile": "1234567890",
    "email": "my@gmail.com",
    "address": "test",
    "localityID": 1,
    "cityID": 1,
    "bookingDate": "2017-12-20",
    "timingID": "1",
    "paymentType": 1,
    "affiliateID": 15,
    "key": "test",
    "password": "test",
    "orderItems": [{
        "id": 3,
        "quantity": 2
           }, {
        "id": 4,
        "quantity": 5
    }]
}

Body:
Based on my understanding I have created below logic to create your payload. This code create exact structure you want to send as payload. In my code I have created mainData array to create payload. In your case you need to pass this mainData  as your ajax payload data. Hopefully this will solve your problem

var mainData={};

$(document).ready(function(){

   $("#submit").click(function(){

    mainData='{'+'\n'+
    '"name":'+ $("#name").val()+',\n'+
    '"mobile": '+$("#mobile").val()+',\n'+
    '"email": '+$("#email").val()+',\n'+
    '"address": '+$("#address").val()+',\n'+
    '"localityID": '+$("#localityID").val()+',\n'+
    '"cityID": '+$("#cityID").val()+',\n'+
    '"bookingDate":'+$("#bookingDate").val()+',\n'+
    '"timingID": '+$("#timingID").val()+',\n'+
    '"paymentType":'+$("#paymentType").val()+',\n'+
    '"affiliateID": '+$("#affiliateID").val()+',\n'+
    '"key": '+$("#key").val()+',\n'+
    '"password":'+$("#password").val()+',\n'+
    '"orderItems": '+$("#orderItems").val()+'\n'+
   ' });';
   console.log("mainData=");
   console.log(mainData);

  });
});

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<input type="text" id="name" placeholder="Name"/>
<input type="number" id="mobile" placeholder="Mobile"/>
<input type="text" id="email" placeholder="Email"/>
<input type="text" id="address" placeholder="address"/>
<input type="text" id="cityID" placeholder="City ID"/>
<input type="text" id="localityID" placeholder="Locality ID"/>
<input type="date" id="bookingDate" placeholder="Booking Date"/>
<input type="text" id="timingID" placeholder="Timing ID"/>
<input type="text" id="paymentType" placeholder="Payment Type"/>
<input type="text" id="affiliateID" placeholder="Affiliate ID"/>
<input type="text" id="key" placeholder="Key"/>
<input type="password" id="password" placeholder="Password"/>
<textarea type="text" id="orderItems" placeholder="order Items"></textarea>
<input type="submit" id="submit" />

After created payload from above code you can pass payload in your ajax as follows

function _getTest(){
                $.ajax({
                url: "domain.com",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(mainData),
                    success: function(data) {
                        console.log(data);
                    },
                    error: function(result) {
                        alert(result.responseText);
                    }
                });
            }

I am also attaching output screenshot for the same


问:
What's wrong with this HTML code?
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

```<code><!DOCTYPE html>
<html>
<head>
    <title>Hi</title>
    <style type="text/css">
    body
    {
        background-color: #369;
    }
    li.changeMe
    {
        background-color: #DEE;
        color: #369;
        font-weight: bold;
        padding: 8px 16px;
        margin: 5px;
        display: inline;
    }
    #bodystuff
    {
        background-color: White;
        display: block;
        padding: 15px 10px;
    }

    </style>
</head>

<body>
    <div style="margin: 15px 10px 0;">
    <div style="font-size: 30pt; font-weight: bold; color: White; font-family: Arial;">My Website</div>
    <div style="float: right; display: block; margin: 0 0 25px 0"><ul style="list-style-type: none; "><li class="changeMe">Hi</li><li class="changeMe">Hello</li></ul></div>
    <div id="bodystuff">Hi this is the body</div>
    </div>
</body>
</html>
</code>```

答: Just add clear:both to the CSS of #bodystuff to clear the floats.

ContentLicense: CC BY-SA 2.5

Title: What's wrong with this HTML code?

Body:
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

<!DOCTYPE html>

    <title>Hi</title>

My Website

Hi

Hello

Hi this is the body


问:
App crashing after theme update
The app I was working on so far was working fine until I added a couple of new activities and tried applied some changes to the theme.

The following is my styles.xml file. I looked into other results and added a parent to AppTheme as I was getting an error regarding AppCompat earlier. I also made AppTheme parent of NoActionBar. One thing I noticed was when I apply AppBarOverlay to Register User Activity it crashes and when I apply other it doesn't. Main Activity is crashing regardless.

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar" parent ="AppTheme">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
</code>```

Below is the Android Manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ati.activate">
<application
    android:allowBackup="true"
    android:icon="@drawable/footprintblue"
    android:label="@string/app_name"
    android:roundIcon="@drawable/footprintgreen"
    android:theme="@style/AppTheme"
    android:supportsRtl="true">

    <activity android:name=".UserManagement.LoginActivity"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".UserManagement.RegisterUserActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.AppBarOverlay">
    </activity>

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
    </activity>

 </application>
</manifest>
</code>```

I have applied AppTheme to android and then overridden the desired themes to other activities. Note: Login screen works and is using AppTheme.NoTitleBar, Register User works without AppBarOverLay theme but crashes when this theme is used.

This is my activity_main.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.ati.activate.MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <!--android:paddingTop="@dimen/appbar_padding_top"-->

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:layout_scrollFlags="scroll|enterAlways">
    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/login_background" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code>```

And this is the snippet of my MainActivity.Java file:

```<code>import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.ati.activate.Fragments.SettingsFragment.AppSettingsFragment;
import com.ati.activate.Fragments.SettingsFragment.ProfileSettingsFragment;

public class MainActivity extends AppCompatActivity{
private AppPagerAdapter mAppPagerAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    createMenu();
}
</code>```

I have tried every solution discussed on the internet but still have not found any solution. Could anyone please help? Thanking you in advance.

Below is the error when Register User Activity is opened with AppTheme.AppBarOverlay:

```<code>    12-08 04:55:08.217 17843-17850/? E/zygote: Failed writing handshake bytes (-1
    of 14): Broken pipe
    12-08 04:55:16.704 17843-17986/com.ati.activate E/StudioProfiler: JVMTI
    error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
    12-08 04:55:16.706 17843-17986/com.ati.activate E/StudioProfiler: JVMTI
    error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
    12-08 04:55:16.818 17843-17843/com.ati.activate E/AndroidRuntime: FATAL
    EXCEPTION: main
                                                                  Process:
    com.ati.activate, PID: 17843

    java.lang.RuntimeException: Unable to start activity

ComponentInfo{com.ati.activate/com.ati.activate.UserManagement.RegisterUserActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                   Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                      at com.ati.activate.UserManagement.RegisterUserActivity.onCreate(RegisterUserActivity.java:13)
                                                                      at android.app.Activity.performCreate(Activity.java:6975)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

And this is the error when Main Activity is opened:

```<code>12-08 04:59:50.431 21418-21586/com.ati.activate E/StudioProfiler: JVMTI

error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
12-08 04:59:50.432 21418-21586/com.ati.activate E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
12-08 04:59:50.518 21418-21418/com.ati.activate E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.ati.activate, PID: 21418
                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ati.activate/com.ati.activate.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                   Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                      at com.ati.activate.MainActivity.onCreate(MainActivity.java:26)
                                                                      at android.app.Activity.performCreate(Activity.java:6975)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

答:
change your manifest file :

```<code><activity android:name=".UserManagement.RegisterUserActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.AppBarOverlay">
</activity>
</code>```

to this :

```<code><activity android:name=".UserManagement.RegisterUserActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
</activity>
</code>```

i think your RegisterUserActivity problem will be solve...

UPDATE for your MainActivty
Chnage style.xml

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

Title: App crashing after theme update

Body:
The app I was working on so far was working fine until I added a couple of new activities and tried applied some changes to the theme.

The following is my styles.xml file. I looked into other results and added a parent to AppTheme as I was getting an error regarding AppCompat earlier. I also made AppTheme parent of NoActionBar. One thing I noticed was when I apply AppBarOverlay to Register User Activity it crashes and when I apply other it doesn't. Main Activity is crashing regardless.

<resources>

Body:
change your manifest file :

<activity android:name=".UserManagement.RegisterUserActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.AppBarOverlay">
</activity>

to this :

<activity android:name=".UserManagement.RegisterUserActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
</activity>

i think your RegisterUserActivity problem will be solve...

UPDATE for your MainActivty
Chnage style.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>


问:
Memory allocation?
I have code that looks like the one below. It shows the current date and date after 100 days. However, I've noticed that result turns out to be same. So I thought maybe the addresses of structure or variable were same.

I put "%p" of variable now, later, lnow, and tnow and the result on the very bottom shows that structure pointer of lnow and tnow are both 02B51AA0 while variable later and now have different address.
Now, if I move lnow = localtime(&later) into different location, after first switch statement, then address changes and it works perfectly. Could you explain why this happens?

```<code>#include <stdio.h>
#include <time.h>
struct tm* tnow;
struct tm* lnow;

int main(void)
{
    time_t now = time(NULL);

    time_t later = now + 100*24*3600;
    printf("%p\t%p\n", &now, &later);
    lnow = localtime(&later);
    tnow = localtime(&now);
    printf("%p\t%p\n", lnow, tnow);
    printf("%d.%d.%d\t", tnow->tm_year+1900, tnow->tm_mon+1, tnow->tm_mday);
    switch (tnow->tm_wday)
    {
        case 0: puts("SUNDAY"); break;
        case 1: puts ("MONDAY"); break;
        case 2: puts("TUESDAY"); break;
        default: puts("ELSE"); break;
    }

    printf("%d.%d.%d\t", lnow->tm_year+1900, lnow->tm_mon+1, lnow->tm_mday);
    switch (lnow->tm_wday)
    {
        case 0: puts("SUNDAY"); break;
        case 1: puts ("MONDAY"); break;
        case 2: puts("TUESDAY"); break;
        default: puts("ELSE"); break;
    }

    return 0;
}
</code>```

Results:

```<code>0061FF2C 0061FF28
02B51AA0 02B51AA0
2017.12.8 ELSE
2017.12.8 ELSE
</code>```

答:
Why are you printing the address of now and later ? These are just time_t values so the address is useless.

localtime returns a pointer to an internal buffer - the same each time, so you need to copy the values out of it if you want to do localtime on a second time.

Title: Memory allocation?

Body:
I have code that looks like the one below. It shows the current date and date after 100 days. However, I've noticed that result turns out to be same. So I thought maybe the addresses of structure or variable were same.

I put "%p" of variable now, later, lnow, and tnow and the result on the very bottom shows that structure pointer of lnow and tnow are both 02B51AA0 while variable later and now have different address.
Now, if I move lnow = localtime(&later) into different location, after first switch statement, then address changes and it works perfectly. Could you explain why this happens?

#include <stdio.h>
#include <time.h>
struct tm* tnow;
struct tm* lnow;

int main(void)
{
    time_t now = time(NULL);

    time_t later = now + 100*24*3600;
    printf("%p\t%p\n", &now, &later);
    lnow = localtime(&later);
    tnow = localtime(&now);
    printf("%p\t%p\n", lnow, tnow);
    printf("%d.%d.%d\t", tnow->tm_year+1900, tnow->tm_mon+1, tnow->tm_mday);
    switch (tnow->tm_wday)
    {
        case 0: puts("SUNDAY"); break;
        case 1: puts ("MONDAY"); break;
        case 2: puts("TUESDAY"); break;
        default: puts("ELSE"); break;
    }

    printf("%d.%d.%d\t", lnow->tm_year+1900, lnow->tm_mon+1, lnow->tm_mday);
    switch (lnow->tm_wday)
    {
        case 0: puts("SUNDAY"); break;
        case 1: puts ("MONDAY"); break;
        case 2: puts("TUESDAY"); break;
        default: puts("ELSE"); break;
    }

    return 0;
}

Results:

0061FF2C 0061FF28
02B51AA0 02B51AA0
2017.12.8 ELSE
2017.12.8 ELSE


问:
Bootstrap 4 Popover with HTML Content
This is my code, but it will not work.

When I use the native Bootstrap PopOver with HTML in it's content, the frontend is not displaying that PopOver and the HTML Source is malformatted.

<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
        <title>test</title>

             Toggle popover

```
</div>
</div>
</p>

<p>Remove Class property.
It can work.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
        <title>test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://cdn.bootcss.com/popper.js/1.11.0/umd/popper.min.js" ></script>
        <script src="https://cdn.bootcss.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
        <style>
            .popover{
                color: #757575 !important;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <span href="#" data-toggle="popover" title="Popover Header" data-html="true" data-content="<div>text text</div>">Toggle popover</span>
        </div>
        <script>
            $(function () {
                $('[data-toggle="popover"]').popover()
            })
        </script>
    </body>
</html></code>```

I am trying to display HTML inside a bootstrap popover, but somehow it's not working. I found some answers here but it won't work for me. Please let me know if I'm doing something wrong.

答:
Just wrap the popover class in single quotes like this.

```<code><div class='popover'>text text</div>
</code>```

instead of

```<code><div class="popover">text text</div>
</code>```

Title: Bootstrap 4 Popover with HTML Content

Body:
This is my code, but it will not work.

When I use the native Bootstrap PopOver with HTML in it's content, the frontend is not displaying that PopOver and the HTML Source is malformatted.

<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
        <title>test</title>

             Toggle popover

Remove Class property.
It can work.

<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
        <title>test</title>

            Toggle popover

I am trying to display HTML inside a bootstrap popover, but somehow it's not working. I found some answers here but it won't work for me. Please let me know if I'm doing something wrong.

Body:
Just wrap the popover class in single quotes like this.

<div class='popover'>text text</div>

instead of

<div class="popover">text text</div>


答:
Simply add clear: both; to the css for #bodystuff.

JS Fiddle demo.

Title: What's wrong with this HTML code?


问:
How to separate fields in a text file with a delimiter
I have a scenario where I have a text file and I want to separate the row values in the text file with a particular delimiter (say, :).

I have generated the text file by storing the output of an SQL query into a text file.

The contents of the text file are

```<code>field 1.2     xxxx
field 2.7.1   xxxx
field 1.9     xxxx
field 1.4     xxxx
field 2.7.1   xxxx
</code>```

I tried this:

```<code>cat /tmp/file.txt | sed 's/ /:/g'
</code>```

but as the space is not consistent over the rows, this does not work for me.

How can I do this?
the output that i am expecting here is something like this

```<code>field :1.2    :xxxx
field :2.7.1  :xxxx
field :1.9    :xxxx
field :1.4    :xxxx
field :2.7.1  :xxxx
</code>```

答:
```<code>$ sed -E 's/[[:blank:]]+/&:/g' /tmp/file.txt
field :1.2     :xxxx
field :2.7.1   :xxxx
field :1.9     :xxxx
field :1.4     :xxxx
field :2.7.1   :xxxx
</code>```

no need to use cat, many cli tools accept both stdin and file inputs

[[:blank:]] to match space and tab characters, if you know there are only space characters, use literal space

+ to match one or more of blank characters, note the use of -E option to enable ERE. Some sed versions might support only -r instead of -E

If ERE is not available, use sed 's/[[:blank:]]\{1,\}/&:/g'

& in replacement section refers to entire matched string

Body:
I have a scenario where I have a text file and I want to separate the row values in the text file with a particular delimiter (say, :).

I have generated the text file by storing the output of an SQL query into a text file.

The contents of the text file are

field 1.2     xxxx
field 2.7.1   xxxx
field 1.9     xxxx
field 1.4     xxxx
field 2.7.1   xxxx

I tried this:

cat /tmp/file.txt | sed 's/ /:/g'

but as the space is not consistent over the rows, this does not work for me.

How can I do this?
the output that i am expecting here is something like this

field :1.2    :xxxx
field :2.7.1  :xxxx
field :1.9    :xxxx
field :1.4    :xxxx
field :2.7.1  :xxxx

Body:
$ sed -E 's/[[:blank:]]+/&:/g' /tmp/file.txt
field :1.2     :xxxx
field :2.7.1   :xxxx
field :1.9     :xxxx
field :1.4     :xxxx
field :2.7.1   :xxxx

no need to use cat, many cli tools accept both stdin and file inputs

[[:blank:]] to match space and tab characters, if you know there are only space characters, use literal space

+ to match one or more of blank characters, note the use of -E option to enable ERE. Some sed versions might support only -r instead of -E

If ERE is not available, use sed 's/[[:blank:]]\{1,\}/&:/g'

& in replacement section refers to entire matched string


问:
Constrained optimization where the constraint is computed as a part of objective function
I made a function f that takes a long time to run. The constraints are calculated at the end of f's routine. How can I return these constraints to cobyla without evaluating f twice?

```<code>import numpy as np
from scipy.optimize import fmin_cobyla as mini
def f(x, returncons=True):
    if returncons: return x[1] - x[0]
    else: return (x[0] - 2)**2 + 4 * (x[1] -x[0]**2)**2

x_opt = mini(f, [1., 1.], args=(False,), cons=f)
</code>```

答:
LRU Cache

This is implementing Paul Panzer's suggestion, it relies on @lru_cache which is a Python 3 feature. We cannot directly apply this decorator to the objective function, because it receives a NumPy array, which is mutable and therefore not hashable. So we need two functions:

func_with_cons computes the objective and constraint, given scalar arguments.

f calls func_with_cons and returns either objective or constraint, based on returncons argument.

Note that we need consargs parameter in the call to fmin_cobyla, because without it the same extra arguments args will be passed to the constraint function.

```<code>from scipy.optimize import fmin_cobyla as mini
from functools import lru_cache

@lru_cache(maxsize=32)
def func_with_cons(x0, x1):
    return (x0 - 2)**2 + 4 * (x1 -x0**2)**2, x0 - x1

def f(x, returncons=True):
    value, cons = func_with_cons(x[0], x[1])
    return cons if returncons else value

func_with_cons.cache_clear()
x_opt = mini(f, (1., 1.), cons=f, args=(False,), consargs=())
print(x_opt)
print(func_with_cons.cache_info())
</code>```

Output:

```<code>[ 1.14491021  1.14491021]
CacheInfo(hits=41, misses=32, maxsize=32, currsize=32)
</code>```

So, the cache works. I changed the constraint from x1-x0 to x0-x1 to show that it also works (the original constraint x1-x0 is satisfied by the global minimum of this function, so it would have no effect on the result).

Cache size can be much smaller: with maxsize=2 we would have 40 hits (vs 41 with the above size).

Global variable

This is implementing Jakob Lovern's suggestion. The function f stores the constraint in a global variable, from which the function cons retrieves it. The use of a global has obvious drawbacks, but then again, this works in Python 2.7.

```<code>def f(x):
    global stored_cons
    stored_cons = x[0] - x[1]
    return (x[0] - 2)**2 + 4 * (x[1] -x[0]**2)**2

def cons(x):
    return stored_cons

x0 = [1., 1.]
f(x0)  # called to initialize stored_cons
x_opt = mini(f, x0, cons=cons)
</code>```

This returns [ 1.14491021,  1.14491021] since the global minimum [2, 4] is disallowed by the constraint.

Body:
I made a function f that takes a long time to run. The constraints are calculated at the end of f's routine. How can I return these constraints to cobyla without evaluating f twice?

import numpy as np
from scipy.optimize import fmin_cobyla as mini
def f(x, returncons=True):
    if returncons: return x[1] - x[0]
    else: return (x[0] - 2)**2 + 4 * (x[1] -x[0]**2)**2

x_opt = mini(f, [1., 1.], args=(False,), cons=f)

Body:
LRU Cache

This is implementing Paul Panzer's suggestion, it relies on @lru_cache which is a Python 3 feature. We cannot directly apply this decorator to the objective function, because it receives a NumPy array, which is mutable and therefore not hashable. So we need two functions:

func_with_cons computes the objective and constraint, given scalar arguments.

f calls func_with_cons and returns either objective or constraint, based on returncons argument.

Note that we need consargs parameter in the call to fmin_cobyla, because without it the same extra arguments args will be passed to the constraint function.

from scipy.optimize import fmin_cobyla as mini
from functools import lru_cache

@lru_cache(maxsize=32)
def func_with_cons(x0, x1):
    return (x0 - 2)**2 + 4 * (x1 -x0**2)**2, x0 - x1

def f(x, returncons=True):
    value, cons = func_with_cons(x[0], x[1])
    return cons if returncons else value

func_with_cons.cache_clear()
x_opt = mini(f, (1., 1.), cons=f, args=(False,), consargs=())
print(x_opt)
print(func_with_cons.cache_info())

Output:

[ 1.14491021  1.14491021]
CacheInfo(hits=41, misses=32, maxsize=32, currsize=32)

So, the cache works. I changed the constraint from x1-x0 to x0-x1 to show that it also works (the original constraint x1-x0 is satisfied by the global minimum of this function, so it would have no effect on the result).

Cache size can be much smaller: with maxsize=2 we would have 40 hits (vs 41 with the above size).

Global variable

This is implementing Jakob Lovern's suggestion. The function f stores the constraint in a global variable, from which the function cons retrieves it. The use of a global has obvious drawbacks, but then again, this works in Python 2.7.

def f(x):
    global stored_cons
    stored_cons = x[0] - x[1]
    return (x[0] - 2)**2 + 4 * (x[1] -x[0]**2)**2

def cons(x):
    return stored_cons

x0 = [1., 1.]
f(x0)  # called to initialize stored_cons
x_opt = mini(f, x0, cons=cons)

This returns [ 1.14491021,  1.14491021] since the global minimum [2, 4] is disallowed by the constraint.


问:
Error when doing the Tensorflow tutorial
I follow this tutorial to do the training on Google cloud ml-engine. I follow it step by step but I am facing error when submit the ml job to cloud. I ran this command.

sam@sam-VirtualBox:~/models/research$ gcloud ml-engine jobs submit training whoami_object_detection_date +%s --job-dir=gs://tf_testing/train --packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz --module-name object_detection.train --region us-central1 --config object_detection/samples/cloud/cloud.yml -- --train_dir=gs://tf_testing/train --pipeline_config_path=gs://tf_testing/data/faster_rcnn_resnet101_pets.config

and I got this error.

ERROR: (gcloud.ml-engine.jobs.submit.training) FAILED_PRECONDITION: Field: package_uris Error: The provided GCS paths [gs://tf_testing/train/packages/8ec87a281aadb58d3d82462bbffafa9d7e521cc03025209704bc643eb9f3bc37/slim-0.1.tar.gz, gs://tf_testing/train/packages/8ec87a281aadb58d3d82462bbffafa9d7e521cc03025209704bc643eb9f3bc37/object_detection-0.1.tar.gz] cannot be read by service account service-499049193648@cloud-ml.google.com.iam.gserviceaccount.com. - '@type': type.googleapis.com/google.rpc.BadRequest fieldViolations: - description: The provided GCS paths [gs://tf_testing/train/packages/8ec87a281aadb58d3d82462bbffafa9d7e521cc03025209704bc643eb9f3bc37/slim-0.1.tar.gz, gs://tf_testing/train/packages/8ec87a281aadb58d3d82462bbffafa9d7e521cc03025209704bc643eb9f3bc37/object_detection-0.1.tar.gz] cannot be read by service account service-499049193648@cloud-ml.google.com.iam.gserviceaccount.com. field: package_uris

I saw this post and this post and tried the solution but it did not help. FYI, I did not change PATH_TO_BE_CONFIGURED when ran this command. Could it be the reason?

sed -i "s|PATH_TO_BE_CONFIGURED|"gs://${YOUR_GCS_BUCKET}"/data|g" \
      object_detection/samples/configs/faster_rcnn_resnet101_pets.config

答:
You need to to allow the service account to read/write to your bucket:

gsutil acl ch -u $SVCACCT:WRITE gs://$BUCKET/

gsutil defacl ch -u $SVCACCT:O gs://$BUCKET/

Alternately:

gcloud ml-engine init-project

Will add the service account as an editor on the project. Make sure to do this in the project that owns the bucket


问:
Need to make a field required when radio button is 'Yes' and not required when 'No'
I have searched on this website and tried all the suggestions and have not been able to get the text field to not be required when selecting 'No' on the radio button.

At the moment if 'Yes' and 'No' are not checked, the text field is not required so form will submit.
But if either fields are checked, then it becomes required even for 'No' :-(

I have the demo here: https://jsfiddle.net/ba9ahpyx/

I only want the 'field_2' input to be required if 'Yes' is selected on the 'field_1' radio button.

I will be hiding the text field when 'No' is selected but have removed that code for now to keep it simple.

HTML

```<code><form method="post" action="#">
<div>
  <div class="radio">
    <span class="label">Do you have your own website? (required)</span>
      <div>
        <label><input type="radio" name="field_1" value="Yes"> Yes</label>
        <label><input type="radio" name="field_1" value="No"> No</label>
      </div>
  </div>
</div>

<div>
  <label for="field_2">Website URL </label>
  <input type="text" name="field_2" id="field_2" value="" />
</div>

<div>
  <input type="submit" value="Submit">
</div>
</form>
</code>```

Jquery

```<code>$(document).ready(function(){
    $('input[name="field_1"]').change(function () {
        if(this.checked) {
            $('#field_2').prop('required',true);
        } else {
            $('#field_2').prop('required',false);
        }
    });
});
</code>```

Thanks for your help.

答:
change jquery with following and it will work for you</p>

```<code>$(document).ready(function(){
    $('input[name="field_1"]').change(function () {
        if($(this).val() =='Yes') {
            $('#field_2').prop('required',true);
        } else {
            $('#field_2').prop('required',false);
        }
    });
});
</code>```

Body:
I have searched on this website and tried all the suggestions and have not been able to get the text field to not be required when selecting 'No' on the radio button.

At the moment if 'Yes' and 'No' are not checked, the text field is not required so form will submit.
But if either fields are checked, then it becomes required even for 'No' :-(

I have the demo here: https://jsfiddle.net/ba9ahpyx/

I only want the 'field_2' input to be required if 'Yes' is selected on the 'field_1' radio button.

I will be hiding the text field when 'No' is selected but have removed that code for now to keep it simple.

HTML

<form method="post" action="#">

    Do you have your own website? (required)

        <input type="radio" name="field_1" value="Yes"> Yes
        <input type="radio" name="field_1" value="No"> No

  Website URL
  <input type="text" name="field_2" id="field_2" value="" />

  <input type="submit" value="Submit">

</form>

Jquery

$(document).ready(function(){
    $('input[name="field_1"]').change(function () {
        if(this.checked) {
            $('#field_2').prop('required',true);
        } else {
            $('#field_2').prop('required',false);
        }
    });
});

Thanks for your help.

Body:
change jquery with following and it will work for you

$(document).ready(function(){
    $('input[name="field_1"]').change(function () {
        if($(this).val() =='Yes') {
            $('#field_2').prop('required',true);
        } else {
            $('#field_2').prop('required',false);
        }
    });
});


问:
ng-repeat values in single input with comma separated
I have list array.Inside that I have one nested array called types.
I am trying to show types.work inside an input field with comma separated.

This is what I have tried:

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

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
      }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
   <input type="text" ng-model="list.name">
   <label ng-repeat="data in list.types">{{data.work}}{{$last ? '' : ', '}}</label>
  </div>
</div></code>```

Can anyone tell me that how to use ng-repeat values in single input?.

答:
In case  You want some other solution. You can iterate over your array in JS file and assign the value to your input model.

  <input type="text" ng-model="listData">

```

Body:
I have list array.Inside that I have one nested array called types.
I am trying to show types.work inside an input field with comma separated.

This is what I have tried:

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

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
      }
});

   <input type="text" ng-model="list.name">
   {{data.work}}{{$last ? '' : ', '}}

Can anyone tell me that how to use ng-repeat values in single input?.

Body:
In case  You want some other solution. You can iterate over your array in JS file and assign the value to your input model.

<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<body>
<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
  <input type="text" ng-model="listData">
  </div>
</div>
</body>
<script>var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
 $scope.listData = "";
 for(var i=0;i<$scope.list[0].types.length;i++){

 if($scope.listData!= undefined){
 $scope.listData = $scope.listData+","+$scope.list[0].types[i].work;
 }

 }
      }
});
</script>
</html>


问:
Java Complex Sorting
I am stuck in that I have an Object Book that got three variables

```<code>String title
int Year
String authorName
</code>```

I must sort the books by one, two or all three of the variables in ascending or descending order, I implemented the title ordering but I am stuck as to what to do when people choose more than one variable to order.

Here is some of my code:

Book Class:

```<code>import java.util.ArrayList;

public class Book{

String title;
String authorName;
int editionYear;

public Book(String title, String authorName, int editionYear){
    this.title = title;
    this.authorName = authorName;
    this.editionYear = editionYear;

}

public String getBookInfo(){

    ArrayList bookInfo = new ArrayList();
    bookInfo.add(this.title);
    bookInfo.add(this.authorName);
    bookInfo.add(this.editionYear);
    return bookInfo.toString();
}

}
</code>```

BookSorter Class:

```<code>import java.util.Arrays;
import java.util.Comparator;

public class BookSorter{

private String sortkey;
private String order;
Book[] Books;

public BookSorter(Book Book1, Book Book2, Book Book3, Book Book4){
    this.Books = new Book[] {Book1, Book2, Book3, Book4};
}

public Book[] sortByTitle(boolean sortorder){
    Comparator<Book> byTitle = new TitleComparator(sortorder);
    Arrays.sort(Books, byTitle);
    for(int i=0;i<4;i++) System.out.println(Books[i].title);
    return Books;
}
}
</code>```

TitleComparator:

```<code>import java.util.Comparator;

class TitleComparator implements Comparator<Book> {

boolean ascending;

public TitleComparator(boolean ascending){
    this.ascending = ascending;
}

public int compare(Book Book1, Book Book2){
    if(ascending == true){
        if(Book1.title.compareToIgnoreCase(Book2.title) > 0) return 1;
        else if(Book1.title.compareToIgnoreCase(Book2.title) < 0) return -1;
        else return 0;
    }else{
        if(Book2.title.compareToIgnoreCase(Book1.title) < 0) return -1;
        else if(Book2.title.compareToIgnoreCase(Book1.title) > 0) return 1;
        else return 0;
    }
}
}
</code>```

I though I could work a little more on the comparator but I am really stuck on how to model such a thing, Thanks in advance

答:
The ascending/descending can be implemented much easier, because it simple "inverts" the compare result. And you can "reuse" the results from the compareToIgnoreCase methods:

```<code>public int compare(Book book1, Book book2) {
   int result = book1.title.compareToIgnoreCase(book2.title);
   return ascending ? result : result * -1;
}
</code>```

The other comparators are pretty similiar (limiting the samples to the compare method):

```<code>public int compare(Book book1, Book book2) {
   int result = book1.author.compareToIgnoreCase(book2.author);
   return ascending ? result : result * -1;
}
</code>```

```<code>public int compare(Book book1, Book book2) {
   Integer year1 = book1.year;
   Integer year2 = book2.year;
   int result = year1.compareTo(year2);
   return ascending ? result : result * -1;
}
</code>```

Title: Java Complex Sorting

Body:
I am stuck in that I have an Object Book that got three variables

String title
int Year
String authorName

I must sort the books by one, two or all three of the variables in ascending or descending order, I implemented the title ordering but I am stuck as to what to do when people choose more than one variable to order.

Here is some of my code:

Book Class:

import java.util.ArrayList;

public class Book{

String title;
String authorName;
int editionYear;

public Book(String title, String authorName, int editionYear){
    this.title = title;
    this.authorName = authorName;
    this.editionYear = editionYear;

}

public String getBookInfo(){

    ArrayList bookInfo = new ArrayList();
    bookInfo.add(this.title);
    bookInfo.add(this.authorName);
    bookInfo.add(this.editionYear);
    return bookInfo.toString();
}

}

BookSorter Class:

import java.util.Arrays;
import java.util.Comparator;

public class BookSorter{

private String sortkey;
private String order;
Book[] Books;

public BookSorter(Book Book1, Book Book2, Book Book3, Book Book4){
    this.Books = new Book[] {Book1, Book2, Book3, Book4};
}

public Book[] sortByTitle(boolean sortorder){
    Comparator<Book> byTitle = new TitleComparator(sortorder);
    Arrays.sort(Books, byTitle);
    for(int i=0;i<4;i++) System.out.println(Books[i].title);
    return Books;
}
}

TitleComparator:

import java.util.Comparator;

class TitleComparator implements Comparator<Book> {

boolean ascending;

public TitleComparator(boolean ascending){
    this.ascending = ascending;
}

public int compare(Book Book1, Book Book2){
    if(ascending == true){
        if(Book1.title.compareToIgnoreCase(Book2.title) > 0) return 1;
        else if(Book1.title.compareToIgnoreCase(Book2.title) < 0) return -1;
        else return 0;
    }else{
        if(Book2.title.compareToIgnoreCase(Book1.title) < 0) return -1;
        else if(Book2.title.compareToIgnoreCase(Book1.title) > 0) return 1;
        else return 0;
    }
}
}

I though I could work a little more on the comparator but I am really stuck on how to model such a thing, Thanks in advance

Body:
The ascending/descending can be implemented much easier, because it simple "inverts" the compare result. And you can "reuse" the results from the compareToIgnoreCase methods:

public int compare(Book book1, Book book2) {
   int result = book1.title.compareToIgnoreCase(book2.title);
   return ascending ? result : result * -1;
}

The other comparators are pretty similiar (limiting the samples to the compare method):

public int compare(Book book1, Book book2) {
   int result = book1.author.compareToIgnoreCase(book2.author);
   return ascending ? result : result * -1;
}

public int compare(Book book1, Book book2) {
   Integer year1 = book1.year;
   Integer year2 = book2.year;
   int result = year1.compareTo(year2);
   return ascending ? result : result * -1;
}