问:
RHEL7 dockerd remote connection
I'm exploring creating a gateway that can start and stop docker containers on a rhel7 system upon.  I've made changes to my /usr/lib/systemd/system/docker.service to start docker on an interface with the following.

```<code>ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:23751 --containerd=/run/containerd/containerd.sock
</code>```

I'm unable to connect to dockerd to get the status of the containers unless I disable the firewall.  But if I disable the firewall,  I can't start conatiners.

```<code>Caused by: com.amihaiemil.docker.UnexpectedResponseException: Expected status 204 but got 500 when calling
 http://192.168.1.70:23751/v1.35/containers/e3f0f09269a699ec27bbac8a5027d1383ae15cf64b5e6b649e76be1297cc2535/start.
Response body was {"message":"driver failed programming external connectivity on endpoint hello-service
(eef135f889322f1899800f19612404e9d8b1f39c7866f31ca5059562aa501bf6):
(iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0 --dport 34570 -j DNAT --to-destination 192.168.10.40:8080 ! -i br-4982fe847356: iptables: No chain/target/match by that name.\n (exit status 1))"}
</code>```

I realize there are consequences of running an open tcp port for dockerd.  Before,  I get everything secure,  I would like to get an idea of how a gateway might do something like this.

Does anyone else have experience doing something like this?

答:
After much trial and error, I found out that firewalld is blocking that port.

To enable the port, do the following.

```<code>sudo firewall-cmd --zone=public --add-port=2375/tcp
</code>```

Please note, doing this opens a very large security vulnerability as the commenter above has pointed out.  In my case, this was done behind a firewall where no outside connections can make a connection to inside my network's firewall.  This is still a bad idea, but in this case it is being used to explore some concepts and is turned off when not being used. Please explore the security implications when doing this.
  Also, the firewall will not save the configuration in the above command unless you use the --permanent argument

Title: RHEL7 dockerd remote connection

Body:
I'm exploring creating a gateway that can start and stop docker containers on a rhel7 system upon.  I've made changes to my /usr/lib/systemd/system/docker.service to start docker on an interface with the following.

ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:23751 --containerd=/run/containerd/containerd.sock

I'm unable to connect to dockerd to get the status of the containers unless I disable the firewall.  But if I disable the firewall,  I can't start conatiners.

Caused by: com.amihaiemil.docker.UnexpectedResponseException: Expected status 204 but got 500 when calling
 http://192.168.1.70:23751/v1.35/containers/e3f0f09269a699ec27bbac8a5027d1383ae15cf64b5e6b649e76be1297cc2535/start.
