问:
Excluding files of a certain size
I'm trying to generate a .csv file that lists all .txt file in a sub-directory but can exclude a .txt file of a certain size.

Without an if statement around file size, I can successfully generate the .csv file list that has the full paths to the .txt files (1105 files total)

```<code>import os
import csv
import os.path
mtn_path = "TEXT_FILE_PATH\\"
a = open(mtn_path + "output.csv", 'w+', newline='')
num_files = 0
for path, dirnames, filenames in os.walk(mtn_path):
    for filename in [f for f in filenames if f.endswith(".txt")]:
#       if os.stat(filename).st_size > 20000:
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep)
            num_files = num_files + 1
)
#
print("The total number of text files found was " + str(num_files))
</code>```

When I include the if os.stat line, I get the error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'INT_NR_H1000Cu_000.mtn_001.txt'

That particular .txt file is the first one listed in the csv file of the working code.

答:
You need to pass the full path to os.stat. Rearrange your code a bit:

```<code>for filename in [f for f in filenames if f.endswith(".txt")]:
    f = os.path.join(path, filename)
    if os.stat(f).st_size > 20000:
        a.write(str(f) + os.linesep)
        num_files = num_files + 1
</code>```

Title: Excluding files of a certain size

Body:
I'm trying to generate a .csv file that lists all .txt file in a sub-directory but can exclude a .txt file of a certain size.

Without an if statement around file size, I can successfully generate the .csv file list that has the full paths to the .txt files (1105 files total)

import os
import csv
import os.path
mtn_path = "TEXT_FILE_PATH\\"
a = open(mtn_path + "output.csv", 'w+', newline='')
num_files = 0
for path, dirnames, filenames in os.walk(mtn_path):
    for filename in [f for f in filenames if f.endswith(".txt")]:
#       if os.stat(filename).st_size > 20000:
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep)
            num_files = num_files + 1
)
#
print("The total number of text files found was " + str(num_files))

When I include the if os.stat line, I get the error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'INT_NR_H1000Cu_000.mtn_001.txt'

That particular .txt file is the first one listed in the csv file of the working code.

Body:
You need to pass the full path to os.stat. Rearrange your code a bit:

for filename in [f for f in filenames if f.endswith(".txt")]:
    f = os.path.join(path, filename)
    if os.stat(f).st_size > 20000:
        a.write(str(f) + os.linesep)
        num_files = num_files + 1


来源: stackexchange

问:
form does not get full text from database
when i try to edit a record, my form does not receive the full text, for example, if in my database I have the string "hello world" in my edit form it will just show me "hello"

edit function

```<code>public function edit($id)
{
    $cooperado = Cooperado::find($id);

    return view('cooperados.edit', compact('cooperado'));
}
</code>```

edit form

```<code>  <form method="post" action="{{ route('cooperados.update', $cooperado->id) }}">
    <div class="form-group">
      <label for="name">Nome :</label>
      <input type="text" class="form-control" name="nameCoop" value={{ $cooperado->nameCoop }} />
    </div>
    <div class="form-group">
      <label for="description">Observações :</label>
      <input type="text" class="form-control" name="description" value={{ $cooperado->description }} />
    </div>
  </form>
</code>```

答:
The problem is that the values should be surrounded by ". See this question.

In your code it should be

value="{{ $cooperado->nameCoop }}"
```

<p>and</p>

<pre class="lang-php prettyprint-override"><code>value="{{ $cooperado->description }}"
</code>```

The " characters tell the browser that the entire attribute value is enclosed between them. Without them, the browser doesn't know where the value ends and where the HTML attributes start.

ContentLicense: CC BY-SA 4.0

Body:
when i try to edit a record, my form does not receive the full text, for example, if in my database I have the string "hello world" in my edit form it will just show me "hello"

edit function

public function edit($id)
{
    $cooperado = Cooperado::find($id);

    return view('cooperados.edit', compact('cooperado'));
}

edit form

  <form method="post" action="{{ route('cooperados.update', $cooperado->id) }}">

      Nome :
      <input type="text" class="form-control" name="nameCoop" value={{ $cooperado->nameCoop }} />

      Observações :
      <input type="text" class="form-control" name="description" value={{ $cooperado->description }} />

  </form>

Body:
The problem is that the values should be surrounded by ". See this question.

In your code it should be

value="{{ $cooperado->nameCoop }}"

and

value="{{ $cooperado->description }}"

The " characters tell the browser that the entire attribute value is enclosed between them. Without them, the browser doesn't know where the value ends and where the HTML attributes start.


问:
Is there a way to throttle/slow a PHP script without missing streaming results from STDOUT?
I'm testing out an interesting "threading" concept in PHP. Basically, I'm working to have a parent process spawn children that do stuff and return the results back to the parent via STDOUT in sort of a callback manner.

The way my example  does it, the inner loop is too tight and burns 99% CPU:

```<code>while(true){
        $ret = $thread->Listen();
        if( $ret == 'DOINGSTUFF' ){
                break;
        }
}
</code>```

I'd like to tone this while loop down to looping every 5 seconds using, for example, a sleep(). This brings CPU utilization to a much more rational level; however I'm concerned it will then "miss" some of the children "threads" returning results in case one child finishes during the parent's sleeping process.

Can a PHP expert tell me whether this concern is well founded and if so, whether there's anything I can do to cope?

答:
Well, as you have already noticed, while(true) is the one burning the CPU and you can't "slow" the thing down. You want your app to behave as a listener, say a socket - it is active only when something wants to talk to it, otherwise it just stays dormant and "listens".
You should really create a listener on one of the ports and re-try your example, emulating a listener will only burn up CPU cycles for no reason. It makes inter-process communication easier too as you got a server and bunch of clients (processes) connected to it so you can share resources any way you like.

Also, re: threading in PHP - all you can do is fork a process, which isn't really threading and is a burden for the OS. Unless there's something that you really want to do in parallel, you should avoid forking at all costs.

ContentLicense: CC BY-SA 3.0

Body:
I'm testing out an interesting "threading" concept in PHP. Basically, I'm working to have a parent process spawn children that do stuff and return the results back to the parent via STDOUT in sort of a callback manner.

The way my example  does it, the inner loop is too tight and burns 99% CPU:

while(true){
        $ret = $thread->Listen();
        if( $ret == 'DOINGSTUFF' ){
                break;
        }
}

I'd like to tone this while loop down to looping every 5 seconds using, for example, a sleep(). This brings CPU utilization to a much more rational level; however I'm concerned it will then "miss" some of the children "threads" returning results in case one child finishes during the parent's sleeping process.

Can a PHP expert tell me whether this concern is well founded and if so, whether there's anything I can do to cope?


问:
Subsetting a matrix by row.names
I have a matrix with the following row.names:

```<code>"X1"   "X5"   "X33"  "X37"  "X52"  "X566"
</code>```

Now I want to select only the rows which match the entries of a list, say:

```<code>include_list <- c("X1", "X5", "X33")
</code>```

I imagine I'd do something like this:

```<code>data.subset <- subset(data, row.names == include_list)
</code>```

However, this particular code does not seem to do the job. How can I perform subsetting in this way?

答:
Just in case someone's include_list is class list (rather than vector), then this is modification of Rich Scriven's answer that works in such case based on this. unlist() should be added:

```<code>m <- matrix(1:30, 6, 5)
rownames(m) <- c("X1", "X5", "X33", "X37", "X52", "X566")
include_list <- list("X1", "X5", "X33")

m[unlist(include_list), ]
</code>```

Title: Subsetting a matrix by row.names

Body:
I have a matrix with the following row.names:

"X1"   "X5"   "X33"  "X37"  "X52"  "X566"

Now I want to select only the rows which match the entries of a list, say:

include_list <- c("X1", "X5", "X33")

I imagine I'd do something like this:

data.subset <- subset(data, row.names == include_list)

However, this particular code does not seem to do the job. How can I perform subsetting in this way?

Body:
Just in case someone's include_list is class list (rather than vector), then this is modification of Rich Scriven's answer that works in such case based on this. unlist() should be added:

m <- matrix(1:30, 6, 5)
rownames(m) <- c("X1", "X5", "X33", "X37", "X52", "X566")
include_list <- list("X1", "X5", "X33")

m[unlist(include_list), ]


问:
Laravel, ENV Variable from routes file
I try to access ENV variable from routes/web.php file, but it keep failing. The reason is I want to make special routes group for dashboard / client area. Here is my latest code;

```<code>$dashboard = env('DASHBOARD_DOMAIN', 'localhost');

Route::group(['domain' => 'dashboard.localhost.dev','middleware' => 'auth'], function () {
    Route::get('/', 'DashboardController@index');
});
</code>```

Above code is work, but I don't want to hard code the domain value like that, because if I use this way I need to change them again everytime I upload my code to production server. But if I put $dashboard as domain value, it simply not work.

答:
I had the same issue. But fixed by changing the function.

Change the variable like this.

```<code>config('dashboard.domain', 'localhost')
</code>```

Clear cache by running

```<code>php artisan config:cache
</code>```

Your code will be like this.

```<code>$dashboard = config('dashboard.domain', 'localhost');

Route::group(['domain' => 'dashboard.localhost.dev','middleware' => 'auth'], function () {
    Route::get('/', 'DashboardController@index');
});
</code>```

Title: Laravel, ENV Variable from routes file

Body:
I try to access ENV variable from routes/web.php file, but it keep failing. The reason is I want to make special routes group for dashboard / client area. Here is my latest code;

$dashboard = env('DASHBOARD_DOMAIN', 'localhost');

Route::group(['domain' => 'dashboard.localhost.dev','middleware' => 'auth'], function () {
    Route::get('/', 'DashboardController@index');
});

Above code is work, but I don't want to hard code the domain value like that, because if I use this way I need to change them again everytime I upload my code to production server. But if I put $dashboard as domain value, it simply not work.

Body:
I had the same issue. But fixed by changing the function.

Change the variable like this.

config('dashboard.domain', 'localhost')

Clear cache by running

php artisan config:cache

Your code will be like this.

$dashboard = config('dashboard.domain', 'localhost');

