问:
Fastest way to iterate over multiple list comprehensions
I have the following code:

```<code>def func(value, start=None, end=None):
    if start is not None and start != 0:
        start = -start
    elif start == 0:
        start = None
    if end is not None:
        end = -end - 1
    return int('{:032b}'.format(value)[end:start], 2)

data = np.random.randint(1, 429496729, 10000)
starts = [10, 50, 100, 200]
stops = [30, 90, 170, 250]
data_dict = [{} for _ in range(len(starts))]

for ii, (start, stop) in enumerate(zip(starts, stops)):
    range_array = np.arange(start, stop, 2)
    data_dict[ii]['one'] = [func(value, 0, 8) for value in data[range_array]]
    data_dict[ii]['two'] = [func(value, 9, 17) for value in data[range_array]]
    data_dict[ii]['three'] = [func(value, 27, 27) for value in data[range_array]]
    data_dict[ii]['four'] = [func(value, 28, 28) for value in data[range_array]]

</code>```

The problem is that this code runs through relatively slowly. However, all other approaches I have tried so far are even slower. Does anyone have an idea how to rewrite this code so that it runs through faster?

答:
You can use numpy broadcasting to vectorize the bitmasking with logical and & and shifting >>.

import numpy as np

np.random.seed(100)
data = np.random.randint(1, 429496729, 10000)
starts = [10, 50, 100, 200]
stops = [30, 90, 170, 250]

# equal to 'start' from calling func(value, start, end)
shift = np.array([0,9,27,28])[:, None]

# equal to 'end - start + 1' from calling func(value, start, end)
bitmask = np.array([9,9,1,1])[:, None]

d = [data[start:stop:2] >> shift & (2**bitmask - 1) for start, stop in zip(starts, stops)]
```
<p>To access the result list <em>d</em></p>
```d[0]
```
<p>Output</p>
```array([[ 54, 227, 291, 281, 229,  59, 508,  87, 365, 416],
       [ 40, 207, 353, 168, 214, 271, 338, 268, 419,  52],
       [  1,   0,   0,   0,   0,   0,   1,   1,   0,   0],
       [  0,   1,   1,   1,   0,   0,   0,   1,   1,   0]])
```
<p>And access similar to your dictionarys</p>
```one, two, three, four = np.arange(4)
d[1][two]
```
<p>Output</p>
```array([ 68, 479, 230, 295, 278, 455, 276,  45, 360, 488, 241, 336, 447,
       316, 181,  94, 138, 404, 223, 310])
```
<hr />
<p>To get the result exactly like the original solution:</p>
<pre class="lang-py prettyprint-override"><code>actual = [
    {
        name: x[index].tolist()
        for index, name
        in enumerate(["one","two","three","four"])
    }
    for x in d
]
</code>```

This produces the exact result and maintains an order of magnitude boost in performance.

Body:
I have the following code:

def func(value, start=None, end=None):
    if start is not None and start != 0:
        start = -start
    elif start == 0:
        start = None
    if end is not None:
        end = -end - 1
    return int('{:032b}'.format(value)[end:start], 2)

data = np.random.randint(1, 429496729, 10000)
starts = [10, 50, 100, 200]
stops = [30, 90, 170, 250]
data_dict = [{} for _ in range(len(starts))]

for ii, (start, stop) in enumerate(zip(starts, stops)):
    range_array = np.arange(start, stop, 2)
    data_dict[ii]['one'] = [func(value, 0, 8) for value in data[range_array]]
    data_dict[ii]['two'] = [func(value, 9, 17) for value in data[range_array]]
    data_dict[ii]['three'] = [func(value, 27, 27) for value in data[range_array]]
    data_dict[ii]['four'] = [func(value, 28, 28) for value in data[range_array]]

The problem is that this code runs through relatively slowly. However, all other approaches I have tried so far are even slower. Does anyone have an idea how to rewrite this code so that it runs through faster?

Body:
You can use numpy broadcasting to vectorize the bitmasking with logical and & and shifting >>.

import numpy as np

np.random.seed(100)
data = np.random.randint(1, 429496729, 10000)
starts = [10, 50, 100, 200]
stops = [30, 90, 170, 250]

# equal to 'start' from calling func(value, start, end)
shift = np.array([0,9,27,28])[:, None]

# equal to 'end - start + 1' from calling func(value, start, end)
bitmask = np.array([9,9,1,1])[:, None]

d = [data[start:stop:2] >> shift & (2**bitmask - 1) for start, stop in zip(starts, stops)]

To access the result list d

d[0]

Output

array([[ 54, 227, 291, 281, 229,  59, 508,  87, 365, 416],
       [ 40, 207, 353, 168, 214, 271, 338, 268, 419,  52],
       [  1,   0,   0,   0,   0,   0,   1,   1,   0,   0],
       [  0,   1,   1,   1,   0,   0,   0,   1,   1,   0]])

And access similar to your dictionarys

one, two, three, four = np.arange(4)
d[1][two]

Output

array([ 68, 479, 230, 295, 278, 455, 276,  45, 360, 488, 241, 336, 447,
       316, 181,  94, 138, 404, 223, 310])

To get the result exactly like the original solution:

actual = [
    {
        name: x[index].tolist()
        for index, name
        in enumerate(["one","two","three","four"])
    }
    for x in d
]

This produces the exact result and maintains an order of magnitude boost in performance.


来源: stackexchange

问:
Query JOIN or not? (optimization)
i was wondering if to use 2 tables is better then using 1 single table .

Scenario:

i have a simple user table and a simple user_details table. i can JOIN tables and select both records.

But i was wondering if to merge 2 table into 1 single table.

what if i have 2milions users records in both tables?

in terms of speed and exec time is better to have a single table when selecting records?

答:
To denormalize or not to denormalize, that is the question...

There is no simple, one-size-fits all response to this question.  It is a case by case decision.

In this instance, it appears that there is exactly one user_detail record per record in the user table (or possibly either 1 or 0 detail record per user record), so shy of subtle caching concerns, there is really little no penalty for "denormalizing".  (indeed in the 1:1 cardinality case, this would effectively be a normalization).

The difficulty in giving a "definitive" recommendation depends on many factors. In particular  (format: I provide a list of questions/parameters to consider and general considerations relevant to these):

what is the frequency of UPDATEs/ DELETEs / INSERTs ?

what is the ratio of reads (SELECTs) vs. writes (UPDATEs, DELETEs, INSERTs) ?

Do the SELECT usually get all the rows from all the tables, or do we only get a few rows and [often or not] only select from one table at a given time ?

If there is a relative little amount of writes compared with reads, it would be possible to create many indexes, some covering the most common queries, and hence logically re-creating of sort, in a more flexible fashion the two (indeed multiple) table setting.  The downside of too many covering indices could of course be to occupy too much disk space (not a big issue these days) but also to possibly impede (to some extent) the cache.  Also too many indices may put undue burden on write operations...

what is the size of a user record? what is the size of a user_detail record?

what is the typical filtering done by a given query?  Do the most common queries return only a few rows, or do they yield several thousand records (or more), most of the time?

If any one of the record average size is "unusually" long, say above 400 bytes, a multi-table may be appropriate. After all, an somewhat depending on the type of filtering done by the queries, the JOIN operation are typically very efficiently done by MySQL, and there is therefore little penalty in keeping separate table.

is the cardinality effectively 1:1  or 1:[0,1] ?

If it isn't the case i.e if we have user records with more than one user_details, given the relatively small number or records (2 millions)  (Yes, 2M is small, not tiny, but small, in modern DBMS contexts),  denormalization would probably be a bad idea.  (possible exception with cases where we query several dozens of time per second the same 4 or 5 fields, some from the user table, some from the user_detail table.

Bottom lines:

2 Million records is relatively small ==> favor selecting a schema that is driven by the semantics of the records/sub-records  rather than addressing, prematurely, performance concerns.  If there are readily effective performance bottlenecks, the issue is probably not caused nor likely to be greatly helped by schema changes.

if 1:1 or 1:[0-1] cardinality, re-uniting the data in a single table is probably a neutral choice, performance wise.

if 1:many cardinality, denormalization ideas are probably premature (again given the "small" database size)

read about SQL optimization, pro-and-cons of indexes of various types, ways of limiting the size of the data, while allowing the same fields/semantics to be recorded.

establish baselines, monitor the performance frequently.

ContentLicense: CC BY-SA 3.0

Title: Query JOIN or not? (optimization)


问:
How do I write my code in a way that when my containers are deployed as Rancher workloads they can communicate?
I have been using Docker to containerise a simple PHP web app that connects to and uses a mySQL database to pull data from. It also includes phpmyadmin as a UI for the management of the database. I have managed to break it up on my local host using Docker into 3 containers, an Apache web server container, a mySQL container and a phpmyadmin container. I now need to deploy these containers onto Rancher in the form of workloads but I am struggling to understand how the workloads can communicate to each other.

In the Dockerfiles and php code I can reference the name of the relevant container in order to connect to it, for example the php pages can reference the name of the 'mydb' container in order to connect to it ($host=my-db-container-name) and pull data from the database as does the phpmyadmin Dockerfile in order to connect to the mySQL server (PMA_HOST=mydb). On Rancher/kubernetes however you cannot do this with workloads etc. Can anyone explain to me some way to change my code so that this can be possible?

I've included some of my code to try and paint a clearer picture of my issue.

SQL Dockerfile

```<code>FROM mysql:latest

ENV MYSQL_ROOT_PASSWORD=mypassword1234

ENV MYSQL_DATABASE=MY_SQL_DATABASE

ENV MYSQL_USER=user

ENV MYSQL_PASSWORD=password

EXPOSE 9906
</code>```

phpmyadmin Dockerfile

```<code>FROM phpmyadmin/phpmyadmin

ENV PMA_HOST=my-own-sql-container //(Here would be where the database container name is referenced.)

EXPOSE 8080

</code>```

Example php script pages that need to connect to mySQL container

```<code>
$host = 'my-own-sql-container'; //Should it reference something on Rancher like the hostname of an ingress?

// Database use name
$user = 'root';

//database user password
$pass = 'mypassword1234';

// database name
$mydatabase = 'MY_SQL_DATABASE';

// check the mysql connection status
$conn = new mysqli($host, $user, $pass, $mydatabase);

if($conn->error){
    echo "not connected".$conn->error;
}
</code>```