Response body was {"message":"driver failed programming external connectivity on endpoint hello-service
(eef135f889322f1899800f19612404e9d8b1f39c7866f31ca5059562aa501bf6):
(iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0 --dport 34570 -j DNAT --to-destination 192.168.10.40:8080 ! -i br-4982fe847356: iptables: No chain/target/match by that name.\n (exit status 1))"}

I realize there are consequences of running an open tcp port for dockerd.  Before,  I get everything secure,  I would like to get an idea of how a gateway might do something like this.

Does anyone else have experience doing something like this?

Body:
After much trial and error, I found out that firewalld is blocking that port.

To enable the port, do the following.

sudo firewall-cmd --zone=public --add-port=2375/tcp

Please note, doing this opens a very large security vulnerability as the commenter above has pointed out.  In my case, this was done behind a firewall where no outside connections can make a connection to inside my network's firewall.  This is still a bad idea, but in this case it is being used to explore some concepts and is turned off when not being used. Please explore the security implications when doing this.
  Also, the firewall will not save the configuration in the above command unless you use the --permanent argument


来源: stackexchange

问:
Specifying an attribute in a generic React component
I am trying to build a generic React select component to show a list of options labeled as whatever is passed to the component. My issue is that I want to be able to specify which attribute to use when printing the records which will not always be the same. For instance, if I pass an array of authors, I would use the full_name attribute to populate the list; however, if I wanted to print a list of books, I would want to use title.

I have an options function that I call to populate the select which looks like this:

```<code>options = () => {
  return this.props.collection.map(o => {
    return (
      <option key={o.id} value={o.id}>/*DISPLAY METHOD HERE*/</option>
    )
  })
}
</code>```

Basically I want to be able to pass in a prop to the component specifying the attribute I want to use (full_name, title, etc) and call that on o (o.full_name, o.title, ...) in the return call. Is this possible?

答:
const SelectPicker = ({ data }) => (
    <select>
      {Object.keys(data).map(key => (
        <option value={key}>{data[key]}</option>
      ))}
    </select>
  );

function App() {
  var obj = {
    userOne: "John Doe",
    userTwo: "John Smith"
  };
  return (

      <SelectPicker data={obj} />

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div></code>```

You might look for something like this?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build a generic React select component to show a list of options labeled as whatever is passed to the component. My issue is that I want to be able to specify which attribute to use when printing the records which will not always be the same. For instance, if I pass an array of authors, I would use the full_name attribute to populate the list; however, if I wanted to print a list of books, I would want to use title.

I have an options function that I call to populate the select which looks like this:

options = () => {
  return this.props.collection.map(o => {
    return (
      <option key={o.id} value={o.id}>/*DISPLAY METHOD HERE*/</option>
    )
  })
}

Basically I want to be able to pass in a prop to the component specifying the attribute I want to use (full_name, title, etc) and call that on o (o.full_name, o.title, ...) in the return call. Is this possible?

Body:
const SelectPicker = ({ data }) => (
    <select>
      {Object.keys(data).map(key => (
        <option value={key}>{data[key]}</option>
      ))}
    </select>
  );

function App() {
  var obj = {
    userOne: "John Doe",
    userTwo: "John Smith"
  };
  return (
    <div className="App">
      <SelectPicker data={obj} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

You might look for something like this?


问:
How to update records on production environment?
Ruby on Rails
We recently added a field to a table and that field is populated when a record is created. However, we have older records in the table. Meaning the newly added fields are not populated in those records. Now I need to update them.
So,.what is the best way to update the older records? The value to populate needs some computation before storing.
The server is hosted on AWS.
I know rake task is one option. But are there any other efficient ways?</p>

答: An alternative you could consider is writing a script that connects directly to your postgres DB, does the computation and updates your old records through a sql query.</p>


问:
Why is getConfiguration occasionally throwing File cannot be null?
This might seem to be a simple question (if that's the case, please excuse me), but after 20 minutes of online searching I did not find any sensible answer.

I have several cron jobs to be executed via QuartzRunner, let's call the first FooBean and the second BarBean for now. FooBean is running daily at 00:00 for 6 (!) hours and sometimes it is not executed properly. After carefully studying the logs I found out that FooBean fails to execute when BarBean fails to execute. BarBean is executed daily at 03:00 and sometimes it throws:

```<code> 22866 java.lang.NullPointerException: File cannot be <null>
 22867     at org.jconfig.FileWatcher.<init>(FileWatcher.java:54)
 22868     at org.jconfig.handler.AbstractHandler.addFileListener(AbstractHandler.java:39)
 22869     at org.jconfig.ConfigurationManager.addFileListener(ConfigurationManager.java:180)
 22870     at org.jconfig.ConfigurationManager.getConfiguration(ConfigurationManager.java:122)
</code>```

sometimes it does not throw it and then FooBean is executed properly. If BarBean fails, then the log shows some Transaction deadlock issue repeatedly for ten minutes and then JDBC connection failures repeated again and again for almost three hours. I do not understand what file is being involved. The line throwing the error looks like:

```<code>    Configuration config = ConfigurationManager.getConfiguration("inventory");
</code>```

and org.jconfig namespaces are involved here. Intuitively this seems to be a misconfiguration, but I did not find any sources which explain the issue.

答:
The ConfigurationManagers getConfiguration-Method tries to load a config file from your classpath. The function concatenates the given name with '_config.xml'.
In your case this would be 'inventory_config.xml' this file should be in available on your classpath (main/resources) because ConfigurationManager tries to load it from there.</p>

Body:
This might seem to be a simple question (if that's the case, please excuse me), but after 20 minutes of online searching I did not find any sensible answer.

I have several cron jobs to be executed via QuartzRunner, let's call the first FooBean and the second BarBean for now. FooBean is running daily at 00:00 for 6 (!) hours and sometimes it is not executed properly. After carefully studying the logs I found out that FooBean fails to execute when BarBean fails to execute. BarBean is executed daily at 03:00 and sometimes it throws:

 22866 java.lang.NullPointerException: File cannot be <null>
 22867     at org.jconfig.FileWatcher.<init>(FileWatcher.java:54)
 22868     at org.jconfig.handler.AbstractHandler.addFileListener(AbstractHandler.java:39)
 22869     at org.jconfig.ConfigurationManager.addFileListener(ConfigurationManager.java:180)
 22870     at org.jconfig.ConfigurationManager.getConfiguration(ConfigurationManager.java:122)

sometimes it does not throw it and then FooBean is executed properly. If BarBean fails, then the log shows some Transaction deadlock issue repeatedly for ten minutes and then JDBC connection failures repeated again and again for almost three hours. I do not understand what file is being involved. The line throwing the error looks like:

    Configuration config = ConfigurationManager.getConfiguration("inventory");

and org.jconfig namespaces are involved here. Intuitively this seems to be a misconfiguration, but I did not find any sources which explain the issue.


问:
Angular doesn't load with a mobile connection
I've got an angular 6 application hosted on my server, with ssl and https protocol. I can enter on my site from my computer with a lot of connection, but on my mobile phone the loading is very slow... about 3-4 minutes.

I've done network profiling with chrome and I can't see what takes a lot of time, vendor.js takes 3 seconds with a fast connection but with a mobile connection the loading doesn't finish.

答:
but on my mobile phone the loading is very slow... about 3-4 minutes.

Run a bandwidth test on your phone to make sure the connection has the required speed. Go to https://google.com/ and search for "speedtest".

Next, build an empty Angular project and try that instead. Verify it loads quickly.

Once you've verified that the phone's speed is not the issue, then it's likely you're seeing a dump of error messages to the console. Even when the console is not visible the cascade of unhandled exceptions will have a negative effect on performance.

You can remotely debug the phone's JavaScript console by using https://jsconsole.com/

Here's an article on how to use it:

https://coderwall.com/p/cvstug/debugging-javascript-errors-on-ios-android-and-other-mobile-devices

Here's a video on it:

https://www.youtube.com/watch?v=Y219Ziuipvc


问:
Can we use Oracle Database directly, without using tools
I want to know is there any difference between Oracle and sql developer tools? </p>

答:
It depends on what you consider a 'tool.'

The database ships with a couple of command-line interfaces, SQLPlus and SQLcl. Those are both tools, they're not a part of the core database code.

You could also use web interfaces like SQL Developer Web, APEX, EM Express, or Enterprise Manager. Some of those ship with the Database, and EM Express runs out of the database, but those are kind of tools too.

You could write your own program to interact with the database, but you're going to use a JDBC driver or something that supports SQLNet...but then are those drivers, tools?

So my answer to you is, it depends on what you mean by 'tool.'

Can you use the database without SQL Developer, yes.


问:
C# Finding specific values from messageformat strings
Given a messageformat string such as str below. I want to be able to get the "notifications" & "name" values which are used to display the text values.

```<code>var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";
</code>```

I have tried using a regex such as:

```<code>var matches = Regex.Matches(str, @"{(.*?)}");
//var matches = Regex.Matches(str, @"(?<=\{)[^}{]*(?=\})");
var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct().ToList();
</code>```

But the above does not take in to account that {notifications,.. is itself wraped in curly braces and includes the inner values that are not needed, which are wrapped in curly braces also.

So in brief I just want to be able to parse a string such as str above and get notifications & name at the returned values.

A string such as var str2 = @"Hello {name}" should just return name as the value.

EDIT

The values notifications & name will not be known in advance - I have just used this as an example, for the values I require to return from the string.

答:
One way to do this would be to write a method that will format a string for you based on an input count and the singular (and plural) form of the string:

```<code>private static string FormatWord(int count, string singluar)
{
    return Format(count, singluar, singluar + "s");
}

private static string FormatWord(int count, string singular, string plural)
{
    return count == 0 ? "no " + plural
        : count == 1 ? "one " + singular
        : count == 42 ? "a universal number of " + plural
        : count + " " + plural;
}
</code>```

Then in use it might look like:

```<code>private static void Main()
{
    var name = "User";

    while (true)
    {
        var count = GetIntFromUser("Enter notification count: ");
        Console.WriteLine($"You have {FormatWord(count, "notification")}. " +
            $"Have a nice day, {name}");
    }
}
</code>```

Note that this method is also using a helper method to get a strongly-typed integer from the user:

```<code>private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    int result;
    var cursorTop = Console.CursorTop;

    do
    {
        ClearSpecificLineAndWrite(cursorTop, prompt);
    } while (!int.TryParse(Console.ReadLine(), out result) ||
             !(validator?.Invoke(result) ?? true));

    return result;
}

private static void ClearSpecificLineAndWrite(int cursorTop, string message)
{
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(message);
}
</code>```

Body:
Given a messageformat string such as str below. I want to be able to get the "notifications" & "name" values which are used to display the text values.

var str = @"You have {notifications, plural,
          zero {no notifications}
           one {one notification}
           =42 {a universal amount of notifications}
         other {# notifications}
        }. Have a nice day, {name}!";

I have tried using a regex such as:

var matches = Regex.Matches(str, @"{(.*?)}");
//var matches = Regex.Matches(str, @"(?<=\{)[^}{]*(?=\})");
var results = matches.Cast<Match>().Select(m => m.Groups[1].Value).Distinct().ToList();

But the above does not take in to account that {notifications,.. is itself wraped in curly braces and includes the inner values that are not needed, which are wrapped in curly braces also.

So in brief I just want to be able to parse a string such as str above and get notifications & name at the returned values.

A string such as var str2 = @"Hello {name}" should just return name as the value.

EDIT

The values notifications & name will not be known in advance - I have just used this as an example, for the values I require to return from the string.

Body:
One way to do this would be to write a method that will format a string for you based on an input count and the singular (and plural) form of the string:

private static string FormatWord(int count, string singluar)
{
    return Format(count, singluar, singluar + "s");
}

private static string FormatWord(int count, string singular, string plural)
{
    return count == 0 ? "no " + plural
        : count == 1 ? "one " + singular
        : count == 42 ? "a universal number of " + plural
        : count + " " + plural;
}

Then in use it might look like:

private static void Main()
{
    var name = "User";

    while (true)
    {
        var count = GetIntFromUser("Enter notification count: ");
        Console.WriteLine($"You have {FormatWord(count, "notification")}. " +
            $"Have a nice day, {name}");
    }
}

Note that this method is also using a helper method to get a strongly-typed integer from the user:

private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    int result;
    var cursorTop = Console.CursorTop;

    do
    {
        ClearSpecificLineAndWrite(cursorTop, prompt);
    } while (!int.TryParse(Console.ReadLine(), out result) ||
             !(validator?.Invoke(result) ?? true));

    return result;
}

private static void ClearSpecificLineAndWrite(int cursorTop, string message)
{
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(message);
}


问:
Using Silverlight for an entire website?
We need to build an administration portal website to support our client/server application. Since we're a .Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend?

The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application.

I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills.

Are there any big no-nos from the experience of StackOverflowers? What are the big positives?

答:
Depends on your goals. If administration portal is part of application and will only be used from computers where your application is installed, there are plenty of advantages of going fully Silverlight - or even WPF.

But if you can see a scenario where it will be used either from random PC or by random person, fully functional HTML/Javascript version is absolutely necessary.

Some reasons are:

Most people don't have silverlight and you'll earn a good load of swearing if they have to download and install it. Some people who have it installed keep it disabled (together with flash and sometimes even images) to avoid distractions and speed up browsing.

When HTML site fails, user gets error page and reloads. When silverlight fails, it can hang or crash.

HTML is what is expected - both by users and web browsers: back and refresh buttons work as they should, hyperlinks and forms work as expected.

Slow internet is still very common, both in remote areas and mobile devices.

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sam

OwnerDisplayName: ima


问:
Merging rows and updating related foreign key
I have a current users table. A distinct user is defined as when the email and phoneNumber together are unique. Currently the table  looks like this:

And another table called giftee_info which has the foreign key on column userId to users.id:

The users table is going to be parsed out into 2 tables: users and user_metadata. Now a distinct user will be defined by the phoneNumber. So you can see in the data above, users with id's 4 and 5 are the same, and have to be merged.

The new users table will look like:

And the new user_metadata table will look like this:

Note how the 4th row has userId of 4, so users 4 and 5 have merged to one user.

And giftee_info will look like this:

See how the 3rd row in giftee_info contains userId 4, as the user with id 5 has been merged into one user.

The data I've provided is basic. In reality there are many rows, and a user with the same number may have 5 different email address (and so are currently treated as separate users in the current schema).

The part I'm having most trouble with is updating giftee_info. So any rows with userId's that have been merged down into one user need to be updated. How can I do this?

答:
Since phonenumber can be NULL, I'm using externalid as the unique identifier below.

Start by creating the new users table from the distinct phone numbers in the old users table:

```<code>CREATE TABLE new_users (id INT PRIMARY KEY AUTO_INCREMENT, externalid VARCHAR(32), phonenumber VARCHAR(32))
SELECT DISTINCT NULL, externalid, phonenumber
FROM users
</code>```

Then put all the emails into the user_metadata table, by joining the old and new users tables to get the emails along with the new user IDs.

```<code>CREATE TABLE user_metadata (id INT PRIMARY KEY AUTO_INCREMENT, userid INT, email VARCHAR(100), subscribe INT(1))
SELECT NULL, nu.id, u.email, 0
FROM new_users as nu
JOIN users AS u ON nu.externalid = u.externalid
</code>```

Now you can update giftee_info by replacing the old user IDs with the new user IDs.

```<code>UPDATE giftee_info AS g
JOIN users as u ON g.userid = u.userid
JOIN new_users As nu ON nu.externalid = u.externalid
SET g.userid = nu.userid
</code>```

Once this is all done you can rename the tables so new_users is now users.

Body:
Since phonenumber can be NULL, I'm using externalid as the unique identifier below.

Start by creating the new users table from the distinct phone numbers in the old users table:

CREATE TABLE new_users (id INT PRIMARY KEY AUTO_INCREMENT, externalid VARCHAR(32), phonenumber VARCHAR(32))
SELECT DISTINCT NULL, externalid, phonenumber
FROM users

Then put all the emails into the user_metadata table, by joining the old and new users tables to get the emails along with the new user IDs.

CREATE TABLE user_metadata (id INT PRIMARY KEY AUTO_INCREMENT, userid INT, email VARCHAR(100), subscribe INT(1))
SELECT NULL, nu.id, u.email, 0
FROM new_users as nu
JOIN users AS u ON nu.externalid = u.externalid

Now you can update giftee_info by replacing the old user IDs with the new user IDs.

UPDATE giftee_info AS g
JOIN users as u ON g.userid = u.userid
JOIN new_users As nu ON nu.externalid = u.externalid
SET g.userid = nu.userid

Once this is all done you can rename the tables so new_users is now users.


问:
Can not create a max column, with list comprehension. sum column works
I try to create a max column with this code. The sum column works

sum:

```<code>for col in list_names:
    for month in [3,6,9,12]:
        companies = companies.withColumn(col + 'sum_'+ str(month) + '_months', sum(companies[col + ult_pats2[month_ix - ix]] for ix in range(month)) )
</code>```

max:

```<code>for col in list_names:
    for month in [3,6,9,12]:
        companies = companies.withColumn(col + 'max_'+ str(month) + '_months', max(companies[col + ult_pats2[month_ix - ix]] for ix in range(month)) )
</code>```

the error message is:

"ValueError: Cannot convert column into bool: please use '&' for
  'and', '|' for 'or', '~' for 'not' when building DataFrame boolean
  expressions"

答:
This looks to me like overwriting the max function by some other package.
Try:

```<code>import pyspark.sql.functions as f
</code>```

And then use the reference f.max(...)

Body:
I try to create a max column with this code. The sum column works

sum:

for col in list_names:
    for month in [3,6,9,12]:
        companies = companies.withColumn(col + 'sum_'+ str(month) + '_months', sum(companies[col + ult_pats2[month_ix - ix]] for ix in range(month)) )

max:

for col in list_names:
    for month in [3,6,9,12]:
        companies = companies.withColumn(col + 'max_'+ str(month) + '_months', max(companies[col + ult_pats2[month_ix - ix]] for ix in range(month)) )

the error message is:

"ValueError: Cannot convert column into bool: please use '&' for
  'and', '|' for 'or', '~' for 'not' when building DataFrame boolean
  expressions"

Body:
This looks to me like overwriting the max function by some other package.
Try:

import pyspark.sql.functions as f

And then use the reference f.max(...)


问:
Linux "join" command not working as it should?
I am working through the first example here: Linux Journey

However, I am not getting the same output after join file.txt file2.txt

Instead, I get:

```<code> Doehn

 Doene

 Suery
</code>```

I can't figure out what's going on- has the join command syntax changed since the publishing of that website?

答:
My crystal ball says your text files are in DOS format, with carriage-return linefeed (CR LF) line endings. That's why your output looks slightly weird when printed on the console.

To fix it, convert the files to unix format. (You may have a dos2unix command; or if you're already using vim, try :set ff=unix; or perl -i -pe 's/\r//' file.txt will do in a pinch.)

The sample files in your link with extra carriage returns are:

file1.txt

```<code>1 John\r
2 Jane\r
3 Mary\r
</code>```

file2.txt

```<code>1 Doe\r
2 Doe\r
3 Sue\r
</code>```

(Using \r to represent a carriage return.)

Now when you run join file1.txt file2.txt, it will first compare the first field of the first line in each file. This succeeds (1 on both sides), so join outputs the common field, a space, the remaining fields from file 1, another space, then the remaining fields from file 2. So the first line of output is

```<code>1 John\r Doe\r
</code>```

(\r is interpreted as part of the field data).

But wait! \r is not a printable character. It has the effect of moving the cursor back to the beginning of the line when printed to a terminal. Using ^ to mark the cursor position, we get the following effect:

```<code>1
 ^
</code>```

```<code>1
  ^
</code>```

```<code>1 J
   ^
</code>```

```<code>1 Jo
    ^
</code>```

```<code>1 Joh
     ^
</code>```

```<code>1 John
      ^
</code>```

Here we print the first carriage return, moving the cursor back:

```<code>1 John
^
</code>```

The next output character (a space) overwrites the 1:

```<code>  John
 ^
</code>```

```<code> DJohn
  ^
</code>```

```<code> Doohn
   ^
</code>```

```<code> Doehn
    ^
</code>```

Another carriage return, but this one has no visible effect:

```<code> Doehn
^
</code>```

And ... done.

The other lines are handled the same way. Each time the carriage return at the end of the last field of file 1 moves the cursor back, so the fields from file 2 overwrite what's already on the screen.

Body:
I am working through the first example here: Linux Journey

However, I am not getting the same output after join file.txt file2.txt

Instead, I get:

 Doehn

 Doene

 Suery

I can't figure out what's going on- has the join command syntax changed since the publishing of that website?

Body:
My crystal ball says your text files are in DOS format, with carriage-return linefeed (CR LF) line endings. That's why your output looks slightly weird when printed on the console.

To fix it, convert the files to unix format. (You may have a dos2unix command; or if you're already using vim, try :set ff=unix; or perl -i -pe 's/\r//' file.txt will do in a pinch.)

The sample files in your link with extra carriage returns are:

file1.txt

1 John\r
2 Jane\r
3 Mary\r

file2.txt

1 Doe\r
2 Doe\r
3 Sue\r

(Using \r to represent a carriage return.)

Now when you run join file1.txt file2.txt, it will first compare the first field of the first line in each file. This succeeds (1 on both sides), so join outputs the common field, a space, the remaining fields from file 1, another space, then the remaining fields from file 2. So the first line of output is

1 John\r Doe\r

(\r is interpreted as part of the field data).

But wait! \r is not a printable character. It has the effect of moving the cursor back to the beginning of the line when printed to a terminal. Using ^ to mark the cursor position, we get the following effect:

1
 ^

1
  ^

1 J
   ^

1 Jo
    ^

1 Joh
     ^

1 John
      ^

Here we print the first carriage return, moving the cursor back:

1 John
^

The next output character (a space) overwrites the 1:

  John
 ^

 DJohn
  ^

 Doohn
   ^

 Doehn
    ^

Another carriage return, but this one has no visible effect:

 Doehn
^

And ... done.

The other lines are handled the same way. Each time the carriage return at the end of the last field of file 1 moves the cursor back, so the fields from file 2 overwrite what's already on the screen.


问:
Excel VBA Loop through Column to Copy and Paste Non Blanks to 3 other Columns?
I am new to Excel VBA and have run into a road block. I am not receiving any errors when I run this and I am unsure where to even start...

I would like to search column C and if there is a non blank copy that value to columns (D,G,I) of the same worksheet.  I would start the searching in Row 4.

I've tried stepping through the code and I'm pretty sure my error is with currVal = ws.Cells(i, "c").  When I step through, nothing happens on the excel sheet (no cells are copied or pasted).

Any assistance is GREATLY appreciated! I've been looking at this all morning.

```<code>Sub Copy()

Dim lastC As Integer
Dim i As Integer
Dim j As Integer
Dim currVal As String
Dim ws As Worksheet

Set ws = ActiveSheet
lastC = ws.Cells(Rows.Count, 1).End(xlUp).Row

For i = 4 To lastC
currVal = ws.Cells(i, "c")
   If ws.Cells(i, 1).Value <> "" Then
       currVal = ws.Cells(i, "D")
       currVal = ws.Cells(i, "G")
       currVal = ws.Cells(i, "I")
    End If

Next i

End Sub
</code>```

Actual results is nothing happens (at least that I can see) and with no errors giving me a place to start looking!

Expected Results would be copying this into 3 additional columns.  The result is an actual formula.  The formula is what i need to be copied.

5/27/2019 9:39 --- value

='15_2019-02_003.CSV'!$A$2  -- formula

I have addressed the formula updating and removing references to the CSV file once the value is pulled from original CSV File.  The purpose of this code is only to search blanks and copy/paste.Picture of Excel WS

答:
Adding to the comments, this is how I would have written that particular code, maybe it helps:

Sub Copy()

    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim lastC As Long: lastC = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    Dim R As Long 'I like to use R (rows) & C (cols), just because makes it more readable (for me)

    For R = 4 To lastC
        With ws
            If .Cells(R, "A").Value <> "" Then
                .Cells(R, "D") = .Cells(R, "C").Value
                .Cells(R, "G") = .Cells(R, "C").Value
                .Cells(R, "I") = .Cells(R, "C").Value
            End If
        End With
    Next R

End Sub
```

PS: I prefer numbers instead of letters for .Cells reference, but in this case is understandable to use letter. Just for best practice - readability wise, shouldn't mix them.

Body:
I am new to Excel VBA and have run into a road block. I am not receiving any errors when I run this and I am unsure where to even start...

I would like to search column C and if there is a non blank copy that value to columns (D,G,I) of the same worksheet.  I would start the searching in Row 4.

I've tried stepping through the code and I'm pretty sure my error is with currVal = ws.Cells(i, "c").  When I step through, nothing happens on the excel sheet (no cells are copied or pasted).

Any assistance is GREATLY appreciated! I've been looking at this all morning.

Sub Copy()

Dim lastC As Integer
Dim i As Integer
Dim j As Integer
Dim currVal As String
Dim ws As Worksheet

Set ws = ActiveSheet
lastC = ws.Cells(Rows.Count, 1).End(xlUp).Row

For i = 4 To lastC
currVal = ws.Cells(i, "c")
   If ws.Cells(i, 1).Value <> "" Then
       currVal = ws.Cells(i, "D")
       currVal = ws.Cells(i, "G")
       currVal = ws.Cells(i, "I")
    End If

Next i

End Sub

Actual results is nothing happens (at least that I can see) and with no errors giving me a place to start looking!

Expected Results would be copying this into 3 additional columns.  The result is an actual formula.  The formula is what i need to be copied.

5/27/2019 9:39 --- value

='15_2019-02_003.CSV'!$A$2  -- formula

I have addressed the formula updating and removing references to the CSV file once the value is pulled from original CSV File.  The purpose of this code is only to search blanks and copy/paste.Picture of Excel WS

Body:
Adding to the comments, this is how I would have written that particular code, maybe it helps:

Sub Copy()

    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim lastC As Long: lastC = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    Dim R As Long 'I like to use R (rows) & C (cols), just because makes it more readable (for me)

    For R = 4 To lastC
        With ws
            If .Cells(R, "A").Value <> "" Then
                .Cells(R, "D") = .Cells(R, "C").Value
                .Cells(R, "G") = .Cells(R, "C").Value
                .Cells(R, "I") = .Cells(R, "C").Value
            End If
        End With
    Next R

End Sub

PS: I prefer numbers instead of letters for .Cells reference, but in this case is understandable to use letter. Just for best practice - readability wise, shouldn't mix them.


问:
Android RequestPermission when administrator does not allow them to be changed
I have a scenario where an android apps permissions are set by an administrator via an MDM which cannot be changed by the user of the device.

What will happen if when the permission is checked and the permission is denied. Then the code requests the permission, and the user selects to allow the permission.

What will happen if the administrator has set the permission to be fixed as denied?

Will the user be informed automatically via another dialog?

Will the onRequestPermissionsResult just state that the permission is denied in the passed array of grantResults?

Or does something else occur. I do not have a set up where I can test this. Hopefully someone can explain the outcome of this scenario

答:
As per the Explain why the app needs permission documentation:

One approach you might use is to provide an explanation only if the user has already denied that permission request. Android provides a utility method, shouldShowRequestPermissionRationale(), that returns true if the user has previously denied the request, and returns false if a user has denied a permission and selected the Don't ask again option in the permission request dialog, or if a device policy prohibits the permission.

So if you ask for permission, the permission will be immediately denied - the user won't see any permission prompt. If shouldShowrequestPermissionRationale() returns false, either the user has permanently denied your permission or the device policy has permanently denied your permission.


问:
"vmstat" and "perf stat -a" show different numbers for context-switching
I'm trying to understand the context-switching rate on my system (running on AWS EC2), and where the switches are coming from. Just getting the number is already confusing, as two tools that I know can output such a metric give me different results. Here's the output from vmstat:

```<code>$ vmstat -w 2
procs -------------------memory------------------ ---swap-- -----io---- --system-- -----cpu-------
 r  b       swpd       free       buff      cache   si   so    bi    bo   in   cs  us sy  id wa st
 8  0          0     443888     492304    8632452    0    0     0     1    0    0  14  2  84  0  0
37  0          0     444820     492304    8632456    0    0     0    20 131602 155911  43  5  52  0  0
 8  0          0     445040     492304    8632460    0    0     0    42 131117 147812  46  4  50  0  0
13  0          0     446572     492304    8632464    0    0     0    34 129154 142260  49  4  46  0  0
</code>```

The number is ~140k-160k/sec.

But perf tells something else:

```<code>$ sudo perf stat -a
 Performance counter stats for 'system wide':

    2980794.013800      cpu-clock (msec)          #   35.997 CPUs utilized
        12,335,935      context-switches          #    0.004 M/sec
         2,086,162      cpu-migrations            #    0.700 K/sec
            11,617      page-faults               #    0.004 K/sec
...
</code>```

0.004 M/sec is apparently 4k/sec.

Why is there a disparity between the two tools? Am I misinterpreting something in either of them, or are their CS metrics somehow different?

FWIW, I've tried doing the same on a machine running a different workload, and the difference there is even twice larger.

Environment:

AWS EC2 c5.9xlarge instance

Amazon Linux, kernel 4.14.94-73.73.amzn1.x86_64

The service runs on Docker 18.06.1-ce

答:
Some recent versions of perf have a unit-scaling bug in the printing code.  Manually do 12.3M / wall-time and see if that's sane.  (spoiler alert: it is according to OP's comment.)

https://lore.kernel.org/patchwork/patch/1025968/

Commit 0aa802a79469 ("perf stat: Get rid of extra clock display
function") introduced the bug in mainline Linux 4.19-rc1 or so.

Thus, perf_stat__update_shadow_stats() now saves scaled values of clock events
  in msecs, instead of original nsecs. But while calculating values of
  shadow stats we still consider clock event values in nsecs. This results
  in a wrong shadow stat values.

Commit 57ddf09173c1 on  Mon, 17 Dec 2018 fixed it in 5.0-rc1, eventually being released with perf upstream version 5.0.

Vendor kernel trees that cherry-pick commits for their stable kernels might have the bug or have fixed the bug earlier.

Body:
I'm trying to understand the context-switching rate on my system (running on AWS EC2), and where the switches are coming from. Just getting the number is already confusing, as two tools that I know can output such a metric give me different results. Here's the output from vmstat:

$ vmstat -w 2
procs -------------------memory------------------ ---swap-- -----io---- --system-- -----cpu-------
 r  b       swpd       free       buff      cache   si   so    bi    bo   in   cs  us sy  id wa st
 8  0          0     443888     492304    8632452    0    0     0     1    0    0  14  2  84  0  0
37  0          0     444820     492304    8632456    0    0     0    20 131602 155911  43  5  52  0  0
 8  0          0     445040     492304    8632460    0    0     0    42 131117 147812  46  4  50  0  0
13  0          0     446572     492304    8632464    0    0     0    34 129154 142260  49  4  46  0  0

The number is ~140k-160k/sec.

But perf tells something else:

$ sudo perf stat -a
 Performance counter stats for 'system wide':

    2980794.013800      cpu-clock (msec)          #   35.997 CPUs utilized
        12,335,935      context-switches          #    0.004 M/sec
         2,086,162      cpu-migrations            #    0.700 K/sec
            11,617      page-faults               #    0.004 K/sec
...

0.004 M/sec is apparently 4k/sec.

Why is there a disparity between the two tools? Am I misinterpreting something in either of them, or are their CS metrics somehow different?

FWIW, I've tried doing the same on a machine running a different workload, and the difference there is even twice larger.

Environment:

AWS EC2 c5.9xlarge instance

Amazon Linux, kernel 4.14.94-73.73.amzn1.x86_64

The service runs on Docker 18.06.1-ce


问:
passing image from collectionViewCell which is located tableviewCell
I ask for help with determining the right approach

when I click on the picture I need to pass text and her to new VC, but the problem is that the project has a great depth struct

the cell lies in the collectionView, which is in the tableViewCell

How do I properly implement the transfer?
(the number of cells is generated automatically)

Another complication is that the code of the cell with which I work lies in another cell.

those. the transfer of information must also be written in it.

```<code>import UIKit
import moa

class RealPhotoInfoTableViewCell: UITableViewCell {

    @IBOutlet private weak var MyCollection: UICollectionView!

    var model: RealPhoto!

    func setCollectionViewDataSourceDelegate(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forRow row: Int) {
        MyCollection.delegate = self
        MyCollection.dataSource = self
        MyCollection.reloadData()
    }
}

extension RealPhotoInfoTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(model?.data.count as Any)
        return model?.data.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RPhotoCell", for: indexPath) as! RealPhotoCollectionViewCell

        cell.realPhotoImage.moa.url = model?.data[indexPath.row].photo

        return cell
    }
}
</code>```

答:
You have two options:
One is Sh_Khan answer using delegation.

Or you can use Notification observers.

This question has been asked before...

Body:
I ask for help with determining the right approach

when I click on the picture I need to pass text and her to new VC, but the problem is that the project has a great depth struct

the cell lies in the collectionView, which is in the tableViewCell

How do I properly implement the transfer?
(the number of cells is generated automatically)

Another complication is that the code of the cell with which I work lies in another cell.

those. the transfer of information must also be written in it.

import UIKit
import moa

class RealPhotoInfoTableViewCell: UITableViewCell {

    @IBOutlet private weak var MyCollection: UICollectionView!

    var model: RealPhoto!

    func setCollectionViewDataSourceDelegate(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forRow row: Int) {
        MyCollection.delegate = self
        MyCollection.dataSource = self
        MyCollection.reloadData()
    }
}

extension RealPhotoInfoTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(model?.data.count as Any)
        return model?.data.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RPhotoCell", for: indexPath) as! RealPhotoCollectionViewCell

        cell.realPhotoImage.moa.url = model?.data[indexPath.row].photo

        return cell
    }
}