Route::group(['domain' => 'dashboard.localhost.dev','middleware' => 'auth'], function () {
    Route::get('/', 'DashboardController@index');
});


问:
Get Tenant Id from RabbitMq Message for Db Connection
I have a microservice architecture with ASP.Net Core applications and RabbitMq as the event bus between the microservices.

I also want to support multi tenancy.

So I have following dependency injection service defined in the Startup.cs to open a connection to the Database on every request based on the user's tenant id.

```<code>services.AddScoped<IDocumentSession>(ds =>
            {
                var store = ds.GetRequiredService<IDocumentStore>();
                var httpContextAccessor = ds.GetRequiredService<IHttpContextAccessor>();
                var tenant = httpContextAccessor?.HttpContext?.User?.Claims.FirstOrDefault(c => c.Type == "tid")?.Value;
                return tenant != null ? store.OpenSession(tenant) : store.OpenSession();
            });
</code>```

The problem is when the service processes an event bus message (like UserUpdatedEvent).

In that case when it tries to open the Db connection, it obviously does not have the user information from the http context.

How do I send/access the tenant id of the respective user when injecting the scoped service and processing an event with RabbitMq?

Or rephrasing my question:
Is there any way to access the RabbitMQ message (and for example its headers) when the dependency injection code is executed?

答:
Since there is no HttpContext, because a RabbitMq request is not a Http request, as pointed out in @istepaniuk's answer, I created my own context and called it AmqpContext:

```<code>public interface IAmqpContext
    {
        void ClearHeaders();
        void AddHeaders(IDictionary<string, object> headers);
        string GetHeaderByKey(string headerKey);
    }

    public class AmqpContext : IAmqpContext
    {
        private readonly Dictionary<string, object> _headers;

        public AmqpContext()
        {
            _headers = new Dictionary<string, object>();
        }

        public void ClearHeaders()
        {
            _headers.Clear();
        }

        public void AddHeaders(IDictionary<string, object> headers)
        {
            foreach (var header in headers)
                _headers.Add(header.Key, header.Value);
        }

        public string GetHeaderByKey(string headerKey)
        {
            if (_headers.TryGetValue(headerKey, out object headerValue))
            {
                return Encoding.Default.GetString((byte[])headerValue);
            }
            return null;
        }
    }
</code>```

And when sending the RabbitMq message I send the tenant id via the headers like this:

```<code>                    var properties = channel.CreateBasicProperties();
                    if (tenantId != null)
                    {
                        var headers = new Dictionary<string, object>
                        {
                            { "tid", tenantId }
                        };
                        properties.Headers = headers;
                    }

                    channel.BasicPublish(exchange: BROKER_NAME,
                                     routingKey: eventName,
                                     mandatory: true,
                                     basicProperties: properties,
                                     body: body);
</code>```

Then when on the receiving service I register the AmqpContext as a scoped service in the Startup.cs:

```<code>services.AddScoped<IAmqpContext, AmqpContext>();
</code>```

When receiving the RabbitMq message, within the consumer channel, a scope and the Amqp context is created:

```<code>consumer.Received += async (model, ea) =>
            {
                var eventName = ea.RoutingKey;
                var message = Encoding.UTF8.GetString(ea.Body);
                var properties = ea.BasicProperties;

                using (var scope = _serviceProvider.CreateScope())
                        {
                            var amqpContext = scope.ServiceProvider.GetService<IAmqpContext>();
                            if (amqpContext != null)
                            {
                                amqpContext.ClearHeaders();
                                if (properties.Headers != null && amqpContext != null)
                                {
                                    amqpContext.AddHeaders(properties.Headers);
                                }
                            }
                            var handler = scope.ServiceProvider.GetService(subscription.HandlerType);
                            if (handler == null) continue;
                            var eventType = _subsManager.GetEventTypeByName(eventName);
                            var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
                            var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
                            await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
                        }

                channel.BasicAck(ea.DeliveryTag, multiple: false);
            };
</code>```

Then when the scoped Db connection service is created (see my question) I can access the tenant id from the message headers:

```<code>    services.AddScoped<IDocumentSession>(ds =>
    {
        var store = ds.GetRequiredService<IDocumentStore>();
        string tenant = null;
        var httpContextAccessor = ds.GetRequiredService<IHttpContextAccessor>();
        if (httpContextAccessor.HttpContext != null)
        {
            tenant = httpContextAccessor.HttpContext.User?.Claims.FirstOrDefault(c => c.Type == "tid")?.Value;
        }
        else
        {
            var amqpContext = ds.GetRequiredService<IAmqpContext>();
            tenant = amqpContext.GetHeaderByKey("tid");
        }
        return tenant != null ? store.OpenSession(tenant) : store.OpenSession();
    });
</code>```

Body:
I have a microservice architecture with ASP.Net Core applications and RabbitMq as the event bus between the microservices.

I also want to support multi tenancy.

So I have following dependency injection service defined in the Startup.cs to open a connection to the Database on every request based on the user's tenant id.

services.AddScoped<IDocumentSession>(ds =>
            {
                var store = ds.GetRequiredService<IDocumentStore>();
                var httpContextAccessor = ds.GetRequiredService<IHttpContextAccessor>();
                var tenant = httpContextAccessor?.HttpContext?.User?.Claims.FirstOrDefault(c => c.Type == "tid")?.Value;
                return tenant != null ? store.OpenSession(tenant) : store.OpenSession();
            });

The problem is when the service processes an event bus message (like UserUpdatedEvent).

In that case when it tries to open the Db connection, it obviously does not have the user information from the http context.

How do I send/access the tenant id of the respective user when injecting the scoped service and processing an event with RabbitMq?

Or rephrasing my question:
Is there any way to access the RabbitMQ message (and for example its headers) when the dependency injection code is executed?

Body:
Since there is no HttpContext, because a RabbitMq request is not a Http request, as pointed out in @istepaniuk's answer, I created my own context and called it AmqpContext:

public interface IAmqpContext
    {
        void ClearHeaders();
        void AddHeaders(IDictionary<string, object> headers);
        string GetHeaderByKey(string headerKey);
    }

    public class AmqpContext : IAmqpContext
    {
        private readonly Dictionary<string, object> _headers;

        public AmqpContext()
        {
            _headers = new Dictionary<string, object>();
        }

        public void ClearHeaders()
        {
            _headers.Clear();
        }

        public void AddHeaders(IDictionary<string, object> headers)
        {
            foreach (var header in headers)
                _headers.Add(header.Key, header.Value);
        }

        public string GetHeaderByKey(string headerKey)
        {
            if (_headers.TryGetValue(headerKey, out object headerValue))
            {
                return Encoding.Default.GetString((byte[])headerValue);
            }
            return null;
        }
    }

And when sending the RabbitMq message I send the tenant id via the headers like this:

                    var properties = channel.CreateBasicProperties();
                    if (tenantId != null)
                    {
                        var headers = new Dictionary<string, object>
                        {
                            { "tid", tenantId }
                        };
                        properties.Headers = headers;
                    }

                    channel.BasicPublish(exchange: BROKER_NAME,
                                     routingKey: eventName,
                                     mandatory: true,
                                     basicProperties: properties,
                                     body: body);

Then when on the receiving service I register the AmqpContext as a scoped service in the Startup.cs:

services.AddScoped<IAmqpContext, AmqpContext>();

When receiving the RabbitMq message, within the consumer channel, a scope and the Amqp context is created:

consumer.Received += async (model, ea) =>
            {
                var eventName = ea.RoutingKey;
                var message = Encoding.UTF8.GetString(ea.Body);
                var properties = ea.BasicProperties;

                using (var scope = _serviceProvider.CreateScope())
                        {
                            var amqpContext = scope.ServiceProvider.GetService<IAmqpContext>();
                            if (amqpContext != null)
                            {
                                amqpContext.ClearHeaders();
                                if (properties.Headers != null && amqpContext != null)
                                {
                                    amqpContext.AddHeaders(properties.Headers);
                                }
                            }
                            var handler = scope.ServiceProvider.GetService(subscription.HandlerType);
                            if (handler == null) continue;
                            var eventType = _subsManager.GetEventTypeByName(eventName);
                            var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
                            var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
                            await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
                        }

                channel.BasicAck(ea.DeliveryTag, multiple: false);
            };

Then when the scoped Db connection service is created (see my question) I can access the tenant id from the message headers:

    services.AddScoped<IDocumentSession>(ds =>
    {
        var store = ds.GetRequiredService<IDocumentStore>();
        string tenant = null;
        var httpContextAccessor = ds.GetRequiredService<IHttpContextAccessor>();
        if (httpContextAccessor.HttpContext != null)
        {
            tenant = httpContextAccessor.HttpContext.User?.Claims.FirstOrDefault(c => c.Type == "tid")?.Value;
        }
        else
        {
            var amqpContext = ds.GetRequiredService<IAmqpContext>();
            tenant = amqpContext.GetHeaderByKey("tid");
        }
        return tenant != null ? store.OpenSession(tenant) : store.OpenSession();
    });


问:
How to define a function to use with scipy.integrate.solve_ivp
I am trying to solve a differential equation using scipy.integrate.solve_ivp

```<code>L*Q'' + R*Q' + (1/C)*Q = E(t), E(t) = 230*sin(50*t)
</code>```

for Q(t) and Q'(t)

```<code>C = 0.0014 #F
dQ_0 = 2.6 #A
L = 1.8 #H
n = 575 #/
Q_0 = 1e-06 #C
R = 43 #Ohm
t_f = 2.8 #s

import numpy as np
from scipy.integrate import solve_ivp

t = np.linspace(0, t_f, n)

def E(x):
    return 230*np.sin(50*x)

y = E(y)

def Q(t, y, R, L, C):
     return (y - L*Q'' - R*Q')*C

init_cond = [Q_0, dQ_0]

y_ivp = solve_ivp(Q, t_span=(0, t_f), y0=init_cond)
</code>```

I am only trying to understand how to correctly define a function that is passed as an argument 'fun' in scipy.integrate.solve_ivp

答:
The answer below is no longer valid, solve_ode has since implemented the args parameter similar to odeint. So indeed