答:
In order to have DNS based service discovery you can create Service objects in kubernetes that reference pods and can be used to connect to these Pods.

Documentation: https://kubernetes.io/docs/concepts/services-networking/service/

ContentLicense: CC BY-SA 4.0

Body:
I have been using Docker to containerise a simple PHP web app that connects to and uses a mySQL database to pull data from. It also includes phpmyadmin as a UI for the management of the database. I have managed to break it up on my local host using Docker into 3 containers, an Apache web server container, a mySQL container and a phpmyadmin container. I now need to deploy these containers onto Rancher in the form of workloads but I am struggling to understand how the workloads can communicate to each other.

In the Dockerfiles and php code I can reference the name of the relevant container in order to connect to it, for example the php pages can reference the name of the 'mydb' container in order to connect to it ($host=my-db-container-name) and pull data from the database as does the phpmyadmin Dockerfile in order to connect to the mySQL server (PMA_HOST=mydb). On Rancher/kubernetes however you cannot do this with workloads etc. Can anyone explain to me some way to change my code so that this can be possible?

I've included some of my code to try and paint a clearer picture of my issue.

SQL Dockerfile

FROM mysql:latest

ENV MYSQL_ROOT_PASSWORD=mypassword1234

ENV MYSQL_DATABASE=MY_SQL_DATABASE

ENV MYSQL_USER=user

ENV MYSQL_PASSWORD=password

EXPOSE 9906

phpmyadmin Dockerfile

FROM phpmyadmin/phpmyadmin

ENV PMA_HOST=my-own-sql-container //(Here would be where the database container name is referenced.)

EXPOSE 8080

Example php script pages that need to connect to mySQL container

$host = 'my-own-sql-container'; //Should it reference something on Rancher like the hostname of an ingress?

// Database use name
$user = 'root';

//database user password
$pass = 'mypassword1234';

// database name
$mydatabase = 'MY_SQL_DATABASE';

// check the mysql connection status
$conn = new mysqli($host, $user, $pass, $mydatabase);

if($conn->error){
    echo "not connected".$conn->error;
}


问:
Better way of converting to lowercase only if it is of type string
I need to sort a table that has columns of varying data types. The problem with sorting the strings is that they are case sensitive. The original code is

```<code>const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => row.data[col])
        : descend((row) => row.data[col])
)
</code>```

and I updated it to the following which works

```<code>const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
        : descend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
)
</code>```

Is there a better way to do this?

答:
You can use the optional function call, it will be executed only if that method is defined for the type:

```<code>row.data[col].toLowerCase?.() ?? row.data[col]
</code>```

The optional function call will return undefined whether the method is not defined, for this reason we need ?? row.data[col] in order to retrieve the previous value.

Body:
I need to sort a table that has columns of varying data types. The problem with sorting the strings is that they are case sensitive. The original code is

const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => row.data[col])
        : descend((row) => row.data[col])
)

and I updated it to the following which works

const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
        : descend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
)

Is there a better way to do this?

Body:
You can use the optional function call, it will be executed only if that method is defined for the type:

row.data[col].toLowerCase?.() ?? row.data[col]

The optional function call will return undefined whether the method is not defined, for this reason we need ?? row.data[col] in order to retrieve the previous value.


问:
IP-address from sk_buff
I am writing a kernel module which registers a netfilter hook. I am trying to get the ip address of the caller by using the sk_buff->saddr member. Is there a way I can get the IP in human readable i.e. x.x.x.x format?

I found the function inet_ntop() but it doesn't seem to be available in kernel headers. How do I convert \xC0\xA8\x00\x01 to 192.168.0.1 ?

答:
There are two macros defined in include/linux/kernel.h

NIPQUAD for ipv4 addresses and NIP6 for ipv6 addresses.

```<code>#define NIPQUAD(addr) \
    ((unsigned char *)&addr)[0], \
    ((unsigned char *)&addr)[1], \
    ((unsigned char *)&addr)[2], \
    ((unsigned char *)&addr)[3]

#define NIP6(addr) \
    ntohs((addr).s6_addr16[0]), \
    ntohs((addr).s6_addr16[1]), \
    ntohs((addr).s6_addr16[2]), \
    ntohs((addr).s6_addr16[3]), \
    ntohs((addr).s6_addr16[4]), \
    ntohs((addr).s6_addr16[5]), \
    ntohs((addr).s6_addr16[6]), \
    ntohs((addr).s6_addr16[7])
</code>```

There are ample examples in the kernel sources that make use of these to print ip addresses in human-readable format. For instance:

```<code>printk(KERN_DEBUG "Received packet from source address: %d.%d.%d.%d!\n",NIPQUAD(iph->saddr));
</code>```

Hope this helps.

OwnerDisplayName: Rohit Kumbhar

Title: IP-address from sk_buff

Body:
There are two macros defined in include/linux/kernel.h

NIPQUAD for ipv4 addresses and NIP6 for ipv6 addresses.

#define NIPQUAD(addr) \
    ((unsigned char *)&addr)[0], \
    ((unsigned char *)&addr)[1], \
    ((unsigned char *)&addr)[2], \
    ((unsigned char *)&addr)[3]

#define NIP6(addr) \
    ntohs((addr).s6_addr16[0]), \
    ntohs((addr).s6_addr16[1]), \
    ntohs((addr).s6_addr16[2]), \
    ntohs((addr).s6_addr16[3]), \
    ntohs((addr).s6_addr16[4]), \
    ntohs((addr).s6_addr16[5]), \
    ntohs((addr).s6_addr16[6]), \
    ntohs((addr).s6_addr16[7])

There are ample examples in the kernel sources that make use of these to print ip addresses in human-readable format. For instance:

printk(KERN_DEBUG "Received packet from source address: %d.%d.%d.%d!\n",NIPQUAD(iph->saddr));

Hope this helps.

OwnerDisplayName: anbhat

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: anbhat


问:
How to display teaser on taxonomy term page in Drupal 7
I'm hitting a wall here. I have a block that lists my taxonomy terms and when I click to view that term page all I see is a list of node titles, the submitted by info, a comment link and RSS feed. There seems to be no way to add the teaser or remove some of the other items. Can anyone point me in the right direction? Thanks in advance.</p>

答:
Theming fields and node.
API documentation about node variables.</p>


问:
Snowflake - ERROR [HY000] [Snowflake][Snowflake] (4)
ERROR [HY000] [Snowflake][Snowflake] (4)

We are running ODBC on a Windows 10 computer. I have posted an image of the error messages below. We are also NOT using a proxy server.

enter image description here

答:
Some systems have proxy settings in their environment; this is not documented on the odbc description on the Snowflake website.
So, if the other solution don't work, check this out.</p>


问:
Anylogic: How to create plot from database table?
In my Anylogic model I succesfully create plots of datasets that count the number of trucks arriving from terminals each hour in my simulation. Now, I want to add the actual/"observed" number of trucks arriving at a terminal, to compare my simulation to these numbers. I added these numbers in a database table (see picture below). Is there a simple way of adding this data to the plot?

I tried it by creating a variable that reads the database table for every hour and adding that to a dataset (like can be seen in the pictures below), but this did not work unfortunately (the plot was empty).

答:
Maybe simply delete the variable and fill the dataset at the start of the model by looping through the dbase table data. Use the dbase query wizard to create a for-loop. Something like this should work:</p>
```<code>int numEntries = (int) selectFrom(observed_arrivals).count();

DataSet myDataSet = new DataSet(numEntries);

List<Tuple> rows = selectFrom(observed_arrivals).list();

for (Tuple
 row : rows) {
    myDataSet.add(row.get( observed_arrivals.hour ), row.get( observed_arrivals.terminal_a ));
}

myChart.addDataSet(myDataSet);
</code>```

Body:
Maybe simply delete the variable and fill the dataset at the start of the model by looping through the dbase table data. Use the dbase query wizard to create a for-loop. Something like this should work:

int numEntries = (int) selectFrom(observed_arrivals).count();

DataSet myDataSet = new DataSet(numEntries);

List<Tuple> rows = selectFrom(observed_arrivals).list();

for (Tuple
 row : rows) {
    myDataSet.add(row.get( observed_arrivals.hour ), row.get( observed_arrivals.terminal_a ));
}

myChart.addDataSet(myDataSet);


问:
Rails Completed 406 Not Acceptable in 64ms
I have a form on my website with a page where I can edit / remove / add mailboxes:

http://example.com/settings/mailboxes

http://example.com/settings/mailboxes/3/edit

http://example.com/settings/mailboxes/3

etc.

Whenever I do something to the mailbox (update, destroy) I'm getting this error:

Redirected to http://example.com/
  Completed 406 Not Acceptable in 64ms

But the data gets updated.

Here's the controller code:

```<code># PUT /mailboxes/1
def update
  @mailbox = Mailbox.find(params[:id])

  if @mailbox.update_attributes(params[:mailbox])
    redirect_to(root_path, :notice => 'Mailbox was successfully updated.')
  else
    render :action => "edit"
  end
end

# DELETE /mailboxes/1
def destroy
  @mailbox = Mailbox.find(params[:id])
  @mailbox.destroy

  redirect_to(root_path)
end
</code>```

Here's routes.rb info:

```<code>match 'settings.js' => 'settings#javascript', :via => :get, :format => :js
scope '/settings' do

  # Directs /settings/mailboxes/* to Settings::MailboxesController
  # (app/controllers/settings/mailboxes_controller.rb)
  resources :mailboxes
end
</code>```

What am I doing wrong? Here's what log shows:

if @mailbox.update_attributes(params[:mailbox])
(rdb:2) response.status
200
(rdb:2) next
/Users/Fallen/Projects/support-app/trunk/app/controllers/mailboxes_controller.rb:65
redirect_to(mailboxes_path, :notice => 'Mailbox was successfully updated.')
(rdb:2) response.status
200
(rdb:2) next
/usr/local/rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_controller/metal/implicit_render.rb:5
default_render unless response_body
(rdb:2) response_body
[" "]
(rdb:2) response.status
406
(rdb:2) cont