问:
Locating the index value of an element in a list inside a dictionary
I need to access certain values of an array inside a dictionary using its value and not its index

For example:

```<code>message_dict = {
  '123456,896':
      [[3453, 57634], [9984, 97585]],
  '157384,899':
      [[3455, 57647], [9989, 97592]]
}
</code>```

If I want to access 57634, I could do:

```<code>s = '123456,896'
message_dict[s][0][1]
</code>```

I want to use the value of [0] instead to find 57634

I tried to specify the value directly, but syntax is invalid.

```<code>s = '123456,896'
i = 3453
message_dict[s]i[1]
</code>```

This reports syntax error, but I have no idea how to specify the value, instead of the position of the value in the array.

答:
In your sublists, you want to treat the first item as a key and the second as a value. A list of pairs is not well suited for that as it will require a linear search, use a nested dict instead.

```<code>message_dict = {
  '123456,896':
      {3453: 57634, 9984: 97585},
  '157384,899':
      {3455: 57647, 9989: 97592}
}

print(message_dict['123456,896'][3453])
</code>```

Output

```<code>57634
</code>```

In the event you cannot change the format of message_dict at the source, here is how you can convert it.

```<code>message_dict = {
  '123456,896':
      [[3453, 57634], [9984, 97585]],
  '157384,899':
      [[3455, 57647], [9989, 97592]]
}

message_dict = {k: dict(lst) for k, lst in message_dict.items()}

print(message_dict)
</code>```