```<code>y_ivp = solve_ivp(Q, t_span=(0, t_f), y0=init_cond, args=(R, L, C))
</code>```

is now valid (do not forget to set appropriate error tolerances, or at least check that the default values arol=1e-3, rtol=1e-6 are appropriate).

Always available was the use of semi-global variables in a closure or lambda expression

```<code>y_ivp = solve_ivp(lambda t,y: Q(t,y,R, L, C), t_span=(0, t_f), y0=init_cond, args=(R, L, C))
</code>```

(obsolete part) solve_ivp has no parameter passing mechanism, so treat the parameters as global variables. You are formulating an ODE for Q, as it is a second order ODE, the state also contains the first derivative, as you somehow recognized in the composition of the initial state. The ODE function then needs to produce the derivative values at a given state. Identify Q(t)=Q[0] and Q'(t)=Q[1], then

```<code>def Q_ode(t, Q):
     return [ Q[1], (E(t) - R*Q[1] - (1/C)*Q[0])/L ]
</code>```

I would continue to name the variables containing Q values with the letter Q.

Body:
I am trying to solve a differential equation using scipy.integrate.solve_ivp

L*Q'' + R*Q' + (1/C)*Q = E(t), E(t) = 230*sin(50*t)

for Q(t) and Q'(t)

C = 0.0014 #F
dQ_0 = 2.6 #A
L = 1.8 #H
n = 575 #/
Q_0 = 1e-06 #C
R = 43 #Ohm
t_f = 2.8 #s

import numpy as np
from scipy.integrate import solve_ivp

t = np.linspace(0, t_f, n)

def E(x):
    return 230*np.sin(50*x)

y = E(y)

