答:
It's a question of chronology. Think about it; the event callback is not executed until later, by which time the value of i is, and has remained since the loop finished, a number equal to whatever value was.

The simplest way to resolve this is to use let for your iteration variable rather than var (this is good practice for variables these days in JavaScript generally, not just in your case.)

let "locks in" the value of i for each closure encountered in your loop. This answer discusses this in more detail.

You can achieve the same result by passing a var-declared iteration variable into the callback scope via an immediately-executed function expression (IIFE).

```<code>gameCircle.onclick = (i => () => checkGame(i))(i);
</code>```

Or, in more readable terms:

```<code>gameCircle.onclick = (function(i) {
    return function() { checkGame(i); };
})(i)
</code>```

Title: Value not assigning in for function

Body:
It's a question of chronology. Think about it; the event callback is not executed until later, by which time the value of i is, and has remained since the loop finished, a number equal to whatever value was.

The simplest way to resolve this is to use let for your iteration variable rather than var (this is good practice for variables these days in JavaScript generally, not just in your case.)

let "locks in" the value of i for each closure encountered in your loop. This answer discusses this in more detail.

You can achieve the same result by passing a var-declared iteration variable into the callback scope via an immediately-executed function expression (IIFE).

gameCircle.onclick = (i => () => checkGame(i))(i);

Or, in more readable terms:

gameCircle.onclick = (function(i) {
    return function() { checkGame(i); };
})(i)


来源: stackexchange

问:
Typescript complains when passing a possibly null (but not null) value to anonymous callback
When I have a property that initially begins as null, how can I pass this as an argument to an anonymous callback function that expects a non null value, without typescript complaining?

I can wrap my function call in an if statement to check for null, which stops typescript complaining at the function call level, but in the callback, typescript still complains.

Here's a snippet of the code. I allow some DatabaseState properties to be null, as this is how they are initialized.

```<code>//types.ts
export interface DatabaseState {
  db: PouchDB.Database | null;
  remoteDb: PouchDB.Database | null;
  dbReplication: PouchDB.Replication.Sync<{}> | null;
  dbSyncStatus: number;
  dbSyncInfo: string;
  dbSyncError: string;
}

//state typing - state: DatabaseState

//An action in database.ts
async startDatabaseSyncronisation({ state, commit, dispatch }) {
  var opts = { live: true, retry: true };

  if (state.remoteDb != null && state.db != null) {

    /* THE IF STATEMENT PREVENTS THE BELOW FUNCTION FROM CAUSING TYPESCRIPT TO COMPLAIN */

    await PouchDB.replicate(state.remoteDb, state.db, opts).on("complete",
      function(info) {

        /* WITHIN THE CALLBACK FUNCTION THOUGH, TYPESCRIPT COMPLAINS THAT state.remoteDb and state.db
        COULD BE NULL AND THE FUNCTION DOESN'T ACCEPT A NULL VALUE */

        let replication = PouchDB.sync(state.remoteDb, state.db, opts)
          .on("paused", function(err: {}) {
            dispatch("onSyncPaused", err);
          })
          .on("active", function() {
            dispatch("onSyncActive");
          })
          .on("denied", function(err: {}) {
            dispatch("onSyncError", err);
          })
          .on("error", function(err: {}) {
            dispatch("onSyncError", err);
          })
          .on("complete", function() {});
        commit(SET_DB_REPLICATION, replication);
      }
    );
  }
},
</code>```

How should I approach these kinds of typing checks?
Is there a more "Typescript-friendly" way of describing an initial value as unset?

The project uses Vue, with Vuex for state management.

答:
The answers of @elderapo and @Andrew were useful.

@elderapo's answer most directly answered my intial query, that is "why does typescript not complain about the function call, but does complain about the callback?":

The value of the state could change somewhere between the if check and complate callback

And @Andrew drew attention to the main issue, using null as a valid value in this case is probably unsafe.

I would highly advise you always account for null. The concept of null was deemed to be a mistake and not protecting yourself against that value makes your code unsafe

Although I don't expect the value of db and remoteDb to revert to null between dispatching the action and the callback, it is better to remove this possibility altogether.
A lack of connection/loss of connection to the database is handled in other code.

Instead of allowing the type to be null simply for initialization, I now initialize them as empty objects with type casting.
Therefore I don't need to disable strictNullChecks (I want them).

New code:

```<code>export interface DatabaseState {
  db: PouchDB.Database;
  remoteDb: PouchDB.Database;
  dbReplication: PouchDB.Replication.Sync<{}>;
  dbSyncStatus: number;
  dbSyncInfo: string;
  dbSyncError: string;
}

const state: DatabaseState = {
  db: {} as PouchDB.Database,
  remoteDb: {} as PouchDB.Database,
  dbReplication: {} as PouchDB.Replication.Sync<{}>,
  dbSyncStatus: SyncStatus.NONE,
  dbSyncInfo: "",
  dbSyncError: ""
};

async startDatabaseSyncronisation({ state, commit, dispatch }) {
  var opts = { live: true, retry: true };
  await PouchDB.replicate(state.remoteDb, state.db, opts).on(
    "complete",
    function(info) {
      let replication = PouchDB.sync(state.remoteDb, state.db, opts)
        .on("paused", function(err: {}) {
          dispatch("onSyncPaused", err);
        })
        .on("active", function() {
          dispatch("onSyncActive");
        })
        .on("denied", function(err: {}) {
          dispatch("onSyncError", err);
        })
        .on("error", function(err: {}) {
          dispatch("onSyncError", err);
        })
        .on("complete", function() {});
      commit(SET_DB_REPLICATION, replication);
    }
  );
},
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I have a property that initially begins as null, how can I pass this as an argument to an anonymous callback function that expects a non null value, without typescript complaining?

I can wrap my function call in an if statement to check for null, which stops typescript complaining at the function call level, but in the callback, typescript still complains.

Here's a snippet of the code. I allow some DatabaseState properties to be null, as this is how they are initialized.

//types.ts
export interface DatabaseState {
  db: PouchDB.Database | null;
  remoteDb: PouchDB.Database | null;
  dbReplication: PouchDB.Replication.Sync<{}> | null;
  dbSyncStatus: number;
  dbSyncInfo: string;
  dbSyncError: string;
}

//state typing - state: DatabaseState

//An action in database.ts
async startDatabaseSyncronisation({ state, commit, dispatch }) {
  var opts = { live: true, retry: true };

  if (state.remoteDb != null && state.db != null) {

    /* THE IF STATEMENT PREVENTS THE BELOW FUNCTION FROM CAUSING TYPESCRIPT TO COMPLAIN */

    await PouchDB.replicate(state.remoteDb, state.db, opts).on("complete",
      function(info) {

        /* WITHIN THE CALLBACK FUNCTION THOUGH, TYPESCRIPT COMPLAINS THAT state.remoteDb and state.db
        COULD BE NULL AND THE FUNCTION DOESN'T ACCEPT A NULL VALUE */

        let replication = PouchDB.sync(state.remoteDb, state.db, opts)
          .on("paused", function(err: {}) {
            dispatch("onSyncPaused", err);
          })
          .on("active", function() {
            dispatch("onSyncActive");
          })
          .on("denied", function(err: {}) {
            dispatch("onSyncError", err);
          })
          .on("error", function(err: {}) {
            dispatch("onSyncError", err);
          })
          .on("complete", function() {});
        commit(SET_DB_REPLICATION, replication);
      }
    );
  }
},

How should I approach these kinds of typing checks?
Is there a more "Typescript-friendly" way of describing an initial value as unset?

The project uses Vue, with Vuex for state management.

Body:
The answers of @elderapo and @Andrew were useful.

@elderapo's answer most directly answered my intial query, that is "why does typescript not complain about the function call, but does complain about the callback?":

The value of the state could change somewhere between the if check and complate callback

And @Andrew drew attention to the main issue, using null as a valid value in this case is probably unsafe.

I would highly advise you always account for null. The concept of null was deemed to be a mistake and not protecting yourself against that value makes your code unsafe

Although I don't expect the value of db and remoteDb to revert to null between dispatching the action and the callback, it is better to remove this possibility altogether.
A lack of connection/loss of connection to the database is handled in other code.

Instead of allowing the type to be null simply for initialization, I now initialize them as empty objects with type casting.
Therefore I don't need to disable strictNullChecks (I want them).

New code:

export interface DatabaseState {
  db: PouchDB.Database;
  remoteDb: PouchDB.Database;
  dbReplication: PouchDB.Replication.Sync<{}>;
  dbSyncStatus: number;
  dbSyncInfo: string;
  dbSyncError: string;
}

const state: DatabaseState = {
  db: {} as PouchDB.Database,
  remoteDb: {} as PouchDB.Database,
  dbReplication: {} as PouchDB.Replication.Sync<{}>,
  dbSyncStatus: SyncStatus.NONE,
  dbSyncInfo: "",
  dbSyncError: ""
};

async startDatabaseSyncronisation({ state, commit, dispatch }) {
  var opts = { live: true, retry: true };
  await PouchDB.replicate(state.remoteDb, state.db, opts).on(
    "complete",
    function(info) {
      let replication = PouchDB.sync(state.remoteDb, state.db, opts)
        .on("paused", function(err: {}) {
          dispatch("onSyncPaused", err);
        })
        .on("active", function() {
          dispatch("onSyncActive");
        })
        .on("denied", function(err: {}) {
          dispatch("onSyncError", err);
        })
        .on("error", function(err: {}) {
          dispatch("onSyncError", err);
        })
        .on("complete", function() {});
      commit(SET_DB_REPLICATION, replication);
    }
  );
},


问:
Get type of Django form widget from within template
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.

To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! field.field.widget.__class__.__name__

Unfortunately, you're not allowed access to underscore variables in templates. Great!

You can test field.field.widget.input_type but this only works for text/password <input ../> types. I need more resolution that that.

To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across ModelForms and standard Forms (something that wouldn't be true if I wrote an intermediary Form class).

If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!

答:
You can make every view that manages forms inherit from a custom generic view where you load into the context the metadata that you need in the templates. The generic form view should include something like this:

```<code>class CustomUpdateView(UpdateView):
    ...
    def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       ...
       for f, value in context["form"].fields.items():
          context["form"].fields[f].type = self.model._meta.get_field(f).get_internal_type()
       ...
       return context