Started PUT "/settings/mailboxes/5" for 127.0.0.1 at 2011-10-14 12:54:38 +0200
  Status Load (0.4ms)  SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`name` = 'Incoming emails fetching' LIMIT 1
   (0.1ms)  BEGIN
   (0.4ms)  UPDATE `statuses` SET `last_action_at` = '2011-10-14 10:54:38' WHERE `statuses`.`id` = 1
   (39.6ms)  COMMIT
  Processing by MailboxesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"0cip2dsYre9anfy/8rEgtuYcgrgC3si6aSuppjzxuHU=", "mailbox"=>{"name"=>"Dev Support #4", "sender_name"=>"example.com Support #4", "email_address"=>"support_dev4@example.com", "color"=>"B2EB3D"}, "commit"=>"Update Mailbox", "id"=>"5"}
  Mailbox Load (0.5ms)  SELECT `mailboxes`.* FROM `mailboxes` WHERE `mailboxes`.`id` = 5 LIMIT 1
  Status Load (0.5ms)  SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`name` = 'Incoming emails fetching' LIMIT 1
   (0.1ms)  BEGIN
   (0.3ms)  UPDATE `statuses` SET `last_action_at` = '2011-10-14 10:54:47' WHERE `statuses`.`id` = 1
   (0.4ms)  COMMIT
   (0.2ms)  BEGIN
   (0.6ms)  UPDATE `mailboxes` SET `color` = 'B2EB3D', `updated_at` = '2011-10-14 10:54:48' WHERE `mailboxes`.`id` = 5
  Mailbox Load (0.7ms)  SELECT `mailboxes`.* FROM `mailboxes`
   (1.2ms)  COMMIT
  Mailbox Load (0.4ms)  SELECT id, name, open_tickets_count FROM `mailboxes`
   (0.3ms)  SELECT COUNT(*) FROM `tickets` WHERE `tickets`.`closed` = 0
  CACHE (0.0ms)  SELECT COUNT(*) FROM `tickets` WHERE `tickets`.`closed` = 0
Redirected to http://localhost:3000/settings/mailboxes
Completed 406 Not Acceptable in 29008ms
```

答: I had this error and ended up here after googling. In my case I was missing the template but did not receive the usual Missing Template Error. I believe it was because I had respond_to :html at the top of the controller.

Body:
I have a form on my website with a page where I can edit / remove / add mailboxes:

http://example.com/settings/mailboxes

http://example.com/settings/mailboxes/3/edit

http://example.com/settings/mailboxes/3

etc.

Whenever I do something to the mailbox (update, destroy) I'm getting this error:

Redirected to http://example.com/
  Completed 406 Not Acceptable in 64ms

But the data gets updated.

Here's the controller code:

# PUT /mailboxes/1
def update
  @mailbox = Mailbox.find(params[:id])

  if @mailbox.update_attributes(params[:mailbox])
    redirect_to(root_path, :notice => 'Mailbox was successfully updated.')
  else
    render :action => "edit"
  end
end

# DELETE /mailboxes/1
def destroy
  @mailbox = Mailbox.find(params[:id])
  @mailbox.destroy

  redirect_to(root_path)
end

Here's routes.rb info:

match 'settings.js' => 'settings#javascript', :via => :get, :format => :js
scope '/settings' do

  # Directs /settings/mailboxes/* to Settings::MailboxesController
  # (app/controllers/settings/mailboxes_controller.rb)
  resources :mailboxes
end

What am I doing wrong? Here's what log shows:

if @mailbox.update_attributes(params[:mailbox])
(rdb:2) response.status
200
(rdb:2) next
/Users/Fallen/Projects/support-app/trunk/app/controllers/mailboxes_controller.rb:65
redirect_to(mailboxes_path, :notice => 'Mailbox was successfully updated.')
(rdb:2) response.status
200
(rdb:2) next
/usr/local/rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.0/lib/action_controller/metal/implicit_render.rb:5
default_render unless response_body
(rdb:2) response_body
[" "]
(rdb:2) response.status
406
(rdb:2) cont

Started PUT "/settings/mailboxes/5" for 127.0.0.1 at 2011-10-14 12:54:38 +0200
  Status Load (0.4ms)  SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`name` = 'Incoming emails fetching' LIMIT 1
   (0.1ms)  BEGIN
   (0.4ms)  UPDATE `statuses` SET `last_action_at` = '2011-10-14 10:54:38' WHERE `statuses`.`id` = 1
   (39.6ms)  COMMIT
  Processing by MailboxesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"0cip2dsYre9anfy/8rEgtuYcgrgC3si6aSuppjzxuHU=", "mailbox"=>{"name"=>"Dev Support #4", "sender_name"=>"example.com Support #4", "email_address"=>"support_dev4@example.com", "color"=>"B2EB3D"}, "commit"=>"Update Mailbox", "id"=>"5"}
  Mailbox Load (0.5ms)  SELECT `mailboxes`.* FROM `mailboxes` WHERE `mailboxes`.`id` = 5 LIMIT 1
  Status Load (0.5ms)  SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`name` = 'Incoming emails fetching' LIMIT 1
   (0.1ms)  BEGIN
   (0.3ms)  UPDATE `statuses` SET `last_action_at` = '2011-10-14 10:54:47' WHERE `statuses`.`id` = 1
   (0.4ms)  COMMIT
   (0.2ms)  BEGIN
   (0.6ms)  UPDATE `mailboxes` SET `color` = 'B2EB3D', `updated_at` = '2011-10-14 10:54:48' WHERE `mailboxes`.`id` = 5
  Mailbox Load (0.7ms)  SELECT `mailboxes`.* FROM `mailboxes`
   (1.2ms)  COMMIT
  Mailbox Load (0.4ms)  SELECT id, name, open_tickets_count FROM `mailboxes`
   (0.3ms)  SELECT COUNT(*) FROM `tickets` WHERE `tickets`.`closed` = 0
  CACHE (0.0ms)  SELECT COUNT(*) FROM `tickets` WHERE `tickets`.`closed` = 0
Redirected to http://localhost:3000/settings/mailboxes
Completed 406 Not Acceptable in 29008ms


问:
How to install OpenJPEG on MacOS, for use with JP2 files and Pillow
There are some similar questions here and especially here, but they don't go into quite the detail I'm seeking.

I'm attempting to read and edit JP2 (aka, JPEG2000) files using pillow. My code is below, and I suppose I don't yet have the OpenJPEG library installed, because I get the error module 'PIL._imaging' has no attribute 'jpeg2k_decoder'. So, I believe that I neeed to install OpenJPEG. Because I it's a system install (not contained within a virtual environment) and the instructions are piecemeal, I'm hoping to get more info.

Pillow's documentation indicates:

To enable JPEG 2000 support, you need to build and install the OpenJPEG library, version 2.0.0 or higher, before building the Python Imaging Library.

And OpenJPEG's install instructions aren't very clear, but seems to also require installation of cmake. The general advice I see everywhere is to uninstall pillow, install the OpenJPEG library, and then reinstall pillow. And I see that people often have to troubleshoot because pillow's reinstall doesn't pick up the new library sometimes.

I'm hoping that those who have been through the process on a Mac can advise on some details:

cmake appears to be required for installing OpenJPEG. Are the instructions at https://cmake.org/install/ sufficient?

The OpenJPEG instructions don't seem complete. Has anyone made step by step instructions that are easier to follow?

Code that returns the error:

```<code>from PIL import Image
import urllib.request
from io import BytesIO

url = 'https://chroniclingamerica.loc.gov/data/batches/dlc_golf_ver01/data/sn84025891/100493731/1901082401/0132.jp2'
img_raw = requests.get(url)
img = Image.open(BytesIO(img_raw.content))
display(img)

------ Outputs an error including: -------
AttributeError: module 'PIL._imaging' has no attribute 'jpeg2k_decoder'

</code>```

Thanks!

答:
IMHO, the easiest way to manage packages under macOS, such as OpenJPEG, is with homebrew.

All you need is:

```<code>brew install openjpeg
</code>```

Search for available packages containing "jp" with:

```<code>brew search jp
</code>```

Sample Output

```<code>==> Formulae
jp              jpdfbookmarks   jpeg-archive    jpeg-xl ✔       jpegoptim       mjpegtools      openjpeg ✔      recoverjpeg
jp2a            jpeg ✔          jpeg-turbo ✔    jpeginfo        jpegrescan      mozjpeg         pjproject
</code>```

Get info about a package with:

```<code>brew info openjpeg
</code>```

Sample Output

```<code>openjpeg: stable 2.4.0 (bottled), HEAD
Library for JPEG-2000 image manipulation
https://www.openjpeg.org/
/opt/homebrew/Cellar/openjpeg/2.4.0 (523 files, 13.6MB) *
  Poured from bottle on 2021-11-25 at 16:35:14
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/openjpeg.rb
License: BSD-2-Clause
==> Dependencies
Build: cmake ✘, doxygen ✘
Required: libpng ✔, libtiff ✔, little-cms2 ✔
==> Options
--HEAD
    Install HEAD version