Output

```<code>{'123456,896': {3453: 57634, 9984: 97585},
 '157384,899': {3455: 57647, 9989: 97592}}
</code>```

Body:
I need to access certain values of an array inside a dictionary using its value and not its index

For example:

message_dict = {
  '123456,896':
      [[3453, 57634], [9984, 97585]],
  '157384,899':
      [[3455, 57647], [9989, 97592]]
}

If I want to access 57634, I could do:

s = '123456,896'
message_dict[s][0][1]

I want to use the value of [0] instead to find 57634

I tried to specify the value directly, but syntax is invalid.

s = '123456,896'
i = 3453
message_dict[s]i[1]

This reports syntax error, but I have no idea how to specify the value, instead of the position of the value in the array.

Body:
In your sublists, you want to treat the first item as a key and the second as a value. A list of pairs is not well suited for that as it will require a linear search, use a nested dict instead.

message_dict = {
  '123456,896':
      {3453: 57634, 9984: 97585},
  '157384,899':
      {3455: 57647, 9989: 97592}
}

print(message_dict['123456,896'][3453])

Output

57634

In the event you cannot change the format of message_dict at the source, here is how you can convert it.

message_dict = {
  '123456,896':
      [[3453, 57634], [9984, 97585]],
  '157384,899':
      [[3455, 57647], [9989, 97592]]
}

message_dict = {k: dict(lst) for k, lst in message_dict.items()}

print(message_dict)

Output

{'123456,896': {3453: 57634, 9984: 97585},
 '157384,899': {3455: 57647, 9989: 97592}}


问:
How to align second line in a bullet-ed un-ordered list
I have a bullet-ed un-ordered list of ingredients on my recipe site.  I have some padding around the list so that it is displayed in the center of the page.  However, when I go to view the page on an iphone or a tablet (a device with a narrower screen), my bullet points are pushed to 2 lines and the second line is not in line with the first.

I believe this is due to the padding code I have around the list so that on a narrow screen, the bullets are still in the center of the page.  When the bullet point is too long that it has to go to 2 lines, the second line is pushed all the way to the left while the bullet is still centered.  I am looking to align the second line with the first (still centered on the page)

I have tried positioning it 'outside' the bullet point, however, because I have made my own bullet point with code this doesn't seem to work.

The code below is the code I have for the cellular device display of this issue.