</code>```

In the template you can access these custom properties through field.field:

```<code>{% if field.field.type == 'BooleanField' %}
     <div class="custom-control custom-checkbox">
     ...
     </div>
{% endif %}
</code>```

By using the debugger of PyCharm or Visual Studio Code you can see all the available metadata, if you need something else besides the field type.

ContentLicense: CC BY-SA 3.0

Body:
You can make every view that manages forms inherit from a custom generic view where you load into the context the metadata that you need in the templates. The generic form view should include something like this:

class CustomUpdateView(UpdateView):
    ...
    def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       ...
       for f, value in context["form"].fields.items():
          context["form"].fields[f].type = self.model._meta.get_field(f).get_internal_type()
       ...
       return context

In the template you can access these custom properties through field.field:

{% if field.field.type == 'BooleanField' %}
     <div class="custom-control custom-checkbox">
     ...
     </div>
{% endif %}

By using the debugger of PyCharm or Visual Studio Code you can see all the available metadata, if you need something else besides the field type.


问:
Why the Python .append() appends two values, instead of one in a list?
I have two lists and one dictrionary:

```<code>a = ['Foo bar', 'Hello!']
b = {'Foo': 'bar', 'Hello': 'foo'}
c = []
</code>```

I'm trying to replace Foo with bar and Hello with foo in every a element and append the new values to c.

Hovewer, this code gives the following output:

```<code>for i in a:
    for entry in b:
        c.append(i.replace(entry, b.get(entry)))

print(c)
</code>```
```<code>['bar bar', 'Foo bar', 'Hello!', 'foo!']
</code>```

Expected output:

```<code>['bar bar', 'foo!']
</code>```

I was expecting the c list to contain only the modified values, not the original ones.

Am I missing something?

答:
This should work:

```<code>a = ['Foo bar', 'Hello!']
b = {'Foo': 'bar', 'Hello': 'foo'}
c = []
for i in a:
    c.append(i)
    for entry in b:
        c[-1] = c[-1].replace(entry, b.get(entry))

print(c)
</code>```

Output:

```<code>['bar bar', 'foo!']
</code>```

The issue with your current code is that you append a new item each time you replace - you only want to edit the last item.

Body:
I have two lists and one dictrionary:

a = ['Foo bar', 'Hello!']
b = {'Foo': 'bar', 'Hello': 'foo'}
c = []

I'm trying to replace Foo with bar and Hello with foo in every a element and append the new values to c.

Hovewer, this code gives the following output:

for i in a:
    for entry in b:
        c.append(i.replace(entry, b.get(entry)))

print(c)

['bar bar', 'Foo bar', 'Hello!', 'foo!']

Expected output:

['bar bar', 'foo!']

I was expecting the c list to contain only the modified values, not the original ones.

Am I missing something?

Body:
This should work:

a = ['Foo bar', 'Hello!']
b = {'Foo': 'bar', 'Hello': 'foo'}
c = []
for i in a:
    c.append(i)
    for entry in b:
        c[-1] = c[-1].replace(entry, b.get(entry))

print(c)

Output:

['bar bar', 'foo!']

The issue with your current code is that you append a new item each time you replace - you only want to edit the last item.


问:
How to register a Jackson Module in Quarkus?
I'd like to register the Kotlin-Module with Jackson in a Quarkus application  so Jackson can deserialize JSON into data classes without needing a NoArgsConstructor. What is the best way to do this?

Update after comment

The application is a REST service written in Kotlin. At the API level we use View classes (e.g. PersonView or PersonWriteView) to abstract from the models and entities on the service resp. persistence layer. To reduce overhead while still getting nice and meaningful equals() and hashcode() functions we use data classes for this.

In the vanilla settings Jackson is not able to directly deserialize into data classes because it needs an empty constructor. This can be monkey patched by applying the no-arg compiler plugin and add an annotation e.g. @NoArgConstructor similar to what Lombok offers. But of course this way we have to annotate each data class in the API which is error prone.

A better solution for this is to include com.fasterxml.jackson.module:jackson-module-kotlin which gets you the marvelous KotlinModule. After this mapper.treeToValue() can directly create data class instances without the need for an empty constructor.
For this to work we have to register the module with the ObjectMapper e.g. via ObjectMapper().findAndRegisterModules(). All I want to know is how to configure the ObjectMapper which is used by Resteasy to unmarshal the JSON to objects.

答:
According to the documentation, you have to register an implementation of the (quarkus-specific) interface ObjectMapperCustomizer.

```<code>import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import io.quarkus.jackson.ObjectMapperCustomizer
import javax.inject.Singleton

@Singleton
class AddKotlinModuleCustomizer : ObjectMapperCustomizer {

    override fun customize(objectMapper: ObjectMapper) {
        objectMapper.registerModule(KotlinModule())
    }
}
</code>```

And of course add the kotlin module as dependency in the pom

```<code>    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-kotlin</artifactId>
      <version>2.10.2</version>
    </dependency>
</code>```

Body:
According to the documentation, you have to register an implementation of the (quarkus-specific) interface ObjectMapperCustomizer.

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import io.quarkus.jackson.ObjectMapperCustomizer
import javax.inject.Singleton

@Singleton
class AddKotlinModuleCustomizer : ObjectMapperCustomizer {

    override fun customize(objectMapper: ObjectMapper) {
        objectMapper.registerModule(KotlinModule())
    }
}

And of course add the kotlin module as dependency in the pom

    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-kotlin</artifactId>
      <version>2.10.2</version>
    </dependency>


问:
Website - Remove/dont show option "save image as" and "open/copy image"
I am development a new website (html + css + javascript) and I want disable the open "save image as" and "open/copy image" in browser (in desktop and smartphone).

My images code:

```<code><a href="images/collection/photo1.jpg" class="photography-entry img image-popup d-flex justify-content-start align-items-end" style="background-image: url(images/collection/photo1.jpg);">
</code>```

It is possible with this code?

Thank you!

答: Well on browser, you can try javascript - oncontextmenu="return false".

Body:
I am development a new website (html + css + javascript) and I want disable the open "save image as" and "open/copy image" in browser (in desktop and smartphone).

My images code:

It is possible with this code?

Thank you!


问:
Output time to a file with the Unix "time" command, but leave the output of the command to the console
I time a command that has some output. I want to output the real time from the time command to a file, but leave the output of the command to the console.

For example, if I do time my_command I get this printed in the console:

```<code>several lines of output from my_command ...
real 1m25.970s
user 0m0.427s
sys 0m0.518s
</code>```

In this case, I want to store only 1m25.970s to a file, but still print the output of the command to the console.

答:
The time command is tricky.  The POSIX specification of time
doesn't define the default output format, but does define a format for the -p (presumably for 'POSIX') option.  Note the (not easily understood) discussion of command sequences in pipelines.

The Bash specification say time prefixes a 'pipeline', which means that time cmd1 | cmd2 times both cmd1 and cmd2.  It writes its results to standard error.  The Korn shell is similar.

The POSIX format requires a single space between the tags such as real and the time; the default format often uses a tab instead of a space.  Note that the /usr/bin/time command may have yet another output format.  It does on macOS, for example, listing 3 times on a single line, by default, with the label after the time value; it supports -p to print in an approximation to the POSIX format (but it has multiple spaces between label and time).

You can easily get all the information written to standard error into a file:

```<code>(time my_command) 2> log.file
</code>```

If my_command or any programs it invokes reports any errors to standard error, those will got to the log file too.  And you will get all three lines of the output from time written to the file.

If your shell is Bash, you may be able to use process substitution to filter some of the output.

I wouldn't try it with a single command line; the hieroglyphs needed to make it work are ghastly and best encapsulated in shell scripts.

For example, a shell script time.filter to capture the output from time and write only the real time to a log file (default log.file, configurable by providing an alternative log file name as the first argument

```<code>#!/bin/sh

output="${1:-log.file}"
shift
sed -E '/^real[[:space:]]+(([0-9]+m)?[0-9]+[.][0-9]+s?)/{ s//\1/; w '"$output"'
        d;}
        /^(user|sys)[[:space:]]+(([0-9]+m)?[0-9]+[.][0-9]+s?)/d' "$@"
</code>```

This assumes your sed uses -E to enable extended regular expressions.
The first line of the script finds the line containing the real label and the time after it (in a number of possible formats — but not all).  It accepts an optional minutes value such as 60m05.003s, or just a seconds value 5.00s, or just 5.0 (POSIX formats — at least one digit after the decimal point is required).  It captures the time part and prints it to the chosen file (by default, log.file; you can specify an alternative name as the first argument on the command line). Note that even GNU sed treats everything after the w command as file name; you have to continue the d (delete) command and the close brace } on a newline. GNU sed does not require the semicolon after d; BSD (macOS) sed does.  The second line recognizes and deletes the lines reportin the user and sys times.  Everything else is passed through unaltered.

The script processes any files you give it after the log file name, or standard input if you give it none.  A better command line notation would use an explicit option (-l logfile) and getopts to specify the log file.

With that in place, we can devise a program that reports to standard error and standard output — my_command:

```<code>echo "nonsense: error: positive numbers are required for argument 1" >&2
dribbler -s 0.4 -r 0.1 -i data -t
echo "apoplexy: unforeseen problems induced temporary amnesia" >&2
</code>```

You could use cat data instead of the dribbler command.  The dribbler command as shown reads lines from data, writes them to standard output, with a random delay with a gaussian distribution between lines.  The mean delay is 0.4 seconds; the standard deviation is 0.1 seconds.  The other two lines are pretending to be commands that report errors to standard error.

My data file contained a nonsense 'poem' called 'The Great Panjandrum'.

With this background in place, we can run the command and capture the real time in log.file, delete (ignore) the user and system time values, while sending the rest of standard error to standard error by using:

$ (time my_command) 2> >(tee raw.stderr | time.filter >&2)

nonsense: error: positive numbers are required for argument 1
So she went into the garden
to cut a cabbage-leaf
to make an apple-pie
and at the same time
a great she-bear coming down the street
pops its head into the shop
What no soap
So he died
and she very imprudently married the Barber
and there were present
the Picninnies
and the Joblillies
and the Garyulies
and the great Panjandrum himself
with the little round button at top
and they all fell to playing the game of catch-as-catch-can
till the gunpowder ran out at the heels of their boots
apoplexy: unforeseen problems induced temporary amnesia

$ cat log.file

0m7.278s
```