==> Analytics
install: 82,101 (30 days), 247,510 (90 days), 1,217,811 (365 days)
install-on-request: 1,835 (30 days), 5,246 (90 days), 20,835 (365 days)
build-error: 0 (30 days)
</code>```

Check what files are in a package with:

```<code>brew ls openjpeg
</code>```

Sample Output

```<code>/opt/homebrew/Cellar/openjpeg/2.4.0/bin/opj_compress
/opt/homebrew/Cellar/openjpeg/2.4.0/bin/opj_decompress
/opt/homebrew/Cellar/openjpeg/2.4.0/bin/opj_dump
/opt/homebrew/Cellar/openjpeg/2.4.0/include/openjpeg-2.4/ (3 files)
/opt/homebrew/Cellar/openjpeg/2.4.0/lib/libopenjp2.2.4.0.dylib
/opt/homebrew/Cellar/openjpeg/2.4.0/lib/openjpeg-2.4/ (3 files)
/opt/homebrew/Cellar/openjpeg/2.4.0/lib/pkgconfig/libopenjp2.pc
/opt/homebrew/Cellar/openjpeg/2.4.0/lib/ (3 other files)
/opt/homebrew/Cellar/openjpeg/2.4.0/share/doc/ (497 files)
/opt/homebrew/Cellar/openjpeg/2.4.0/share/man/ (4 files)
</code>```

Check how PIL is configured with:

```<code>python3 -m PIL        # or use "pythonXXX -m PIL" if that's how you start Python
</code>```

Sample Output

```<code>--------------------------------------------------------------------
Pillow 9.0.1
Python 3.10.0 (v3.10.0:b494f5935c, Oct  4 2021, 14:59:19) [Clang 12.0.5 (clang-1205.0.22.11)]
--------------------------------------------------------------------
Python modules loaded from /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/PIL
Binary modules loaded from /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/PIL
--------------------------------------------------------------------
--- PIL CORE support ok, compiled for 9.0.1
--- TKINTER support ok, loaded 8.6
--- FREETYPE2 support ok, loaded 2.11.1
--- LITTLECMS2 support ok, loaded 2.13
--- WEBP support ok, loaded 1.2.2
--- WEBP Transparency support ok
--- WEBPMUX support ok
--- WEBP Animation support ok
--- JPEG support ok, compiled for libjpeg-turbo 2.1.2
--- OPENJPEG (JPEG2000) support ok, loaded 2.4.0
--- ZLIB (PNG/ZIP) support ok, loaded 1.2.11
--- LIBTIFF support ok, loaded 4.2.0
*** RAQM (Bidirectional Text) support not installed
*** LIBIMAGEQUANT (Quantization method) support not installed
--- XCB (X protocol) support ok
--------------------------------------------------------------------
BLP
Extensions: .blp
Features: open
--------------------------------------------------------------------
BMP image/bmp
Extensions: .bmp
Features: open, save
--------------------------------------------------------------------
BUFR
Extensions: .bufr
Features: open, save
--------------------------------------------------------------------
CUR
Extensions: .cur
Features: open
--------------------------------------------------------------------
DCX
Extensions: .dcx
Features: open
--------------------------------------------------------------------
DDS
Extensions: .dds
Features: open, save
--------------------------------------------------------------------
DIB image/bmp
Extensions: .dib
Features: open, save
--------------------------------------------------------------------
EPS application/postscript
Extensions: .eps, .ps
Features: open, save
--------------------------------------------------------------------
FITS
Extensions: .fit, .fits
Features: open, save
--------------------------------------------------------------------
FLI
Extensions: .flc, .fli
Features: open
--------------------------------------------------------------------
FTEX
Extensions: .ftc, .ftu
Features: open
--------------------------------------------------------------------
GBR
Extensions: .gbr
Features: open
--------------------------------------------------------------------
GIF image/gif
Extensions: .gif
Features: open, save, save_all
--------------------------------------------------------------------
GRIB
Extensions: .grib
Features: open, save
--------------------------------------------------------------------
HDF5
Extensions: .h5, .hdf
Features: open, save
--------------------------------------------------------------------
ICNS image/icns
Extensions: .icns
Features: open, save
--------------------------------------------------------------------
ICO image/x-icon
Extensions: .ico
Features: open, save
--------------------------------------------------------------------
IM
Extensions: .im
Features: open, save
--------------------------------------------------------------------
IMT
Features: open
--------------------------------------------------------------------
IPTC
Extensions: .iim
Features: open
--------------------------------------------------------------------
JPEG image/jpeg
Extensions: .jfif, .jpe, .jpeg, .jpg
Features: open, save
--------------------------------------------------------------------
JPEG2000 image/jp2
Extensions: .j2c, .j2k, .jp2, .jpc, .jpf, .jpx
Features: open, save
--------------------------------------------------------------------
MCIDAS
Features: open
--------------------------------------------------------------------
MPEG video/mpeg
Extensions: .mpeg, .mpg
Features: open
--------------------------------------------------------------------
MSP
Extensions: .msp
Features: open, save, decode
--------------------------------------------------------------------
PCD
Extensions: .pcd
Features: open
--------------------------------------------------------------------
PCX image/x-pcx
Extensions: .pcx
Features: open, save
--------------------------------------------------------------------
PIXAR
Extensions: .pxr
Features: open
--------------------------------------------------------------------
PNG image/png
Extensions: .apng, .png
Features: open, save, save_all
--------------------------------------------------------------------
PPM image/x-portable-anymap
Extensions: .pbm, .pgm, .pnm, .ppm
Features: open, save
--------------------------------------------------------------------
PSD image/vnd.adobe.photoshop
Extensions: .psd
Features: open
--------------------------------------------------------------------
SGI image/sgi
Extensions: .bw, .rgb, .rgba, .sgi
Features: open, save
--------------------------------------------------------------------
SPIDER
Features: open, save
--------------------------------------------------------------------
SUN
Extensions: .ras
Features: open
--------------------------------------------------------------------
TGA image/x-tga
Extensions: .icb, .tga, .vda, .vst
Features: open, save
--------------------------------------------------------------------
TIFF image/tiff
Extensions: .tif, .tiff
Features: open, save, save_all
--------------------------------------------------------------------
WEBP image/webp
Extensions: .webp
Features: open, save, save_all
--------------------------------------------------------------------
WMF
Extensions: .emf, .wmf
Features: open, save
--------------------------------------------------------------------
XBM image/xbm
Extensions: .xbm
Features: open, save
--------------------------------------------------------------------
XPM image/xpm
Extensions: .xpm
Features: open
--------------------------------------------------------------------
XVTHUMB
Features: open
--------------------------------------------------------------------
</code>```

Body:
There are some similar questions here and especially here, but they don't go into quite the detail I'm seeking.

I'm attempting to read and edit JP2 (aka, JPEG2000) files using pillow. My code is below, and I suppose I don't yet have the OpenJPEG library installed, because I get the error module 'PIL._imaging' has no attribute 'jpeg2k_decoder'. So, I believe that I neeed to install OpenJPEG. Because I it's a system install (not contained within a virtual environment) and the instructions are piecemeal, I'm hoping to get more info.

Pillow's documentation indicates:

To enable JPEG 2000 support, you need to build and install the OpenJPEG library, version 2.0.0 or higher, before building the Python Imaging Library.

And OpenJPEG's install instructions aren't very clear, but seems to also require installation of cmake. The general advice I see everywhere is to uninstall pillow, install the OpenJPEG library, and then reinstall pillow. And I see that people often have to troubleshoot because pillow's reinstall doesn't pick up the new library sometimes.

I'm hoping that those who have been through the process on a Mac can advise on some details:

cmake appears to be required for installing OpenJPEG. Are the instructions at https://cmake.org/install/ sufficient?

The OpenJPEG instructions don't seem complete. Has anyone made step by step instructions that are easier to follow?

Code that returns the error:

from PIL import Image
import urllib.request
from io import BytesIO

url = 'https://chroniclingamerica.loc.gov/data/batches/dlc_golf_ver01/data/sn84025891/100493731/1901082401/0132.jp2'
img_raw = requests.get(url)
img = Image.open(BytesIO(img_raw.content))
display(img)

------ Outputs an error including: -------
AttributeError: module 'PIL._imaging' has no attribute 'jpeg2k_decoder'

Thanks!

Body:
IMHO, the easiest way to manage packages under macOS, such as OpenJPEG, is with homebrew.

All you need is:

brew install openjpeg

Search for available packages containing "jp" with:

brew search jp

Sample Output

==> Formulae
jp              jpdfbookmarks   jpeg-archive    jpeg-xl ✔       jpegoptim       mjpegtools      openjpeg ✔      recoverjpeg
jp2a            jpeg ✔          jpeg-turbo ✔    jpeginfo        jpegrescan      mozjpeg         pjproject

Get info about a package with:

brew info openjpeg

Sample Output

openjpeg: stable 2.4.0 (bottled), HEAD
Library for JPEG-2000 image manipulation
https://www.openjpeg.org/
/opt/homebrew/Cellar/openjpeg/2.4.0 (523 files, 13.6MB) *
  Poured from bottle on 2021-11-25 at 16:35:14
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/openjpeg.rb
License: BSD-2-Clause
==> Dependencies
Build: cmake ✘, doxygen ✘
Required: libpng ✔, libtiff ✔, little-cms2 ✔
==> Options
--HEAD
    Install HEAD version
==> Analytics
install: 82,101 (30 days), 247,510 (90 days), 1,217,811 (365 days)
install-on-request: 1,835 (30 days), 5,246 (90 days), 20,835 (365 days)
build-error: 0 (30 days)

Check what files are in a package with:

brew ls openjpeg

Sample Output

/opt/homebrew/Cellar/openjpeg/2.4.0/bin/opj_compress
/opt/homebrew/Cellar/openjpeg/2.4.0/bin/opj_decompress
/opt/homebrew/Cellar/openjpeg/2.4.0/bin/opj_dump
/opt/homebrew/Cellar/openjpeg/2.4.0/include/openjpeg-2.4/ (3 files)
/opt/homebrew/Cellar/openjpeg/2.4.0/lib/libopenjp2.2.4.0.dylib
/opt/homebrew/Cellar/openjpeg/2.4.0/lib/openjpeg-2.4/ (3 files)
/opt/homebrew/Cellar/openjpeg/2.4.0/lib/pkgconfig/libopenjp2.pc
/opt/homebrew/Cellar/openjpeg/2.4.0/lib/ (3 other files)
/opt/homebrew/Cellar/openjpeg/2.4.0/share/doc/ (497 files)
/opt/homebrew/Cellar/openjpeg/2.4.0/share/man/ (4 files)

Check how PIL is configured with:

python3 -m PIL        # or use "pythonXXX -m PIL" if that's how you start Python

Sample Output

--------------------------------------------------------------------
Pillow 9.0.1
Python 3.10.0 (v3.10.0:b494f5935c, Oct  4 2021, 14:59:19) [Clang 12.0.5 (clang-1205.0.22.11)]
--------------------------------------------------------------------
Python modules loaded from /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/PIL
Binary modules loaded from /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/PIL
--------------------------------------------------------------------
--- PIL CORE support ok, compiled for 9.0.1
--- TKINTER support ok, loaded 8.6
--- FREETYPE2 support ok, loaded 2.11.1
--- LITTLECMS2 support ok, loaded 2.13
--- WEBP support ok, loaded 1.2.2
--- WEBP Transparency support ok
--- WEBPMUX support ok
--- WEBP Animation support ok
--- JPEG support ok, compiled for libjpeg-turbo 2.1.2
--- OPENJPEG (JPEG2000) support ok, loaded 2.4.0
--- ZLIB (PNG/ZIP) support ok, loaded 1.2.11
--- LIBTIFF support ok, loaded 4.2.0
*** RAQM (Bidirectional Text) support not installed
*** LIBIMAGEQUANT (Quantization method) support not installed
--- XCB (X protocol) support ok
--------------------------------------------------------------------
BLP
Extensions: .blp
Features: open
--------------------------------------------------------------------
BMP image/bmp
Extensions: .bmp
Features: open, save
--------------------------------------------------------------------
BUFR
Extensions: .bufr
Features: open, save
--------------------------------------------------------------------
CUR
Extensions: .cur
Features: open
--------------------------------------------------------------------
DCX
Extensions: .dcx
Features: open
--------------------------------------------------------------------
DDS
Extensions: .dds
Features: open, save
--------------------------------------------------------------------
DIB image/bmp
Extensions: .dib
Features: open, save
--------------------------------------------------------------------
EPS application/postscript
Extensions: .eps, .ps
Features: open, save
--------------------------------------------------------------------
FITS
Extensions: .fit, .fits
Features: open, save
--------------------------------------------------------------------
FLI
Extensions: .flc, .fli
Features: open
--------------------------------------------------------------------
FTEX
Extensions: .ftc, .ftu
Features: open
--------------------------------------------------------------------
GBR
Extensions: .gbr
Features: open
--------------------------------------------------------------------
GIF image/gif
Extensions: .gif
Features: open, save, save_all
--------------------------------------------------------------------
GRIB
Extensions: .grib
Features: open, save
--------------------------------------------------------------------
HDF5
Extensions: .h5, .hdf
Features: open, save
--------------------------------------------------------------------
ICNS image/icns
Extensions: .icns
Features: open, save
--------------------------------------------------------------------
ICO image/x-icon
Extensions: .ico
Features: open, save
--------------------------------------------------------------------
IM
Extensions: .im
Features: open, save
--------------------------------------------------------------------
IMT
Features: open
--------------------------------------------------------------------
IPTC
Extensions: .iim
Features: open
--------------------------------------------------------------------
JPEG image/jpeg
Extensions: .jfif, .jpe, .jpeg, .jpg
Features: open, save
--------------------------------------------------------------------
JPEG2000 image/jp2
Extensions: .j2c, .j2k, .jp2, .jpc, .jpf, .jpx
Features: open, save
--------------------------------------------------------------------
MCIDAS
Features: open
--------------------------------------------------------------------
MPEG video/mpeg
Extensions: .mpeg, .mpg
Features: open
--------------------------------------------------------------------
MSP
Extensions: .msp
Features: open, save, decode
--------------------------------------------------------------------
PCD
Extensions: .pcd
Features: open
--------------------------------------------------------------------
PCX image/x-pcx
Extensions: .pcx
Features: open, save
--------------------------------------------------------------------
PIXAR
Extensions: .pxr
Features: open
--------------------------------------------------------------------
PNG image/png
Extensions: .apng, .png
Features: open, save, save_all
--------------------------------------------------------------------
PPM image/x-portable-anymap
Extensions: .pbm, .pgm, .pnm, .ppm
Features: open, save
--------------------------------------------------------------------
PSD image/vnd.adobe.photoshop
Extensions: .psd
Features: open
--------------------------------------------------------------------
SGI image/sgi
Extensions: .bw, .rgb, .rgba, .sgi
Features: open, save
--------------------------------------------------------------------
SPIDER
Features: open, save
--------------------------------------------------------------------
SUN
Extensions: .ras
Features: open
--------------------------------------------------------------------
TGA image/x-tga
Extensions: .icb, .tga, .vda, .vst
Features: open, save
--------------------------------------------------------------------
TIFF image/tiff
Extensions: .tif, .tiff
Features: open, save, save_all
--------------------------------------------------------------------
WEBP image/webp
Extensions: .webp
Features: open, save, save_all
--------------------------------------------------------------------
WMF
Extensions: .emf, .wmf
Features: open, save
--------------------------------------------------------------------
XBM image/xbm
Extensions: .xbm
Features: open, save
--------------------------------------------------------------------
XPM image/xpm
Extensions: .xpm
Features: open
--------------------------------------------------------------------
XVTHUMB
Features: open
--------------------------------------------------------------------


问:
Redirect to SHOW action in another controller
After creating a Person associated with a specific Account, how do I redirect back to the Account page?

The account_id is passed to the CREATE Person action via a URL parameter as follows:

```<code>http://localhost:3000/people/new?account_id=1
</code>```

Here is the code:

```<code><h2>Account:
    <%= Account.find_by_id(params[:account_id]).organizations.
        primary.first.name %>