```<code>    @media only screen and (max-width : 480px)
    { ul[data-rte-list] li>*:first-child::before  {
        content: "•";
        position: outside;
        line-height: 1.5em !important;
        top: 2px;
        padding-right: 10px;
        font-size: 22px;
        padding-left: 100px;
        color: #373737;
        opacity: .4;
    }

}
</code>```

This is exactly what the page looks like:

答:
This is just a wild attempt but from the way I see it you're applying the padding to the child elements of your li. You should apply it to the ul element so that the entire list is padded.

div {
  width: 400px;
  margin: auto;
  background-color: #dadada;
}

ul {
  list-style: none;
  padding-left: 100px;
}

ul li > *:first-child::before {
  content: "•";
  position: outside;
  line-height: 1.5em !important;
  top: 2px;
  padding-right: 10px;
  font-size: 22px;
  color: #373737;
  opacity: 0.4;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<ul>
  <li>
    <span>1 can coconut milk</span>
  </li>
  <li>
    <span>1/4 cup date syrup (substitute maple syrup or honey)</span>
  </li>
  <li>
    <span>1 tsp vanilla</span>
  </li>
</ul>
</div></code>```

Body:
I have a bullet-ed un-ordered list of ingredients on my recipe site.  I have some padding around the list so that it is displayed in the center of the page.  However, when I go to view the page on an iphone or a tablet (a device with a narrower screen), my bullet points are pushed to 2 lines and the second line is not in line with the first.

I believe this is due to the padding code I have around the list so that on a narrow screen, the bullets are still in the center of the page.  When the bullet point is too long that it has to go to 2 lines, the second line is pushed all the way to the left while the bullet is still centered.  I am looking to align the second line with the first (still centered on the page)

I have tried positioning it 'outside' the bullet point, however, because I have made my own bullet point with code this doesn't seem to work.

The code below is the code I have for the cellular device display of this issue.

    @media only screen and (max-width : 480px)
    { ul[data-rte-list] li>*:first-child::before  {
        content: "•";
        position: outside;
        line-height: 1.5em !important;
        top: 2px;
        padding-right: 10px;
        font-size: 22px;
        padding-left: 100px;
        color: #373737;
        opacity: .4;
    }

}

This is exactly what the page looks like:

Body:
This is just a wild attempt but from the way I see it you're applying the padding to the child elements of your li. You should apply it to the ul element so that the entire list is padded.

div {
  width: 400px;
  margin: auto;
  background-color: #dadada;
}

ul {
  list-style: none;
  padding-left: 100px;
}

ul li > *:first-child::before {
  content: "•";
  position: outside;
  line-height: 1.5em !important;
  top: 2px;
  padding-right: 10px;
  font-size: 22px;
  color: #373737;
  opacity: 0.4;
}

<div>
<ul>
  <li>
    <span>1 can coconut milk</span>
  </li>
  <li>
    <span>1/4 cup date syrup (substitute maple syrup or honey)</span>
  </li>
  <li>
    <span>1 tsp vanilla</span>
  </li>
</ul>
</div>


问:
Why does active record pattern not work with rich domain models?
I'm reading the architectural patterns chapter of POEAA, and Fowler says that "As the domain logic gets more complicated and you begin moving toward a rich Domain Model (116), the simple approach of an Active Record (160) starts to break down.  The one-to-one match of domain classes to tables starts to fail as you factor domain logic into smaller classes. Relational databases don't handle inheritance, so it becomes difficult to use strategies [Gang of Four] and other neat OO patterns. As the domain logic gets feisty, you want to be able to test it without having to talk to the database all the time."

I didn't really understand this.  By "one to one match of domain classes to tables", does he mean that only for classes where there is no associations or single table inheritance hierarchy?

And why does factoring domain logic into smaller classes cause the pattern to fail?

答: No, I think he is talking about the domain logic. With active record the object carries both data and behavior. So that is a one-to-one match. If you start separating data/behaviour, like in the Data Mapper pattern, it becomes one-to-many. I have the impression that you sometimes really have to read that book like academic nonsense to understand what he means. :-)</p>

ContentLicense: CC BY-SA 3.0


问:
Videojs-marker: how can I customize a special marker rather than using general 'markers'?
I’m using videojs-marker plugin(http://www.sampingchuang.com/videojs-markers) to build a customized player by which the users can annotate (name the action of a person) some parts (not just a point) of a video, so my plan is to make every marker have its proper width(thus it can cover the duration of this action) and also a proper display time for the overlay text.

```<code><script>
var player = videojs("my-video", {
    controls: true,
    autoplay: false,
    preload: 'auto',
...
player.markers({
       markerStyle: {
          'width':'10px',
          'border-radius': '30%',
          'background-color': '#009DE0'
       },
       markerTip:{
          display: true,
          text: function(marker) {
             return marker.text;
          },
          time: function(marker) {
             return marker.time;
          }
       },
       breakOverlay:{
          display: true,
          displayTime: 1,
          style:{
             'width':'100%',
             'height': '20%',
             'background-color': 'rgba(0,0,0,0.7)',
             'color': 'white',
             'font-size': '17px'
          },
          text: function(marker) {
             return marker.overlayText;
          }
       },
       onMarkerClick: function(marker) {},
       onMarkerReached: function(marker) {},
         markers: [
         {time: 9.5, text: "1",overlayText: 'attack', class: 'custom-marker'},
         {time: 15, text: "2",overlayText: 'defense'}
         ]

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

So, the users will manipulate another div to add a special marker by entering the information: start time, end time and definition for each action. Then this marker will show in the timeline, I have already some ideas about this part. So now, I just wonder how to create ‘marker’ object and set its own ‘markerStyle’ rather than using ‘markers’ class and entering new informations in this markers’ list

```<code>markers: [
     {time: 9.5, text: "p1",overlayText: 'attack', class: 'custom-marker'},
     {time: 15, text: "p2",overlayText: 'defense'}
     ]
</code>```

I’m new here, and I’m sorry if the description is not clear, please give me your feedback,thanks!

答:
I spent too much time thinking about the width, so that i omit an attribute: the 'duration'. The solution is simple , just by adding duration to the snippet:</p>

```<code>markers: [
 {time: 9.5,duration:3, text: "p1",overlayText: 'attack', class: 'custom-marker'},
 {time: 15, duration:2 ,text: "p2",overlayText: 'defense'}
 ]
</code>```

Body:
I spent too much time thinking about the width, so that i omit an attribute: the 'duration'. The solution is simple , just by adding duration to the snippet:

markers: [
 {time: 9.5,duration:3, text: "p1",overlayText: 'attack', class: 'custom-marker'},
 {time: 15, duration:2 ,text: "p2",overlayText: 'defense'}
 ]


问:
Mock api calls from Storybook
Does axios-mock-adapter only work on requests made with axios?

I have written a component that POSTs to an API (using vanilla XHR, not axios).  I'm testing it in Storybook and want to intercept those POST requests since the endpoint doesn't exist yet:

```<code>import React from "react"
import { storiesOf } from "@kadira/storybook"
import MyComponent from "./MyComponent"
import axios from "axios"
import MockAdapter from "axios-mock-adapter"

var mock = new MockAdapter(axios)

storiesOf("My Component", module).addWithInfo(
  "Simulator",
  () => {
    mock.onPost().reply(500)
    return <MyComponent />
  },
  {}
)
</code>```

My component still is trying to hit the API endpoint and I am getting a 404 response - not the expected 500 response.

Does axios-mock-adapter only work on requests made with axios?
Does the mock call have to be inside MyComponent?

Thanks.

答: I've started using json-server to intercept API calls. You have to start it in one tab, and start storybook in another, but it is pretty cool.

Title: Mock api calls from Storybook

Body:
Does axios-mock-adapter only work on requests made with axios?

I have written a component that POSTs to an API (using vanilla XHR, not axios).  I'm testing it in Storybook and want to intercept those POST requests since the endpoint doesn't exist yet:

import React from "react"
import { storiesOf } from "@kadira/storybook"
import MyComponent from "./MyComponent"
import axios from "axios"
import MockAdapter from "axios-mock-adapter"

var mock = new MockAdapter(axios)

storiesOf("My Component", module).addWithInfo(
  "Simulator",
  () => {
    mock.onPost().reply(500)
    return <MyComponent />
  },
  {}
)

My component still is trying to hit the API endpoint and I am getting a 404 response - not the expected 500 response.

Does axios-mock-adapter only work on requests made with axios?
Does the mock call have to be inside MyComponent?

Thanks.


问:
Passing state to parent component
I'm refactoring some code to make a more aesthetically pleasing render of a table. I will link a codesandbox that shows both the old and new implementations.

So if you select the two dropdowns at the top, in the old implementation section when you check one of the boxes next to the fieldName you will see 3 additional input boxes appear; lengthType, size, and maxArrayElements. The change handlers for these are in the main component index.js.

I have since made a separate component TableRowWithCheckbox that introduces some new functionality that uses a checkbox to keep track of what row is selected.

In the new implementation (the table) I have decided to render the 3 inputs mentioned above, inside the table. I'm having trouble keeping track of the inputs since they are now moved inside this new component.

Should I initialize state for lengthType, size, and maxArrayElements inside this new component then have the change handler inside the main component? Or initialize the state values AND have the change handles in the main component?

TableRowWithCheckbox component below.

```<code>import React, { Component } from "react";
import { Table, Checkbox, Dropdown, Input } from "semantic-ui-react";

const lengthTypeOptions = [
  { key: "fixed", text: "Fixed", value: "fixed" },
  { key: "variable", text: "Variable", value: "variable" }
];

export default class TableRowWithCheckbox extends Component {
  constructor(props) {
    super(props);
    const { initialState } = this.props;
    this.state = {
      fieldCheckbox: initialState
    };
  }

  checkbox = () => {
    this.setState({ fieldCheckbox: !this.state.fieldCheckbox }, () => {
      console.log("checkbox --> ", this.state.fieldCheckbox);
      const {
        name,
        dataType,
        isArray,
        position,
        box,
        lengthType,
        size,
        maxArrayElements
      } = this.props;
      box({
        name,
        dataType,
        isArray,
        position,
        isChecked: this.state.fieldCheckbox,
        lengthType,
        size,
        maxArrayElements
      });
    });
  };

  render() {
    const {
      name,
      dataType,
      isArray,
      position,
      lengthType,
      size,
      maxArrayElements
    } = this.props;
    const { fieldCheckbox } = this.state;
    return (
      <>
        <Table.Row>
          <Checkbox
            style={{ marginTop: "20px" }}
            checkbox
            onChange={this.checkbox}
          />
          <Table.Cell>{name}</Table.Cell>
          <Table.Cell>{dataType}</Table.Cell>
          <Table.Cell>{JSON.stringify(isArray)}</Table.Cell>
          <Table.Cell>{position}</Table.Cell>
          <Table.Cell>
            <Dropdown
              placeholder="Pick a length Type:"
              clearable
              selection
              search
              fluid
              noResultsMessage="Please search again"
              multiple={false}
              value={this.state.lengthType}
              options={lengthTypeOptions}
              header="CHOOSE A LENGTH TYPE"
              onChange={this.props.updateLengthType}
              required
            />
          </Table.Cell>
          <Table.Cell>
            <Input
              onChange={this.props.onSizeChange}
              type="number"
              name="size"
              min="1"
              placeholder="1"
              required
            />
          </Table.Cell>
          <Table.Cell>
            <Input
              onChange={this.props.onChangeMaxArrayElements}
              type="number"
              name="maxArrayElements"
              placeholder="1"
              min="1"
              max="100"
              required
            />
          </Table.Cell>
        </Table.Row>
      </>
    );
  }
}
</code>```

Codesandbox link here

答: The convention for passing state to a parent is via callback methods.  The parent should pass the child a function to call when there is something to update; and the parameters passed into the function would be ones you want to set in the parent state. That way the parent's method would just need to call this.setState() with the params coming into the function.</p>

Title: Passing state to parent component

Body:
I'm refactoring some code to make a more aesthetically pleasing render of a table. I will link a codesandbox that shows both the old and new implementations.

So if you select the two dropdowns at the top, in the old implementation section when you check one of the boxes next to the fieldName you will see 3 additional input boxes appear; lengthType, size, and maxArrayElements. The change handlers for these are in the main component index.js.

I have since made a separate component TableRowWithCheckbox that introduces some new functionality that uses a checkbox to keep track of what row is selected.

In the new implementation (the table) I have decided to render the 3 inputs mentioned above, inside the table. I'm having trouble keeping track of the inputs since they are now moved inside this new component.

Should I initialize state for lengthType, size, and maxArrayElements inside this new component then have the change handler inside the main component? Or initialize the state values AND have the change handles in the main component?

TableRowWithCheckbox component below.

import React, { Component } from "react";
import { Table, Checkbox, Dropdown, Input } from "semantic-ui-react";

const lengthTypeOptions = [
  { key: "fixed", text: "Fixed", value: "fixed" },
  { key: "variable", text: "Variable", value: "variable" }
];

export default class TableRowWithCheckbox extends Component {
  constructor(props) {
    super(props);
    const { initialState } = this.props;
    this.state = {
      fieldCheckbox: initialState
    };
  }

  checkbox = () => {
    this.setState({ fieldCheckbox: !this.state.fieldCheckbox }, () => {
      console.log("checkbox --> ", this.state.fieldCheckbox);
      const {
        name,
        dataType,
        isArray,
        position,
        box,
        lengthType,
        size,
        maxArrayElements
      } = this.props;
      box({
        name,
        dataType,
        isArray,
        position,
        isChecked: this.state.fieldCheckbox,
        lengthType,
        size,
        maxArrayElements
      });
    });
  };

  render() {
    const {
      name,
      dataType,
      isArray,
      position,
      lengthType,
      size,
      maxArrayElements
    } = this.props;
    const { fieldCheckbox } = this.state;
    return (
      <>

          <Checkbox
            style={{ marginTop: "20px" }}
            checkbox
            onChange={this.checkbox}
          />

{name}

{dataType}

{JSON.stringify(isArray)}

{position}

            <Dropdown
              placeholder="Pick a length Type:"
              clearable
              selection
              search
              fluid
              noResultsMessage="Please search again"
              multiple={false}
              value={this.state.lengthType}
              options={lengthTypeOptions}
              header="CHOOSE A LENGTH TYPE"
              onChange={this.props.updateLengthType}
              required
            />

            <Input
              onChange={this.props.onSizeChange}
              type="number"
              name="size"
              min="1"
              placeholder="1"
              required
            />

            <Input
              onChange={this.props.onChangeMaxArrayElements}
              type="number"
              name="maxArrayElements"
              placeholder="1"
              min="1"
              max="100"
              required
            />

      </>
    );
  }
}

Codesandbox link here


问:
read a text file and remove all occurences of a duplicates
I have a text file called test1.txt I want to remove all occurences of the duplicates. that means only unique words will be there.
example.

test1.txt:

```<code>hello i am a businessman  i am also a student
</code>```

output should be:

```<code>hello businessman also student
</code>```

my approach was like this:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("test1.txt"));

        ArrayList<String> list1 = new ArrayList<String>();

        while (input.hasNext()) {
            list1.add(input.next());

        }

        for(int i=0;i<list1.size();i++){
        for(int j=i+1;j<list1.size();j++){
            if(list1.get(i).equals(list1.get(j))){
                list1.remove(j);
                j--;
               }
             }
         }

        System.out.println("List 1: " + list1);

    }

}
</code>```

but it's not what i am looking for. i want to remove all occurence of duplicate so that i can output only unique words.

答:
Tackle the sentence word-by-word. If the word has not been seen before, add it to a "dictionary" of words that have been seen. If the word is in the dictionary, remove it.

First split the string into an array of words, then loop through that array following the above logic.

Body:
I have a text file called test1.txt I want to remove all occurences of the duplicates. that means only unique words will be there.
example.

test1.txt:

hello i am a businessman  i am also a student

output should be:

hello businessman also student

my approach was like this:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("test1.txt"));

        ArrayList<String> list1 = new ArrayList<String>();

        while (input.hasNext()) {
            list1.add(input.next());

        }

        for(int i=0;i<list1.size();i++){
        for(int j=i+1;j<list1.size();j++){
            if(list1.get(i).equals(list1.get(j))){
                list1.remove(j);
                j--;
               }
             }
         }

        System.out.println("List 1: " + list1);

    }

}

but it's not what i am looking for. i want to remove all occurence of duplicate so that i can output only unique words.


问:
An array converting question
I have an array below,

```<code>var array = {
    "Id":[1,2,3],
    "Name":["one","two","five"],
    "row":[8,9,7]
}
</code>```

but I want to transform it into

```<code>var array2 =
{"data":
    [
    {"Id":1,"Name":"one","Row:8"},
    {"Id":2,"Name":"two","Row:9"},
    {"Id":3,"Name":"five","Row:7"},
    ]
}
</code>```

Is this possible?

答:
it's not an array. it's an object.</p>

```<code>var myArr = [1,2,3]; //Array definition

var myObj = {test:"1",test2:"2"}; //Object Definition

var array = [1,[1,2,3]]; // multidimensional array
</code>```

Title: An array converting question

Body:
I have an array below,

var array = {
    "Id":[1,2,3],
    "Name":["one","two","five"],
    "row":[8,9,7]
}

but I want to transform it into

var array2 =
{"data":
    [
    {"Id":1,"Name":"one","Row:8"},
    {"Id":2,"Name":"two","Row:9"},
    {"Id":3,"Name":"five","Row:7"},
    ]
}

Is this possible?

Body:
it's not an array. it's an object.

var myArr = [1,2,3]; //Array definition

var myObj = {test:"1",test2:"2"}; //Object Definition

var array = [1,[1,2,3]]; // multidimensional array


问:
In the JSON Response String contains auto-added Backslashes
I am calling a webservice to get a JSON string response and It contains backslashes which is not in original string. Below is my code for requesting a JSON string object which is:       {"name":"Name","id":1}

```<code>protected String doInBackground(String... uri)
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }
</code>```

In post execute I just try to parse this respose string into JSONObject. code is bellow:

```<code>protected void onPostExecute(String result) {
        super.onPostExecute(result);
        TextView t1=(TextView)findViewById(R.id.textView1);
        TextView t2=(TextView)findViewById(R.id.textView2);

        //String s = result.replaceAll("\\", ""); //I have tried to escape backslashes also using this line.
        String name="failure";
        int id;
        try
        {
            t1.setText(result);
            JSONObject reader = new JSONObject(result.toString()); //Exception on this line.
            //name = reader.getString("name").toString();
            //id = reader.getInt("id");
            t2.setText(name);
        }
        catch (Exception e)
        {
            t2.setText(e.toString());
        }
    }
</code>```

Rsponse string is: "{\"name\":\"Name\",\"id\":1}"
And when I try to parse it to JSONObject it throws an exception says: org.json.JSONException value   "{"name":"Name","id":1}" type cannot converted into json object.

答: Look at your list message converters. It looks like your Json converter (MappingJackson2HttpMessageConverter for example) resides before StringMessageConverter. And json adding escape character '\' before '"' to every string it converts.</p>

Body:
I am calling a webservice to get a JSON string response and It contains backslashes which is not in original string. Below is my code for requesting a JSON string object which is:       {"name":"Name","id":1}

protected String doInBackground(String... uri)
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

In post execute I just try to parse this respose string into JSONObject. code is bellow:

protected void onPostExecute(String result) {
        super.onPostExecute(result);
        TextView t1=(TextView)findViewById(R.id.textView1);
        TextView t2=(TextView)findViewById(R.id.textView2);

        //String s = result.replaceAll("\\", ""); //I have tried to escape backslashes also using this line.
        String name="failure";
        int id;
        try
        {
            t1.setText(result);
            JSONObject reader = new JSONObject(result.toString()); //Exception on this line.
            //name = reader.getString("name").toString();
            //id = reader.getInt("id");
            t2.setText(name);
        }
        catch (Exception e)
        {
            t2.setText(e.toString());
        }
    }

Rsponse string is: "{\"name\":\"Name\",\"id\":1}"
And when I try to parse it to JSONObject it throws an exception says: org.json.JSONException value   "{"name":"Name","id":1}" type cannot converted into json object.


问:
Conversion failed when converting date and/or time from character string while inserting datetime SQL
I inserted some columns from an excel file into a SQL Table.

I am trying to select the date column but I get
"Conversion failed when converting date and/or time from character string while inserting datetime"

My Query is

```<code>Select
CONVERT(datetime2, SS.OrderDate) Date_Created
--CAST(SS.OrderDate as datetime2) Date_Created
FROM Table SS (nolock)
</code>```

Both of these lines fail.

My date column look like this:

```<code>43613
43612
43611
</code>```

Which excel can format back into (does anyone know how? what format is this?)

```<code>5/28/2019
5/27/2019
5/26/2019
</code>```

How can I get the same to be done in SQL?

答:
The short answer is that this works for most dates.</p>

```<code>select dateadd(day, 43613, '1899-12-30')
</code>```

Body:
I inserted some columns from an excel file into a SQL Table.

I am trying to select the date column but I get
"Conversion failed when converting date and/or time from character string while inserting datetime"

My Query is

Select
CONVERT(datetime2, SS.OrderDate) Date_Created
--CAST(SS.OrderDate as datetime2) Date_Created
FROM Table SS (nolock)

Both of these lines fail.

My date column look like this:

43613
43612
43611

Which excel can format back into (does anyone know how? what format is this?)

5/28/2019
5/27/2019
5/26/2019

How can I get the same to be done in SQL?

Body:
The short answer is that this works for most dates.

select dateadd(day, 43613, '1899-12-30')


答: In React,  idea is to lift your state up where you will actually modify it. So in your case, it makes sense to have your state and change handlers both inside of your main component.</p>

Title: Passing state to parent component


答:
Excel "serial" dates are the number of days since 1900-01-01 (where 1 is 1900-01-01, so subtract 1 first)

You can convert it like so:

```<code>SELECT
    CONVERT( date, DATEADD( day, SS.OrderDate - 1, '1900-01-01' ) ) AS OrderDate
</code>```

Title: Conversion failed when converting date and/or time from character string while inserting datetime SQL

Body:
Excel "serial" dates are the number of days since 1900-01-01 (where 1 is 1900-01-01, so subtract 1 first)

You can convert it like so:

SELECT
    CONVERT( date, DATEADD( day, SS.OrderDate - 1, '1900-01-01' ) ) AS OrderDate


问:
Getting started with GLSL
I've been doing graphic programming using the fixed pipeline of OpenGL after learning in school and I'm thinking of starting to learn GLSL. However I'm using Intel GMA X3100 card on Windows and it seems that GLSL is only supported up to version 1.10. I would like to ask if it is wise for me to start learning GLSL 1.1 first? (I have a book about GLSL 3.3 but I can't run the tutorials to see the effects, ending up of getting the concept first).</p>

答: If you want to develop a shader, you pretty much need an implementation that can render the shaders you write. If you're really short of funds, you could consider using a software emulation like Mesa3D, but if at all possible, you really want one in hardware. Given the current market, that pretty much means having a reasonably current nVidia or ATI/AMD graphics processor. Yes, if you're going to release something on the market, you probably want to do testing with an Intel as well, but in all honesty about all you're going to be able to do with most shader code on an Intel GPU is verify graceful failure.

Title: Getting started with GLSL


问:
Is it possible to define the increment factor for reallocations to std::vec::Vec?
I have a slowly growing std::vec::Vec. For every reallocation of the vector when it exceeds its capacity, I want the reallocation to be done by a static number of elements.

For example, I initially allocate a vector with 1024 elements. When it reaches its capacity, I want it to be reallocated with 32 elements more and I want this parameter to be configurable.

I'm looking for a function like this:

```<code>Vec::new(initial_capacity, capacity_increment);
</code>```

Where:

```<code>initial_capacity = 1024;
capacity_increment = 32;
</code>```

Is this functionality available in Rust (nightly or stable)?

The docs say that you can only specify initial capacity, but it is not clear how the size is increased on every reallocation or if this parameter can ever be changed. In fact the docs say that the Vec is going to be a (pointer, capacity, length) triplet no more and no less.

Is there any way to have capacity increment configuration?

I need this feature because I may have a large number of elements in the vector, and every reallocation by some small amount of extra capacity is going to cause considerable delays in the processes I am running.

答:
No, Vec (as of Rust 1.35) does not provide any mechanism to control the reallocation strategy.

When you call methods like Vec::push, the current implementation of Vec will double the capacity when the vector is full. When you call methods like reserve_exact, the current implementation of Vec directly uses your capacity.

the docs say that the Vec is going to be a (pointer, capacity, length) triplet no more and no less.

This doesn't preclude the possibility of Vec being extended in a very cautious manner. For example, Vec is built from a RawVec, which is parameterized by an allocator. So long as you use a zero-sized allocator (such as Global), the size will still be true.

It would be conceptually straight-forward to have another type parameter to control the resizing behavior. That being said, it seems unlikely to occur anytime soon.

Workarounds

If you really needed something like this, you can create a newtype around a Vec and call reserve_exact at all the appropriate points.

```<code>struct MyVec<T> {
    v: Vec<T>,
    increment: usize,
}

impl<T> MyVec<T> {
    fn new(capacity: usize, increment: usize) -> MyVec<T> {
        MyVec {
            v: Vec::with_capacity(capacity),
            increment,
        }
    }

    fn push(&mut self, val: T) {
        if self.v.len() == self.v.capacity() {
            self.v.reserve_exact(self.increment);
        }
        self.v.push(val);
    }
}
</code>```

Free advice

Don't try to optimize this until you have benchmarks that:

Show that this is a bottleneck

Can be used to prove that your "optimizations" actually make things faster

I may have a large number of elements in the vector, and every reallocation by some small amount of extra capacity is going to cause considerable delays in the processes I am running.

I agree with this as a gut feeling, which is why your idea is so confusing to me:

I want it to be reallocated with 32 elements more

32 elements is a small amount of extra capacity; by doing this it seems as if you'd be decreasing performance.

Body:
I have a slowly growing std::vec::Vec. For every reallocation of the vector when it exceeds its capacity, I want the reallocation to be done by a static number of elements.

For example, I initially allocate a vector with 1024 elements. When it reaches its capacity, I want it to be reallocated with 32 elements more and I want this parameter to be configurable.

I'm looking for a function like this:

Vec::new(initial_capacity, capacity_increment);

Where:

initial_capacity = 1024;
capacity_increment = 32;

Is this functionality available in Rust (nightly or stable)?

The docs say that you can only specify initial capacity, but it is not clear how the size is increased on every reallocation or if this parameter can ever be changed. In fact the docs say that the Vec is going to be a (pointer, capacity, length) triplet no more and no less.

Is there any way to have capacity increment configuration?

I need this feature because I may have a large number of elements in the vector, and every reallocation by some small amount of extra capacity is going to cause considerable delays in the processes I am running.

Body:
No, Vec (as of Rust 1.35) does not provide any mechanism to control the reallocation strategy.

When you call methods like Vec::push, the current implementation of Vec will double the capacity when the vector is full. When you call methods like reserve_exact, the current implementation of Vec directly uses your capacity.

the docs say that the Vec is going to be a (pointer, capacity, length) triplet no more and no less.

This doesn't preclude the possibility of Vec being extended in a very cautious manner. For example, Vec is built from a RawVec, which is parameterized by an allocator. So long as you use a zero-sized allocator (such as Global), the size will still be true.

It would be conceptually straight-forward to have another type parameter to control the resizing behavior. That being said, it seems unlikely to occur anytime soon.

Workarounds

If you really needed something like this, you can create a newtype around a Vec and call reserve_exact at all the appropriate points.

struct MyVec<T> {
    v: Vec<T>,
    increment: usize,
}

impl<T> MyVec<T> {
    fn new(capacity: usize, increment: usize) -> MyVec<T> {
        MyVec {
            v: Vec::with_capacity(capacity),
            increment,
        }
    }

    fn push(&mut self, val: T) {
        if self.v.len() == self.v.capacity() {
            self.v.reserve_exact(self.increment);
        }
        self.v.push(val);
    }
}

Free advice

Don't try to optimize this until you have benchmarks that:

Show that this is a bottleneck

Can be used to prove that your "optimizations" actually make things faster

I may have a large number of elements in the vector, and every reallocation by some small amount of extra capacity is going to cause considerable delays in the processes I am running.

I agree with this as a gut feeling, which is why your idea is so confusing to me:

I want it to be reallocated with 32 elements more

32 elements is a small amount of extra capacity; by doing this it seems as if you'd be decreasing performance.


问:
Create method that returns associated object's attribute value if current object's attribute is nil (jsonb type)
I have the following two classes:

```<code>class Account < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb

  has_one :plan
end

class Plan < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb
end
</code>```

And will be calling features like this:

```<code>account.features    # being account is an instance of Account
# or
account.features[:feature_key]
</code>```

The thing is I want account to look for features or features[:feature_key] within itself, and if that is nil or empty it should pick the value from the associated Plan object.

Something like:

```<code>features.present? ? features : plan.features
# and
features[:feature_key].present ? features[:feature_key] : plan.features[:feature_key]
</code>```

But in a proper method within Account class

答:
Well, it's not best practice, but you can override the getter with a custom method. In your case:

```<code>def features
  return features[:feature_key] if features[:feature_key].present?
  return plan&.features[:feature_key] if plan&.features[:feature_key].present?
end
</code>```

Not sure that's the logic you need, but that'll work for an override if you put it in the Account model. The preferred way to do it would be to name the method something else and call that method so you can still access the unmodified attribute if need be.

Body:
I have the following two classes:

class Account < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb

  has_one :plan
end

class Plan < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb
end

And will be calling features like this:

account.features    # being account is an instance of Account
# or
account.features[:feature_key]

The thing is I want account to look for features or features[:feature_key] within itself, and if that is nil or empty it should pick the value from the associated Plan object.

Something like:

features.present? ? features : plan.features
# and
features[:feature_key].present ? features[:feature_key] : plan.features[:feature_key]

But in a proper method within Account class

Body:
Well, it's not best practice, but you can override the getter with a custom method. In your case:

def features
  return features[:feature_key] if features[:feature_key].present?
  return plan&.features[:feature_key] if plan&.features[:feature_key].present?
end

Not sure that's the logic you need, but that'll work for an override if you put it in the Account model. The preferred way to do it would be to name the method something else and call that method so you can still access the unmodified attribute if need be.


问:
How to add Json Formatters to MvcCore?
I'm following the next tutorial of IdentityServer4 implementation for API , but I can't call the method AddJsonFormatters() to services.AddMvcCore().
I'm currently configuring the API from an empty template in ASP.NET Core 3.0.0

I have added NuGet package Microsoft.AspNetCore.Mvc.Formatters.Json with no results.
Also, I understand that using AddMvc() instead of AddMvcCore() would be a partial solution but I can't use AddAuthorization() on AddMvc()

```<code>//code extracted from the link
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();
    }
}
</code>```

This is the error message I see above:

'IMvcCoreBuilder' does not contain a definition for
  'AddJsonFormatters' and no accessible extension method
  'AddJsonFormatters' accepting a first argument of type
  'IMVCoreBuilder' could be found (are you using a missing directive or
  an assembly reference?)

Is this the method? Should I send an MVCCoreBuilder? How do I do that? MvcJsonMvcCoreBuilderExtensions.AddJsonFormatters Method

答:
When you call services.AddMvc() you get an IMvcBuilder.

if you want to add more output or input formatters, the IMvcBuilder has an extension method that you can call AddMvcOptions bellow you have an example of an XmlDataContractSerializerOutputFormatter that was added

```<code>    mvcBuilder.AddMvcOptions(options =>
        {
            options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter(options));
</code>```

Mvc already has a JsonOutputFormatter ,so inside of the AddMvcOptions you can get it and also and add your own custom mediatypes if you need it.

```<code>var jsonOutputFormatter = options.OutputFormatters.OfType<JsonOutputFormatter>().FirstOrDefault();

        if (jsonOutputFormatter != null)
        {
            jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.Vnd+json.all);
            jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.ApplicationOctetStream);
        }