(The time taken is normally between 6 and 8 seconds.  There are 17 lines, so you'd expect it to take around 6.8 seconds at 0.4 seconds per line.)  The blank line is from time; it is pretty hard to remove that blank line, and only that blank line, especially as POSIX says it is optional.  It isn't worth it.

Body:
I time a command that has some output. I want to output the real time from the time command to a file, but leave the output of the command to the console.

For example, if I do time my_command I get this printed in the console:

several lines of output from my_command ...
real 1m25.970s
user 0m0.427s
sys 0m0.518s

In this case, I want to store only 1m25.970s to a file, but still print the output of the command to the console.

Body:
The time command is tricky.  The POSIX specification of time
doesn't define the default output format, but does define a format for the -p (presumably for 'POSIX') option.  Note the (not easily understood) discussion of command sequences in pipelines.

The Bash specification say time prefixes a 'pipeline', which means that time cmd1 | cmd2 times both cmd1 and cmd2.  It writes its results to standard error.  The Korn shell is similar.

The POSIX format requires a single space between the tags such as real and the time; the default format often uses a tab instead of a space.  Note that the /usr/bin/time command may have yet another output format.  It does on macOS, for example, listing 3 times on a single line, by default, with the label after the time value; it supports -p to print in an approximation to the POSIX format (but it has multiple spaces between label and time).

You can easily get all the information written to standard error into a file:

(time my_command) 2> log.file

If my_command or any programs it invokes reports any errors to standard error, those will got to the log file too.  And you will get all three lines of the output from time written to the file.

If your shell is Bash, you may be able to use process substitution to filter some of the output.

I wouldn't try it with a single command line; the hieroglyphs needed to make it work are ghastly and best encapsulated in shell scripts.

For example, a shell script time.filter to capture the output from time and write only the real time to a log file (default log.file, configurable by providing an alternative log file name as the first argument

#!/bin/sh

output="${1:-log.file}"
shift
sed -E '/^real[[:space:]]+(([0-9]+m)?[0-9]+[.][0-9]+s?)/{ s//\1/; w '"$output"'
        d;}
        /^(user|sys)[[:space:]]+(([0-9]+m)?[0-9]+[.][0-9]+s?)/d' "$@"

This assumes your sed uses -E to enable extended regular expressions.
The first line of the script finds the line containing the real label and the time after it (in a number of possible formats — but not all).  It accepts an optional minutes value such as 60m05.003s, or just a seconds value 5.00s, or just 5.0 (POSIX formats — at least one digit after the decimal point is required).  It captures the time part and prints it to the chosen file (by default, log.file; you can specify an alternative name as the first argument on the command line). Note that even GNU sed treats everything after the w command as file name; you have to continue the d (delete) command and the close brace } on a newline. GNU sed does not require the semicolon after d; BSD (macOS) sed does.  The second line recognizes and deletes the lines reportin the user and sys times.  Everything else is passed through unaltered.

The script processes any files you give it after the log file name, or standard input if you give it none.  A better command line notation would use an explicit option (-l logfile) and getopts to specify the log file.

With that in place, we can devise a program that reports to standard error and standard output — my_command:

echo "nonsense: error: positive numbers are required for argument 1" >&2
dribbler -s 0.4 -r 0.1 -i data -t
echo "apoplexy: unforeseen problems induced temporary amnesia" >&2

You could use cat data instead of the dribbler command.  The dribbler command as shown reads lines from data, writes them to standard output, with a random delay with a gaussian distribution between lines.  The mean delay is 0.4 seconds; the standard deviation is 0.1 seconds.  The other two lines are pretending to be commands that report errors to standard error.

My data file contained a nonsense 'poem' called 'The Great Panjandrum'.

With this background in place, we can run the command and capture the real time in log.file, delete (ignore) the user and system time values, while sending the rest of standard error to standard error by using:

$ (time my_command) 2> >(tee raw.stderr | time.filter >&2)

nonsense: error: positive numbers are required for argument 1
So she went into the garden
to cut a cabbage-leaf
to make an apple-pie
and at the same time
a great she-bear coming down the street
pops its head into the shop
What no soap
So he died
and she very imprudently married the Barber
and there were present
the Picninnies
and the Joblillies
and the Garyulies
and the great Panjandrum himself
with the little round button at top
and they all fell to playing the game of catch-as-catch-can
till the gunpowder ran out at the heels of their boots
apoplexy: unforeseen problems induced temporary amnesia

$ cat log.file

0m7.278s