def Q(t, y, R, L, C):
     return (y - L*Q'' - R*Q')*C

init_cond = [Q_0, dQ_0]

y_ivp = solve_ivp(Q, t_span=(0, t_f), y0=init_cond)

I am only trying to understand how to correctly define a function that is passed as an argument 'fun' in scipy.integrate.solve_ivp

Body:
The answer below is no longer valid, solve_ode has since implemented the args parameter similar to odeint. So indeed

y_ivp = solve_ivp(Q, t_span=(0, t_f), y0=init_cond, args=(R, L, C))

is now valid (do not forget to set appropriate error tolerances, or at least check that the default values arol=1e-3, rtol=1e-6 are appropriate).

Always available was the use of semi-global variables in a closure or lambda expression

y_ivp = solve_ivp(lambda t,y: Q(t,y,R, L, C), t_span=(0, t_f), y0=init_cond, args=(R, L, C))

(obsolete part) solve_ivp has no parameter passing mechanism, so treat the parameters as global variables. You are formulating an ODE for Q, as it is a second order ODE, the state also contains the first derivative, as you somehow recognized in the composition of the initial state. The ODE function then needs to produce the derivative values at a given state. Identify Q(t)=Q[0] and Q'(t)=Q[1], then

def Q_ode(t, Q):
     return [ Q[1], (E(t) - R*Q[1] - (1/C)*Q[0])/L ]

I would continue to name the variables containing Q values with the letter Q.


问:
How to initialize a method in state in a constructor that is dependent on another methods value
I'm trying to initialize three functions as state in the constructor in order to get the values from those functions and have those values available in state before the first render. However, one of the functions have a variable dependent on the value of a previous function and so I get an error.

How would I fix this problem? Code is below!

App.js file

```<code>import React from "react";
import Calendar from "./Calendar"

function App() {
    return (
        <div>
            <Calendar />
        </div>

    )
}

export default App;
</code>```

Calendar.js file

```<code>import React from "react";

class Calendar extends React.Component {
    constructor() {
        super();

    this.state = {
        //curLastDate() is dependent on lastDayOfMonth()
        lastDayOfMonth: this.storeLastDate(),
        currentLastDate: this.curLastDate()
    }
}
    /*
    Stores the last date of all months of the current year
    Format: [ ["Thu", "Jan", "31", "2019]... ]
    */
    storeLastDate() {
            let date,
                string,
                lastDate,
                list = [];

            date = new Date();

            for (let i = 1; i < 13; i++) {

                lastDate = new Date(date.getFullYear(), i, 0);
                string = lastDate.toDateString().split(" ");
                list.push(string);
            }

            return list;
    }

/*
Finds the matching month of current date
*/
curLastDate() {

    for (let i = 0; i < this.state.lastDayOfMonth.length; i++) {
        if (this.state.currentDate[1] === this.state.lastDayOfMonth[i][1]) {
            console.log(this.state.lastDayOfMonth[i][1]);
            return this.state.lastDayOfMonth[i][1];
        }
    }
}

render() {
    return (
        null
        )
    }

}
export default Calendar;
</code>```

Ultimately, I want to initialize the values I get from the functions to the state before React has its first render. Thanks for the help in advance!

答:
Try something like this:

If you re-use your function curLastDate, just pass lastDayOfMonth

import React, {useState, useEffect} from "react";

function Calendar() {
    //curLastDate() is dependent on lastDayOfMonth()
    const [lastDayOfMonth, setLastDayOfMonth] = useState();
    const [currentLastDate, setCurrentLastDate] = useState();

    useEffect(async () => {
        const list = await storeLastDate();
        setLastDayOfMonth(list);
        const curLastDateRet = curLastDate(list);
        setCurrentLastDate(curLastDateRet);
    }, []);

    const storeLastDate = () => {
        return new Promise((resolve, reject) => {
            let date,
                string,
                lastDate,
                list = [];

            date = new Date();

            for (let i = 1; i < 13; i++) {

                lastDate = new Date(date.getFullYear(), i, 0);
                string = lastDate.toDateString().split(" ");
                list.push(string);
            }
            resolve(list);
        });
    }

    /*
    Finds the matching month of current date
    */
    const curLastDate = lastDayOfMonth => {
        for (let i = 0; i < lastDayOfMonth.length; i++) {
            if (this.state.currentDate[1] === lastDayOfMonth[i][1]) {
                console.log(lastDayOfMonth[i][1]);
                return lastDayOfMonth[i][1];
            }
        }
    }

    return (
        <></>// some content here
    )

}
export default Calendar;

```

Body:
I'm trying to initialize three functions as state in the constructor in order to get the values from those functions and have those values available in state before the first render. However, one of the functions have a variable dependent on the value of a previous function and so I get an error.

How would I fix this problem? Code is below!

App.js file

import React from "react";
import Calendar from "./Calendar"

function App() {
    return (

            <Calendar />

    )
}

export default App;

Calendar.js file

import React from "react";

class Calendar extends React.Component {
    constructor() {
        super();

    this.state = {
        //curLastDate() is dependent on lastDayOfMonth()
        lastDayOfMonth: this.storeLastDate(),
        currentLastDate: this.curLastDate()
    }
}
    /*
    Stores the last date of all months of the current year
    Format: [ ["Thu", "Jan", "31", "2019]... ]
    */
    storeLastDate() {
            let date,
                string,
                lastDate,
                list = [];

            date = new Date();

            for (let i = 1; i < 13; i++) {

                lastDate = new Date(date.getFullYear(), i, 0);
                string = lastDate.toDateString().split(" ");
                list.push(string);
            }

            return list;
    }

/*
Finds the matching month of current date
*/
curLastDate() {

    for (let i = 0; i < this.state.lastDayOfMonth.length; i++) {
        if (this.state.currentDate[1] === this.state.lastDayOfMonth[i][1]) {
            console.log(this.state.lastDayOfMonth[i][1]);
            return this.state.lastDayOfMonth[i][1];
        }
    }
}

render() {
    return (
        null
        )
    }

}
export default Calendar;

Ultimately, I want to initialize the values I get from the functions to the state before React has its first render. Thanks for the help in advance!


问:
What is the type of result? Is it possible?
I try to search an answer to my question...
What is the type of this expression will be at C language?

```<code>unsigned short a, b;
a = 0x1;
b = 0x2;
if((a ^ b) > 0) //This expression...
...
</code>```

I understand that this is not a completely correct code that can cause an error. I should use != instead >.

I think that the type of the result of the expression will be unsigned int. I read about it in Stephen Pratt’s book.

If we have two types, then the result of an expression involving these types must be a superior type. (int or unsigned int)

If these two variables have any other values, can it be that this expression will be less than zero?
(If we set the most significant bit in the number, it will become negative, provided that it has signed data type)

I think it is impossible, but I could be wrong.
I made my guess, but I want to know the correct answer to my question.

答:
In (a ^ b) > 0, where a and b are unsigned short:

If unsigned short is narrower than int, a and b are each converted to int (per the integer promotions, C 2018 6.3.1.1 2, and because unsigned short being narrower than int necessarily means int can represent all values of unsigned short).

Otherwise, a and b are converted to unsigned int (ibid).

For a ^ b, the usual arithmetic conversions are performed (6.5.11). In this expression, the usual arithmetic conversions do not change the types (6.3.1.8 1). Also per the usual arithmetic conversions, the result has the same type as the operands after the conversions. Thus, the result is int or unsigned int as described above.

(a ^ b) has the same type as a ^ b (6.5.1 5).

For (a ^ b) > 0, the result has type int (6.5.8 6).

Body:
I try to search an answer to my question...
What is the type of this expression will be at C language?

unsigned short a, b;
a = 0x1;
b = 0x2;
if((a ^ b) > 0) //This expression...
...

I understand that this is not a completely correct code that can cause an error. I should use != instead >.

I think that the type of the result of the expression will be unsigned int. I read about it in Stephen Pratt’s book.

If we have two types, then the result of an expression involving these types must be a superior type. (int or unsigned int)

If these two variables have any other values, can it be that this expression will be less than zero?
(If we set the most significant bit in the number, it will become negative, provided that it has signed data type)

I think it is impossible, but I could be wrong.
I made my guess, but I want to know the correct answer to my question.


答:
The expression a ^ b likely has type int, but will have type unsigned int in the event that there are any values that can be represented as unsigned shorts but not as ints.  Its value will not exceed USHRT_MAX for general a and b of type unsigned short, and will be exactly 3 for the specific a and b in the example.

(From comments:)

I wondered if it could happen that the result of [(a^b)] would be a negative number. in this case, the result of the expression ((a^b) > 0) will be a false

It will never evaluate to a negative number because whether the usual arithmetic promotions result in the operands being converted to int or to unsigned int, the resulting values will be unchanged, and therefore non-negative.  Neither operand's sign bit, if any, will be set, so the result's sign bit, if any, will not be set either.

The expression (a ^ b) > 0 has type int, and it evaluates to 1 for the given a and b.  More generally, it evaluates to the same result as a != b for a and b of integer type.  Of course, that can evaluate to 0.  On the other hand, the related expression (a ^ b) >= 0 will always evaluate to 1 for a and b of unsigned type.

Title: What is the type of result? Is it possible?


问:
Using "umlauts" in C++ code

Possible Duplicate:

  C++ source in unicode

I just discovered this line of code in a project:

```<code>string überwachung;
</code>```

I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine with visual studio 2008.

Is this a special microsoft feature, or are umlauts allowed with other compilers too?

Are there any potential problems with that (portability,system language settings..)?

I can clearly remember this was not allowed. When did it change?

Kind regards for any clarification

P.S.: the tool cppcheck will even mark this usage as an error, even though it compiles

答:
I believe this is the clause that applies...

2.2 Character Sets

The basic source character set
  consists of 96 characters: the space
  character, the control characters
  representing horizontal tab, vertical
  tab, form feed, and new-line, plus the
  following 91 graphical characters:

```<code>a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9
_ { } [ ] # ( ) < > % : ; . ? * + - / ˆ & | ˜ ! = , \ " ’
</code>```

So the use of the unlaut would appear to be a compiler-specific extension.

Title: Using "umlauts" in C++ code

Body:
Possible Duplicate:

  C++ source in unicode

I just discovered this line of code in a project:

string überwachung;

I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine with visual studio 2008.

Is this a special microsoft feature, or are umlauts allowed with other compilers too?

Are there any potential problems with that (portability,system language settings..)?

I can clearly remember this was not allowed. When did it change?

Kind regards for any clarification

P.S.: the tool cppcheck will even mark this usage as an error, even though it compiles

Body:
I believe this is the clause that applies...

2.2 Character Sets

The basic source character set
  consists of 96 characters: the space
  character, the control characters
  representing horizontal tab, vertical
  tab, form feed, and new-line, plus the
  following 91 graphical characters:

a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9
_ { } [ ] # ( ) < > % : ; . ? * + - / ˆ & | ˜ ! = , \ " ’

So the use of the unlaut would appear to be a compiler-specific extension.


问:
How to extract a subString from android java String?
I tried to extract Sub-String from java string, but failed. i tried like this

```<code>String text = "audios/{any_number} any_audio_name.mp3";
text= text.substring(text.indexOf('/'), text.indexOf('3')-2);
</code>```

Updated

I need String contains only any_audio_name and removing audios/ , any number e.g. {123} and .mp3

For example audios/{211} new school poem.mp3 to new school poem

答:
Thanks for everyone, who give me idea for solving this issue.</p>

```<code> String text = "audios/{any_number}any_audio_name.mp3";
 text= text.substring(text.indexOf('/')+1, text.indexOf('.')).replaceAll("\\{|\\}|[\\d.]","");
 System.out.println(text);
</code>```

Body:
I tried to extract Sub-String from java string, but failed. i tried like this

String text = "audios/{any_number} any_audio_name.mp3";
text= text.substring(text.indexOf('/'), text.indexOf('3')-2);

Updated

I need String contains only any_audio_name and removing audios/ , any number e.g. {123} and .mp3

For example audios/{211} new school poem.mp3 to new school poem

Body:
Thanks for everyone, who give me idea for solving this issue.

 String text = "audios/{any_number}any_audio_name.mp3";
 text= text.substring(text.indexOf('/')+1, text.indexOf('.')).replaceAll("\\{|\\}|[\\d.]","");
 System.out.println(text);


问:
How to combine multiple arrays in javascript?
I want to combine some multiple arrays into one array.

I tried _.zip of lodash library, but that's not what I want.

Here is the arrays:

```<code>var arr1 = [
    'a', 'b'
];
var arr2 = [
    'c', 'd'
];
var arr3 = [
    'e'
];
</code>```

And I want this output:

```<code>var result = [
    ['a', 'c', 'e'],
    ['a', 'd', 'e'],
    ['b', 'c', 'e'],
    ['b', 'd', 'e']
];
</code>```

答:
As others have noted, this is called the Cartesian Product of your arrays.  I find it easier to build it by folding (reducing) over one that takes the product of two arrays.

const product = (xs, ys) =>
  xs .flatMap (x => ys .map (y => [x, y] .flat () ) )

const productAll = (...xss) =>
  xss .reduce (product)

console .log (
  productAll ( ['a', 'b'], ['c', 'd'], ['e'])
)```

If your environment doesn't support flat and flatmap, they are pretty easy to shim.

If you want to supply the arrays inside one array [['a', 'b'], ['c', 'd'], ['e']] instead of separately, just replace ...xss with xss.

Body:
I want to combine some multiple arrays into one array.

I tried _.zip of lodash library, but that's not what I want.

Here is the arrays:

var arr1 = [
    'a', 'b'
];
var arr2 = [
    'c', 'd'
];
var arr3 = [
    'e'
];

And I want this output:

var result = [
    ['a', 'c', 'e'],
    ['a', 'd', 'e'],
    ['b', 'c', 'e'],
    ['b', 'd', 'e']
];

Body:
As others have noted, this is called the Cartesian Product of your arrays.  I find it easier to build it by folding (reducing) over one that takes the product of two arrays.

const product = (xs, ys) =>
  xs .flatMap (x => ys .map (y => [x, y] .flat () ) )

const productAll = (...xss) =>
  xss .reduce (product)

console .log (
  productAll ( ['a', 'b'], ['c', 'd'], ['e'])
)

If your environment doesn't support flat and flatmap, they are pretty easy to shim.

If you want to supply the arrays inside one array [['a', 'b'], ['c', 'd'], ['e']] instead of separately, just replace ...xss with xss.


问:
How can I upload or store images in a folder using Flask?
I currently have my images in a binary format along with the extension of the images. I would like to store images in a folder using flask. How can I do that?

Format of the image.

```<code>image = {
    'img_src': binary_format_of_image,
    'ext': image_extension,
    'id': image_id
}
</code>```

答:
Flask has a intro into uploading files through your Flask Application

An approach from that page:

```<code>def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload-my-image', methods=['POST'])
def upload_file():
   # check if the post request has the file part
   if 'file' not in request.files:
       flash('No file part')
       return redirect(request.url)
   file = request.files['file']
   # if user does not select file, browser also
   # submit an empty part without filename
   if file.filename == '':
       flash('No selected file')
       return redirect(request.url)
   if file and allowed_file(file.filename):
       filename = secure_filename(file.filename)
       file.save(os.path.join(ABSOLUTE_PATH_TO_YOUR_FOLDER, filename))
       new_image = Image(
           path=PATH_TO_YOUR_FOLDER,
           filename=filename,
           ext=filename.rsplit('.', 1)[1].lower()
       )
       # Save new_image model
       return redirect(url_for('uploaded_file', filename=filename))
</code>```

The datastructure that Flask request.files use is a FileStorage.

Also note that the <form> tag has to be marked with enctype=multipart/form-data and a <input type=file>

Body:
I currently have my images in a binary format along with the extension of the images. I would like to store images in a folder using flask. How can I do that?

Format of the image.

image = {
    'img_src': binary_format_of_image,
    'ext': image_extension,
    'id': image_id
}

Body:
Flask has a intro into uploading files through your Flask Application

An approach from that page:

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload-my-image', methods=['POST'])
def upload_file():
   # check if the post request has the file part
   if 'file' not in request.files:
       flash('No file part')
       return redirect(request.url)
   file = request.files['file']
   # if user does not select file, browser also
   # submit an empty part without filename
   if file.filename == '':
       flash('No selected file')
       return redirect(request.url)
   if file and allowed_file(file.filename):
       filename = secure_filename(file.filename)
       file.save(os.path.join(ABSOLUTE_PATH_TO_YOUR_FOLDER, filename))
       new_image = Image(
           path=PATH_TO_YOUR_FOLDER,
           filename=filename,
           ext=filename.rsplit('.', 1)[1].lower()
       )
       # Save new_image model
       return redirect(url_for('uploaded_file', filename=filename))

The datastructure that Flask request.files use is a FileStorage.

Also note that the <form> tag has to be marked with enctype=multipart/form-data and a <input type=file>


问:
How to trap nested SMTPAddressFailedException
My app has a loop over email recipients, some of whom might have bad addresses. When a bad one is encountered, I'd like it reported to the user and the loop to continue. The problem is even though I trap all possible exceptions, the SMTPAddressFailedException gets trapped instead by javax:

javax.mail.SendFailedException: Invalid Addresses;
  nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.1.1 : Recipient address rejected: User unknown in virtual mailbox table

and the remaining recipients get skipped. What's the proper way to handle this?

Here's the code;

```<code>            List<Entry> theEntries = theConcours.GetEntriesList();
        for(Entry entry : theEntries){
            MasterPersonExt mp = aConcours.GetMasterPersonnelObject().GetMasterPerson(entry.GetOwnerUnique()) ;
            String owneremail = mp.getEmail();
            String ownername = mp.getFirstName() + " " + mp.getLastName();
            curOwnerUniqueName = mp.getUniqueName();
            System.out.println("Processing " + mp.getUniqueName() + " email: " + owneremail);
            MimeMessage message = new MimeMessage(session);
            try {
                message.setFrom(new InternetAddress(mailuser));
                System.out.println("From set while processing " + curOwnerUniqueName);
            } catch (AddressException ex) {
                String msg = "AddressException for: " + mailuser + " while processing " + curOwnerUniqueName;
                //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            } catch (MessagingException ex) {
               // Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException for: " + mailuser + " while processing " + curOwnerUniqueName;
                //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            }
            try {
                message.setSubject("Your JCNA Concours Entry");
            } catch (MessagingException ex) {
               // Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException setting Subject while processing " + curOwnerUniqueName ;
                //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            }
            InternetAddress ownerInternetAddr;
             try {
                ownerInternetAddr = new InternetAddress(owneremail);
            } catch (AddressException ex) {
                String msg = "Bad judge eMail address for " + curOwnerUniqueName + "  \"" + mp.getEmail() + "\"";
                okDialog(msg);
                Logger.getLogger(SendMailSSL.class.getName()).log(Level.INFO, msg, ex);
                continue;
            }
            try {
                ///
                message.addRecipient(Message.RecipientType.TO, ownerInternetAddr);
            } catch (MessagingException ex) {
               // Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException setting TO while processing " + curOwnerUniqueName + "  \"" + mp.getEmail() + "\"";
                okDialog(msg);
                Logger.getLogger(SendMailSSL.class.getName()).log(Level.INFO, msg, ex);
                continue;
            }
            String ownerFirst = entry.GetOwnerFirst();
            String  entryplacard = "http://www.concoursbuilder.us/manual-uploads/" + theConcours.GetHostClub() + "/" + concoursName + "/Placards/" + entry.GetOwnerLast() + "_" +  entry.GetUniqueDescription() + "-Placard.pdf";
            String jagModel = entry.GetModel();
            String[] theVals = {ownerFirst, jagModel, concoursName, judgingStarts, lunchTime,
                                awardsTime, concoursChairFirstLastName, concoursChairEmail, entryplacard, schedbyclass};
            messageContent  = replaceTagsWithValues(content_template, theTags, theVals);
            try {
                message.setContent(messageContent, "text/html; charset=utf-8");
            } catch (MessagingException ex) {
                //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException setting Content while processing " + curOwnerUniqueName + "  \"" + mp.getEmail() + "\"";
                okDialog(msg);
                Logger.getLogger(SendMailSSL.class.getName()).log(Level.INFO, msg, ex);
                continue;
           }
            //send the message
            try {
                Transport.send(message);
                System.out.println("message sent successfully...");
            } catch (SMTPAddressFailedException ex){
                String msg = "SMTPAddressFailedException while processing Owner " + ownername + " email address " + owneremail + " is invalid.";
                System.out.println(msg);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            } catch (MessagingException ex) {
               // Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException while processing Owner " + ownername + " email address " + owneremail;
                System.out.println(msg);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            }
        }
</code>```

答:
I solved the problem by implementing a helper function called sendMailToAnEntrant() The for-loop then has a single call to sendMailToAnEntrant() in a try-catch. This results in the exception thrown by the javax code to be trapped. Seems to work.</p>

```<code>            for(Entry entry : theEntries){
        try {
            //sendMailToAnEntrant(Concours aConcours, String aFromEmailAddress, String aSubject, String aContentTemplate, String [] aTags, Entry aEntry, Session aSession)
            sendMailToAnEntrant(aConcours, mailuser, "Your JCNA Concours Entry", content_template, theTags, entry, session);
        } catch (MessagingException ex) {
            MasterPersonExt mp = aConcours.GetMasterPersonnelObject().GetMasterPerson(entry.GetOwnerUnique()) ;
            String owneremail = mp.getEmail();
            String ownername = mp.getFirstName() + " " + mp.getLastName();

            String msg = "Messaging Exception in sendMailToAnEntrant() for: " + ownername + " Email: " + owneremail;
            System.out.println(msg);
            okDialog(msg);
            aConcours.GetLogger().log(Level.INFO, msg, ex);
            //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
            continue;
        }
</code>```

Body:
My app has a loop over email recipients, some of whom might have bad addresses. When a bad one is encountered, I'd like it reported to the user and the loop to continue. The problem is even though I trap all possible exceptions, the SMTPAddressFailedException gets trapped instead by javax:

javax.mail.SendFailedException: Invalid Addresses;
  nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.1.1 : Recipient address rejected: User unknown in virtual mailbox table

and the remaining recipients get skipped. What's the proper way to handle this?

Here's the code;

            List<Entry> theEntries = theConcours.GetEntriesList();
        for(Entry entry : theEntries){
            MasterPersonExt mp = aConcours.GetMasterPersonnelObject().GetMasterPerson(entry.GetOwnerUnique()) ;
            String owneremail = mp.getEmail();
            String ownername = mp.getFirstName() + " " + mp.getLastName();
            curOwnerUniqueName = mp.getUniqueName();
            System.out.println("Processing " + mp.getUniqueName() + " email: " + owneremail);
            MimeMessage message = new MimeMessage(session);
            try {
                message.setFrom(new InternetAddress(mailuser));
                System.out.println("From set while processing " + curOwnerUniqueName);
            } catch (AddressException ex) {
                String msg = "AddressException for: " + mailuser + " while processing " + curOwnerUniqueName;
                //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            } catch (MessagingException ex) {
               // Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException for: " + mailuser + " while processing " + curOwnerUniqueName;
                //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            }
            try {
                message.setSubject("Your JCNA Concours Entry");
            } catch (MessagingException ex) {
               // Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException setting Subject while processing " + curOwnerUniqueName ;
                //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            }
            InternetAddress ownerInternetAddr;
             try {
                ownerInternetAddr = new InternetAddress(owneremail);
            } catch (AddressException ex) {
                String msg = "Bad judge eMail address for " + curOwnerUniqueName + "  \"" + mp.getEmail() + "\"";
                okDialog(msg);
                Logger.getLogger(SendMailSSL.class.getName()).log(Level.INFO, msg, ex);
                continue;
            }
            try {
                ///
                message.addRecipient(Message.RecipientType.TO, ownerInternetAddr);
            } catch (MessagingException ex) {
               // Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException setting TO while processing " + curOwnerUniqueName + "  \"" + mp.getEmail() + "\"";
                okDialog(msg);
                Logger.getLogger(SendMailSSL.class.getName()).log(Level.INFO, msg, ex);
                continue;
            }
            String ownerFirst = entry.GetOwnerFirst();
            String  entryplacard = "http://www.concoursbuilder.us/manual-uploads/" + theConcours.GetHostClub() + "/" + concoursName + "/Placards/" + entry.GetOwnerLast() + "_" +  entry.GetUniqueDescription() + "-Placard.pdf";
            String jagModel = entry.GetModel();
            String[] theVals = {ownerFirst, jagModel, concoursName, judgingStarts, lunchTime,
                                awardsTime, concoursChairFirstLastName, concoursChairEmail, entryplacard, schedbyclass};
            messageContent  = replaceTagsWithValues(content_template, theTags, theVals);
            try {
                message.setContent(messageContent, "text/html; charset=utf-8");
            } catch (MessagingException ex) {
                //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException setting Content while processing " + curOwnerUniqueName + "  \"" + mp.getEmail() + "\"";
                okDialog(msg);
                Logger.getLogger(SendMailSSL.class.getName()).log(Level.INFO, msg, ex);
                continue;
           }
            //send the message
            try {
                Transport.send(message);
                System.out.println("message sent successfully...");
            } catch (SMTPAddressFailedException ex){
                String msg = "SMTPAddressFailedException while processing Owner " + ownername + " email address " + owneremail + " is invalid.";
                System.out.println(msg);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            } catch (MessagingException ex) {
               // Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "MessagingException while processing Owner " + ownername + " email address " + owneremail;
                System.out.println(msg);
                okDialog(msg);
                aConcours.GetLogger().log(Level.INFO, msg, ex);
                continue;
            }
        }

Body:
I solved the problem by implementing a helper function called sendMailToAnEntrant() The for-loop then has a single call to sendMailToAnEntrant() in a try-catch. This results in the exception thrown by the javax code to be trapped. Seems to work.

            for(Entry entry : theEntries){
        try {
            //sendMailToAnEntrant(Concours aConcours, String aFromEmailAddress, String aSubject, String aContentTemplate, String [] aTags, Entry aEntry, Session aSession)
            sendMailToAnEntrant(aConcours, mailuser, "Your JCNA Concours Entry", content_template, theTags, entry, session);
        } catch (MessagingException ex) {
            MasterPersonExt mp = aConcours.GetMasterPersonnelObject().GetMasterPerson(entry.GetOwnerUnique()) ;
            String owneremail = mp.getEmail();
            String ownername = mp.getFirstName() + " " + mp.getLastName();

            String msg = "Messaging Exception in sendMailToAnEntrant() for: " + ownername + " Email: " + owneremail;
            System.out.println(msg);
            okDialog(msg);
            aConcours.GetLogger().log(Level.INFO, msg, ex);
            //Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
            continue;
        }


问:
html question want to move a table beside another
I have two tables. One above the other. I want to move the bottom table to the right of the top table. Right now when I run the server, the top table is positioned above the bottom table. Is there a way to move the bottom table to the right side of the top table?</p>

```<code><table>
        <tr><th>Type</th><th>Quantity</th></tr>
        </tr><td>Tape + Film</td><td>{{total_tape_and_film_items}}</td></tr>
        </tr><td>Electrical Equipment</td><td>{{total_electrical_equipment_items}}</td></tr>
</tables>

<table>
        <tr><th></th><th>Status</th><th>Quantity</th></tr>
        <tr><td><a id="new_client" href='{% url tiptop.views.in_items client.pk%}'/>View</a></td><td>In</td><td>{{in_items|length}}</td</tr>
        <tr><td><a id="new_client" href='{% url tiptop.views.out_items client.pk%}'/>View</a></td><td>Out</td><td>{{out_items|length}}</td</tr>
        <tr><td><a id="new_client" href='{% url tiptop.views.empty_items client.pk%}'/>View</a></td><td>Empty</td><td>{{empty_items|length}}</td</tr>
</table>
</code>```

答: If you don't have to support IE<8, you can set display: inline-block on the tables. This will make them behave like inline elements on the outside, but block-level elements on the inside. You'll also want to explicitly set the table widths, as well as the width of the containing block, unless you want the second table to pop below the first one when there's not enough room.

Body:
I have two tables. One above the other. I want to move the bottom table to the right of the top table. Right now when I run the server, the top table is positioned above the bottom table. Is there a way to move the bottom table to the right side of the top table?

Type	Quantity

Tape + Film	{{total_tape_and_film_items}}

Electrical Equipment	{{total_electrical_equipment_items}}

</tables>

	Status	Quantity

View	In	{{in_items|length}}</td

View	Out	{{out_items|length}}</td

View	Empty	{{empty_items|length}}</td


问:
Manually start uwsgi with python3.6 and python2 and django 2
I just started to use uWSGI and Django. I want to invoke it manually.
I'm using python36, Django 2 and if I install uWSGI (pip install uwsgi) in venv and everything is ok.

Q1. When using outside of venv I first installed uWSGI:

pip install uwsgi -> 2.0.18 version

Installed plugins: sudo apt-get install python3-setuptools

Trying to run with python36:

uwsgi  --plugin-dir=/usr/lib/uwsgi/plugins --plugin python3 --master --http :5000 --home ~/my_playground/webapps/  --chdir ~/my_playground/webapps/p_tscze/ --module p_tscze.wsgi:application

Plugins in /usr/lib/uwsgi/plugins:

```<code>/usr/lib/uwsgi/plugins$ ls | grep python3
asyncio_python36_plugin.so
asyncio_python3_plugin.so
python36_plugin.so
python3_plugin.so

</code>```

Result obtained -> note python 2.7:

```<code>!!! UNABLE to load uWSGI plugin: ./python36_plugin.so: undefined symbol: uwsgi_legion_scrolls !!!
*** Starting uWSGI 2.0.18 (64bit) on [Wed May 29 18:04:24 2019] ***
compiled with version: 7.4.0 on 29 May 2019 15:30:14
os: Linux-4.15.0-45-generic #48-Ubuntu SMP Tue Jan 29 16:28:13 UTC 2019
nodename: start-tehnicka
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /usr/lib/uwsgi/plugins
detected binary path: /usr/local/bin/uwsgi
chdir() to /home/anel/my_playground/webapps/p_tscze/
your processes number limit is 3618
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :5000 fd 4
uwsgi socket 0 bound to TCP address 127.0.0.1:34279 (port auto-assigned) fd 3
Python version: 2.7.15rc1 (default, Nov 12 2018, 14:31:15)  [GCC 7.3.0]
Set PythonHome to /home/anel/my_playground/webapps/
ImportError: No module named site
</code>```

So please can you let me know what I'm doing wrong?

Q2. When comparing the result of the admin page (./manage.py runserver) and result obtained using uwsgi frontend is not the same, why?

Thanks in advance

答:
For future references:

```<code>wget https://projects.unbit.it/downloads/uwsgi-2.0.18.tar.gz
tar -xzvf uwsgi-2.0.18.tar.gz
cd uwsgi-2.0.18
python3 uwsgiconfig.py --build nolang #build binary with python3
python3 uwsgiconfig.py --plugin plugins/python nolang python36 # create a new binary
</code>```

Run newly created binary uwsgi (we can link to this binary):

```<code>./uwsgi  --plugin-dir=/home/anel/uwsgi-2.0.18 --plugin python36 --master --http :5000 --home ~/my_playground/webapps/  --chdir ~/my_playground/webapps/p_tscze/ --module p_tscze.wsgi:application
</code>```

Body:
I just started to use uWSGI and Django. I want to invoke it manually.
I'm using python36, Django 2 and if I install uWSGI (pip install uwsgi) in venv and everything is ok.

Q1. When using outside of venv I first installed uWSGI:

pip install uwsgi -> 2.0.18 version

Installed plugins: sudo apt-get install python3-setuptools

Trying to run with python36:

uwsgi  --plugin-dir=/usr/lib/uwsgi/plugins --plugin python3 --master --http :5000 --home ~/my_playground/webapps/  --chdir ~/my_playground/webapps/p_tscze/ --module p_tscze.wsgi:application

Plugins in /usr/lib/uwsgi/plugins:

/usr/lib/uwsgi/plugins$ ls | grep python3
asyncio_python36_plugin.so
asyncio_python3_plugin.so
python36_plugin.so
python3_plugin.so

Result obtained -> note python 2.7:

!!! UNABLE to load uWSGI plugin: ./python36_plugin.so: undefined symbol: uwsgi_legion_scrolls !!!
*** Starting uWSGI 2.0.18 (64bit) on [Wed May 29 18:04:24 2019] ***
compiled with version: 7.4.0 on 29 May 2019 15:30:14
os: Linux-4.15.0-45-generic #48-Ubuntu SMP Tue Jan 29 16:28:13 UTC 2019
nodename: start-tehnicka
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /usr/lib/uwsgi/plugins
detected binary path: /usr/local/bin/uwsgi
chdir() to /home/anel/my_playground/webapps/p_tscze/
your processes number limit is 3618
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :5000 fd 4
uwsgi socket 0 bound to TCP address 127.0.0.1:34279 (port auto-assigned) fd 3
Python version: 2.7.15rc1 (default, Nov 12 2018, 14:31:15)  [GCC 7.3.0]
Set PythonHome to /home/anel/my_playground/webapps/
ImportError: No module named site

So please can you let me know what I'm doing wrong?

Q2. When comparing the result of the admin page (./manage.py runserver) and result obtained using uwsgi frontend is not the same, why?

Thanks in advance

Body:
For future references:

wget https://projects.unbit.it/downloads/uwsgi-2.0.18.tar.gz
tar -xzvf uwsgi-2.0.18.tar.gz
cd uwsgi-2.0.18
python3 uwsgiconfig.py --build nolang #build binary with python3
python3 uwsgiconfig.py --plugin plugins/python nolang python36 # create a new binary

Run newly created binary uwsgi (we can link to this binary):

./uwsgi  --plugin-dir=/home/anel/uwsgi-2.0.18 --plugin python36 --master --http :5000 --home ~/my_playground/webapps/  --chdir ~/my_playground/webapps/p_tscze/ --module p_tscze.wsgi:application


问:
Bubbling up exceptions in coroutines
In Kotlin coroutines, an async call will not throw until the value is retrieved. However, when I  launch a suspend function in an async block, the exception is not trapped as I would expect.

Here's the sample code:

```<code>fun start() {
    GlobalScope.launch {
        try {
            val def1 = async { doWork1() }
            val def2 = async { doWork2() }
            Log.d("test", "Result ${def1.await()}, ${def2.await()}")
        } catch (ex: Exception) {
            Log.e("test", "Error", ex)
        }
    }
}

private suspend fun doWork1(): Int {
    delay(1000L)
    throw Exception("work 1")
}

private suspend fun doWork2(): Int {
    delay(1000L)
    return 1
}
</code>```

This crashes instead of trapping the exception in the catch block.

On the other hand, this works fine

```<code>fun start() {
    GlobalScope.launch {
        try {
            val value = doWork1()
            Log.d("test", "Result: $value")
        } catch (ex: Exception) {
            Log.e("test", "Error", ex)
        }
    }
}

private suspend fun doWork1(): Int {
    delay(1000L)
    throw Exception("work 1")
}
</code>```

Why aren't exceptions trapped in the first example?

答:
Second case is simple: you're only running 1 job with GlobalScope.launch, and exception is cleanly caught.

In first case however your async calls create jobs that are children of your GlobalScope.launch.

Exception is actually delayed until await() call, but it doesn't rethrow in that case. Instead async job propagates exception to its parent job (launch) which proceeds to cancel itself and all children jobs immediately. It forwards exception to its ExceptionHandler which by default is uncaught.

You should install exception handler on your parent job context - this allows clean handling of any exception within coroutine or its children:

```<code>GlobalScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
        println("Error: $throwable")
}) {
    val def1 = async { doWork1() }
    val def2 = async { doWork2() }
    println("Result ${def1.await()} ${def2.await()}")
}
</code>```

Read in detail about coroutine exception handling in Exception Handling docs.

Title: Bubbling up exceptions in coroutines

Body:
In Kotlin coroutines, an async call will not throw until the value is retrieved. However, when I  launch a suspend function in an async block, the exception is not trapped as I would expect.

Here's the sample code:

fun start() {
    GlobalScope.launch {
        try {
            val def1 = async { doWork1() }
            val def2 = async { doWork2() }
            Log.d("test", "Result ${def1.await()}, ${def2.await()}")
        } catch (ex: Exception) {
            Log.e("test", "Error", ex)
        }
    }
}

private suspend fun doWork1(): Int {
    delay(1000L)
    throw Exception("work 1")
}

private suspend fun doWork2(): Int {
    delay(1000L)
    return 1
}

This crashes instead of trapping the exception in the catch block.

On the other hand, this works fine

fun start() {
    GlobalScope.launch {
        try {
            val value = doWork1()
            Log.d("test", "Result: $value")
        } catch (ex: Exception) {
            Log.e("test", "Error", ex)
        }
    }
}

private suspend fun doWork1(): Int {
    delay(1000L)
    throw Exception("work 1")
}

Why aren't exceptions trapped in the first example?

Body:
Second case is simple: you're only running 1 job with GlobalScope.launch, and exception is cleanly caught.

In first case however your async calls create jobs that are children of your GlobalScope.launch.

Exception is actually delayed until await() call, but it doesn't rethrow in that case. Instead async job propagates exception to its parent job (launch) which proceeds to cancel itself and all children jobs immediately. It forwards exception to its ExceptionHandler which by default is uncaught.

You should install exception handler on your parent job context - this allows clean handling of any exception within coroutine or its children:

GlobalScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
        println("Error: $throwable")
}) {
    val def1 = async { doWork1() }
    val def2 = async { doWork2() }
    println("Result ${def1.await()} ${def2.await()}")
}

Read in detail about coroutine exception handling in Exception Handling docs.


问:
how to get a d3.js graph's value at a particular point?
I've got a group of graphs (using angular 7 and d3.js v5).
with axis x=> date , y values, it's a curve (basis).
I'd like to be able to enter a date and display at this particular date the value. My problem is , i do not see how to retreive the calculated values for a given date.
Is it possible?
I did not find anything.

I add an image to clarify.

thanks for any help :)

答:
There isn't a simple answer that'd work in general case.

In your case however, since you are using basis curve, and your data is in equal intervals, you can use d3 basis interpolator https://github.com/d3/d3-interpolate#interpolateBasis

<!DOCTYPE html>

  <meta charset="utf-8">

```

Body:
There isn't a simple answer that'd work in general case.

In your case however, since you are using basis curve, and your data is in equal intervals, you can use d3 basis interpolator https://github.com/d3/d3-interpolate#interpolateBasis

<!DOCTYPE html>

<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body {
      margin: 0;
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }

    path {
      fill: none;
      stroke: black;
    }

    rect {
      fill: white;
    }
  </style>
</head>

<body>
  <script>
    var points = [{
        x: 0,
        y: 0
      },
      {
        x: 5,
        y: 10
      },
      {
        x: 10,
        y: 20
      },
      {
        x: 15,
        y: 15
      },
      {
        x: 20,
        y: 5
      },
      {
        x: 25,
        y: 10
      },
      {
        x: 30,
        y: 12
      },
      {
        x: 35,
        y: 5
      },
      {
        x: 40,
        y: 20
      },
    ];

    var interp = d3.interpolateBasis(points.map(function(p) {
      return p.y;
    }));
    var scaleX = d3.scaleLinear()
      .domain([0, 40])
      .range([0, 200]);
    var scaleY = d3.scaleLinear()
      .domain([-10, 30])
      .range([200, 0]);
    var lineGen = d3.line()
      .x(function(d) {
        return scaleX(d.x);
      })
      .y(function(d) {
        return scaleY(d.y);
      })
      .curve(d3.curveBasis);

    var svg = d3.select("body").append("svg")
      .attr("width", 200)
      .attr("height", 200);

    svg.append('rect')
      .attr('width', 200)
      .attr('height', 200)
      .on('mousemove', function() {
        var x = d3.event.x;
        var y = interp(x / scaleX(40));
        svg.select('circle')
          .attr('cx', x)
          .attr('cy', scaleY(y));
        svg.select('text')
          .text('x: ' + scaleX.invert(x) + ', y: ' + y);
      })

    svg.append('path')
      .attr('d', lineGen(points));

    svg.append('text')
      .attr('y', 20);

    svg.append('circle')
      .attr('r', 3);
  </script>
</body>


问:
Difference between std::pair and std::tuple with only two members?
Is there a difference between an std::pair and an std::tuple with only two members? (Besides the obvious that std::pair requires two and only two members and tuple may have more or less...)

答:
Note that with C++ 17, one can use the same interface to read data from both pair and tuple with two elements.

```<code>auto [a, b] = FunctionToReturnPairOrTuple();
</code>```

No need to use get<> :)

Body:
Note that with C++ 17, one can use the same interface to read data from both pair and tuple with two elements.

auto [a, b] = FunctionToReturnPairOrTuple();

No need to use get<> :)


问:
How to convert a series of tuples to DataFrame?
I'm trying to add some extra data in additional columns to a data frame.

Consider this example code:

```<code>import pandas
import numpy

def more_data(d):
    return 1, 2

df = pandas.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pandas.DataFrame(x)
df2 = pandas.concat([df, df1], axis=1)

print(df2)
</code>```

The output is:

```<code>A  B       0
0  1  17  (1, 2)
1  2  16  (1, 2)
2  3  15  (1, 2)
</code>```

No surprise because apply() returns a sequence of tuples, which is faithfully added as a column of tuples to the data frame. What I want, however, is two more columns with the values returned in the tuples. How would that work?

答:
Try this

import pandas
import numpy

def more_data(d):
    return 1, 2

df = pandas.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pandas.DataFrame(x)
df1= pandas.concat([df, df1], axis=1)

df1[['new_1', 'new_2']] = pandas.DataFrame([list(x) for x in df1[0]])

# Result
print(df1)
   A   B       0  new_1  new_2
0  1  17  (1, 2)      1      2
1  2  16  (1, 2)      1      2
2  3  15  (1, 2)      1      2
```

Body:
I'm trying to add some extra data in additional columns to a data frame.

Consider this example code:

import pandas
import numpy

def more_data(d):
    return 1, 2

df = pandas.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pandas.DataFrame(x)
df2 = pandas.concat([df, df1], axis=1)

print(df2)

The output is:

A  B       0
0  1  17  (1, 2)
1  2  16  (1, 2)
2  3  15  (1, 2)

No surprise because apply() returns a sequence of tuples, which is faithfully added as a column of tuples to the data frame. What I want, however, is two more columns with the values returned in the tuples. How would that work?


问:
I need my image to remain after the image changes
I have created an app that has multiple image changes. After the original image1 is changed from a pushed button it switches to a new image2.
if i go out of the app and then back in, the image2 is back to image1. How can i get the image2 to stay?

Is this persisting data, can someone please help me?

答:
Then I would use this:

.h

```<code>int imageValue;
</code>```

.m

```<code>-(void)exitingApp {

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

[prefs setInteger:imageValue forKey:@"value"];

}

-(void)init {

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

imageValue = [prefs integerForKey:@"value"];

myImageView.image = [UIImage imageNamed:@"image%i", imageValue];

}

-(void)switchToImage1 {
//This is how you go about changing the image in the app
imageValue = 1;
myImageView.image = [UIImage imageNamed:@"image%i", imageValue];

}
</code>```

Body:
Then I would use this:

.h

int imageValue;

.m

-(void)exitingApp {

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

[prefs setInteger:imageValue forKey:@"value"];

}

-(void)init {

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

imageValue = [prefs integerForKey:@"value"];

myImageView.image = [UIImage imageNamed:@"image%i", imageValue];

}

-(void)switchToImage1 {
//This is how you go about changing the image in the app
imageValue = 1;
myImageView.image = [UIImage imageNamed:@"image%i", imageValue];

}


问:
Proper explanation of median javascript code listed below
I'm just looking for a solid explanation of the code listed below? I understand how median works but am unsure why this format properly finds the median each time.     </p>

```<code>   function median(array) {
  array.sort(function(a, b) {
  return a - b;
  });
  var middle = array.length / 2;
  return middle % 1 ? array[middle - 0.5] : (array[middle - 1] +
  array[middle]) / 2;
   }
</code>```

答:
It would actually help if you put a console.log(array) right after the array.sort to visualize it better:

function median(array) {
  array.sort(function(a, b) {
    return a - b;
  });
  console.log(array)  // <-- so you can see the sorted array
  var middle = array.length / 2;
  return middle % 1 ? array[middle - 0.5] : (array[middle - 1] + array[middle]) / 2;
}

console.log(median([5,4,3,2,1]))```

By definition median is:

The median is the value separating the higher half from the lower half
  of a data sample. For a data set, it may be thought of as the "middle"
  value. For example, in the data set {1, 3, 3, 6, 7, 8, 9}, the median
  is 6, the fourth largest, and also the fourth smallest, number in the
  sample

So first the array must be sorted so we can figure out which is the smallest and which the largest number. Then we find out the middle of the array. After that we simply check if the length was an even or odd number by using the % modulus operator => (5/2)%1 would be 0.5 where (4/2)%1 would be 0 and based on that we select the proper item by index from the array (Note array indexes start from 0).

Lets use array of [5,4,3,2,1] as an example:

Sorted that would be [1,2,3,4,5], the remainder of the length of the array divided by 2 would be 2.5 and modulus 1 of that would mean 0.5. So in this case we would pick array[middle-0.5] value from the array which would mean array[2.5-0.5] which would be 2. Our array at index 2 has the value of 3 hence the median of that array is 3.

In the case of [1,2,3,4] the median would be 2.5 since the modulus would return 0 and we would go to the else of the ternary operator which is:

(array[middle - 1] + array[middle]) / 2

That in our case would mean (array[2-1] + array[2]) / 2 that when we replace the values from the array indexes would be (2+3)/2 = 2.5

Hope this clears it.

Body:
I'm just looking for a solid explanation of the code listed below? I understand how median works but am unsure why this format properly finds the median each time.

   function median(array) {
  array.sort(function(a, b) {
  return a - b;
  });
  var middle = array.length / 2;
  return middle % 1 ? array[middle - 0.5] : (array[middle - 1] +
  array[middle]) / 2;
   }

Body:
It would actually help if you put a console.log(array) right after the array.sort to visualize it better:

function median(array) {
  array.sort(function(a, b) {
    return a - b;
  });
  console.log(array)  // <-- so you can see the sorted array
  var middle = array.length / 2;
  return middle % 1 ? array[middle - 0.5] : (array[middle - 1] + array[middle]) / 2;
}

console.log(median([5,4,3,2,1]))

By definition median is:

The median is the value separating the higher half from the lower half
  of a data sample. For a data set, it may be thought of as the "middle"
  value. For example, in the data set {1, 3, 3, 6, 7, 8, 9}, the median
  is 6, the fourth largest, and also the fourth smallest, number in the
  sample

So first the array must be sorted so we can figure out which is the smallest and which the largest number. Then we find out the middle of the array. After that we simply check if the length was an even or odd number by using the % modulus operator => (5/2)%1 would be 0.5 where (4/2)%1 would be 0 and based on that we select the proper item by index from the array (Note array indexes start from 0).

Lets use array of [5,4,3,2,1] as an example:

Sorted that would be [1,2,3,4,5], the remainder of the length of the array divided by 2 would be 2.5 and modulus 1 of that would mean 0.5. So in this case we would pick array[middle-0.5] value from the array which would mean array[2.5-0.5] which would be 2. Our array at index 2 has the value of 3 hence the median of that array is 3.

In the case of [1,2,3,4] the median would be 2.5 since the modulus would return 0 and we would go to the else of the ternary operator which is:

(array[middle - 1] + array[middle]) / 2

That in our case would mean (array[2-1] + array[2]) / 2 that when we replace the values from the array indexes would be (2+3)/2 = 2.5

Hope this clears it.


问:
How to create a target that creates a directory if it doesn't exist?
In my makefile configuration, all object files get compiled into a specific directory. The compiler complains if it doesn't exist. I would like to create a makefile target that recognizes any object file and creates that directory before any other target runs and actually compiles object files.

So far, I have experimented with pattern-match and double-colon rules.

```<code>obj:
    mkdir obj

obj/%.o :: | obj

obj/example.o :: src/example.cc includes/example.hh
    $(build_obj_file) # macro to do the actual job
</code>```

With this code, only the last target runs for obj/example.o. I would have expected both object targets to run separately.

When I replace the pattern-match with the static obj/example.o I get the desired result. Also when I use static pattern-match like obj/example.o : obj/%.o :: obj.

I don't really want to include obj as an additional dependency for every other object file or to create a seperate list of all object files for static pattern matching. Either way would be very brittle and error prone.

What would you suggest to solve such a task?

答:
You cannot use pattern rules to "add extra prerequisites" to a set of targets.  Pattern rules must provide a recipe; if they don't then they are considered to delete the pattern rule.

Because you have provided so little of your real makefile, it's difficult to suggest a solution that will work for you.

If you want to use order-only prerequisites you either need to add them into a pattern rule that will match your target:

```<code>obj/%.o : src/%.cc | obj
         $(build_obj_file)
</code>```

or else define the prerequisite relationship separately:

```<code>obj/example.o: | obj
</code>```

Body:
In my makefile configuration, all object files get compiled into a specific directory. The compiler complains if it doesn't exist. I would like to create a makefile target that recognizes any object file and creates that directory before any other target runs and actually compiles object files.

So far, I have experimented with pattern-match and double-colon rules.

obj:
    mkdir obj

obj/%.o :: | obj

obj/example.o :: src/example.cc includes/example.hh
    $(build_obj_file) # macro to do the actual job

With this code, only the last target runs for obj/example.o. I would have expected both object targets to run separately.

When I replace the pattern-match with the static obj/example.o I get the desired result. Also when I use static pattern-match like obj/example.o : obj/%.o :: obj.

I don't really want to include obj as an additional dependency for every other object file or to create a seperate list of all object files for static pattern matching. Either way would be very brittle and error prone.

What would you suggest to solve such a task?

Body:
You cannot use pattern rules to "add extra prerequisites" to a set of targets.  Pattern rules must provide a recipe; if they don't then they are considered to delete the pattern rule.

Because you have provided so little of your real makefile, it's difficult to suggest a solution that will work for you.

If you want to use order-only prerequisites you either need to add them into a pattern rule that will match your target:

obj/%.o : src/%.cc | obj
         $(build_obj_file)

or else define the prerequisite relationship separately:

obj/example.o: | obj


问:
NodeJS query processing results design pattern avoid nested then statements
I am writing an application in NodeJS10 and Mongoose5. I am writing a custom server-side pagination function. I want to run the pagination in a controller for separation of concerns and reusability.

I have a query to get data and return it in a then() response handler. I am then calling the custom pagination function inside the then() handler. This works, but I am concerned about the "nested" then/catch patterns. I think this might be messy especially if there is any additional processing required on the data before returning the response.

Here is the "nested" structure. How can I improve this to make it no longer nested and more readable while still catching all possible errors and returning the response correctly? Note that this works just fine, it's just the design pattern is messy and I want to avoid the "nested" then() statements if possible.

```<code>router.get('/:id', (req, res, next) => {
  const origin = 'routes/items.js GET /:id';

  const id = req.params.id;

  items.find({
    _id: id
  }).then(data => {

    uiCtrl.pagination(data, req.query).then((result) => {
      res.status(200).send(result);
    }).catch((error) => {
      console.error(`pagination failed ${error}`);
      res.status(500).send(`pagination failed ${error}`);
    });

  }).catch((error) => {
    console.log(`${origin} ${error}`);
    res.status(404).send('Not found');
  });

});
</code>```

Here is the custom async function being called inside the query result above.

```<code>const uiCtrl = {};

uiCtrl.pagination = async (data, query) => {

  // pagination logic here
  return data;
}

module.exports = uiCtrl;
</code>```

答:
Here is the reworked solution based on the accepted answer. I was getting this error, I think this is due to placing the 'async' keyword directly in the router definition e.g. router.get('/', async (req, res, next). Perhaps because in this format it is not handled with then or catch.

(node:3564) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3564) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I ended up with a slightly modified solution, I made a wrapper function and called it with a then() handler. Thanks!

```<code>router.get('/', (req, res, next) => {
  const origin = 'routes/items.js GET /';

    async function queryWrapper() {
        let data, results;

        try {
          data = await items.find();
          console.log(`data ${data}`);
        }
        catch (err) {
          console.log(`${origin} ${err}`);
        }
        try {
          results = await uiCtrl.pagination(data, req.query);
        }
        catch (err) {
          console.error(`pagination failed ${err}`);
        }

        if (results) {
          return results;
        } else {
          return false;
        }
      }

      queryWrapper().then((result) => {
        res.status(200).send(result);
      }).catch((error) => {
        console.error(`${error}`);
        res.status(500).send(`${error}`);
      });
});
</code>```

Body:
I am writing an application in NodeJS10 and Mongoose5. I am writing a custom server-side pagination function. I want to run the pagination in a controller for separation of concerns and reusability.

I have a query to get data and return it in a then() response handler. I am then calling the custom pagination function inside the then() handler. This works, but I am concerned about the "nested" then/catch patterns. I think this might be messy especially if there is any additional processing required on the data before returning the response.

Here is the "nested" structure. How can I improve this to make it no longer nested and more readable while still catching all possible errors and returning the response correctly? Note that this works just fine, it's just the design pattern is messy and I want to avoid the "nested" then() statements if possible.

router.get('/:id', (req, res, next) => {
  const origin = 'routes/items.js GET /:id';

  const id = req.params.id;

  items.find({
    _id: id
  }).then(data => {

    uiCtrl.pagination(data, req.query).then((result) => {
      res.status(200).send(result);
    }).catch((error) => {
      console.error(`pagination failed ${error}`);
      res.status(500).send(`pagination failed ${error}`);
    });

  }).catch((error) => {
    console.log(`${origin} ${error}`);
    res.status(404).send('Not found');
  });

});

Here is the custom async function being called inside the query result above.

const uiCtrl = {};

uiCtrl.pagination = async (data, query) => {

  // pagination logic here
  return data;
}

module.exports = uiCtrl;

Body:
Here is the reworked solution based on the accepted answer. I was getting this error, I think this is due to placing the 'async' keyword directly in the router definition e.g. router.get('/', async (req, res, next). Perhaps because in this format it is not handled with then or catch.

(node:3564) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3564) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I ended up with a slightly modified solution, I made a wrapper function and called it with a then() handler. Thanks!

router.get('/', (req, res, next) => {
  const origin = 'routes/items.js GET /';

    async function queryWrapper() {
        let data, results;

        try {
          data = await items.find();
          console.log(`data ${data}`);
        }
        catch (err) {
          console.log(`${origin} ${err}`);
        }
        try {
          results = await uiCtrl.pagination(data, req.query);
        }
        catch (err) {
          console.error(`pagination failed ${err}`);
        }

        if (results) {
          return results;
        } else {
          return false;
        }
      }

      queryWrapper().then((result) => {
        res.status(200).send(result);
      }).catch((error) => {
        console.error(`${error}`);
        res.status(500).send(`${error}`);
      });
});


问:
DataType JSONP is screwing up ASP.NET MVC + JQuery 1.5+ plugins?
I've been working with MVC 3 & JQuery 1.5.2 and I'm using some plugins like jqGrid and Token Input. I notice that with both if the datatype is set to json they fail (where they did work in jQuery before 1.5) since the ajax request datatype seems to interpret this as jsonp and the ajax call looks for a callback in line with the way jsonp works, which most of the plugins don't implement. If however I remove the datatype or change it to text json all the plugins work fine.

For example, the only way I could get the latest jqGrid to work was to modify the source to accept "text json" as the datatype.

I can't understand why datatype=json has been changed so that now it needs to be datatype='text json' seems like a pretty big breaking change to me?

Has anyone got any idea or what's going on or workarounds for this?

答:
You may wish to read this article

jQuery 1.5 broke my JSONP request, and its my own damn fault.


问:
jQuery Button.click() event is triggered twice
I have the following problem with this code:

```<code><button id="delete">Remove items</button>

$("#delete").button({
     icons: {
             primary: 'ui-icon-trash'
     }
}).click(function() {
     alert("Clicked");
});
</code>```

If I click this button, the alert show up two times. It's not only with this specific button but with every single button I create.

What am I doing wrong?

答:
This can be caused for following reasons:

You have included the script more than once in the same html file

You have added the event listener twice (eg: using onclick attribute on the element and also with jquery

The event is bubbled up to some parent element. (you may consider using event.stopPropagation).

If you use template inheritance like extends in Django, most probably you have included the script in more than one file which are combined together by include or extend template tags

If you are using Django template, you have wrongly placed a block inside another.

So, you should either find them out and remove the duplicate import. It is the best thing to do.

Another solution is to remove all click event listeners first in the script like:

```<code>$("#myId").off().on("click", function(event) {
event.stopPropagation();
});
</code>```

You can skip event.stopPropagation(); if you are sure that the event is not bubbled.

Body:
I have the following problem with this code:

<button id="delete">Remove items</button>

$("#delete").button({
     icons: {
             primary: 'ui-icon-trash'
     }
}).click(function() {
     alert("Clicked");
});

If I click this button, the alert show up two times. It's not only with this specific button but with every single button I create.

What am I doing wrong?

Body:
This can be caused for following reasons:

You have included the script more than once in the same html file

You have added the event listener twice (eg: using onclick attribute on the element and also with jquery

The event is bubbled up to some parent element. (you may consider using event.stopPropagation).

If you use template inheritance like extends in Django, most probably you have included the script in more than one file which are combined together by include or extend template tags

If you are using Django template, you have wrongly placed a block inside another.

So, you should either find them out and remove the duplicate import. It is the best thing to do.

Another solution is to remove all click event listeners first in the script like:

$("#myId").off().on("click", function(event) {
event.stopPropagation();
});

You can skip event.stopPropagation(); if you are sure that the event is not bubbled.