</code>```

Title: How to add Json Formatters to MvcCore?

Body:
I'm following the next tutorial of IdentityServer4 implementation for API , but I can't call the method AddJsonFormatters() to services.AddMvcCore().
I'm currently configuring the API from an empty template in ASP.NET Core 3.0.0

I have added NuGet package Microsoft.AspNetCore.Mvc.Formatters.Json with no results.
Also, I understand that using AddMvc() instead of AddMvcCore() would be a partial solution but I can't use AddAuthorization() on AddMvc()

//code extracted from the link
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();
    }
}

This is the error message I see above:

'IMvcCoreBuilder' does not contain a definition for
  'AddJsonFormatters' and no accessible extension method
  'AddJsonFormatters' accepting a first argument of type
  'IMVCoreBuilder' could be found (are you using a missing directive or
  an assembly reference?)

Is this the method? Should I send an MVCCoreBuilder? How do I do that? MvcJsonMvcCoreBuilderExtensions.AddJsonFormatters Method

Body:
When you call services.AddMvc() you get an IMvcBuilder.

if you want to add more output or input formatters, the IMvcBuilder has an extension method that you can call AddMvcOptions bellow you have an example of an XmlDataContractSerializerOutputFormatter that was added

    mvcBuilder.AddMvcOptions(options =>
        {
            options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter(options));

Mvc already has a JsonOutputFormatter ,so inside of the AddMvcOptions you can get it and also and add your own custom mediatypes if you need it.

var jsonOutputFormatter = options.OutputFormatters.OfType<JsonOutputFormatter>().FirstOrDefault();

        if (jsonOutputFormatter != null)
        {
            jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.Vnd+json.all);
            jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.ApplicationOctetStream);
        }


问:
SQL Query :count the number of model available for each colour
count the number of model available for each colour</p>

答:
```<code>SELECT color, count(distinct model)
  FROM table
 GROUP BY color