(The time taken is normally between 6 and 8 seconds.  There are 17 lines, so you'd expect it to take around 6.8 seconds at 0.4 seconds per line.)  The blank line is from time; it is pretty hard to remove that blank line, and only that blank line, especially as POSIX says it is optional.  It isn't worth it.


问:
where is this toggle() function coming from in angular code?
I'm using this code for a side nav: https://stackblitz.com/edit/mat-sidenav-responsive?file=app%2Fsidenav-responsive-example.html

its uses this from template reference variable #sidenav

```<code><a href="#" (click)="sidenav.toggle()">Vodafone Airtime</a>
</code>```

I want to know where is this .toggle() function coming from, its a property of the sidenav object? where can I view all these properties?

答:
Yes, it's a method of Angular Material's sidenav. This component is assigned to a variable named sidenav here:

```<code>  <mat-sidenav #sidenav [(mode)]="over" [(opened)]="opened" class="bottom-to-top">
</code>```

For further reading on sidenav's methods, inputs, outputs and properties, best start with the official docs:
https://material.angular.io/components/sidenav/api

Body:
I'm using this code for a side nav: https://stackblitz.com/edit/mat-sidenav-responsive?file=app%2Fsidenav-responsive-example.html

its uses this from template reference variable #sidenav

Vodafone Airtime

I want to know where is this .toggle() function coming from, its a property of the sidenav object? where can I view all these properties?

Body:
Yes, it's a method of Angular Material's sidenav. This component is assigned to a variable named sidenav here:

  <mat-sidenav #sidenav [(mode)]="over" [(opened)]="opened" class="bottom-to-top">

For further reading on sidenav's methods, inputs, outputs and properties, best start with the official docs:
https://material.angular.io/components/sidenav/api


问:
Is it possible to run a game from pygame using WSL and jupyter lab?
I'm trying to run a Mario Kart clone from a github repository on WSL (Debian), but my WSL doesn't include X11. So, I would like to know if it's possible to launch it from Jupyter lab. When I try to launch it, I get an error:

```<code>pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5047:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM default
Traceback (most recent call last):
  File "MarioKart.pyw", line 14, in <module>
    screen = pygame.display.set_mode(MENU_DIMENSIONS)
pygame.error: No available video device
</code>```

The github repo: https://github.com/s4rd0n1k/pygame_mariokart

答:
Your immediate issue is a sound issue.  This should be fixed by

export SDL_AUDIODRIVER='dsp'

Or whatever is necessary to set an environment variable in Jupyter Lab.

Beyond that, I don't know if the graphics will work.

Body:
I'm trying to run a Mario Kart clone from a github repository on WSL (Debian), but my WSL doesn't include X11. So, I would like to know if it's possible to launch it from Jupyter lab. When I try to launch it, I get an error:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5047:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM default
Traceback (most recent call last):
  File "MarioKart.pyw", line 14, in <module>
    screen = pygame.display.set_mode(MENU_DIMENSIONS)
pygame.error: No available video device

The github repo: https://github.com/s4rd0n1k/pygame_mariokart


问:
Firestore how to get organized random key?
I just migrated my data from Realtime Database to Firestore and started to use firestore but I had a function to push() in Realtime Database and also save push().key so I changed it to add() or set() for Firestore but I realize that add().id set().id is totally random key unlike Realtime Database push().key is organized like the later push().key is always behind previous push().key. I must save data and it must be organized like push(). Is there any solution to generate keys that are organized like push().key??

```<code>//I tried 2 options

//option 1
ref.add({something:something}).then((gref)=>{ref.doc(gref.id).set({key:gref.id},{merge:true})})

//option 2
var ref = db.doc();
ref.set({something:something,key:ref.id})
</code>```

both generates unorganized keys unlike push().key

答:
I searched, read documents and I realized that Firestore doesn't provide organized key as Realtime Database but I found solution for this. If someone need organized key, you have to use timestamp and sort as ascending or descending.
just like </p>

```<code>// when you want to save data..
ref.set({timestamp:firebase.firestore.FieldValue.serverTimestamp()})
// and if you want get data..
db.collection('something').orderBy("timestamp", "asc").get()
// it will sort automatically!
</code>```

Body:
I just migrated my data from Realtime Database to Firestore and started to use firestore but I had a function to push() in Realtime Database and also save push().key so I changed it to add() or set() for Firestore but I realize that add().id set().id is totally random key unlike Realtime Database push().key is organized like the later push().key is always behind previous push().key. I must save data and it must be organized like push(). Is there any solution to generate keys that are organized like push().key??

//I tried 2 options

//option 1
ref.add({something:something}).then((gref)=>{ref.doc(gref.id).set({key:gref.id},{merge:true})})

//option 2
var ref = db.doc();
ref.set({something:something,key:ref.id})

both generates unorganized keys unlike push().key

Body:
I searched, read documents and I realized that Firestore doesn't provide organized key as Realtime Database but I found solution for this. If someone need organized key, you have to use timestamp and sort as ascending or descending.
just like

// when you want to save data..
ref.set({timestamp:firebase.firestore.FieldValue.serverTimestamp()})
// and if you want get data..
db.collection('something').orderBy("timestamp", "asc").get()
// it will sort automatically!


问:
Make interface contain children specified by enum in Typescript
Say I have a dictionary of behaviours, in my specific case it's a dictionary of sorting functions.

I want to pass one to another function that goes ahead and actually performs the sort. To do that, I declare an Enum containing possible sorting methods. In my specific case I have alphabetical, counter alphabetical, oldest, newest and a whole stack of others. So if I want to export a set of functions, I want to have an object extending this enum. However, from some quick code tests, I wasn't able to find any sort of method of constricting an object to an enum and still specifying the fact that each element inside this enum is a function.

Take this as an example:

```<code>enum sorts {
    alphabetical,
    counterAlphabetical,
    oldest,
    newes
    ...
}
</code>```

And I have an object defining these functions:

```<code>const SortingFunctions: sorts = {
    alphabetical: (i: SampleObject, j: SampleObject): SampleObject => // implement function
}
</code>```

Then I get an error:

TS2322: Type '{ alphabetical: (i: SampleObject, j:SampleObject) => SampleObject }' is not assignable to type 'SampleObjectFilter'.

So if I want to tell typescript that every entry in that enum follows a particular signature, I can either get the user to pass the correct item from the SortingFunctions object (the one with the implementations) or I can get a resolver function to resolve the correct sorting function based off of the input value which was originally specified over the enum.

```<code>function sort(sortingMethod: sorts): SampleObject[] {
    return SortingFunctions[sortingMethod](SampleObjects); // Some Sorting algorithm implementation, that's irrelevant
}
</code>```

Which I think is the preferred method of declaring an object as using variable declaration method would result in the types not being explicitly defined.

So anyway, I tried declaring the SortingFunctions object as an object containing keys of the sorts enum like so:

```<code>const SortingFunctions: {
    [Algorithm as keyof sorts: string]: (i: SampleObject, j: SampleObject) => SampleObject
} = {
    // implementations
};
</code>```

but of course that threw a syntax error.

Anyway, the question is whether it is possible to use an enum to declare properties of a dictionary of functions in such a way that the compiler knows to reference that enum should that usage come up.

Sorry for the word count.
I appreciate the help.

答:
Did you mean something like this:</p>

```<code>enum SortMethod {
    alphabetical,
    counterAlphabetical,
    // oldest,
    // newes
};

type SortFN<T> = (a: T, b: T) => T;
type SortMethods<T> = Record<SortMethod, SortFN<T>>

const numericSortMethods: SortMethods<number> = {
    [SortMethod.alphabetical]: (a, b) => {
        return a > b ? a : b
    },
    [SortMethod.counterAlphabetical]: (a, b) => {
        return b > a ? a : b
    }
};

</code>```

Body:
Say I have a dictionary of behaviours, in my specific case it's a dictionary of sorting functions.

I want to pass one to another function that goes ahead and actually performs the sort. To do that, I declare an Enum containing possible sorting methods. In my specific case I have alphabetical, counter alphabetical, oldest, newest and a whole stack of others. So if I want to export a set of functions, I want to have an object extending this enum. However, from some quick code tests, I wasn't able to find any sort of method of constricting an object to an enum and still specifying the fact that each element inside this enum is a function.

Take this as an example:

enum sorts {
    alphabetical,
    counterAlphabetical,
    oldest,
    newes
    ...
}

And I have an object defining these functions:

const SortingFunctions: sorts = {
    alphabetical: (i: SampleObject, j: SampleObject): SampleObject => // implement function
}

Then I get an error:

TS2322: Type '{ alphabetical: (i: SampleObject, j:SampleObject) => SampleObject }' is not assignable to type 'SampleObjectFilter'.

So if I want to tell typescript that every entry in that enum follows a particular signature, I can either get the user to pass the correct item from the SortingFunctions object (the one with the implementations) or I can get a resolver function to resolve the correct sorting function based off of the input value which was originally specified over the enum.

function sort(sortingMethod: sorts): SampleObject[] {
    return SortingFunctions[sortingMethod](SampleObjects); // Some Sorting algorithm implementation, that's irrelevant
}

Which I think is the preferred method of declaring an object as using variable declaration method would result in the types not being explicitly defined.

So anyway, I tried declaring the SortingFunctions object as an object containing keys of the sorts enum like so:

const SortingFunctions: {
    [Algorithm as keyof sorts: string]: (i: SampleObject, j: SampleObject) => SampleObject
} = {
    // implementations
};

but of course that threw a syntax error.

Anyway, the question is whether it is possible to use an enum to declare properties of a dictionary of functions in such a way that the compiler knows to reference that enum should that usage come up.

Sorry for the word count.
I appreciate the help.

Body:
Did you mean something like this:

enum SortMethod {
    alphabetical,
    counterAlphabetical,
    // oldest,
    // newes
};

type SortFN<T> = (a: T, b: T) => T;
type SortMethods<T> = Record<SortMethod, SortFN<T>>

const numericSortMethods: SortMethods<number> = {
    [SortMethod.alphabetical]: (a, b) => {
        return a > b ? a : b
    },
    [SortMethod.counterAlphabetical]: (a, b) => {
        return b > a ? a : b
    }
};


答:
The problem you're having is that you're always appending for every value in the dictionary, you should build up a string and then append it after checking the dictionary. You can also use the dictionaries items to avoid getting the value seperate from the key

```<code>for i in a:
    new_val = i
    for key, val in b.items():
        new_val = new_val.replace(key, val)
    c.append(new_val)
</code>```

Title: Why the Python .append() appends two values, instead of one in a list?

Body:
The problem you're having is that you're always appending for every value in the dictionary, you should build up a string and then append it after checking the dictionary. You can also use the dictionaries items to avoid getting the value seperate from the key

for i in a:
    new_val = i
    for key, val in b.items():
        new_val = new_val.replace(key, val)
    c.append(new_val)


问:
Testing Neural Network build from scratch (XOR)
So, I have recently implemented a neural network from scratch in python by following 3Blue1Brown's videos and I am currently doing the testing part of my implementation. This is done by doing the AND, OR, and XOR problems. It seems like the network works in the AND and OR problems, however, not in the XOR problem. I Get the following predictions:

AND

```<code>Input:     Output:
0, 0       0.048
1, 0       0.018
0, 1       0.020
1, 1       0.974
</code>```

OR

```<code>Input:     Output:
0, 0       0.026
1, 0       0.984
0, 1       0.988
1, 1       0.997
</code>```

XOR

```<code>Input:     Output:
0, 0       0.049
1, 0       0.842
0, 1       0.842
1, 1       0.844 <- WRONG!
</code>```

These results have been predicted with a model of 1 hidden layer with 2 neurons, and the sigmoid function in both the hidden layer and in the output layer.

I have tried different amounts of testing data, epochs, dimensions in the hidden layers, and hidden layers, and nothing seems to work.

So, my question is if anyone has any idea why i get the wrong result in the XOR problem but not in the AND and the OR problems? And if so, how to fix it?

答: typically the XOR function requires a more complex model. Add another hidden layer of two neurons and that should be sufficient.</p>

Body:
So, I have recently implemented a neural network from scratch in python by following 3Blue1Brown's videos and I am currently doing the testing part of my implementation. This is done by doing the AND, OR, and XOR problems. It seems like the network works in the AND and OR problems, however, not in the XOR problem. I Get the following predictions:

AND

Input:     Output:
0, 0       0.048
1, 0       0.018
0, 1       0.020
1, 1       0.974

OR

Input:     Output:
0, 0       0.026
1, 0       0.984
0, 1       0.988
1, 1       0.997

XOR

Input:     Output:
0, 0       0.049
1, 0       0.842
0, 1       0.842
1, 1       0.844 <- WRONG!

These results have been predicted with a model of 1 hidden layer with 2 neurons, and the sigmoid function in both the hidden layer and in the output layer.

I have tried different amounts of testing data, epochs, dimensions in the hidden layers, and hidden layers, and nothing seems to work.

So, my question is if anyone has any idea why i get the wrong result in the XOR problem but not in the AND and the OR problems? And if so, how to fix it?


问:
Passing function from another class to this class
I know, title is hard to understand.

So, i have this class:

```<code>class ConfigDict(dict):

    def __init__(self, dic):
        super(ConfigDict, self).__init__(dic)

    def required(self, keys_array, function):
        print 'required'

    def valid(self, function = None):
        print 'valid'
</code>```

And what i want - i create instance of this class with dict as parameter:

```<code>ConfigDict({'a' : 'b'})
</code>```

It's working, thats good. But i want pass function as argument in dict from ConfigDict class without importing methods from ConfigDict.

For example, i want do this:

```<code> ConfigDict({'a' : ('b', required(['test'], valid))})
</code>```

I know that required in ConfigDict do nothing now. Expected result is:

```<code>>> ConfigDict({'a' : ('b', required(['test'], valid()))})
required called with ['test'], valid for {a : b}
valid called from required with None for {a : b}
</code>```

So, after creating instance of ConfigDict with {'a' : ('b', required['test'], valid())} dict, i want that this instance in __init__ method make loop in all dict elements, and if founds tuple in value, execute founded nested function in itselfs.

Is here any way to do this without importing all methods from ConfigDict?

EDIT:

As i expected i must better explain what i need.

Ok, we take this fragment:

```<code>ConfigDict({'a' : ('b', required(['test'], valid))})
</code>```

This made us new instance of ConfigDict. These functions in touple is used to validate value, in this case it is 'b'. I made few changes waiting for response, so calling this class is now look that:

```<code>cd = ConfigDict()
cd.feed({'a' : 'b'})
</code>```

I can call functions like that:

```<code>cd.feed({'a' : ('b', cg.required(['test']))})
</code>```

What is work's very well, but there's one thing - it not pass to required function the value. ConfigDicts.required should get an array and value, in this case 'b'. I don't expect to find way to do this myself, except using everywhere lambda's what i like to avoid.

So, my question been bit changed - is there a any way to get 'b' value from inside required function? I can pass 'b' as argument directly into required, but i expect to have many functions call in tuple, passing value for each make a little mess in code.

Also, anyone please, edit title of my post, i lack of words to describe this problem :)