</h2>

<%= form_for @person do |f| %>

    <%= f.hidden_field :account_id, :value => params[:account_id] %><br />
    <%= f.label :first_name %><br />
    <%= f.text_field :first_name %><br />
    <%= f.label :last_name %><br />
    <%= f.text_field :last_name %><br />
    <%= f.label :email1 %><br />
    <%= f.text_field :email1 %><br />
    <%= f.label :home_phone %><br />
    <%= f.text_field :home_phone %><br />
    <%= f.submit "Add person" %>

<% end %>

class PeopleController < ApplicationController

    def new
        @person = Person.new
    end

    def create
        @person = Person.new(params[:person])
        if @person.save
            flash[:success] = "Person added successfully"
            redirect_to account_path(params[:account_id])
        else
            render 'new'
        end
    end
end
</code>```

When I submit the above form I get the following error message:

```<code>Routing Error

No route matches {:action=>"destroy", :controller=>"accounts"}
</code>```

Why is the redirect_to routing to the DESTROY action?  I want to redirect via the SHOW action.  Any help will be greatly appreciated.

答:
params[:account_id] exists in the form, but when you pass it to create you're sending it along in the person hash, so you'd access it via params[:person][:account_id]

params[:account_id] is nil, hence the bad route.  To be honest, I'm not sure why, but resource_path(nil) ends up routing to destroy instead of show.  In either case, it's a broken route without an id parameter.

```<code># so you *could* change it to:
redirect_to account_path(params[:person][:account_id])

# or simpler:
redirect_to account_path(@person.account_id)

# but what you probably *should* change it to is:
redirect_to @person.account
</code>```

Rails will inherently understand this last option, ascertaining the path from the class of the record, and getting the id from #to_param

Body:
After creating a Person associated with a specific Account, how do I redirect back to the Account page?

The account_id is passed to the CREATE Person action via a URL parameter as follows:

http://localhost:3000/people/new?account_id=1

Here is the code:

Account:
    <%= Account.find_by_id(params[:account_id]).organizations.
        primary.first.name %>

<%= form_for @person do |f| %>

    <%= f.hidden_field :account_id, :value => params[:account_id] %>

    <%= f.label :first_name %>

    <%= f.text_field :first_name %>

    <%= f.label :last_name %>

    <%= f.text_field :last_name %>

    <%= f.label :email1 %>

    <%= f.text_field :email1 %>

    <%= f.label :home_phone %>

    <%= f.text_field :home_phone %>

    <%= f.submit "Add person" %>

<% end %>

class PeopleController < ApplicationController

    def new
        @person = Person.new
    end

    def create
        @person = Person.new(params[:person])
        if @person.save
            flash[:success] = "Person added successfully"
            redirect_to account_path(params[:account_id])
        else
            render 'new'
        end
    end
end

When I submit the above form I get the following error message:

Routing Error

No route matches {:action=>"destroy", :controller=>"accounts"}

Why is the redirect_to routing to the DESTROY action?  I want to redirect via the SHOW action.  Any help will be greatly appreciated.

Body:
params[:account_id] exists in the form, but when you pass it to create you're sending it along in the person hash, so you'd access it via params[:person][:account_id]

params[:account_id] is nil, hence the bad route.  To be honest, I'm not sure why, but resource_path(nil) ends up routing to destroy instead of show.  In either case, it's a broken route without an id parameter.

# so you *could* change it to:
redirect_to account_path(params[:person][:account_id])

# or simpler:
redirect_to account_path(@person.account_id)

# but what you probably *should* change it to is:
redirect_to @person.account

Rails will inherently understand this last option, ascertaining the path from the class of the record, and getting the id from #to_param


问:
Accessing local database from kubernetes cluster
I have a database running in local machine which i can access it using 127.0.0.1 or localhost, I need to access this database from my spring boot application which is deployed in local minikube kubernetes cluster.

how can i do that.

答: Use the external IP of your machine (f.e. wifi or ethernet) and connect to that. Be aware that you need to expose your database externally in that case.</p>


问:
I want to run Power Shell script with admin privileges
I want to run this powershell script with admin privileges so it won't give me the error:

Script Output with error

Here is the script:

```<code>$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"

Foreach ($process in $processes){
    try {
    $f = Get-Process $process -ErrorAction Stop
    $f | kill
    Write-Output "$process killed."
        }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException]{
    Write-Output "No instances of $process running."
        }
}

Start-Sleep -Seconds 3
</code>```

I want to run this script so it kill the processes that are giving errors

答:
I'm not sure what exactly you are asking about. If you want to start a script as administrator, you need to open PowerShell window "As administrator".

BTW, the script itself can be simplified without losing functionality:

```<code>$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"

Get-Process -Name $processes -ErrorAction SilentlyContinue | Stop-Process -Verbose
</code>```

Body:
I want to run this powershell script with admin privileges so it won't give me the error:

Script Output with error

Here is the script:

$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"

Foreach ($process in $processes){
    try {
    $f = Get-Process $process -ErrorAction Stop
    $f | kill
    Write-Output "$process killed."
        }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException]{
    Write-Output "No instances of $process running."
        }
}

Start-Sleep -Seconds 3

I want to run this script so it kill the processes that are giving errors

Body:
I'm not sure what exactly you are asking about. If you want to start a script as administrator, you need to open PowerShell window "As administrator".

BTW, the script itself can be simplified without losing functionality:

$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"

Get-Process -Name $processes -ErrorAction SilentlyContinue | Stop-Process -Verbose


问:
Why would this give a Use of uninitialised value of size 8
In my code I have a class named membrane with a function named exciteMod(), a function named decide() and a variable named delta_U. The first line of exciteMod() is this->delta_U = 0. In decide() I have an exponent of -delta_U (exp(-this->delta_U)). which cause an error Use of uninitialised value of size 8. The only place where I call decide() is inside of exciteMod(). What might cause this? I don't have any error about delta_U which is generated in valgrind.

Relevant segment of the code:

    void membrane::exciteMod(){
      this->delta_U = 0;
      /* Do some stuff which does not directly affect this->delta_U*/
      std::tr1::shared_ptr<bead> bit = this->beads.begin();
      while (bit != this->nead.end()){
        std::tr1::shared_ptr<bead> b = *bit++;
        //calculate the doubles U and nextU on b, nothing here gives a warning in valgrind,     anyhow U and nextU on b are always defined
       this->delta_U += (b->nextU - b->U);
      }
      decide();
    }

    void membrane::decide(){
      double r = P.r.ran3() // the random function from numerical recepies
      double f = - this->delta_U;
      if (r > exp(f)){ //this gives the warning even though delta_U is valid
        /*stuff*/
      }
    }
```
<p>This is the warning:</p>
```> ==467==    Use of uninitialised value of size 8
> ==467==    at 0x300B00D75D: __ieee754_exp (in /lib64/libm-2.5.so)
> ==467==    by 0x300B022FA3: exp (in /lib64/libm-2.5.so)
> ==467==    by 0x40BB9A: membrane::decide() (membrane.cpp:813)
> ==467==    by 0x40EBB1: membrane::exciteMod() (membrane.cpp:639)
> ==467==    by 0x413994: membrane::MCstep(int) (membrane.cpp:486)
> ==467==    by 0x402767: main (main.cpp:14)
```