</code>```


问:
Auto-layout: What creates constraints named UIView-Encapsulated-Layout-Width & Height?
My layout constraints are fine in Interface Builder but an exception occurs at runtime thanks to some part of the framework applying fixed height and width constraints that I really don't want. Why are they there, and how to turn them off?

They're the last two constraints shown in the logged list:

```<code>2014-04-26 09:02:58.687 BBCNews[32058:60b] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSLayoutConstraint:0xbf478a0 UIView:0xbf4a3c0.height == 0.28125*UIView:0xbf4a3c0.width>",
    "<NSLayoutConstraint:0xbf47190 UIView:0xbf4a3c0.leading == BNMyNewsCell_landscape:0xbf48b10.leading>",
    "<NSLayoutConstraint:0xbf47160 UIView:0xbf4a3c0.trailing == BNMyNewsCell_landscape:0xbf48b10.trailing>",
    "<NSLayoutConstraint:0xbf47130 BNMyNewsCell_landscape:0xbf48b10.bottom == UIView:0xbf4a3c0.bottom>",
    "<NSLayoutConstraint:0xbf47100 UIView:0xbf4a3c0.top == BNMyNewsCell_landscape:0xbf48b10.top>",
    "<NSLayoutConstraint:0xd4c3c40 'UIView-Encapsulated-Layout-Width' H:[BNMyNewsCell_landscape:0xbf48b10(304)]>",
    "<NSLayoutConstraint:0xd4c38a0 'UIView-Encapsulated-Layout-Height' V:[BNMyNewsCell_landscape:0xbf48b10(290)]>"
}
Will attempt to recover by breaking constraint