答: This is a cop-out, but you're really flexing here to write something that'd probably be much better accomplished (better understood, fewer subtle bugs) by a Domain Specific Language.</p>

Body:
I know, title is hard to understand.

So, i have this class:

class ConfigDict(dict):

    def __init__(self, dic):
        super(ConfigDict, self).__init__(dic)

    def required(self, keys_array, function):
        print 'required'

    def valid(self, function = None):
        print 'valid'

And what i want - i create instance of this class with dict as parameter:

ConfigDict({'a' : 'b'})

It's working, thats good. But i want pass function as argument in dict from ConfigDict class without importing methods from ConfigDict.

For example, i want do this:

 ConfigDict({'a' : ('b', required(['test'], valid))})

I know that required in ConfigDict do nothing now. Expected result is:

>> ConfigDict({'a' : ('b', required(['test'], valid()))})
required called with ['test'], valid for {a : b}
valid called from required with None for {a : b}

So, after creating instance of ConfigDict with {'a' : ('b', required['test'], valid())} dict, i want that this instance in __init__ method make loop in all dict elements, and if founds tuple in value, execute founded nested function in itselfs.

Is here any way to do this without importing all methods from ConfigDict?

EDIT:

As i expected i must better explain what i need.

Ok, we take this fragment:

ConfigDict({'a' : ('b', required(['test'], valid))})

This made us new instance of ConfigDict. These functions in touple is used to validate value, in this case it is 'b'. I made few changes waiting for response, so calling this class is now look that:

cd = ConfigDict()
cd.feed({'a' : 'b'})

I can call functions like that:

cd.feed({'a' : ('b', cg.required(['test']))})

What is work's very well, but there's one thing - it not pass to required function the value. ConfigDicts.required should get an array and value, in this case 'b'. I don't expect to find way to do this myself, except using everywhere lambda's what i like to avoid.

So, my question been bit changed - is there a any way to get 'b' value from inside required function? I can pass 'b' as argument directly into required, but i expect to have many functions call in tuple, passing value for each make a little mess in code.

Also, anyone please, edit title of my post, i lack of words to describe this problem :)


问:
set view height as matchparent programmatically in kotlin
I need to set programatically the height of a button as matchparent  in my constraintLayout class.

```<code>open class Myword @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
     ) : ConstraintLayout(context,attrs) {

    var set = ConstraintSet()
    val tastoetim= Button(this.context)
    init{
        this.addView(tastoetim)
        tastoetim.requestLayout()

        set.connect(tastoetim.id, ConstraintSet.LEFT,this.id, ConstraintSet.LEFT, 10)
        set.connect(tastoetim.id, ConstraintSet.BOTTOM,this.id, ConstraintSet.BOTTOM, 0)

        tastoetim.minHeight = 0
        tastoetim.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT

    } }

</code>```

this does not work.

As already pointed out by author of this post (set height of imageview as matchparent programmatically), none of these answers works.

答:
From the documentation for ConstraintLayout:

Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".

In my experience, using MATCH_PARENT can have some odd results.

In your case, you will want to do something like the following:

```<code>open class Myword @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {

    init {
        val tastoetim = Button(this.context)
        // The new Button needs an id, otherwise, it is "NO_ID" (-1)
        tastoetim.id = View.generateViewId()
        val lp = ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.WRAP_CONTENT,
            ConstraintLayout.LayoutParams.MATCH_CONSTRAINT
        )
        this.addView(tastoetim, lp)

        // Get the ConstraintSet only after the view is added.
        val set = ConstraintSet()
        set.clone(this)

        set.connect(
            tastoetim.id,
            ConstraintSet.LEFT,
            ConstraintSet.PARENT_ID,
            ConstraintSet.LEFT,
            10
        )

        // For match constraints, we need a top and a bottom view to connect to. Here the
        // parent top is assumed, but it could be another view.
        set.connect(
            tastoetim.id,
            ConstraintSet.TOP,
            ConstraintSet.PARENT_ID,
            ConstraintSet.TOP,
            0
        )
        set.connect(
            tastoetim.id,
            ConstraintSet.BOTTOM,
            ConstraintSet.PARENT_ID,
            ConstraintSet.BOTTOM,
            0
        )

        // Apply the updated ConstraintSet back to the ConstraintLayout.
        set.applyTo(this)
    }
}
</code>```

Body:
I need to set programatically the height of a button as matchparent  in my constraintLayout class.

open class Myword @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
     ) : ConstraintLayout(context,attrs) {

    var set = ConstraintSet()
    val tastoetim= Button(this.context)
    init{
        this.addView(tastoetim)
        tastoetim.requestLayout()

        set.connect(tastoetim.id, ConstraintSet.LEFT,this.id, ConstraintSet.LEFT, 10)
        set.connect(tastoetim.id, ConstraintSet.BOTTOM,this.id, ConstraintSet.BOTTOM, 0)

        tastoetim.minHeight = 0
        tastoetim.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT

    } }

this does not work.

As already pointed out by author of this post (set height of imageview as matchparent programmatically), none of these answers works.

Body:
From the documentation for ConstraintLayout:

Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".

In my experience, using MATCH_PARENT can have some odd results.

In your case, you will want to do something like the following:

open class Myword @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {

    init {
        val tastoetim = Button(this.context)
        // The new Button needs an id, otherwise, it is "NO_ID" (-1)
        tastoetim.id = View.generateViewId()
        val lp = ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.WRAP_CONTENT,
            ConstraintLayout.LayoutParams.MATCH_CONSTRAINT
        )
        this.addView(tastoetim, lp)

        // Get the ConstraintSet only after the view is added.
        val set = ConstraintSet()
        set.clone(this)

        set.connect(
            tastoetim.id,
            ConstraintSet.LEFT,
            ConstraintSet.PARENT_ID,
            ConstraintSet.LEFT,
            10
        )

        // For match constraints, we need a top and a bottom view to connect to. Here the
        // parent top is assumed, but it could be another view.
        set.connect(
            tastoetim.id,
            ConstraintSet.TOP,
            ConstraintSet.PARENT_ID,
            ConstraintSet.TOP,
            0
        )
        set.connect(
            tastoetim.id,
            ConstraintSet.BOTTOM,
            ConstraintSet.PARENT_ID,
            ConstraintSet.BOTTOM,
            0
        )

        // Apply the updated ConstraintSet back to the ConstraintLayout.
        set.applyTo(this)
    }
}


问:
ValueError: Input contains NaN, infinity or a value too large for dtype('float64') using LinearRegression
I am practicing machine learning in python. I am stuck on an obstacle but I am having difficulties. The data set I am using is titanic.csv. I am trying to calculate the Age column missing values using Linear Regression.

```<code>training = dftrain[['Age','SibSp','Parch','Fare','Pclass','Sex_female',
                'Sex_male','Embarked_C','Embarked_Q','Embarked_S']]
testing  = dftest[['Age','SibSp','Parch','Fare','Pclass','Sex_female',
               'Sex_male','Embarked_C','Embarked_Q','Embarked_S']]
unify = pd.concat([training, testing])
train = unify[unify['Age'].notnull()]
clf = LinearRegression()
#clf.fit(train.drop(['Age'],axis = 1), train['Age'])
pd.set_option('display.max_rows',None )
train
</code>```

I have manually tried to fix the error by doing,

```<code>train[train['Age'].isnull()]
</code>```

using the above code I getting columns with no values indicating that there are no NaN values. I did this for all the columns. I also checked using,

```<code>train.notnull().count()
Age           1046
SibSp         1046
Parch         1046
Fare          1046
Pclass        1046
Sex_female    1046
Sex_male      1046
Embarked_C    1046
Embarked_Q    1046
Embarked_S    1046
dtype: int64
</code>```

but whenever I think everything is good to go and I uncomment the clf.fit() function I get the error

```<code>ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
</code>```

Please help I can't figure out what is wrong in my code.

答:
I got the same error because my data (in a couple of the columns) contained some non-numeric values. Once I did some datawrangling (replaced null values with the mean of that column), then it worked fine.

```<code>mean=df['bedrooms'].mean()
df['bedrooms'].replace(np.nan,mean, inplace=True)
</code>```

then

```<code>features =["floors" ,"bedrooms" ,"sqft" ,"bathrooms"]
X = df[features]
Y = df['price']
lm = LinearRegression()
lm.fit(X,Y)
lm.score(X, Y)
</code>```

Body:
I am practicing machine learning in python. I am stuck on an obstacle but I am having difficulties. The data set I am using is titanic.csv. I am trying to calculate the Age column missing values using Linear Regression.

training = dftrain[['Age','SibSp','Parch','Fare','Pclass','Sex_female',
                'Sex_male','Embarked_C','Embarked_Q','Embarked_S']]
testing  = dftest[['Age','SibSp','Parch','Fare','Pclass','Sex_female',
               'Sex_male','Embarked_C','Embarked_Q','Embarked_S']]
unify = pd.concat([training, testing])
train = unify[unify['Age'].notnull()]
clf = LinearRegression()
#clf.fit(train.drop(['Age'],axis = 1), train['Age'])
pd.set_option('display.max_rows',None )
train

I have manually tried to fix the error by doing,

train[train['Age'].isnull()]

using the above code I getting columns with no values indicating that there are no NaN values. I did this for all the columns. I also checked using,