答:
The most likely cause of uninitialized value is that at least one of b->nextU or b->U that you are adding to delta_U is itself uninitialized. That is:

```<code>foo = 0;
foo += some_uninitialized_value;
if (foo)  // Valgrind warns here
</code>```

You would like Valgrind to report when foo becomes uninitialized. Unfortunately, doing so  produces too many "false positive" warnings to be practical.

You can insert into your loop calls to VALGRIND_CHECK_MEM_IS_DEFINED (see Valgrind user manual), and Valgrind will signal the exact moment when delta_U becomes undefined.

Body:
In my code I have a class named membrane with a function named exciteMod(), a function named decide() and a variable named delta_U. The first line of exciteMod() is this->delta_U = 0. In decide() I have an exponent of -delta_U (exp(-this->delta_U)). which cause an error Use of uninitialised value of size 8. The only place where I call decide() is inside of exciteMod(). What might cause this? I don't have any error about delta_U which is generated in valgrind.

Relevant segment of the code:

    void membrane::exciteMod(){
      this->delta_U = 0;
      /* Do some stuff which does not directly affect this->delta_U*/
      std::tr1::shared_ptr<bead> bit = this->beads.begin();
      while (bit != this->nead.end()){
        std::tr1::shared_ptr<bead> b = *bit++;
        //calculate the doubles U and nextU on b, nothing here gives a warning in valgrind,     anyhow U and nextU on b are always defined
       this->delta_U += (b->nextU - b->U);
      }
      decide();
    }

    void membrane::decide(){
      double r = P.r.ran3() // the random function from numerical recepies
      double f = - this->delta_U;
      if (r > exp(f)){ //this gives the warning even though delta_U is valid
        /*stuff*/
      }
    }

This is the warning:

> ==467==    Use of uninitialised value of size 8
> ==467==    at 0x300B00D75D: __ieee754_exp (in /lib64/libm-2.5.so)
> ==467==    by 0x300B022FA3: exp (in /lib64/libm-2.5.so)
> ==467==    by 0x40BB9A: membrane::decide() (membrane.cpp:813)
> ==467==    by 0x40EBB1: membrane::exciteMod() (membrane.cpp:639)
> ==467==    by 0x413994: membrane::MCstep(int) (membrane.cpp:486)
> ==467==    by 0x402767: main (main.cpp:14)

Body:
The most likely cause of uninitialized value is that at least one of b->nextU or b->U that you are adding to delta_U is itself uninitialized. That is:

foo = 0;
foo += some_uninitialized_value;
if (foo)  // Valgrind warns here

You would like Valgrind to report when foo becomes uninitialized. Unfortunately, doing so  produces too many "false positive" warnings to be practical.

You can insert into your loop calls to VALGRIND_CHECK_MEM_IS_DEFINED (see Valgrind user manual), and Valgrind will signal the exact moment when delta_U becomes undefined.


问:
Is pkce able to protect agaisnt the compromise of mobile app secret hash and access code?
I understand the Oauth code flow which involves the mobile app, app server, auth server, resource server. The app server is registered with auth server using the clientidand secret. The idea being that mobile app calls an endpoint of the app server which triggers the code flow eventually resulting in callback from the auth server to the app server with the auth code. The app server presents the secret and code to auth server to get the access token.

The other legacy option where there is no clientid and secret is the implicit flow wherein the mobile app receives the redirect url with the auth code (assuming redirect url destination is a SPA) which will invoke auth server endpoint to get the access token.

This is insecure because anyone can steal the access code from the url.

The solution to this for clients like mobile app is to use pkce. A random number hash is sent in the initial request which is verified later on when the auth code is passed to retrieve the access token.

This prevents the compromise of the access code from the url if an attacker is snooping because without initial hash the auth code is useless.

However how can the situation where the mobile phone is hacked and the secret and auth code is recorded by an attacker be handled to prevent misuse?

答:
However how can the situation where the mobile phone is hacked and the
secret and auth code is recorded by an attacker be handled to prevent
misuse?

This is out of scope for OAuth 2.0 & related specifications. This issue is similar to storing encryption details in a server, but still, the server can be attacked by gaining physical access. It's a different attack vector altogether. It is user's duty to make sure their devices are safe from other vulnerabilities.

However, PKCE provides an extra security layer for public clients' usage of OAuth flow. It prevents attacks based on redirect (authorization code stealing), by establishing secondary validation at the authorization server.

In general, read through OAuth 2.0 Threat Model and Security Considerations &  OAuth 2.0 for Native Apps for best practice suggestions.


问:
CORS error on XHR request but only on android (iOS works fine...)
I have an android/iOS app made with Capacitor that serve a html file that make XHR request to my server.

It works fine on iOS emulator/device, but not on android emulator. I get the following error

```<code>File: http://example.com/ - Line 0 - Msg: Access to XMLHttpRequest at 'https://example.com/api/users/me?_=1644242401129' from origin 'http://example.com' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I do have an Access-Control-Allow-Origin set. Proof is that it works on iOS with the following origin allowed :

capacitor://example.com

But on android, it looks like the origin used is http://example.com as the errors says.

I did allow this url on my headers 'Access-Control-Allow-Origin' but it still fail and get me the same error.

    $allowed_domains = [
        'https://example.com',
        'http://example.com',
        'capacitor://example.com', //iOS working fine
    ];

    if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {

        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Credentials: true');
    }

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

       header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
       header('Access-Control-Allow-Headers: origin, content-type, accept, API');
       header('content-type: application/json; charset=utf-8');
       http_response_code(200);
       exit;
    }

```

答:
Solved it by removing the following entry in capacitor.config.json

```<code>  "server": {
    "hostname": "example.com"
  },
</code>```

This changed my origin to http://localhost for android and to capacitor://localhost for iOS.

Allowed both origins on my server and now it works on android but not on iOS.
Cookies are not sent with my XHR requests anymore on iOS (working fine on android).

So i guess the solution is to build on iOS with the server hostname, and build on android without it. Great..

Body:
I have an android/iOS app made with Capacitor that serve a html file that make XHR request to my server.

It works fine on iOS emulator/device, but not on android emulator. I get the following error

File: http://example.com/ - Line 0 - Msg: Access to XMLHttpRequest at 'https://example.com/api/users/me?_=1644242401129' from origin 'http://example.com' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I do have an Access-Control-Allow-Origin set. Proof is that it works on iOS with the following origin allowed :

capacitor://example.com

But on android, it looks like the origin used is http://example.com as the errors says.

I did allow this url on my headers 'Access-Control-Allow-Origin' but it still fail and get me the same error.

    $allowed_domains = [
        'https://example.com',
        'http://example.com',
        'capacitor://example.com', //iOS working fine
    ];

    if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {

        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Credentials: true');
    }

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

       header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
       header('Access-Control-Allow-Headers: origin, content-type, accept, API');
       header('content-type: application/json; charset=utf-8');
       http_response_code(200);
       exit;
    }

Body:
Solved it by removing the following entry in capacitor.config.json

  "server": {
    "hostname": "example.com"
  },

This changed my origin to http://localhost for android and to capacitor://localhost for iOS.

Allowed both origins on my server and now it works on android but not on iOS.
Cookies are not sent with my XHR requests anymore on iOS (working fine on android).

So i guess the solution is to build on iOS with the server hostname, and build on android without it. Great..


问:
How to fix error TS2345 in functional component React?
I have a small React + Typescript application. I am running a filtering function which is executed when some buttons are clicked or a value is entered into an input.

I have interfaces everywhere. I also passed the interface to the state, or the fact that I will have an empty array. But I keep getting an error with the following text:

"TS2345: Argument of type 'TodoItemInterface[] | undefined' is not assignable to parameter of type 'TodoItemInterface[]'. Type 'undefined' is not assignable to type 'TodoItemInterface[]'."

I can’t find how and where to pass that I definitely won’t have undefined or fix this error in a different way. Please help. Below I send the code of the function in useEffect and functions with a state that are related to it.

error is thrown here in filterItems.

```<code>useEffect(() => {
    const newArray = searchInputFilter(filterItems(todoListStateArray, infoSearchObject.filter), textForSearch);

    setVisibleTodoListItems(newArray);

}, [infoSearchObject, todoListStateArray, textForSearch])
</code>```

Another code

```<code>   const filterItems = (arr: TodoItemInterface[], filter: string) => {
        if (filter === 'all') {
            return arr;
        } else if (filter === 'active') {
            return arr.filter((item) => (!item.done));
        } else if (filter === 'done') {
            return arr.filter((item) => item.done);
        }

    };

    const searchInputFilter = (arr: TodoItemInterface[], search: string) => {
        if (search.length === 0) {
            return arr;
        }

        return arr.filter((item) => {
            return item.subtitle.toLowerCase().includes(search.toLowerCase());
        });
    }

    const [infoSearchObject, setInfoSearchObject] = useState({inWork: '', done: '', filter: 'all'});
    const [todoListStateArray, setTodoListStateArray] = useState<TodoItemInterface[] | []>(todoListDefault);
    const [visibleTodoListItems, setVisibleTodoListItems] = useState<TodoItemInterface[] | []>(todoListDefault);
    const [textForSearch, setTextForSearch] = useState('');
</code>```

答:
That is actually one of the benefits in using typescript; It’s actually telling you there is the possibility that your filterItems can possibly return undefined, and that happens when neither of your conditions are true.

As a solution, you should add a return value when none of the conditions are met:

const filterItems = (arr: TodoItemInterface[], filter: string): TodoItemInterface[] => {
        if (filter === 'all') {
            return arr;
        } else if (filter === 'active') {
            return arr.filter((item) => (!item.done));
        } else if (filter === 'done') {
            return arr.filter((item) => item.done);
        }
        return arr;
    };
```

To note that in the example I also added a return type to your function; That is pretty important to ensure consistency in what get actually returned from it.

Body:
I have a small React + Typescript application. I am running a filtering function which is executed when some buttons are clicked or a value is entered into an input.

I have interfaces everywhere. I also passed the interface to the state, or the fact that I will have an empty array. But I keep getting an error with the following text:

"TS2345: Argument of type 'TodoItemInterface[] | undefined' is not assignable to parameter of type 'TodoItemInterface[]'. Type 'undefined' is not assignable to type 'TodoItemInterface[]'."

I can’t find how and where to pass that I definitely won’t have undefined or fix this error in a different way. Please help. Below I send the code of the function in useEffect and functions with a state that are related to it.

error is thrown here in filterItems.

useEffect(() => {
    const newArray = searchInputFilter(filterItems(todoListStateArray, infoSearchObject.filter), textForSearch);

    setVisibleTodoListItems(newArray);

}, [infoSearchObject, todoListStateArray, textForSearch])

Another code

   const filterItems = (arr: TodoItemInterface[], filter: string) => {
        if (filter === 'all') {
            return arr;
        } else if (filter === 'active') {
            return arr.filter((item) => (!item.done));
        } else if (filter === 'done') {
            return arr.filter((item) => item.done);
        }

    };

    const searchInputFilter = (arr: TodoItemInterface[], search: string) => {
        if (search.length === 0) {
            return arr;
        }

        return arr.filter((item) => {
            return item.subtitle.toLowerCase().includes(search.toLowerCase());
        });
    }

    const [infoSearchObject, setInfoSearchObject] = useState({inWork: '', done: '', filter: 'all'});
    const [todoListStateArray, setTodoListStateArray] = useState<TodoItemInterface[] | []>(todoListDefault);
    const [visibleTodoListItems, setVisibleTodoListItems] = useState<TodoItemInterface[] | []>(todoListDefault);
    const [textForSearch, setTextForSearch] = useState('');

Body:
That is actually one of the benefits in using typescript; It’s actually telling you there is the possibility that your filterItems can possibly return undefined, and that happens when neither of your conditions are true.

As a solution, you should add a return value when none of the conditions are met:

const filterItems = (arr: TodoItemInterface[], filter: string): TodoItemInterface[] => {
        if (filter === 'all') {
            return arr;
        } else if (filter === 'active') {
            return arr.filter((item) => (!item.done));
        } else if (filter === 'done') {
            return arr.filter((item) => item.done);
        }
        return arr;
    };

To note that in the example I also added a return type to your function; That is pretty important to ensure consistency in what get actually returned from it.


问:
List of files and folders that don't require authentication
How can I get a list of shared files or folders that don't require you to authenticate to download the file etc, is there a specific attribute for the listed files and folders using "files_list_folder"</p>

答: There isn't such a property on the entries returned by files_list_folder/files_list_folder_continue directly, but you can use files_get_temporary_link to get a temporary direct link to a file. The files_get_temporary_link call itself requires authorization, but the resulting link doesn't.


问:
Dropdown menu not working with Bootstrap 4 and Laravel 6
I am using Laravel 6 and Bootstrap 4. The dropdown menu in the right side of my navbar worked fine until I ran the command npm install. After that the dropdown menu stopped working... when I click on it nothing happen. In the dropdown menu there are the name of the connected user and the logout.

layout:

```<code><!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('/js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <!-- Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link href="{{ asset('/css/app.css') }}" rel="stylesheet" type="text/css">

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</head>
<body style="overflow: hidden; ">
    <div id="app">
        @include('../inc/navbar')
        <main class="py-4">
            @yield('content')
        </main>
        <br>
        <br>
        <br>
        @include('../inc/footer')
    </div>
    </body>
</html>
</code>```

navbar:

```<code>            <!-- Right Side Of Navbar -->
            <ul class="navbar-nav ml-auto">
                <!-- Authentication Links -->
                @guest
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                    </li>
                    @if (Route::has('register'))
                        <li class="nav-item">
                            <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                        </li>
                    @endif
                @else <!-- This dropdown menu doesn't work-->
                    <li class="nav-item dropdown">
                        <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                            {{ Auth::user()->name . ' ' . Auth::user()->surname }} <span class="caret"></span>
                        </a>

                        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="{{ route('logout') }}"
                               onclick="event.preventDefault();
                                             document.getElementById('logout-form').submit();">
                                {{ __('Logout') }}
                            </a>

                            <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                @csrf
                            </form>
                        </div>
                    </li>
                @endguest
            </ul>
</code>```

package.json:

```<code>{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^4.0.7",
        "lodash": "^4.17.13",
        "popper.js": "^1.16.0",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.20.1",
        "sass-loader": "7.*",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    }
}
</code>```

webpack.mix.js

```<code>const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');
</code>```

So currently I cannot logout from the app because the dropdown menu doesn't work.
I read on internet to find the solution and I think that the problem is Popper. How may I configure Popper to solve that problem making the dropdown menu work?

答:
First check your css and js file location is perfect.
then you change
data-bs-toggle="dropdown" to data-toggle="dropdown". I hope it will be help you.</p>

Body:
I am using Laravel 6 and Bootstrap 4. The dropdown menu in the right side of my navbar worked fine until I ran the command npm install. After that the dropdown menu stopped working... when I click on it nothing happen. In the dropdown menu there are the name of the connected user and the logout.

layout:

<!doctype html>
getLocale()) }}">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link href="{{ asset('/css/app.css') }}" rel="stylesheet" type="text/css">

        @include('../inc/navbar')

            @yield('content')

        @include('../inc/footer')

navbar:

                @guest

                        {{ __('Login') }}

                    @if (Route::has('register'))

                            {{ __('Register') }}

                    @endif
                @else

                            {{ Auth::user()->name . ' ' . Auth::user()->surname }}

                                {{ __('Logout') }}

                            <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                @csrf
                            </form>

                @endguest

package.json:

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^4.0.7",
        "lodash": "^4.17.13",
        "popper.js": "^1.16.0",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.20.1",
        "sass-loader": "7.*",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    }
}

webpack.mix.js

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

So currently I cannot logout from the app because the dropdown menu doesn't work.
I read on internet to find the solution and I think that the problem is Popper. How may I configure Popper to solve that problem making the dropdown menu work?


问:
On index attribute in ggraph
I’ m using ggraph to plot graphs based on hierarchical edge bundling. I’m using the example from https://www.r-graph-gallery.com/311-add-labels-to-hierarchical-edge-bundling.html. I have a question about the significance of index in the network representation?  Can we replace the color of the links with another attribute?

The code:

```<code>library(ggraph)
library(igraph)
library(tidyverse)
library(RColorBrewer)

# create a data frame giving the hierarchical structure of your individuals
set.seed(1234)
d1 <- data.frame(from="origin", to=paste("group", seq(1,10), sep=""))
d2 <- data.frame(from=rep(d1$to, each=10), to=paste("subgroup", seq(1,100), sep="_"))
edges <- rbind(d1, d2)

# create a dataframe with connection between leaves (individuals)
all_leaves <- paste("subgroup", seq(1,100), sep="_")
connect <- rbind(
  data.frame( from=sample(all_leaves, 100, replace=T) , to=sample(all_leaves, 100, replace=T)),
  data.frame( from=sample(head(all_leaves), 30, replace=T) , to=sample( tail(all_leaves), 30, replace=T)),
  data.frame( from=sample(all_leaves[25:30], 30, replace=T) , to=sample( all_leaves[55:60], 30, replace=T)),
  data.frame( from=sample(all_leaves[75:80], 30, replace=T) , to=sample( all_leaves[55:60], 30, replace=T)) )
connect$value <- runif(nrow(connect))

# create a vertices data.frame. One line per object of our hierarchy
vertices  <-  data.frame(
  name = unique(c(as.character(edges$from), as.character(edges$to))) ,
  value = runif(111)
)
# Let's add a column with the group of each name. It will be useful later to color points
vertices$group  <-  edges$from[ match( vertices$name, edges$to ) ]
#Let's add information concerning the label we are going to add: angle, horizontal adjustement and potential flip
#calculate the ANGLE of the labels
vertices$id <- NA
myleaves <- which(is.na( match(vertices$name, edges$from) ))
nleaves <- length(myleaves)
vertices$id[ myleaves ] <- seq(1:nleaves)
vertices$angle <- 90 - 360 * vertices$id / nleaves

# calculate the alignment of labels: right or left
# If I am on the left part of the plot, my labels have currently an angle < -90
vertices$hjust <- ifelse( vertices$angle < -90, 1, 0)

# flip angle BY to make them readable
vertices$angle <- ifelse(vertices$angle < -90, vertices$angle+180, vertices$angle)
# Create a graph object
mygraph <- igraph::graph_from_data_frame( edges, vertices=vertices )

# The connection object must refer to the ids of the leaves:
from  <-  match( connect$from, vertices$name)
to  <-  match( connect$to, vertices$name)
ggraph(mygraph, layout = 'dendrogram', circular = TRUE) +
  geom_conn_bundle(data = get_con(from = from, to = to), alpha=0.2, width=0.9, aes(colour=..index..)) +
  scale_edge_colour_distiller(palette = "RdPu") +

  geom_node_text(aes(x = x*1.15, y=y*1.15, filter = leaf, label=name, angle = angle, hjust=hjust, colour=group), size=2, alpha=1) +

  geom_node_point(aes(filter = leaf, x = x*1.07, y=y*1.07, colour=group, size=value, alpha=0.2)) +
  scale_colour_manual(values= rep( brewer.pal(9,"Paired") , 30)) +
  scale_size_continuous( range = c(0.1,10) )
</code>```

答:
You can specify the attributes directly like this:

```<code>ggraph(mygraph, layout = 'dendrogram', circular = TRUE) +
  geom_conn_bundle(data = get_con(from = from, to = to), alpha=0.2, width=0.9, aes(colour=x)) +
  scale_edge_colour_distiller(palette = "RdPu")