<NSLayoutConstraint:0xbf478a0 UIView:0xbf4a3c0.height == 0.28125*UIView:0xbf4a3c0.width>
</code>```

答:
I was facing a similar issue and solved it with the following.

Environment: Swift 5.0, xcode 10.2.1, Setting views programmatically

Warning message: Unable to simultaneously satisfy constraints... 'UIView-Encapsulated-Layout-Width' UIView:0x0000000000.width == 0   (active)>"
)

Code with warning

```<code>override func loadView() {

view = UIView()

/// Adds the subviews to the view and sets their properties and constraints
setupViews()

}
</code>```

Code that cleared warning

```<code>override func loadView() {

/// Needed to set the frame of the root view to the window frame.
let window = UIWindow()
view = UIView(frame: window.frame)

/// Adds the subviews to the view and sets their properties and constraints
setupViews()
}
</code>```

Notes on the loadView() method: "If you use Interface Builder to create your views and initialize the view controller, you must not override this method. You can override this method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the view property. The views you create should be unique instances and should not be shared with any other view controller object. Your custom implementation of this method should not call super." - Apple documentation

Notes on the root view:

"If you prefer to create views programmatically ... you do so by overriding
your view controller’s loadView method. Your implementation of this method
should do the following:

Create a root view object. The root view contains all other views associated
with your view controller. You typically define the frame for this view to
match the size of the app window, which itself should fill the screen. However,
the frame is adjusted based on how your view controller is displayed. See “View
Controller View Resizing.”

You can use a generic UIView object, a custom view you define, or any other
view that can scale to fill the screen.

Create additional subviews and add them to the root view." - Old apple
documentation?

Body:
My layout constraints are fine in Interface Builder but an exception occurs at runtime thanks to some part of the framework applying fixed height and width constraints that I really don't want. Why are they there, and how to turn them off?

They're the last two constraints shown in the logged list:

2014-04-26 09:02:58.687 BBCNews[32058:60b] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSLayoutConstraint:0xbf478a0 UIView:0xbf4a3c0.height == 0.28125*UIView:0xbf4a3c0.width>",
    "<NSLayoutConstraint:0xbf47190 UIView:0xbf4a3c0.leading == BNMyNewsCell_landscape:0xbf48b10.leading>",
    "<NSLayoutConstraint:0xbf47160 UIView:0xbf4a3c0.trailing == BNMyNewsCell_landscape:0xbf48b10.trailing>",
    "<NSLayoutConstraint:0xbf47130 BNMyNewsCell_landscape:0xbf48b10.bottom == UIView:0xbf4a3c0.bottom>",
    "<NSLayoutConstraint:0xbf47100 UIView:0xbf4a3c0.top == BNMyNewsCell_landscape:0xbf48b10.top>",
    "<NSLayoutConstraint:0xd4c3c40 'UIView-Encapsulated-Layout-Width' H:[BNMyNewsCell_landscape:0xbf48b10(304)]>",
    "<NSLayoutConstraint:0xd4c38a0 'UIView-Encapsulated-Layout-Height' V:[BNMyNewsCell_landscape:0xbf48b10(290)]>"
}
Will attempt to recover by breaking constraint

<NSLayoutConstraint:0xbf478a0 UIView:0xbf4a3c0.height == 0.28125*UIView:0xbf4a3c0.width>

Body:
I was facing a similar issue and solved it with the following.

Environment: Swift 5.0, xcode 10.2.1, Setting views programmatically

Warning message: Unable to simultaneously satisfy constraints... 'UIView-Encapsulated-Layout-Width' UIView:0x0000000000.width == 0   (active)>"
)

Code with warning

override func loadView() {

view = UIView()

/// Adds the subviews to the view and sets their properties and constraints
setupViews()

}

Code that cleared warning

override func loadView() {

/// Needed to set the frame of the root view to the window frame.
let window = UIWindow()
view = UIView(frame: window.frame)

/// Adds the subviews to the view and sets their properties and constraints
setupViews()
}

Notes on the loadView() method: "If you use Interface Builder to create your views and initialize the view controller, you must not override this method. You can override this method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the view property. The views you create should be unique instances and should not be shared with any other view controller object. Your custom implementation of this method should not call super." - Apple documentation

Notes on the root view:

"If you prefer to create views programmatically ... you do so by overriding
your view controller’s loadView method. Your implementation of this method
should do the following:

Create a root view object. The root view contains all other views associated
with your view controller. You typically define the frame for this view to
match the size of the app window, which itself should fill the screen. However,
the frame is adjusted based on how your view controller is displayed. See “View
Controller View Resizing.”

You can use a generic UIView object, a custom view you define, or any other
view that can scale to fill the screen.

Create additional subviews and add them to the root view." - Old apple
documentation?