train.notnull().count()
Age           1046
SibSp         1046
Parch         1046
Fare          1046
Pclass        1046
Sex_female    1046
Sex_male      1046
Embarked_C    1046
Embarked_Q    1046
Embarked_S    1046
dtype: int64

but whenever I think everything is good to go and I uncomment the clf.fit() function I get the error

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

Please help I can't figure out what is wrong in my code.

Body:
I got the same error because my data (in a couple of the columns) contained some non-numeric values. Once I did some datawrangling (replaced null values with the mean of that column), then it worked fine.

mean=df['bedrooms'].mean()
df['bedrooms'].replace(np.nan,mean, inplace=True)

then

features =["floors" ,"bedrooms" ,"sqft" ,"bathrooms"]
X = df[features]
Y = df['price']
lm = LinearRegression()
lm.fit(X,Y)
lm.score(X, Y)


问:
Failing to run external Bash program — /usr/bin/bash: bad interpreter: No such file or directory
I'm trying to run a CLI tool in Linux (Mint) which allows me to edit subtitles. It is named subedit: github link. In order to run it, I've added executable permission with chmod +x and added it to the path in bash. However, when I run it, I get the following error message:

```<code>bash: /home/main/Documents/shellTools/subedit/subedit: /usr/bin/bash: bad interpreter: No such file or directory
</code>```

I'm not very experienced with external bash programs and forgot to do something that would be obvious in hindsight.

When I do echo $PATH this is the output:

```<code>/home/main/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/main/Documents/shellTools/subedit/
</code>```

Could somebody please help?

答:
Assuming bash is installed, (it usually is), change the first line of subedit from:

```<code>#!/usr/bin/bash
</code>```

to:

```<code>#!/bin/bash
</code>```

Or if one would prefer not to edit subedit, try this one-liner covering what Al-waleed Shihadeh suggested:

```<code>ln -s "$(which bash)" /usr/bin/bash
</code>```

Body:
I'm trying to run a CLI tool in Linux (Mint) which allows me to edit subtitles. It is named subedit: github link. In order to run it, I've added executable permission with chmod +x and added it to the path in bash. However, when I run it, I get the following error message:

bash: /home/main/Documents/shellTools/subedit/subedit: /usr/bin/bash: bad interpreter: No such file or directory

I'm not very experienced with external bash programs and forgot to do something that would be obvious in hindsight.

When I do echo $PATH this is the output:

/home/main/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/main/Documents/shellTools/subedit/

Could somebody please help?

Body:
Assuming bash is installed, (it usually is), change the first line of subedit from:

#!/usr/bin/bash

to:

#!/bin/bash

Or if one would prefer not to edit subedit, try this one-liner covering what Al-waleed Shihadeh suggested:

ln -s "$(which bash)" /usr/bin/bash


问:
Nested for loop in nodejs seems to be running asynchronously
So I have two for loops, and one is nested inside another but the results they return seem to be running the first loop and returning its results than the nested loop. How could I make it run in a synchronous behavior?
For example, all the topicData gets printed in a row instead of printing one topicData and moving on to the nested for loop.
I'm not sure if this is the proper way to implement the async await. Any pointers would be appreciated. Thanks</p>

```<code>exports.create = (event, context, callback) => {

  var topicTimestamp = "";
  var endpoint = "";

  sns.listTopics(async function(err, data) {
    if (err) {
      console.log(err, err.stack);
    } else {
      console.log(data);
      for (var topic in data.Topics){ //first loop
        //var topicData = "";
        //retrieve each topic and append to topicList if it is lakeview topic
        var topicData =  await data.Topics[topic].TopicArn;
        topicTimestamp = topicData.slice(22, 34); //get only the topic createdAt

        var params = {
          TopicArn: topicData //topicData
        };
        console.log("SUBS per" + params.TopicArn);

        //retrieve subscriptions attached to each topic
        sns.listSubscriptionsByTopic(params, async function(err, subscriptionData){
          console.log(subscriptionData);
          //console.log("SUBS per" + params.TopicArn);
          if (err) {
            console.log(err, err.stack); // an error occurred
          } else  {
            var endpointList = [];
            for (var sub in subscriptionData.Subscriptions) { //nested loop

              endpoint = await subscriptionData.Subscriptions[sub].Endpoint;

              console.log("ENDPOINT:: " + endpoint);
              endpointList.push(endpoint);
            }
          } // end of else listSub

          //put topic info into table
          var topicsParams = {
            TableName: tableName,
            Item: {
              id: uuidv4(),
              createdAt: timestamp,
              topicCreatedAt: topicTimestamp,
              topic: topicData,
              phoneNumbers: endpointList
            },
          };

          endpointList = [];  //reset to empty array

          dynamoDb.put(topicsParams, (error) => {...}
</code>```

答:
There are couple of issues here

You are trying to do callback style code in loops while you have promise methods available.

You could also do things in parallel using promise.all

Because of callback style the code is very complicated

You are awaiting where it is not required. For example in the callback

You can try to use this way

```<code>exports.create = async (event, context, callback) => {

  try {
    let topicTimestamp = "";
    let endpoint = "";
    const data = await sns.listTopics().promise();
    // eslint-disable-next-line guard-for-in
    for (const topic in data.Topics) { // first loop
    // var topicData = "";
    // retrieve each topic and append to topicList if it is lakeview topic
      const topicData = data.Topics[topic].TopicArn;
      topicTimestamp = topicData.slice(22, 34); // get only the topic createdAt

      const params = {
        "TopicArn": topicData // topicData
      };
      console.log(`SUBS per${ params.TopicArn}`);

      const subscriptionData = await sns.listSubscriptionsByTopic(params).promise();
      const endpointList = [];
      // eslint-disable-next-line guard-for-in
      for (const sub in subscriptionData.Subscriptions) { // nested loop
        endpoint = subscriptionData.Subscriptions[sub].Endpoint;
        console.log(`ENDPOINT:: ${ endpoint}`);
        endpointList.push(endpoint);
      }

      // put topic info into table
      const topicsParams = {
        "TableName": tableName,
        "Item": {
          "id": uuidv4(),
          "createdAt": timestamp,
          "topicCreatedAt": topicTimestamp,
          "topic": topicData,
          "phoneNumbers": endpointList
        }
      };

      // Similarly use dynamodb .promise functions here
    }
  } catch (Err) {
    console.log(Err);
  }
};

</code>```

aws-sdk by default supports callback style. To convert them to promise you need to add .promise() at end.

At the moment this example is using for loop but you could do the same thing using Promise.all as well.

Hope this helps.

Body:
So I have two for loops, and one is nested inside another but the results they return seem to be running the first loop and returning its results than the nested loop. How could I make it run in a synchronous behavior?
For example, all the topicData gets printed in a row instead of printing one topicData and moving on to the nested for loop.
I'm not sure if this is the proper way to implement the async await. Any pointers would be appreciated. Thanks