</code>```

The same for y. You can also change the the parameter using the dots after and before the variable: ..x.. or ..y..

Update:

```<code># The connection object must refer to the ids of the leaves:
from  <-  match( connect$from, vertices$name)
to  <-  match( connect$to, vertices$name)
value  <-  match( connect$value, vertices$name)
ggraph(mygraph, layout = 'dendrogram', circular = TRUE) +
  geom_conn_bundle(data = get_con(from = from, to = to, vakue = value), alpha=0.2, width=0.9,
                   aes(colour=..value..)) +
  scale_edge_colour_distiller(palette = "RdPu") +

  geom_node_text(aes(x = x*1.15, y=y*1.15, filter = leaf, label=name, angle = angle, hjust=hjust, colour=group), size=2, alpha=1) +

  geom_node_point(aes(filter = leaf, x = x*1.07, y=y*1.07, colour=group, size=value, alpha=0.2)) +
  scale_colour_manual(values= rep( brewer.pal(9,"Paired") , 30)) +
  scale_size_continuous( range = c(0.1,10) )
</code>```

Title: On index attribute in ggraph

Body:
I’ m using ggraph to plot graphs based on hierarchical edge bundling. I’m using the example from https://www.r-graph-gallery.com/311-add-labels-to-hierarchical-edge-bundling.html. I have a question about the significance of index in the network representation?  Can we replace the color of the links with another attribute?

The code:

library(ggraph)
library(igraph)
library(tidyverse)
library(RColorBrewer)

# create a data frame giving the hierarchical structure of your individuals
set.seed(1234)
d1 <- data.frame(from="origin", to=paste("group", seq(1,10), sep=""))
d2 <- data.frame(from=rep(d1$to, each=10), to=paste("subgroup", seq(1,100), sep="_"))
edges <- rbind(d1, d2)

# create a dataframe with connection between leaves (individuals)
all_leaves <- paste("subgroup", seq(1,100), sep="_")
connect <- rbind(
  data.frame( from=sample(all_leaves, 100, replace=T) , to=sample(all_leaves, 100, replace=T)),
  data.frame( from=sample(head(all_leaves), 30, replace=T) , to=sample( tail(all_leaves), 30, replace=T)),
  data.frame( from=sample(all_leaves[25:30], 30, replace=T) , to=sample( all_leaves[55:60], 30, replace=T)),
  data.frame( from=sample(all_leaves[75:80], 30, replace=T) , to=sample( all_leaves[55:60], 30, replace=T)) )
connect$value <- runif(nrow(connect))

# create a vertices data.frame. One line per object of our hierarchy
vertices  <-  data.frame(
  name = unique(c(as.character(edges$from), as.character(edges$to))) ,
  value = runif(111)
)
# Let's add a column with the group of each name. It will be useful later to color points
vertices$group  <-  edges$from[ match( vertices$name, edges$to ) ]
#Let's add information concerning the label we are going to add: angle, horizontal adjustement and potential flip
#calculate the ANGLE of the labels
vertices$id <- NA
myleaves <- which(is.na( match(vertices$name, edges$from) ))
nleaves <- length(myleaves)
vertices$id[ myleaves ] <- seq(1:nleaves)
vertices$angle <- 90 - 360 * vertices$id / nleaves

# calculate the alignment of labels: right or left
# If I am on the left part of the plot, my labels have currently an angle < -90
vertices$hjust <- ifelse( vertices$angle < -90, 1, 0)

# flip angle BY to make them readable
vertices$angle <- ifelse(vertices$angle < -90, vertices$angle+180, vertices$angle)
# Create a graph object
mygraph <- igraph::graph_from_data_frame( edges, vertices=vertices )

# The connection object must refer to the ids of the leaves:
from  <-  match( connect$from, vertices$name)
to  <-  match( connect$to, vertices$name)
ggraph(mygraph, layout = 'dendrogram', circular = TRUE) +
  geom_conn_bundle(data = get_con(from = from, to = to), alpha=0.2, width=0.9, aes(colour=..index..)) +
  scale_edge_colour_distiller(palette = "RdPu") +

  geom_node_text(aes(x = x*1.15, y=y*1.15, filter = leaf, label=name, angle = angle, hjust=hjust, colour=group), size=2, alpha=1) +

  geom_node_point(aes(filter = leaf, x = x*1.07, y=y*1.07, colour=group, size=value, alpha=0.2)) +
  scale_colour_manual(values= rep( brewer.pal(9,"Paired") , 30)) +
  scale_size_continuous( range = c(0.1,10) )

Body:
You can specify the attributes directly like this:

ggraph(mygraph, layout = 'dendrogram', circular = TRUE) +
  geom_conn_bundle(data = get_con(from = from, to = to), alpha=0.2, width=0.9, aes(colour=x)) +
  scale_edge_colour_distiller(palette = "RdPu")

The same for y. You can also change the the parameter using the dots after and before the variable: ..x.. or ..y..

Update:

# The connection object must refer to the ids of the leaves:
from  <-  match( connect$from, vertices$name)
to  <-  match( connect$to, vertices$name)
value  <-  match( connect$value, vertices$name)
ggraph(mygraph, layout = 'dendrogram', circular = TRUE) +
  geom_conn_bundle(data = get_con(from = from, to = to, vakue = value), alpha=0.2, width=0.9,
                   aes(colour=..value..)) +
  scale_edge_colour_distiller(palette = "RdPu") +

  geom_node_text(aes(x = x*1.15, y=y*1.15, filter = leaf, label=name, angle = angle, hjust=hjust, colour=group), size=2, alpha=1) +

  geom_node_point(aes(filter = leaf, x = x*1.07, y=y*1.07, colour=group, size=value, alpha=0.2)) +
  scale_colour_manual(values= rep( brewer.pal(9,"Paired") , 30)) +
  scale_size_continuous( range = c(0.1,10) )


问:
Podman image not updating like it has to
I ran the following commands to change some lines in a file contained in a podman container:

# RUN THE IMAGE
podman run -it opensearchproject/opensearch-dashboards:1.2.0 /bin/bash

# READ CONTENT

cat config\opensearch_dashboards.yml

# OLD CONTENT

while IFS='' read -r a; do
    echo "${a//localhost/0.0.0.0}"
done < opensearch_dashboards.yml > opensearch_dashboards.yml.t
mv opensearch_dashboards.yml{.t,}

# READ NEW CONTENT

cat config\opensearch_dashboards.yml

# NEW CONTENT LOOKS FINE, CLOSE SESSION

exit

# RUN IMAGE, AGAIN

podman run -it opensearchproject/opensearch-dashboards:1.2.0 /bin/bash

# READ CONTENT AGAIN

cat config\opensearch_dashboards.yml

# OLD CONTENT SHOWS UP
```

What am I missing? I thought I could update the image, but it doesn't work. Everytime the replace works, it goes up in flames. I'm new to containers and I feel stuck.

答:
Making changes in a container doesn't update the underlying image. A container has an ephemeral filesystem that only exists for the lifetime of the container -- when the container exits, the filesystem is gone.

Images are effectively read-only. If you want to make changes to the image, create a new one using an appropriate Dockerfile. You would probably start with something like:

```<code>FROM opensearchproject/opensearch-dashboards:1.2.0

...
</code>```

Where you would replace ... with appropriate RUN or COPY commands to modify the image to meet your needs.

Body:
I ran the following commands to change some lines in a file contained in a podman container:

# RUN THE IMAGE
podman run -it opensearchproject/opensearch-dashboards:1.2.0 /bin/bash

# READ CONTENT

cat config\opensearch_dashboards.yml

# OLD CONTENT

while IFS='' read -r a; do
    echo "${a//localhost/0.0.0.0}"
done < opensearch_dashboards.yml > opensearch_dashboards.yml.t
mv opensearch_dashboards.yml{.t,}

# READ NEW CONTENT

cat config\opensearch_dashboards.yml

# NEW CONTENT LOOKS FINE, CLOSE SESSION

exit

# RUN IMAGE, AGAIN

podman run -it opensearchproject/opensearch-dashboards:1.2.0 /bin/bash

# READ CONTENT AGAIN

cat config\opensearch_dashboards.yml

# OLD CONTENT SHOWS UP

What am I missing? I thought I could update the image, but it doesn't work. Everytime the replace works, it goes up in flames. I'm new to containers and I feel stuck.

Body:
Making changes in a container doesn't update the underlying image. A container has an ephemeral filesystem that only exists for the lifetime of the container -- when the container exits, the filesystem is gone.

Images are effectively read-only. If you want to make changes to the image, create a new one using an appropriate Dockerfile. You would probably start with something like:

FROM opensearchproject/opensearch-dashboards:1.2.0

...

Where you would replace ... with appropriate RUN or COPY commands to modify the image to meet your needs.


问:
Is there R syntax to delete rows with specific, multiple NAs in columns?
Hello coding community,

If my data frame looks like:

```<code>ID     Col1 Col2 Col3 Col4
Per1   1    2    3    4
Per2   2    NA   NA   NA
Per3   NA   NA   5    NA
</code>```

Is there any syntax to delete the row associated with ID = Per2, on the basis that Col2, Col3, AND Col4 = NA? I am hoping for code that will allow me to delete a row on the basis that three specific columns (Col2, Col3, and Col4) ALL are NA. This code would NOT delete the row ID = Per3, even though there are three NAs.

Please note that I know how to delete a specific row, but my data frame is big so I do not want to manually sort through all rows/columns.

Big thanks!

答:
Using if_any

```<code>library(dplyr)
df %>%
  filter(if_any(Col2:Col4, complete.cases))
    ID Col1 Col2 Col3 Col4
1 Per1    1    2    3    4
2 Per3   NA   NA    5   NA
</code>```

Body:
Hello coding community,

If my data frame looks like:

ID     Col1 Col2 Col3 Col4
Per1   1    2    3    4
Per2   2    NA   NA   NA
Per3   NA   NA   5    NA

Is there any syntax to delete the row associated with ID = Per2, on the basis that Col2, Col3, AND Col4 = NA? I am hoping for code that will allow me to delete a row on the basis that three specific columns (Col2, Col3, and Col4) ALL are NA. This code would NOT delete the row ID = Per3, even though there are three NAs.

Please note that I know how to delete a specific row, but my data frame is big so I do not want to manually sort through all rows/columns.

Big thanks!

Body:
Using if_any

library(dplyr)
df %>%
  filter(if_any(Col2:Col4, complete.cases))
    ID Col1 Col2 Col3 Col4
1 Per1    1    2    3    4
2 Per3   NA   NA    5   NA