exports.create = (event, context, callback) => {

  var topicTimestamp = "";
  var endpoint = "";

  sns.listTopics(async function(err, data) {
    if (err) {
      console.log(err, err.stack);
    } else {
      console.log(data);
      for (var topic in data.Topics){ //first loop
        //var topicData = "";
        //retrieve each topic and append to topicList if it is lakeview topic
        var topicData =  await data.Topics[topic].TopicArn;
        topicTimestamp = topicData.slice(22, 34); //get only the topic createdAt

        var params = {
          TopicArn: topicData //topicData
        };
        console.log("SUBS per" + params.TopicArn);

        //retrieve subscriptions attached to each topic
        sns.listSubscriptionsByTopic(params, async function(err, subscriptionData){
          console.log(subscriptionData);
          //console.log("SUBS per" + params.TopicArn);
          if (err) {
            console.log(err, err.stack); // an error occurred
          } else  {
            var endpointList = [];
            for (var sub in subscriptionData.Subscriptions) { //nested loop

              endpoint = await subscriptionData.Subscriptions[sub].Endpoint;

              console.log("ENDPOINT:: " + endpoint);
              endpointList.push(endpoint);
            }
          } // end of else listSub

          //put topic info into table
          var topicsParams = {
            TableName: tableName,
            Item: {
              id: uuidv4(),
              createdAt: timestamp,
              topicCreatedAt: topicTimestamp,
              topic: topicData,
              phoneNumbers: endpointList
            },
          };

          endpointList = [];  //reset to empty array

          dynamoDb.put(topicsParams, (error) => {...}

Body:
There are couple of issues here

You are trying to do callback style code in loops while you have promise methods available.

You could also do things in parallel using promise.all

Because of callback style the code is very complicated

You are awaiting where it is not required. For example in the callback

You can try to use this way

exports.create = async (event, context, callback) => {

  try {
    let topicTimestamp = "";
    let endpoint = "";
    const data = await sns.listTopics().promise();
    // eslint-disable-next-line guard-for-in
    for (const topic in data.Topics) { // first loop
    // var topicData = "";
    // retrieve each topic and append to topicList if it is lakeview topic
      const topicData = data.Topics[topic].TopicArn;
      topicTimestamp = topicData.slice(22, 34); // get only the topic createdAt

      const params = {
        "TopicArn": topicData // topicData
      };
      console.log(`SUBS per${ params.TopicArn}`);

      const subscriptionData = await sns.listSubscriptionsByTopic(params).promise();
      const endpointList = [];
      // eslint-disable-next-line guard-for-in
      for (const sub in subscriptionData.Subscriptions) { // nested loop
        endpoint = subscriptionData.Subscriptions[sub].Endpoint;
        console.log(`ENDPOINT:: ${ endpoint}`);
        endpointList.push(endpoint);
      }

      // put topic info into table
      const topicsParams = {
        "TableName": tableName,
        "Item": {
          "id": uuidv4(),
          "createdAt": timestamp,
          "topicCreatedAt": topicTimestamp,
          "topic": topicData,
          "phoneNumbers": endpointList
        }
      };

      // Similarly use dynamodb .promise functions here
    }
  } catch (Err) {
    console.log(Err);
  }
};

aws-sdk by default supports callback style. To convert them to promise you need to add .promise() at end.

At the moment this example is using for loop but you could do the same thing using Promise.all as well.

Hope this helps.


问:
Is it possible to create an object on a background thread with no reference on the main thread?
Equities trading application uses a class library for getting callbacks on stock quote updates, another class library for getting callbacks on order executions or cancelations. I currently have the callbacks execute in the thread pool. I start one background thread for each callback. The threads are very short lived and the work involved includes fetching the data and notifying the observers. Once observers are notified the background thread dies. When I have strategies subscribing to over 1000 actively traded symbols I get OutOfMemory exceptions.

How can I improve this design? I was thinking of starting two threads at the start, one for quotes, the other for executions, and creating each object on its respective threads. Then just have a shared object which allows adding and removing observers to the threads. But 1) how would you keep the thread alive to receive the callbacks? 2) How can you even have a callback object which is initialized on a thread with no reference on the main thread? Is this even possible?

Any help would be appreciated.

答:
To me

I currently have the callbacks execute in the thread pool

and

Once observers are notified the background thread dies

are mildly contradictory. I suspect you might be intending to use threads from a pool, but accidentally using new 'free' (unpooled) threads each time.

You might want to look at the documentation for WeakReference.

However, I suggest you use a profiler/perfmon to find the resource leak first and foremost. Replacing the whole shebang with a queuing approach sounds reasonable, but it's pretty close to what you'd have anyway with a proper threadpool.


问:
Custom Number Format from UserForm
I've got a text box in a user form where the user puts unit (for example "kg"). I am trying to use this unit to format number of a cell (to add the unit after the value in a cell)

```<code>Sub Custom_unit()

Dim Cust_un As String

Cust_un = IM_Form1.TextBox1.Value
Selection.NumberFormat = "0" & Cust_un

End Sub
</code>```

This is my attempt but when I try to run it, I get a Run-time error '1004': Unable to set the NumberFormat property of the Range class.

答:
How to add quotes to NumberFormat

Given an input from a textbox, you get a string value, e.g. "kg".
In order to use that as a NumberFormat suffix
you need to enclose the unit string with quotes.

You could do that by assigning

```<code>Selection.NumberFormat = "0" & """" & Cust_un & """"
</code>```

or alternatively

```<code>Selection.NumberFormat = "0" & Chr(34) & Cust_un & Chr(34)
</code>```

Note that VBA can neither interprete a single quote (") as string,
nor a single quote enclosed by a start and end quote (""").
Yyou have to include a pair of quotes within the surrounding quotes instead, i.e. """" to make it understood.
The alternative uses the Chr() function
returning a string containing the character associated with the specified character code 34, i.e. the double quote character.

You might prefer to use a help function to return the correct NumberFormat, such as

```<code>Function getNumberFormat(ByVal unit As String, Optional NumFmt As String = "0 ") As String
    unit = Replace(unit, Chr(34), vbNullString)         ' remove existing double quotes
    getNumberFormat = NumFmt & Chr(34) & unit & Chr(34) ' build NumberFormat including quotes around unit
    ' or: getNumberFormat = NumFmt & """" & unit & """"
End Function
</code>```

Example call

Assuming your Custom_unit() procedure resides in the UserForm code module use Me.TextBox1.Text to refer to the current UserForm instance instead of referring to the default instance of the userform. An example call could be as follows:

```<code>Sub Custom_unit()
    Selection.NumberFormat = getNumberFormat(Me.TextBox1.Text)
End Sub
</code>```

BTW a hint: in most cases it's better to avoid selection references, c.f. How to avoid using Select in VBA?

Title: Custom Number Format from UserForm

Body:
I've got a text box in a user form where the user puts unit (for example "kg"). I am trying to use this unit to format number of a cell (to add the unit after the value in a cell)

Sub Custom_unit()

Dim Cust_un As String

Cust_un = IM_Form1.TextBox1.Value
Selection.NumberFormat = "0" & Cust_un

End Sub

This is my attempt but when I try to run it, I get a Run-time error '1004': Unable to set the NumberFormat property of the Range class.

Body:
How to add quotes to NumberFormat

Given an input from a textbox, you get a string value, e.g. "kg".
In order to use that as a NumberFormat suffix
you need to enclose the unit string with quotes.

You could do that by assigning

Selection.NumberFormat = "0" & """" & Cust_un & """"

or alternatively

Selection.NumberFormat = "0" & Chr(34) & Cust_un & Chr(34)

Note that VBA can neither interprete a single quote (") as string,
nor a single quote enclosed by a start and end quote (""").
Yyou have to include a pair of quotes within the surrounding quotes instead, i.e. """" to make it understood.
The alternative uses the Chr() function
returning a string containing the character associated with the specified character code 34, i.e. the double quote character.

You might prefer to use a help function to return the correct NumberFormat, such as

Function getNumberFormat(ByVal unit As String, Optional NumFmt As String = "0 ") As String
    unit = Replace(unit, Chr(34), vbNullString)         ' remove existing double quotes
    getNumberFormat = NumFmt & Chr(34) & unit & Chr(34) ' build NumberFormat including quotes around unit
    ' or: getNumberFormat = NumFmt & """" & unit & """"
End Function

Example call

Assuming your Custom_unit() procedure resides in the UserForm code module use Me.TextBox1.Text to refer to the current UserForm instance instead of referring to the default instance of the userform. An example call could be as follows:

Sub Custom_unit()
    Selection.NumberFormat = getNumberFormat(Me.TextBox1.Text)
End Sub

BTW a hint: in most cases it's better to avoid selection references, c.f. How to avoid using Select in VBA?


问:
How do I display image in Alert/confirm box in Javascript?
How to display image in alert box or confirm box? I have been trying with below code but getting image url in the alert box. Please anybody help me to get solve or please give any other suggestions if it does not possible.</p>

```<code>var image = document.getElementById("myImage").src="hackanm.gif";
alert("OnLoad image"+image );
</code>```

答:
I created a function that might help. All it does is imitate the alert but put an image instead of text.

```<code>function alertImage(imgsrc) {
$('.d').css({
    'position': 'absolute',
    'top': '0',
    'left': '50%',
    '-webkit-transform': 'translate(-50%, 0)'
});
$('.d').animate({
    opacity: 0
}, 0)
$('.d').animate({
    opacity: 1,
    top: "10px"
}, 250)
$('.d').append('An embedded page on this page says')
$('.d').append('<br><img src="' + imgsrc + '">')
$('.b').css({
  'position':'absolute',
  '-webkit-transform': 'translate(-100%, -100%)',
  'top':'100%',
  'left':'100%',
  'display':'inline',
  'background-color':'#598cbd',
  'border-radius':'4px',
  'color':'white',
  'border':'none',
  'width':'66',
  'height':'33'
})
}
</code>```

<button onclick="$('.d').html('')" class="b">OK</button>

```

<pre class="lang-css prettyprint-override"><code>.d{
font-size: 17px;
  font-family: sans-serif;
}
.b{
  display: none;
}
</code>```

Body:
How to display image in alert box or confirm box? I have been trying with below code but getting image url in the alert box. Please anybody help me to get solve or please give any other suggestions if it does not possible.

var image = document.getElementById("myImage").src="hackanm.gif";
alert("OnLoad image"+image );

Body:
I created a function that might help. All it does is imitate the alert but put an image instead of text.

function alertImage(imgsrc) {
$('.d').css({
    'position': 'absolute',
    'top': '0',
    'left': '50%',
    '-webkit-transform': 'translate(-50%, 0)'
});
$('.d').animate({
    opacity: 0
}, 0)
$('.d').animate({
    opacity: 1,
    top: "10px"
}, 250)
$('.d').append('An embedded page on this page says')
$('.d').append('<br><img src="' + imgsrc + '">')
$('.b').css({
  'position':'absolute',
  '-webkit-transform': 'translate(-100%, -100%)',
  'top':'100%',
  'left':'100%',
  'display':'inline',
  'background-color':'#598cbd',
  'border-radius':'4px',
  'color':'white',
  'border':'none',
  'width':'66',
  'height':'33'
})
}

<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<div class="d"><button onclick="$('.d').html('')" class="b">OK</button></div>

.d{
font-size: 17px;
  font-family: sans-serif;
}
.b{
  display: none;
}


问:
Can you add multiple values to a string?
```<code>
foreach(Feed('example.url') as $f ) {
                        if (strpos($f->title, $title) !== false) {
                            $closed_text    = 'closed';
                            $maintenance_text = 'Maintenance';
                            $exception_text = 'could be';

                            if (strpos($f->title, $title) !== false){

                                if(strpos($f->description, $closed_text) !== false){
                                    echo (strpos($f->description, $exception_text) === false) ?
                                        '<span>Closed</span>' :
                                        '<span>Open</span>' ;

                                } else if(strpos($f->description, $maintenance_text) !== false){
                                    echo (strpos($f->description, $exception_text) === false) ?
                                         '<span>Maintenance</span>' :
                                         '<span>Open</span>' ;

                                } else {
                                    echo '<span>Open</span>';
                                }
                            }
                        }
                    }
</code>```

I want to assign more possible values to $exception_text.

Example:

$exception_text = 'could be' and 'maybe' and 'possibly'; So if one of these word is in the text the if statement is true.

Any help is greatly appreciated!

答:
Consider using regex is more appropriate for your case :

```<code>$exception_text = '(could be|maybe|possibly)';

if (\preg_match($exception_text, $f->description)) {
    // your stuff
}
</code>```

With regex you can search multiple pattern in your string.

Body:
foreach(Feed('example.url') as $f ) {
                        if (strpos($f->title, $title) !== false) {
                            $closed_text    = 'closed';
                            $maintenance_text = 'Maintenance';
                            $exception_text = 'could be';

                            if (strpos($f->title, $title) !== false){

                                if(strpos($f->description, $closed_text) !== false){
                                    echo (strpos($f->description, $exception_text) === false) ?
                                        'Closed' :
                                        'Open' ;

                                } else if(strpos($f->description, $maintenance_text) !== false){
                                    echo (strpos($f->description, $exception_text) === false) ?
                                         'Maintenance' :
                                         'Open' ;

                                } else {
                                    echo 'Open';
                                }
                            }
                        }
                    }

I want to assign more possible values to $exception_text.

Example:

$exception_text = 'could be' and 'maybe' and 'possibly'; So if one of these word is in the text the if statement is true.

Any help is greatly appreciated!

Body:
Consider using regex is more appropriate for your case :

$exception_text = '(could be|maybe|possibly)';

if (\preg_match($exception_text, $f->description)) {
    // your stuff
}

With regex you can search multiple pattern in your string.


问:
How to change colours of a group bar plot?
i am fairly new to R and I am having trouble changing the colours of a grouped bar plot. My code that I have inputted is the following:

```<code>library(plotly)
Samples <- c("1" , "2" , "P3")
D0 <- c(5.55, 5.605, 5.414)
D28 <- c(5.642, 1.658, 5.551)
data <- data.frame(Samples, D0, D28)
p <- plot_ly(data, x = ~Samples, y = ~D0, type = 'bar' , name = 'D0') %>%
  add_trace(y = ~D28, name = 'D28') %>%
  layout(yaxis = list(title = 'Concentration (mM)'), barmode = 'group')
p
</code>```

this is the resulting graph. i am interested in just changing the colour of the blue and the colour of the orange and to keep the same format they are coloured in (first bar plot=one colour and second bar plot=another colour). I have tried a different code but this results in all of them getting coloured with the same colour. Does anyone know which code to use to get what I want? Thanks in advance!

答:
You just need to specify the color for each separately, since you are calling D0 in plot_ly and D28 in add_trace.

plot_ly(data, x = ~Samples, y = ~D0, type = 'bar' , name = 'D0', color = I("black")) %>%
    add_trace(y = ~D28, name = 'D28', color = I("yellow")) %>%
    layout(yaxis = list(title = 'Concentration (mM)'), barmode = 'group')
```

Body:
i am fairly new to R and I am having trouble changing the colours of a grouped bar plot. My code that I have inputted is the following:

library(plotly)
Samples <- c("1" , "2" , "P3")
D0 <- c(5.55, 5.605, 5.414)
D28 <- c(5.642, 1.658, 5.551)
data <- data.frame(Samples, D0, D28)
p <- plot_ly(data, x = ~Samples, y = ~D0, type = 'bar' , name = 'D0') %>%
  add_trace(y = ~D28, name = 'D28') %>%
  layout(yaxis = list(title = 'Concentration (mM)'), barmode = 'group')
p

this is the resulting graph. i am interested in just changing the colour of the blue and the colour of the orange and to keep the same format they are coloured in (first bar plot=one colour and second bar plot=another colour). I have tried a different code but this results in all of them getting coloured with the same colour. Does anyone know which code to use to get what I want? Thanks in advance!


问:
My custom cursor doesnt work if I use the LiveServer port, but works using the html directory

html {
  cursor: url('C:/Users/Usuario/Documents/website/pinkCursor.cur'), auto;
}
```

Im using this to specify the cursor directory, it works if I use the same directory (file:///C:/Users/Usuario/Documents/website/website.html) on the browser, but if I try to use the LiveServer plugin, the cursor doesnt work, it uses the default cursor from windows.

This is using the directory on browser:

This is using the LiveServer plugin:

Error message:

答:
You should always use relative paths to your assets.

Try:

html {
  cursor: url('pinkCursor.cur'), auto;
}
```

This means the .cur file is in the same folder as the loaded page.

Body:
html {
  cursor: url('C:/Users/Usuario/Documents/website/pinkCursor.cur'), auto;
}

Im using this to specify the cursor directory, it works if I use the same directory (file:///C:/Users/Usuario/Documents/website/website.html) on the browser, but if I try to use the LiveServer plugin, the cursor doesnt work, it uses the default cursor from windows.

This is using the directory on browser:

This is using the LiveServer plugin:

Error message:

Body:
You should always use relative paths to your assets.

Try:

html {
  cursor: url('pinkCursor.cur'), auto;
}

This means the .cur file is in the same folder as the loaded page.


问:
Hiding a Div till clicked, and not hiding again once clicked again
So, once the button is clicked it reveals the information.

Which is great and what I need to be done, but say the user inputs some other information and wants to get a different set of information, it'll re-hide the info.

Hopefully that is enough context.

Basically I don't want the Jquery to run a second time. Just for the one click and not another..

Jquery:

```<code>$("#userSubmit").click(function() {
    $("#hidden").toggle();
});
</code>```

CSS:

```<code>#hidden {
  display: none;
}
</code>```

答:
```<code>   <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").toggle();
      });
    });
    </script>

<div>This is a paragraph.</div>
<button>hide() and show()</button>
</code>```

Body:
So, once the button is clicked it reveals the information.

Which is great and what I need to be done, but say the user inputs some other information and wants to get a different set of information, it'll re-hide the info.

Hopefully that is enough context.

Basically I don't want the Jquery to run a second time. Just for the one click and not another..

Jquery:

$("#userSubmit").click(function() {
    $("#hidden").toggle();
});

CSS:

#hidden {
  display: none;
}


问:
How to start a new Django project using poetry?
How to start a new Django project using poetry?

With virtualenv it is simple:

```<code>virtualenv -p python3 env_name --no-site-packages
source env_name/bin/activate
pip install django
django-admin.py startproject demo
pip freeze > requirements.txt
</code>```

What will be equivalent to this using Poetry?

答:
Create a new project folder and step in:

```<code>$ mkdir djangodemo
$ cd djangodemo
</code>```

Create a basic pyproject.toml with django as dependency:

```<code>$ poetry init --no-interaction --dependency django
</code>```

Create venv with all dependencies needed:

```<code>$ poetry install
</code>```

Init your demo-project

```<code>$ poetry run django-admin.py startproject djangodemo
</code>```

Body:
How to start a new Django project using poetry?

With virtualenv it is simple:

virtualenv -p python3 env_name --no-site-packages
source env_name/bin/activate
pip install django
django-admin.py startproject demo
pip freeze > requirements.txt

What will be equivalent to this using Poetry?

Body:
Create a new project folder and step in:

$ mkdir djangodemo
$ cd djangodemo

Create a basic pyproject.toml with django as dependency:

$ poetry init --no-interaction --dependency django

Create venv with all dependencies needed:

$ poetry install

Init your demo-project

$ poetry run django-admin.py startproject djangodemo


问:
Selecting lines between two marker patterns
How can I select lines which are occurring between two different marker patterns in a file using Tcl?

For example: Suppose the file contains:

```<code>abc
def1
ghi1
jkl1
mno
abc
def2
ghi2
jkl2
mno
pqr
stu
</code>```

And the starting pattern is abc and ending pattern is mno. So, I need the output as:

```<code>def1
ghi1
jkl1
def2
ghi2
jkl2
</code>```

答:
You just need a little state machine:</p>

```<code>      set inrange false
      while {[gets $fh line] != -1} {
          if {$inrange} {
              if {$line eq "mno"} {
                  set inrange false
              } else {
                  puts $line
              }
          } else {
              if {$line eq "abc"} {
                  set inrange true
              }
          }
      }
</code>```

Body:
How can I select lines which are occurring between two different marker patterns in a file using Tcl?

For example: Suppose the file contains:

abc
def1
ghi1
jkl1
mno
abc
def2
ghi2
jkl2
mno
pqr
stu

And the starting pattern is abc and ending pattern is mno. So, I need the output as:

def1
ghi1
jkl1
def2
ghi2
jkl2

Body:
You just need a little state machine:

      set inrange false
      while {[gets $fh line] != -1} {
          if {$inrange} {
              if {$line eq "mno"} {
                  set inrange false
              } else {
                  puts $line
              }
          } else {
              if {$line eq "abc"} {
                  set inrange true
              }
          }
      }


问:
Append text to product title on multiple pages in WooCommerce
I'm trying to append text to WooCommerce product title in the order meta - if products has a specific tag. I'm working from

"Append text to product title if product has product-tag on cart in WooCommerce"

"Display custom payment field in Woocommerce Admin, Orders and emails"

This is what I have so fare:

add_filter( 'woocommerce_get_order_item_totals', 'add_udstilling_below_cart_item_name', 10, 3 );
function add_udstilling_below_cart_item_name( $total_rows, $order, $tax_display ) {;

    $new_total_rows = [];

    foreach($total_rows as $key => $total ){
        $new_total_rows[$key] = $total;

        }
    }

    return $new_total_rows;
}
```

答:
Based on your previous question and this new question, I assume that you would like to see the product title adjusted 'everywhere'.

IMPORTANT!! You should definitely read the following post to
  understand that this is a general adjustment, so that you ultimately
  no longer need the code from your previous post / question

Changing WooCommerce cart item names

In other words, you can start using the code below to see the adjustment in the following places

Order-receive (Thank you) page,

email notifications

My Account Orders> Single order details

Cart & Checkout and Backend Order edit pages.

Now you have change the names everywhere except on Shop archives and product pages…

function add_udstilling_order_item_name( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get product id
        $product_id = $cart_item['product_id'];

        if( method_exists( $product, 'set_name' ) && has_term( 'udstillingsmodel', 'product_tag', $product_id ) ) {
            $product->set_name( $product->get_name() . '(test)' );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'add_udstilling_order_item_name', 10, 1 );
```


问:
Open directory windows with "Go to URL" in SSRS 2017
it is possible open a directory with "Go to URL" in SSRS 2017?
Im try this:

Image with im trying

field link have this information: "File://///192.168.1.2/Documentos/EMP/PV/"

Any help?

答:
Yes you can

Ensure your formatting for the filed that holds the directory information like this :

\\192.168.1.2\documentos\EMP\PV\