问:
How remove NAN from C++ vector?
I have

```<code>std::vector<double>x={1,2,NAN,3, NAN, 4}
</code>```

when I try x.erase(remove(x.begin(), x.end(), NAN), x.end(), I still see NAN as

```<code>for (auto i:x)
    std::cout<<i<<" ";
</code>```

gives

```<code>1 2 -nan(ind) 3 -nan(ind) 4
</code>```

how can I remove the NANs so the output is below?

```<code>1 2 3 4
</code>```

EDIT: x is a vector of doubles, not ints

答:
In the weird, wild world of IEEE 754 floating point, NaN != NaN. In other words, two not-a-number values do not compare as equal to each other. So, you cannot simply let std::remove do an equality test.

You need to supply your own predicate that calls a function to determine whether or not a floating-point value is NaN. If you're targeting C++11 or later, the standard library provides such a function: std::isnan. (If not, the situation is a bit more complicated.)

Putting it all together, then, the correct code would look like this:

```<code>#include <cmath>
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<double> x = {
                              1,
                              2,
                              std::numeric_limits<double>::quiet_NaN(),
                              3,
                              std::numeric_limits<double>::quiet_NaN(),
                              4
                            };

    std::cout << "Before removing: ";
    for (auto i : x)
    {
        std::cout << i << " ";
    }
    std::cout << "\n";

    x.erase(std::remove_if(std::begin(x),
                           std::end(x),
                           [](const auto& value) { return std::isnan(value); }),
            std::end(x));

    std::cout << "After removing: ";
    for (auto i : x)
    {
        std::cout << i << " ";
    }

    return 0;
}
</code>```

In case it got lost in all the demo code, the relevant part is just:

```<code>x.erase(std::remove_if(std::begin(x),
                       std::end(x),
                       [](const auto& value) { return std::isnan(value); }),
        std::end(x));
</code>```

where I am passing a lambda to std::remove_if as a unary predicate. It calls std::isnan, passing in the value to check, and it returns the result, which is a Boolean indicating whether or not the value is not-a-number. If the predicate returns true, std::remove_if does the removal; otherwise, it doesn't.

Note that the logic in floating-point world is typically that NaN values are infectious. In other words, any operation involving a NaN will return NaN as a result. So, it strikes me as a bit odd that you're trying to remove all NaN values. Be careful not to just shove them under the rug as if they weren't there.

Title: How remove NAN from C++ vector?

Body:
I have

std::vector<double>x={1,2,NAN,3, NAN, 4}

when I try x.erase(remove(x.begin(), x.end(), NAN), x.end(), I still see NAN as

for (auto i:x)
    std::cout<<i<<" ";

gives

1 2 -nan(ind) 3 -nan(ind) 4

how can I remove the NANs so the output is below?

1 2 3 4

EDIT: x is a vector of doubles, not ints

Body:
In the weird, wild world of IEEE 754 floating point, NaN != NaN. In other words, two not-a-number values do not compare as equal to each other. So, you cannot simply let std::remove do an equality test.

You need to supply your own predicate that calls a function to determine whether or not a floating-point value is NaN. If you're targeting C++11 or later, the standard library provides such a function: std::isnan. (If not, the situation is a bit more complicated.)

Putting it all together, then, the correct code would look like this:

#include <cmath>
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<double> x = {
                              1,
                              2,
                              std::numeric_limits<double>::quiet_NaN(),
                              3,
                              std::numeric_limits<double>::quiet_NaN(),
                              4
                            };

    std::cout << "Before removing: ";
    for (auto i : x)
    {
        std::cout << i << " ";
    }
    std::cout << "\n";

    x.erase(std::remove_if(std::begin(x),
                           std::end(x),
                           [](const auto& value) { return std::isnan(value); }),
            std::end(x));

    std::cout << "After removing: ";
    for (auto i : x)
    {
        std::cout << i << " ";
    }

    return 0;
}

In case it got lost in all the demo code, the relevant part is just:

x.erase(std::remove_if(std::begin(x),
                       std::end(x),
                       [](const auto& value) { return std::isnan(value); }),
        std::end(x));

where I am passing a lambda to std::remove_if as a unary predicate. It calls std::isnan, passing in the value to check, and it returns the result, which is a Boolean indicating whether or not the value is not-a-number. If the predicate returns true, std::remove_if does the removal; otherwise, it doesn't.

Note that the logic in floating-point world is typically that NaN values are infectious. In other words, any operation involving a NaN will return NaN as a result. So, it strikes me as a bit odd that you're trying to remove all NaN values. Be careful not to just shove them under the rug as if they weren't there.


来源: stackexchange

问:
How to run commands on a remote host with an existing user on that machine
I am writing a shell scripts that requires to run commands on multiple remote host based on condition it satisfies. how can i run the commands on the remote host using its key pair and assign the output of those commands to a variable on the primary host.

I tried using

```<code>sshpass -f keypair hostname 'command' | 'commands'
</code>```

but this command executed on the host itself.

答:
Use command substitution to assign the output of a command to a variable. You also need to run the ssh command and specify the remote username.

```<code>variable=$(sshpass -f keypair ssh username@hostname 'command')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing a shell scripts that requires to run commands on multiple remote host based on condition it satisfies. how can i run the commands on the remote host using its key pair and assign the output of those commands to a variable on the primary host.

I tried using

sshpass -f keypair hostname 'command' | 'commands'

but this command executed on the host itself.

Body:
Use command substitution to assign the output of a command to a variable. You also need to run the ssh command and specify the remote username.

variable=$(sshpass -f keypair ssh username@hostname 'command')


答:
This doesn't work, since NAN doesn't equal NAN (this is not specified by C++ standard, but in IEEE 754 standard, which your system probably conforms to). std::remove, uses equality as the condition to choose elements for removal.

Instead of std::remove, you need to use std::remove_if with a predicate using std::isnan.

Title: How remove NAN from C++ vector?


问:
Compare two dataframe columns in same dataframe and return text contained in first column
I have data loaded into a dataframe but cannot figure out how to compare the parsed data against the other column and return only matches.

This seems like it should be easy but I just don't see it. I've tried splitting the values out to compare but here's where I get stuck.

```<code>import pandas as pd

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

df['col1_split'] = df['col1'].str.split(';')
df['col2_split'] = df['col2'].str.split(';')

# output something like...
df['output'] = [null,';c1312;',';d1310;']

</code>```

I'd expect to see something like -

1st row - return null, as t9010 is not contained in col2_split

2nd row - return c1312, as it is in col2_split

3rd row - return d1310 but not c1512, as only d1310 is in col2_split

lastly, the final text should be returned semicolon delimited and with leading and trailing semicolons i.e. ;t9010; or ;c1312; or ;d1310;c1512; if there is more than one.

答:
We can use a nested list comprehension for this:

```<code>df['common'] = pd.Series([[sub for sub in left if sub in right] for left, right in zip(df['col1_split'], df['col2_split'])]).str.join(';')

print(df['common'])
</code>```

Output:

```<code>0          ;
1    ;c1312;
2    ;d1310;
Name: common, dtype: object
</code>```

Body:
I have data loaded into a dataframe but cannot figure out how to compare the parsed data against the other column and return only matches.

This seems like it should be easy but I just don't see it. I've tried splitting the values out to compare but here's where I get stuck.

import pandas as pd

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

df['col1_split'] = df['col1'].str.split(';')
df['col2_split'] = df['col2'].str.split(';')

# output something like...
df['output'] = [null,';c1312;',';d1310;']

I'd expect to see something like -

1st row - return null, as t9010 is not contained in col2_split

2nd row - return c1312, as it is in col2_split

3rd row - return d1310 but not c1512, as only d1310 is in col2_split

lastly, the final text should be returned semicolon delimited and with leading and trailing semicolons i.e. ;t9010; or ;c1312; or ;d1310;c1512; if there is more than one.

Body:
We can use a nested list comprehension for this:

df['common'] = pd.Series([[sub for sub in left if sub in right] for left, right in zip(df['col1_split'], df['col2_split'])]).str.join(';')

print(df['common'])

Output:

0          ;
1    ;c1312;
2    ;d1310;
Name: common, dtype: object


问:
Angular 7 Type 'void' is not assignable to type 'ObservableInput<{}>'
I can not figure it out why i got this error

```<code>  getByURL(url: string): any {
    return this.apiService.get(url).pipe(map(data => data));
  }

  getByNextPage(): Observable<any> {
    const url = 'url';
    this.getByURL(url).pipe(
      expand(data => {
        console.log(data);
      })
    );
  }
</code>```

I got this error at line that has expand(data => ... . I want to use expand() so i can recursive the call for the next api.

```<code>Type 'void' is not assignable to type 'ObservableInput<{}>'
</code>```

Any hint would be really appreciate. Thanks

答:
You need check data type of data variable and return data in your method.</p>

```<code>getByNextPage(): Observable<any> {
    const url = 'url';
    this.getByURL(url).pipe(
      expand(data => {
        console.log(data);
        return data;
      })
    );
  }
</code>```

Body:
I can not figure it out why i got this error

  getByURL(url: string): any {
    return this.apiService.get(url).pipe(map(data => data));
  }

  getByNextPage(): Observable<any> {
    const url = 'url';
    this.getByURL(url).pipe(
      expand(data => {
        console.log(data);
      })
    );
  }

I got this error at line that has expand(data => ... . I want to use expand() so i can recursive the call for the next api.

Type 'void' is not assignable to type 'ObservableInput<{}>'

Any hint would be really appreciate. Thanks

Body:
You need check data type of data variable and return data in your method.

getByNextPage(): Observable<any> {
    const url = 'url';
    this.getByURL(url).pipe(
      expand(data => {
        console.log(data);
        return data;
      })
    );
  }


问:
How to use this Huffman coding implementation?
I have found this Literate Haskell snippet implementing Huffman coding, but I don't understand how to use it. Some functions make sense to me—for example, I can write:

```<code>a = freqList "lol"
build list a
</code>```

But how can I compute the Huffman encoding of this string? The encode and encode' functions appear to take a Bits argument.

Here is the code from the Huffman coding implementation, minus the Literate Haskell comments:

```<code>module Huffman where

import Control.Arrow
import Data.List
import qualified Data.Map as M
import Data.Function

class Eq a => Bits a where
    zer :: a
    one :: a

instance Bits Int where
    zer = 0
    one = 1

instance Bits Bool where
    zer = False
    one = True

type Codemap a = M.Map Char [a]

data HTree  = Leaf Char Int
            | Fork HTree HTree Int
            deriving (Show)

weight :: HTree -> Int
weight (Leaf _ w)    = w
weight (Fork _ _ w)  = w

merge t1 t2 = Fork t1 t2 (weight t1 + weight t2)

freqList :: String -> [(Char, Int)]
freqList = M.toList . M.fromListWith (+) . map (flip (,) 1)

buildTree :: [(Char, Int)] -> HTree
buildTree = bld . map (uncurry Leaf) . sortBy (compare `on` snd)
    where  bld (t:[])    = t
           bld (a:b:cs)  = bld $ insertBy (compare `on` weight) (merge a b) cs

buildCodemap :: Bits a => HTree -> Codemap a
buildCodemap = M.fromList . buildCodelist
    where  buildCodelist (Leaf c w)    = [(c, [])]
           buildCodelist (Fork l r w)  = map (addBit zer) (buildCodelist l) ++ map (addBit one) (buildCodelist r)
             where addBit b = second (b :)

stringTree :: String -> HTree
stringTree = buildTree . freqList

stringCodemap :: Bits a => String -> Codemap a
stringCodemap = buildCodemap . stringTree

encode :: Bits a => Codemap a -> String -> [a]
encode m = concat . map (m M.!)

encode' :: Bits a => HTree -> String -> [a]
encode' t = encode $ buildCodemap t

decode :: Bits a => HTree -> [a] -> String
decode tree = dcd tree
    where  dcd (Leaf c _) []        = [c]
           dcd (Leaf c _) bs        = c : dcd tree bs
           dcd (Fork l r _) (b:bs)  = dcd (if b == zer then l else r) bs
</code>```

答:
The answer you looking for is</p>

```<code>myString = "Ho-ho-ho"
result = encode (stringCodemap myString) myString
</code>```

Body:
I have found this Literate Haskell snippet implementing Huffman coding, but I don't understand how to use it. Some functions make sense to me—for example, I can write:

a = freqList "lol"
build list a

But how can I compute the Huffman encoding of this string? The encode and encode' functions appear to take a Bits argument.

Here is the code from the Huffman coding implementation, minus the Literate Haskell comments:

module Huffman where

import Control.Arrow
import Data.List
import qualified Data.Map as M
import Data.Function

class Eq a => Bits a where
    zer :: a
    one :: a

instance Bits Int where
    zer = 0
    one = 1

instance Bits Bool where
    zer = False
    one = True

type Codemap a = M.Map Char [a]

data HTree  = Leaf Char Int
            | Fork HTree HTree Int
            deriving (Show)

weight :: HTree -> Int
weight (Leaf _ w)    = w
weight (Fork _ _ w)  = w

merge t1 t2 = Fork t1 t2 (weight t1 + weight t2)

freqList :: String -> [(Char, Int)]
freqList = M.toList . M.fromListWith (+) . map (flip (,) 1)

buildTree :: [(Char, Int)] -> HTree
buildTree = bld . map (uncurry Leaf) . sortBy (compare `on` snd)
    where  bld (t:[])    = t
           bld (a:b:cs)  = bld $ insertBy (compare `on` weight) (merge a b) cs

buildCodemap :: Bits a => HTree -> Codemap a
buildCodemap = M.fromList . buildCodelist
    where  buildCodelist (Leaf c w)    = [(c, [])]
           buildCodelist (Fork l r w)  = map (addBit zer) (buildCodelist l) ++ map (addBit one) (buildCodelist r)
             where addBit b = second (b :)

stringTree :: String -> HTree
stringTree = buildTree . freqList

stringCodemap :: Bits a => String -> Codemap a
stringCodemap = buildCodemap . stringTree

encode :: Bits a => Codemap a -> String -> [a]
encode m = concat . map (m M.!)

encode' :: Bits a => HTree -> String -> [a]
encode' t = encode $ buildCodemap t

decode :: Bits a => HTree -> [a] -> String
decode tree = dcd tree
    where  dcd (Leaf c _) []        = [c]
           dcd (Leaf c _) bs        = c : dcd tree bs
           dcd (Fork l r _) (b:bs)  = dcd (if b == zer then l else r) bs

Body:
The answer you looking for is

myString = "Ho-ho-ho"
result = encode (stringCodemap myString) myString


问:
SUM days to the DB date
When I try to add 30 days with the date obtained in the Database is giving this error.

```<code>DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date today = Calendar.getInstance().getTime();

String reportDate = df.format(today);

String endDay = rset.getString("vip_end");

endDay.add(Calendar.DAY_OF_MONTH, 30)
</code>```

Error

```<code>Error:(76, 70) java: cannot find symbol
  symbol:   method add(int,int)
  location: variable endDay of type java.lang.String
</code>```

答:
tl;dr

```<code>LocalDate                        // Represent a date-only value, without time-of-day and without time zone.
.now(                            // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).
    ZoneId.of( "Asia/Tokyo" )    // Specify your time zone. Use proper `Continent/Region` names, never 2-4 character pseudo-zones such as IST or PST or EST or CST.
)                                // Returns a `LocalDate` object.
.plusDays( 30 )                  // Add days to determine a later date. Returns a new `LocalDate` object rather than mutating the original.
.toString()                      // Generate text representing the value of this `LocalDate` object, in standard ISO 8601 format YYYY-MM-DD.
</code>```

2019-06-30

No add method on String

You declared endDay to be a String. Then you called the method add. But there is no method add on String class. Thus your error, as explained in the error message.

java.time

You are using terrible date-time classes that were supplanted years ago by the modern java.time classes with the adoption of JSR 310. Stop doing that.

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

Time zone

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
</code>```

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

```<code>ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.
</code>```

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

```<code>LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
</code>```

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.

```<code>LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
</code>```

Generating text

Your output format is in standard ISO 8601 format. This format is used by default in the LocalDate class for parsing/generating strings. So no need to specify a formatting pattern.

```<code>String output = LocalDate.of( 2019 , Month.JANUARY , 23 ).toString() ;
</code>```

2019-01-23

Date math

Add 30 days.

```<code>LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDate later = today.plusDays( 30 ) ;
</code>```

The java.time classes follow the immutable objects pattern. So they return a new fresh object based on the values of the original.

Title: SUM days to the DB date

Body:
When I try to add 30 days with the date obtained in the Database is giving this error.

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date today = Calendar.getInstance().getTime();

String reportDate = df.format(today);

String endDay = rset.getString("vip_end");

endDay.add(Calendar.DAY_OF_MONTH, 30)

Error

Error:(76, 70) java: cannot find symbol
  symbol:   method add(int,int)
  location: variable endDay of type java.lang.String

Body:
tl;dr

LocalDate                        // Represent a date-only value, without time-of-day and without time zone.
.now(                            // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).
    ZoneId.of( "Asia/Tokyo" )    // Specify your time zone. Use proper `Continent/Region` names, never 2-4 character pseudo-zones such as IST or PST or EST or CST.
)                                // Returns a `LocalDate` object.
.plusDays( 30 )                  // Add days to determine a later date. Returns a new `LocalDate` object rather than mutating the original.
.toString()                      // Generate text representing the value of this `LocalDate` object, in standard ISO 8601 format YYYY-MM-DD.

2019-06-30

No add method on String

You declared endDay to be a String. Then you called the method add. But there is no method add on String class. Thus your error, as explained in the error message.

java.time

You are using terrible date-time classes that were supplanted years ago by the modern java.time classes with the adoption of JSR 310. Stop doing that.

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

Time zone

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Generating text

Your output format is in standard ISO 8601 format. This format is used by default in the LocalDate class for parsing/generating strings. So no need to specify a formatting pattern.

String output = LocalDate.of( 2019 , Month.JANUARY , 23 ).toString() ;

2019-01-23

Date math

Add 30 days.

LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDate later = today.plusDays( 30 ) ;

The java.time classes follow the immutable objects pattern. So they return a new fresh object based on the values of the original.


问:
Functional map-like data structure with arbitrary length data as keys?
It could very well be that the answer to this question is an obvious and resounding "there's no such thing", but I'll give it a shot: Is there a functional map-like data structure that is more efficient than a standard map when the keys have an arbitrary, often very big, size?

For the sake of concreteness, consider the Haskell type

```<code>(Ord k) => Map [k] v
</code>```

in which lookups can take a very long time if lists need to be compared down to a deep level. I guess hashing is also out of the question due to the arbitrary length of the lists. I still can't help but think there could be a clever data structure out there.

答:
Is hashing out of the question? There's no prefix of the key structure that can be computed efficiently?

If not, how about a hashmap? Take the very big key, reduce it to something very small, use that as an index into a structure.

hashmap on Hackage.

Johan Tibbel's talk on hash tree structures

ContentLicense: CC BY-SA 3.0

Body:
It could very well be that the answer to this question is an obvious and resounding "there's no such thing", but I'll give it a shot: Is there a functional map-like data structure that is more efficient than a standard map when the keys have an arbitrary, often very big, size?

For the sake of concreteness, consider the Haskell type

(Ord k) => Map [k] v

in which lookups can take a very long time if lists need to be compared down to a deep level. I guess hashing is also out of the question due to the arbitrary length of the lists. I still can't help but think there could be a clever data structure out there.


问:
ModuleNotFoundError: No module named 'rest_framework'. How can I fix this error?
I am new to Django. I am using Ubuntu, Apache, and virtualenv. I am running Ubuntu on DigitalOcean. I am trying to use Django and React together. So I downloaded djangorestframework. But when I run the server, I encountered this problem.

```<code>(new_app) sot232@ubuntu:/var/www/html/django_app/commercial$ python3 manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
    raise _exception[0](_exception[1]).with_traceback(_exception[2])
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/home/sot232/new_app/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'rest_framework'
</code>```

I included rest_framework properly in the settings.py file.

```<code>INSTALLED_APPS = [
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'commercial',
]
</code>```

I tried these commands.

```<code>sudo pip3 install djangorestframework
sudo pip install djangorestframework
sudo pip install django-rest-swagger
sudo apt-get install python3-setuptools
</code>```

I also tried to install djangorestframework after sudo su.

(I tried other suggestions too. But I can't remember those.)

In addition, here's what I got on a python shell.

```<code>Python 3.7.3 (default, Apr  3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import rest_framework
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'rest_framework'
>>>
</code>```

Here is a dist-packages in case you need it.

```<code>(new_app) sot232@ubuntu:/usr/local/lib/python3.7/dist-packages$ ls
Django-2.2.1.dist-info               pytz-2019.1.dist-info
__pycache__                          rest_framework
corsheaders                          sqlparse
django                               sqlparse-0.3.0.dist-info
django_cors_headers-3.0.0.dist-info  virtualenv-16.5.0.dist-info
djangorestframework-3.9.4.dist-info  virtualenv.py
pytz                                 virtualenv_support
</code>```

How can I fix my problem?

Any help will be appreciated. I saw other posts on StackOverFlow that seem to be similar to mine, but nothing seemed to resolve my problem.

(Edit 1)

While the env is activated, I tried to run pip install djangorestframework, and I got this error message.

```<code>(new_app) sot232@ubuntu:~/new_app/bin$ pip install djangorestframework
Collecting djangorestframework
  Using cached https://files.pythonhosted.org/packages/1b/fe/fcebec2a98fbd1548da1c12ce8d7f634a02a9cce350833fa227a625ec624/djangorestframework-3.9.4-py2.py3-none-any.whl
Installing collected packages: djangorestframework
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/sot232/new_app/lib/python3.7/site-packages/djangorestframework-3.9.4.dist-info'
Consider using the `--user` option or check the permissions.
</code>```

(Edit 2)

I run pip freeze and pip3 freeze. I received this result.

```<code>sot232@ubuntu:~/new_app/bin$ source activate
(new_app) sot232@ubuntu:~/new_app/bin$ pip freeze
Django==2.2.1
mysqlclient==1.4.2.post1
pytz==2019.1
sqlparse==0.3.0
</code>```

It seems like rest_framework is not installed on my virtualenv. However, djangorestframework==3.9.4 is installed globally.

答: Everything I've tried failed. I simply created another virtualenv and reinstalled everything. Now, it is working like a charm.</p>

Body:
I am new to Django. I am using Ubuntu, Apache, and virtualenv. I am running Ubuntu on DigitalOcean. I am trying to use Django and React together. So I downloaded djangorestframework. But when I run the server, I encountered this problem.

(new_app) sot232@ubuntu:/var/www/html/django_app/commercial$ python3 manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
    raise _exception[0](_exception[1]).with_traceback(_exception[2])
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/home/sot232/new_app/lib/python3.7/site-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/home/sot232/new_app/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'rest_framework'

I included rest_framework properly in the settings.py file.

INSTALLED_APPS = [
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'commercial',
]

I tried these commands.

sudo pip3 install djangorestframework
sudo pip install djangorestframework
sudo pip install django-rest-swagger
sudo apt-get install python3-setuptools

I also tried to install djangorestframework after sudo su.

(I tried other suggestions too. But I can't remember those.)

In addition, here's what I got on a python shell.

Python 3.7.3 (default, Apr  3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import rest_framework
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'rest_framework'
>>>

Here is a dist-packages in case you need it.

(new_app) sot232@ubuntu:/usr/local/lib/python3.7/dist-packages$ ls
Django-2.2.1.dist-info               pytz-2019.1.dist-info
__pycache__                          rest_framework
corsheaders                          sqlparse
django                               sqlparse-0.3.0.dist-info
django_cors_headers-3.0.0.dist-info  virtualenv-16.5.0.dist-info
djangorestframework-3.9.4.dist-info  virtualenv.py
pytz                                 virtualenv_support

How can I fix my problem?

Any help will be appreciated. I saw other posts on StackOverFlow that seem to be similar to mine, but nothing seemed to resolve my problem.

(Edit 1)

While the env is activated, I tried to run pip install djangorestframework, and I got this error message.

(new_app) sot232@ubuntu:~/new_app/bin$ pip install djangorestframework
Collecting djangorestframework
  Using cached https://files.pythonhosted.org/packages/1b/fe/fcebec2a98fbd1548da1c12ce8d7f634a02a9cce350833fa227a625ec624/djangorestframework-3.9.4-py2.py3-none-any.whl
Installing collected packages: djangorestframework
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/sot232/new_app/lib/python3.7/site-packages/djangorestframework-3.9.4.dist-info'
Consider using the `--user` option or check the permissions.

(Edit 2)

I run pip freeze and pip3 freeze. I received this result.

sot232@ubuntu:~/new_app/bin$ source activate
(new_app) sot232@ubuntu:~/new_app/bin$ pip freeze
Django==2.2.1
mysqlclient==1.4.2.post1
pytz==2019.1
sqlparse==0.3.0

It seems like rest_framework is not installed on my virtualenv. However, djangorestframework==3.9.4 is installed globally.


问:
How can I check in powershell if Get-ChildItem has failed?
In my powershell script I have the following line:

```<code>$DirectoryInfo = Get-ChildItem $PathLog | Where-Object { $_.PSIsContainer }
</code>```

to read some data from the path given in the variable $PathLog. But I realizes that even if the Get-ChildItem command failed (for example, the given path in $PathLog does not exist), and an error is written to the shell, the script continues.

How can I check if this Get-ChildItem was successfull? I want to use it to trigger an if clause as follows which stops the script at that moment:

```<code>if (???) {
    "There was an error"
    return
}
</code>```

What to put into the brackets? How how to do it otherwise?

答:
Depending on what you're parsing and whether you're interested in the exception, this might help:

(Get-ChildItem Env:\MYENVKEY -ErrorAction SilentlyContinue).Value | %{ IF($null -eq $_) { $result="not found" } ELSE { $result=$_ } };

It'll try and get the value and safely handle if it's found or not.

Body:
In my powershell script I have the following line:

$DirectoryInfo = Get-ChildItem $PathLog | Where-Object { $_.PSIsContainer }

to read some data from the path given in the variable $PathLog. But I realizes that even if the Get-ChildItem command failed (for example, the given path in $PathLog does not exist), and an error is written to the shell, the script continues.

How can I check if this Get-ChildItem was successfull? I want to use it to trigger an if clause as follows which stops the script at that moment:

if (???) {
    "There was an error"
    return
}

What to put into the brackets? How how to do it otherwise?


问:
How to write Python 3 dictionary in C# .Net Framework 4.6 WPF App
I'm new to C# and the .Net Framework 4.6. I do know Python, and I was wondering how to do something like this Python dictionary in C#:

GameData = {"VP":0, "Hamsters":"yes"};
```

<p>I've already looked into C# dictionaries and arrays, that's not what I'm looking for. I want something that can be retrieved by something like this:</p>

```GameData["Hamsters"];
// Returns "yes"
```

答:
Welcome to c#. Strong typing is a bitch. You do want a dictionary, but you need to specify the types of the key and value in the key value pairs during the instantiation of said dictionary. In your case, its string, and string.

```<code>Dictionary<string, string> yourDictionary = new Dictionary<string, string>();
</code>```

Passing in these types in angle brackets after the type name is called generics in c#.

You can use the keyword 'var' to assume the implied type. Sometimes the implied type cannot be determined, and you must specify a type on the left hand side of the assignment operator. Thats not the case here though.

```<code>var yourDictionary = new Dictionary<string, string>();
</code>```

You can also use a block at the end of the constructor to specify attributes or properties about the object.

```<code>var yourDictionary = new Dictionary<string, string>()
{
  {"aKey", "aValue"},
  {"anotherKey", "anotherValue"}
};
</code>```

Now you should be able to access the values with

```<code>yourDictionary["aKey"];
</code>```

and

```<code>yourDictionary["anotherKey"];
</code>```

Careful though, because trying to get a key thats not there will throw an exception. Adding a duplicate key will also throw an exception. You can put the get calls in a try catch block

```<code>try{
  yourDictionary["anotherKey"];
}
catch(Exception ex){
  //do something with the error here
}
</code>```

Body:
I'm new to C# and the .Net Framework 4.6. I do know Python, and I was wondering how to do something like this Python dictionary in C#:

GameData = {"VP":0, "Hamsters":"yes"};

I've already looked into C# dictionaries and arrays, that's not what I'm looking for. I want something that can be retrieved by something like this:

GameData["Hamsters"];
// Returns "yes"

Body:
Welcome to c#. Strong typing is a bitch. You do want a dictionary, but you need to specify the types of the key and value in the key value pairs during the instantiation of said dictionary. In your case, its string, and string.

Dictionary<string, string> yourDictionary = new Dictionary<string, string>();

Passing in these types in angle brackets after the type name is called generics in c#.

You can use the keyword 'var' to assume the implied type. Sometimes the implied type cannot be determined, and you must specify a type on the left hand side of the assignment operator. Thats not the case here though.

var yourDictionary = new Dictionary<string, string>();

You can also use a block at the end of the constructor to specify attributes or properties about the object.

var yourDictionary = new Dictionary<string, string>()
{
  {"aKey", "aValue"},
  {"anotherKey", "anotherValue"}
};

Now you should be able to access the values with

yourDictionary["aKey"];

and

yourDictionary["anotherKey"];

Careful though, because trying to get a key thats not there will throw an exception. Adding a duplicate key will also throw an exception. You can put the get calls in a try catch block

try{
  yourDictionary["anotherKey"];
}
catch(Exception ex){
  //do something with the error here
}


问:
How to output values from sp_execute_external_script into table
Having the following code, how can I output the values from the external python script into a sql table that I can query after.

```<code>EXECUTE sp_execute_external_script
@language = N'Python',
@script = N'
            import pandas as pd
            import numpy as np

            rd = np.random.randn(100)
            df = pd.DataFrame(rd).describe()
            print(df)'
</code>```

Thanks in advance.

答:
```<code>declare @py nvarchar(max);

set @py = N'from pandas.io.json import json_normalize

rdd = {"documents": [{"id": "1", "score": 0.97},{"id": "2","score": 0.87},{"id": "3", "score": 0.78}],"errors": []}
print(type(rdd))

df = json_normalize(rdd, "documents")
print(df)
print(type(df))
';

drop table if exists apiresults
create table apiresults (id int, score float)

insert into apiresults
exec sp_execute_external_script
    @language = N'Python',
    @script = @py,
    @output_data_1_name =N'df'

select * from apiresults
</code>```

Body:
Having the following code, how can I output the values from the external python script into a sql table that I can query after.

EXECUTE sp_execute_external_script
@language = N'Python',
@script = N'
            import pandas as pd
            import numpy as np

            rd = np.random.randn(100)
            df = pd.DataFrame(rd).describe()
            print(df)'

Thanks in advance.


问:
Access Data in the navigation controller
I have a controller1 which contains a view which contain many subviews ( Textfields,....).
I use a navigation controller. I push the controller1 and in this controller I push an other controller2.

My problem is to access the data of the controller1, for example I want to access the data of the textfield of my controller1 in the controller2.

How I can do this please ???

Thanks for your answers

答:
By controller1 and controller2, I'll assume that you mean UIViewController. If that is what you mean, than just create IBOutlets of the objects that you want to access in the first UIViewController. Then #import the first UIViewController in your second UIViewController and then you can access the IBOutlets from there.

Next time please search as this is a fairly common question and has been answered numerous times all over the internet.


问:
Play framework stops immediately after starded
When I run sbt and call command run server say "press  and worked while I not press . But when i try to call sbt with argument run (i.e. type ./sbt run &<enter> in command prompt) server started and immediately begin stop, like I press  in console.

How I should run my server and detach one from console?

答:
dist is need instead run.

Thank to @cchantep

see more here https://www.playframework.com/documentation/2.7.x/Deploying#Using-the-dist-task


问:
React, Want to get current mouse position of the current element
I want to get the current mouse position within a
, and then draw something on that position in the
.

```<code><chrome screen>
----------------------------------------------
|                                            |
|    <div>                                   |
|    --------------------------              |
|    |                        |              |
|    |                        |              |
|    | .  <-- mouse position and i want to draw something here
|    |        when clicking here             |
|    |------------------------|              |
|                                            |
|--------------------------------------------|
</code>```

I tried to code with React Framework. And the problem is that I cannot get an accurate position to draw something.

I googled on how to get current position of the current element in react, and tried below

```<code>render(){
    return (
        <canvas ref="canvas" className="DrawReflect" onMouseDown={this.startDrawing}>
        </canvas>
    );
}

startDrawing(e){

    switch(this.context.drawingTool){

        case "pen":
            // Stuck on getting mouse position. None of google's source is not accurate.
            //this.drawPen(e.nativeEvent.offsetX, e.nativeEvent.offsetY);
            //this.drawPen(e.pageX - e.target.offsetLeft, e.pageY - e.target.offsetTop);

            break;
    }
}

drawPen(cursorX, cursorY){
    // Just for showing drawing information in a label
    this.context.updateDrawInfo({
        cursorX: cursorX,
        cursorY: cursorY,
        drawingNow: true
    });

    // Draw something
    const canvas = this.refs.canvas;
    const canvasContext = canvas.getContext("2d");
    canvasContext.beginPath();
    canvasContext.arc(
                    cursorX, cursorY /* start position */,
                    1, /* radius */
                    0, /* start angle */
                    2 * Math.PI /* end angle */);
    canvasContext.stroke();

}
</code>```

So simply put,
How do I get the current mouse position of the div in React?

答: I made you a pen using e.clientX - e.target.offsetLeft and e.clientY - e.target.offsetTop. The top left corner of the canvas (in pink) is giving me 0,0 which seems right.

Body:
I want to get the current mouse position within a
, and then draw something on that position in the
.

<chrome screen>
----------------------------------------------
|                                            |
|
                                   |
|    --------------------------              |
|    |                        |              |
|    |                        |              |
|    | .  <-- mouse position and i want to draw something here
|    |        when clicking here             |
|    |------------------------|              |
|                                            |
|--------------------------------------------|

I tried to code with React Framework. And the problem is that I cannot get an accurate position to draw something.

I googled on how to get current position of the current element in react, and tried below

render(){
    return (
        <canvas ref="canvas" className="DrawReflect" onMouseDown={this.startDrawing}>
        </canvas>
    );
}

startDrawing(e){

    switch(this.context.drawingTool){

        case "pen":
            // Stuck on getting mouse position. None of google's source is not accurate.
            //this.drawPen(e.nativeEvent.offsetX, e.nativeEvent.offsetY);
            //this.drawPen(e.pageX - e.target.offsetLeft, e.pageY - e.target.offsetTop);

            break;
    }
}

drawPen(cursorX, cursorY){
    // Just for showing drawing information in a label
    this.context.updateDrawInfo({
        cursorX: cursorX,
        cursorY: cursorY,
        drawingNow: true
    });

    // Draw something
    const canvas = this.refs.canvas;
    const canvasContext = canvas.getContext("2d");
    canvasContext.beginPath();
    canvasContext.arc(
                    cursorX, cursorY /* start position */,
                    1, /* radius */
                    0, /* start angle */
                    2 * Math.PI /* end angle */);
    canvasContext.stroke();

}

So simply put,
How do I get the current mouse position of the div in React?


问:
What must I know to use GNU Screen properly?
I've just introduced a friend to GNU Screen and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent Screen utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.?

It would be awesome.

答:
There is some interesting work being done on getting a good GNU screen setup happening by default in the next version of Ubuntu Server, which includes using the bottom of the screen to show all the windows as well as other useful machine details (like number of updates available and whether the machine needs a reboot). You can probably grab their .screenrc and customise it to your needs.

The most useful commands I have in my .screenrc are the following:

```<code>shelltitle "$ |bash" # Make screen assign window titles automatically
hardstatus alwayslastline "%w" # Show all window titles at bottom line of term
</code>```

This way I always know what windows are open, and what is running in them at the moment, too.

OwnerDisplayName: PintSizedCat

LastEditorDisplayName: EnderMB

Body:
There is some interesting work being done on getting a good GNU screen setup happening by default in the next version of Ubuntu Server, which includes using the bottom of the screen to show all the windows as well as other useful machine details (like number of updates available and whether the machine needs a reboot). You can probably grab their .screenrc and customise it to your needs.

The most useful commands I have in my .screenrc are the following:

shelltitle "$ |bash" # Make screen assign window titles automatically
hardstatus alwayslastline "%w" # Show all window titles at bottom line of term

This way I always know what windows are open, and what is running in them at the moment, too.

OwnerDisplayName: David Dean


问:
Apache default page is opening when i try to open my ip address
Recently i have hosted a webapp in linode using apache2. It was working fine but some thing happened suddenly, it starts opening apache default page when i try to open my webpage. If any one has faced it, can you please help me in getting out of this.

Thank you all.

! https://i.stack.imgur.com/1NOHl.jpg
Previously it was /var/www/html, i have modified to /var/www/html_backup

```<code><VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.

        ServerName ip_addrs
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html_backup

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</code>```

答:
You'll need to run the Django app. There are several approaches, I like running the Django app through gunicorn and let Nginx or Apache handle the static stuff and proxy the Django calls through Apache.

It appears to me like you might not be running the app at all right now.  Test it by switching to the root of your project and use the python manage.py runserver command. I suspect you had it running somewhere and have stopped it. You'll want to use something other than runserver when you get going.

Body:
Recently i have hosted a webapp in linode using apache2. It was working fine but some thing happened suddenly, it starts opening apache default page when i try to open my webpage. If any one has faced it, can you please help me in getting out of this.

Thank you all.

! https://i.stack.imgur.com/1NOHl.jpg
Previously it was /var/www/html, i have modified to /var/www/html_backup

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.

        ServerName ip_addrs
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html_backup

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined


问:
Block php files except in one directory
I'm trying to block all calls to php files in a specific folder and subfolders except for one specific folder and its subfolders.

I've tried a number of different regex permutations and I can get the regex to match properly, it's implementing in htaccess where I have a problem.

This is the htaccess file as it is now:

```<code><FilesMatch "\.(?i:php)$">
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
</FilesMatch>
</code>```

and this is the regex expression that matches properly outside of htaccess:

```<code>^(?!.*(thedirectory)).*(?i:php)$
</code>```

When I check that regex against index.php it matches. When I check against /thedirectory/index.php it does not match. When I check against /someotherdirectory/style.css it does not match.

How I'd like it to work is:

```<code>domain.com/folder/index.php -> 404 Error
domain.com/folder/thedirectory/index.php -> resolves
domain.com/folder/someotherdirectory/index.php -> 404 Error
domain.com/folder/someotherdirectory/afunction.php -> 404 Error
domain.com/folder/someotherdirectory/style.css -> resolves
</code>```

答:
The <Files> and <FilesMatch> sections match just the filename, not the directory path. So attempting to do so will naturally fail.

An alternative approach is to simply create an additional .htaccess file in the directory you want to allow access, which will override the parent:

```<code>Require all granted
</code>```

Title: Block php files except in one directory

Body:
I'm trying to block all calls to php files in a specific folder and subfolders except for one specific folder and its subfolders.

I've tried a number of different regex permutations and I can get the regex to match properly, it's implementing in htaccess where I have a problem.

This is the htaccess file as it is now:

<FilesMatch "\.(?i:php)$">
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
</FilesMatch>

and this is the regex expression that matches properly outside of htaccess:

^(?!.*(thedirectory)).*(?i:php)$

When I check that regex against index.php it matches. When I check against /thedirectory/index.php it does not match. When I check against /someotherdirectory/style.css it does not match.

How I'd like it to work is:

domain.com/folder/index.php -> 404 Error
domain.com/folder/thedirectory/index.php -> resolves
domain.com/folder/someotherdirectory/index.php -> 404 Error
domain.com/folder/someotherdirectory/afunction.php -> 404 Error
domain.com/folder/someotherdirectory/style.css -> resolves

Body:
The <Files> and <FilesMatch> sections match just the filename, not the directory path. So attempting to do so will naturally fail.

An alternative approach is to simply create an additional .htaccess file in the directory you want to allow access, which will override the parent:

Require all granted


问:
Converting a vector in R into a lower/upper triangular matrix in specific order
I have a vector where the order of the elements are important, for example:

v<-c(1,2,3,4,5,6,7,8,9,10)

I would like to arrange my vector into a lower/upper triangular matrix with a specific order:

```<code>1 2 4 7
0 3 5 8
0 0 6 9
0 0 0 10
</code>```

or

```<code>1 0 0 0
2 3 0 0
4 5 6 0
7 8 9 10
</code>```

I think I can make it whith a for, but I don't know how, and blanks could be filled with NAs or 0's

thanks

答:
You can fill up the upper triangular matrix by doing

```<code>mat <- matrix(0, nrow = 4, ncol = 4)
mat[upper.tri(mat, diag = TRUE)] <- v

mat
#     [,1] [,2] [,3] [,4]
#[1,]    1    2    4    7
#[2,]    0    3    5    8
#[3,]    0    0    6    9
#[4,]    0    0    0   10
</code>```

Lower triangle doesn't follow the same sequence as upper triangle so doing

```<code>mat[lower.tri(mat, diag = TRUE)] <- v
</code>```

doesn't give the expected outcome.

We can get the indices of lower triangle, order them according to row and then update the matrix

```<code>order_mat <- which(lower.tri(mat, diag = TRUE), arr.ind = TRUE)
mat[order_mat[order(order_mat[, 1]), ]]  <- v

mat
#     [,1] [,2] [,3] [,4]
#[1,]    1    0    0    0
#[2,]    2    3    0    0
#[3,]    4    5    6    0
#[4,]    7    8    9   10
</code>```

Or as @Gregor commented a much simpler way is to transpose the upper triangular result

```<code>mat <- matrix(0, nrow = 4, ncol = 4)
mat[upper.tri(mat, diag = TRUE)] <- v #Upper triangle
t(mat)   #Lower triangle
</code>```

Body:
I have a vector where the order of the elements are important, for example:

v<-c(1,2,3,4,5,6,7,8,9,10)

I would like to arrange my vector into a lower/upper triangular matrix with a specific order:

1 2 4 7
0 3 5 8
0 0 6 9
0 0 0 10

or

1 0 0 0
2 3 0 0
4 5 6 0
7 8 9 10

I think I can make it whith a for, but I don't know how, and blanks could be filled with NAs or 0's

thanks

Body:
You can fill up the upper triangular matrix by doing

mat <- matrix(0, nrow = 4, ncol = 4)
mat[upper.tri(mat, diag = TRUE)] <- v

mat
#     [,1] [,2] [,3] [,4]
#[1,]    1    2    4    7
#[2,]    0    3    5    8
#[3,]    0    0    6    9
#[4,]    0    0    0   10

Lower triangle doesn't follow the same sequence as upper triangle so doing

mat[lower.tri(mat, diag = TRUE)] <- v

doesn't give the expected outcome.

We can get the indices of lower triangle, order them according to row and then update the matrix

order_mat <- which(lower.tri(mat, diag = TRUE), arr.ind = TRUE)
mat[order_mat[order(order_mat[, 1]), ]]  <- v

mat
#     [,1] [,2] [,3] [,4]
#[1,]    1    0    0    0
#[2,]    2    3    0    0
#[3,]    4    5    6    0
#[4,]    7    8    9   10

Or as @Gregor commented a much simpler way is to transpose the upper triangular result

mat <- matrix(0, nrow = 4, ncol = 4)
mat[upper.tri(mat, diag = TRUE)] <- v #Upper triangle
t(mat)   #Lower triangle


问:
When is apache Storm 2.0 expected to be released?
Apache Storm 2.0 SNAPSHOT has been tagged on github for a long time (years?) but isn't available for download and I cant find an ETA/roadmap.

My understanding was 2.0 removed a lot of clojure and improved performance (I might be wrong on the later), but is 2.0 dead?

答: Storm 2.0 has been released now.</p>

Body: Storm 2.0 has been released now.


问:
Define an array of objects with a distinct object key
How, if at all, can TypeScript define an array that constrains a specified object key to be distinct?

Here is a demo that indicates the requirements.

```<code>type Magician = {
  distinctKey: string;
  lastName: string;
};

// How, if at all, can we make line 19 be a compiler error?
type ObjectArrayWithDistinctKey<TItem, TKey> = TItem[];

const example: ObjectArrayWithDistinctKey<Magician, 'distinctKey'> = [
  {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
  {
    distinctKey: 'ammar1956', // error!
    lastName: 'Ammar'
  }
];
</code>```

I appreciate that this is a job for something like a Map not an array.

答:
No this is a behavior that isn't possible in Arrays, the reason is that Arrays can only be of a single type "A", A's cannot compare themselves against other A's.

This is a behavior that can however be achieved with tuple, or variable length tuples.

EDIT: There are many ways to achieve this with tuples, i would say there is no best way it really depends on your the whole situation, that's why i didn't add a solution however this is atleast one way is to turn a Union MagicianA | MagicianB into permutations of tuples [MagicianA | MagicianB] | [MagicianB, MagicianA] this allows the ordering to not matter but to force distinct keys and length.

```<code>interface Magician<DistinctKey extends "ammar1956" | "vernon1894"> {
  distinctKey: DistinctKey;
  lastName: string;
};
type AmmarMagician = Magician<"ammar1956">;
type VernonMagician = Magician<"vernon1894">;

/* Easiest quality of life solution */
type Overwrite<T, S extends any> = { [P in keyof T]: S[P] };
type TupleUnshift<T extends any[], X> = T extends any ? ((x: X, ...t: T) => void) extends (...t: infer R) => void ? R : never : never;
type TuplePush<T extends any[], X> = T extends any ? Overwrite<TupleUnshift<T, any>, T & { [x: string]: X }> : never;

type UnionToTuple<U> = UnionToTupleRecursively<[], U>;

type UnionToTupleRecursively<T extends any[], U> = {
    1: T;
    0: UnionToTupleRecursively_<T, U, U>;
}[[U] extends [never] ? 1 : 0]

type UnionToTupleRecursively_<T extends any[], U, S> =
    S extends any ? UnionToTupleRecursively<TupleUnshift<T, S> | TuplePush<T, S>, Exclude<U, S>> : never;
/* End Easiest qulaity of life solution */

const example: UnionToTuple<AmmarMagician | VernonMagician> = [
  {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
]; // works

const example2: UnionToTuple<AmmarMagician | VernonMagician> = [
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
    {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
]; // works swapped

const example3: UnionToTuple<AmmarMagician | VernonMagician> = [
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
    {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
    {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
]; // fails duplicates.
</code>```

Or you can also do something like this for variable length....

```<code>type ValidKeys = "ammar1956" | "vernon1894" | "UnknownMagician"
interface Magician<DistinctKey extends ValidKeys> {
  distinctKey: DistinctKey;
  lastName: string;
};
type AmmarMagician = Magician<"ammar1956">;
type VernonMagician = Magician<"vernon1894">;
type UnknownMagician = Magician<"UnknownMagician">;

/* Easiest quality of life solution */
type MagiciansArray = [AmmarMagician, VernonMagician, ...UnknownMagician[]];
/* End Easiest qulaity of life solution */
const example: MagiciansArray = [
  {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
  {
      distinctKey: "UnknownMagician",
      lastName: "hello"
  }
]; // works
</code>```

Body:
How, if at all, can TypeScript define an array that constrains a specified object key to be distinct?

Here is a <a href="http://type%20Magician%20=%20%7B%20%20%20distinctKey:%20string;%20%20%20lastName:%20string;%20%7D;%20%20//%20How,%20if%20at%20all,%20can%20we%20make%20line%2019%20be%20a%20compiler%20error?%20type%20ObjectArrayWithDistinctKey%3CTItem,%20TKey%3E%20=%20TItem[];%20%20%20const%20example:%20ObjectArrayWithDistinctKey%3CMagician,%20'distinctKey'%3E%20=%20[%20%20%20%7B%20%20%20%20%20distinctKey:%20'ammar1956',%20%20%20%20%20lastName:%20'Ammar'%20%20%20%7D,%20%20%20%7B%20%20%20%20%20distinctKey:%20'vernon1894',%20%20%20%20%20lastName:%20'Vernon'%20%20%20%7D,%20%20%20%7B%20%20%20%20%20distinctKey:%20'ammar1956',%20//%20error!%20%20%20%20%20lastName:%20'Ammar'%20%20%20%7D%20];" rel="nofollow noreferrer">demo that indicates the requirements.

type Magician = {
  distinctKey: string;
  lastName: string;
};

// How, if at all, can we make line 19 be a compiler error?
type ObjectArrayWithDistinctKey<TItem, TKey> = TItem[];

const example: ObjectArrayWithDistinctKey<Magician, 'distinctKey'> = [
  {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
  {
    distinctKey: 'ammar1956', // error!
    lastName: 'Ammar'
  }
];

I appreciate that this is a job for something like a Map not an array.

Body:
No this is a behavior that isn't possible in Arrays, the reason is that Arrays can only be of a single type "A", A's cannot compare themselves against other A's.

This is a behavior that can however be achieved with tuple, or variable length tuples.

EDIT: There are many ways to achieve this with tuples, i would say there is no best way it really depends on your the whole situation, that's why i didn't add a solution however this is atleast one way is to turn a Union MagicianA | MagicianB into permutations of tuples [MagicianA | MagicianB] | [MagicianB, MagicianA] this allows the ordering to not matter but to force distinct keys and length.

interface Magician<DistinctKey extends "ammar1956" | "vernon1894"> {
  distinctKey: DistinctKey;
  lastName: string;
};
type AmmarMagician = Magician<"ammar1956">;
type VernonMagician = Magician<"vernon1894">;

/* Easiest quality of life solution */
type Overwrite<T, S extends any> = { [P in keyof T]: S[P] };
type TupleUnshift<T extends any[], X> = T extends any ? ((x: X, ...t: T) => void) extends (...t: infer R) => void ? R : never : never;
type TuplePush<T extends any[], X> = T extends any ? Overwrite<TupleUnshift<T, any>, T & { [x: string]: X }> : never;

type UnionToTuple<U> = UnionToTupleRecursively<[], U>;

type UnionToTupleRecursively<T extends any[], U> = {
    1: T;
    0: UnionToTupleRecursively_<T, U, U>;
}[[U] extends [never] ? 1 : 0]

type UnionToTupleRecursively_<T extends any[], U, S> =
    S extends any ? UnionToTupleRecursively<TupleUnshift<T, S> | TuplePush<T, S>, Exclude<U, S>> : never;
/* End Easiest qulaity of life solution */

const example: UnionToTuple<AmmarMagician | VernonMagician> = [
  {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
]; // works

const example2: UnionToTuple<AmmarMagician | VernonMagician> = [
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
    {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
]; // works swapped

const example3: UnionToTuple<AmmarMagician | VernonMagician> = [
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
    {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
    {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
]; // fails duplicates.

Or you can also do something like this for variable length....

type ValidKeys = "ammar1956" | "vernon1894" | "UnknownMagician"
interface Magician<DistinctKey extends ValidKeys> {
  distinctKey: DistinctKey;
  lastName: string;
};
type AmmarMagician = Magician<"ammar1956">;
type VernonMagician = Magician<"vernon1894">;
type UnknownMagician = Magician<"UnknownMagician">;

/* Easiest quality of life solution */
type MagiciansArray = [AmmarMagician, VernonMagician, ...UnknownMagician[]];
/* End Easiest qulaity of life solution */
const example: MagiciansArray = [
  {
    distinctKey: 'ammar1956',
    lastName: 'Ammar'
  },
  {
    distinctKey: 'vernon1894',
    lastName: 'Vernon'
  },
  {
      distinctKey: "UnknownMagician",
      lastName: "hello"
  }
]; // works


问:
Cannot run git clone or pip install commands
So i'm pretty new to the whole windows repo cloning thing. I installed python 2.7, added the path to my windows cmd and I still cannot run any git clone commands. It shows the following output :

git clone
  File "", line 1
    git clone
            ^

I've been scouring the internet for an answer but apparently it should work if I use cmd.
Any help would be appreciated!

git clone
  File "", line 1
    git clone
            ^

答:
I have had the same issue recently with 3.7, so I made a new username and it worked. Kind of nice, a clean new Windows profile, even though I just started using it again compared to linux. A pain though.

Make sure all other versions of Python are not installed, or at least affecting the path to the file you need the pip installs to be saved. Python can be saved in a few different locations, and some rare times it has been shown in very obscure places. Check where your file saved on your PC. Probablu C:/ then could be many paths. /Users/UnserNameHere/Windows/ProgramFiles. I would use the search bar in the good old GUI while searching under the C drive (if you have multiple HDD/SDD then pic the one used for the C drive, if nothing comes up try the other drives.

Your looking for a file PythonFoundation I can't remember the entire name, however it will have a very long name Python Foundation are in the name of the file. This is where thing are store and where the path should be sending modules, at least the correct file inside that file.

Also try doing it from other Python versions installed. If you had 3.6 and got 3.7 it doesn't mean 3.6 has been deleted. Also doesn't mean you path, is not set to 3.6 while using 3.7. Same with Python 2, most people or many have both. The pip commands vary between python versions pip3 I believe is used (getting windows and linux a little mixed up right now)

If all fails do it the old fashon way, find the mod, download it, and move it to the python file I mentioned above. The homepage for python should have a tab linking to a page, or it's on the main page, letting you know where it has been known to save. Google how to see he path Pip is taking, or how to see if pip is installed and where, and what paths are set to.


问:
Where To Override Django CreateView?
I opened up a prior issue on SO regarding manytomany fields not being saved in Django Createview here.  Django CreateView With ManyToManyField  After troubleshooting most of today, I have found that this code actually works:

```<code>class CreateAuthorView(LoginRequiredMixin,CreateView):

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.save()
        instance = form.save()

        if instance.access_level == "Custom":
            obj = NewAuthor.objects.get(secret=instance.name)
            obj.access.add(instance.created_by.id)
            print(instance.created_by.id)
            print(obj.access.all())
            instance = form.save()
            obj.save()
            form.save_m2m()
            instance = form.save()

        return super(CreateAuthorView, self).form_valid(form)
</code>```

When I issue the print(obj.access.all()) I can see in my console that the

```<code>    obj.access.add(instance.created_by.id)
</code>```

Line of code actually does exactly what I want it to do...it adds the created_by.id to the access(ManyToManyField) field that I have defined in my model.  However, when the record actually gets cut, only the values that the user selected in the form are added to the access field, and the created_by.id never makes it to the database.

Should I be overriding CreateView somewhere else in order for the created_by to take affect?  It appears as if my initial update in form_valid is being overwritten is what I suspect.  Actually I've proven it because my update is in fact in my console but not making it to the database.  Thanks in advance for any thoughts on how best to solve.

答:
I found the answer to my question via this SO question.  It turns out you have to override SAVE in the ModelForm in order to save M2M fields.  Save Many-To-Many Field Django Forms
This one was tricky.</p>

Title: Where To Override Django CreateView?

Body:
I opened up a prior issue on SO regarding manytomany fields not being saved in Django Createview here.  Django CreateView With ManyToManyField  After troubleshooting most of today, I have found that this code actually works:

class CreateAuthorView(LoginRequiredMixin,CreateView):

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.save()
        instance = form.save()

        if instance.access_level == "Custom":
            obj = NewAuthor.objects.get(secret=instance.name)
            obj.access.add(instance.created_by.id)
            print(instance.created_by.id)
            print(obj.access.all())
            instance = form.save()
            obj.save()
            form.save_m2m()
            instance = form.save()

        return super(CreateAuthorView, self).form_valid(form)

When I issue the print(obj.access.all()) I can see in my console that the

    obj.access.add(instance.created_by.id)

Line of code actually does exactly what I want it to do...it adds the created_by.id to the access(ManyToManyField) field that I have defined in my model.  However, when the record actually gets cut, only the values that the user selected in the form are added to the access field, and the created_by.id never makes it to the database.

Should I be overriding CreateView somewhere else in order for the created_by to take affect?  It appears as if my initial update in form_valid is being overwritten is what I suspect.  Actually I've proven it because my update is in fact in my console but not making it to the database.  Thanks in advance for any thoughts on how best to solve.


问:
Temperature Converter is giving me NaN
I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.

This is what I have tried to do but it gives me NaN

function temperatureConverter(valNum) {

  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Temperature Converter</h2>

Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>

<p>

  <label>Fahrenheit</label>

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter(this.value)">

  <input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">

</p>

<p>Celcius: <span id="outputCelcius"></span></p></code>```

答:
Your code is not working because in your #button1 you wrote:

```<code>onclick="temperatureConverter(this.value)"
</code>```

where this is not #inputFahrenheit but #button1. Therefore this.value actually equals to "OK".

To fix your problem, you need to change your temperatureConverter function to get value of #inputFahrenheit instead of using onclick="temperatureConverter(this.value)".

Similar situation happens in your #reset1, therefore your reset input will not work as well. You need to apply the same concept into your reset function, which I suggest to create a new function dedicated just for that.

Generally, it is not encouraged to use the same function to perform completely different actions.

function temperatureConverter(){
  var input = document.getElementById('inputFahrenheit');
  var value = input.value;
  value = parseFloat(value);

  var output = document.getElementById('outputCelcius');
  output.innerHTML = (value - 32)/1.8;
}

function resetTemperature(){

  /* clear the temperature */
  console.log('clear');

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Temperature Converter</h2>

<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>

<p>

  <label>Fahrenheit</label>

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter()">

  <input id= "reset1" type= "reset" value= "Clear" onclick="resetTemperature()">

</p>

<p>Celcius: <span id="outputCelcius"></span></p></code>```

Title: Temperature Converter is giving me NaN

Body:
I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.

This is what I have tried to do but it gives me NaN

function temperatureConverter(valNum) {

  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}

Temperature Converter

Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work

Type a value in the Fahrenheit field to convert te value to Celsius:

  Fahrenheit

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter(this.value)">

  <input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">

Celcius:

Body:
Your code is not working because in your #button1 you wrote:

onclick="temperatureConverter(this.value)"

where this is not #inputFahrenheit but #button1. Therefore this.value actually equals to "OK".

To fix your problem, you need to change your temperatureConverter function to get value of #inputFahrenheit instead of using onclick="temperatureConverter(this.value)".

Similar situation happens in your #reset1, therefore your reset input will not work as well. You need to apply the same concept into your reset function, which I suggest to create a new function dedicated just for that.

Generally, it is not encouraged to use the same function to perform completely different actions.

function temperatureConverter(){
  var input = document.getElementById('inputFahrenheit');
  var value = input.value;
  value = parseFloat(value);

  var output = document.getElementById('outputCelcius');
  output.innerHTML = (value - 32)/1.8;
}

function resetTemperature(){

  /* clear the temperature */
  console.log('clear');

}

<h2>Temperature Converter</h2>

<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>

<p>

  <label>Fahrenheit</label>

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter()">

  <input id= "reset1" type= "reset" value= "Clear" onclick="resetTemperature()">

</p>

<p>Celcius: <span id="outputCelcius"></span></p>


问:
virtual function with user-defined-type vector
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

```<code>class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};
</code>```

but when I write the derived class:

```<code>#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};
</code>```

I get this error:

```<code>invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’
</code>```

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?

答:
It's forbidden.  Because you've redefined myStruct in your derived class, vector<myStruct> is a different type in the derived class than it is in the base class.  They are two different myStructs.

You can only change the return type of that virtual function to something inherited from the return type declared in the base class.  But vector<TestSon::myStruct> does not inherit from vector<TestFather::myStruct>

Body:
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};

but when I write the derived class:

#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};

I get this error:

invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?


问:
Issue understanding how to access memory from the stack
I am trying to teach myself assembly and was having some difficult with the interactions between the stack and accessing it. I am using a x86 64 bit system and was doing a simple program that pushes 5 and 2 into the stack (in that order) and then call a function. So, if the word size is 2 bytes then I should be able to get to 2 by doing [esp+2] account for the return address. However, I am getting 0 because when I use edg and step through, the value (by moving it into a register) is 00000002000000 so I can access it with [esp+8] and then 5 with [esp+16]  however, that would mean that a word size is 4? So does that mean that the size of the word depends on bit of the system? What about even just the register used? Instead is it because the size for each segment of the stack is 8 bytes on a 64 bit system?</p>

答:
Instead is it because the size for each segment of the stack is 8 bytes on a 64 bit system?

Yes.

When you push these things then call a function, this is your stack:

```<code>+-----------------+
|        5        | RSP+0x10
+-----------------+
|        2        | RSP+0x08
+-----------------+
|   Return Addr   | RSP+0x00
+-----------------+
</code>```

Likewise, on a 32-bit system you're looking at this for your stack:

```<code>+-----------------+
|        5        | ESP+0x08
+-----------------+
|        2        | ESP+0x04
+-----------------+
|   Return Addr   | ESP+0x00
+-----------------+
</code>```

As an aside, remember that the 64-bit registers start with an R (RSP, RAX, etc). Also, depending on your operating system you're likely to be incorrectly passing parameters via the stack. 64-bit systems use registers for the first N parameters then the stack from then on. The registers are different depending on whether you're passing integers/pointers or floating point. For your purposes, with SystemV the first 6 are passed via RDI, RSI, RDX, RCX, R8 and R9 (in that order). 64-bit Windows uses RCX, RDX, R8 and R9 for the first 4 (in that order). This isn't important now while you're learning, but it'll become increasingly important as you start calling into other modules/OS APIs.

Body:
Instead is it because the size for each segment of the stack is 8 bytes on a 64 bit system?

Yes.

When you push these things then call a function, this is your stack:

+-----------------+
|        5        | RSP+0x10
+-----------------+
|        2        | RSP+0x08
+-----------------+
|   Return Addr   | RSP+0x00
+-----------------+

Likewise, on a 32-bit system you're looking at this for your stack:

+-----------------+
|        5        | ESP+0x08
+-----------------+
|        2        | ESP+0x04
+-----------------+
|   Return Addr   | ESP+0x00
+-----------------+

As an aside, remember that the 64-bit registers start with an R (RSP, RAX, etc). Also, depending on your operating system you're likely to be incorrectly passing parameters via the stack. 64-bit systems use registers for the first N parameters then the stack from then on. The registers are different depending on whether you're passing integers/pointers or floating point. For your purposes, with SystemV the first 6 are passed via RDI, RSI, RDX, RCX, R8 and R9 (in that order). 64-bit Windows uses RCX, RDX, R8 and R9 for the first 4 (in that order). This isn't important now while you're learning, but it'll become increasingly important as you start calling into other modules/OS APIs.


问:
Loading an entire cache line at once to avoid contention for multiple elements of it
Assuming that there are three pieces of data that I need from a heavily contended cache line, is there a way to load all three things "atomically" so as to avoid more than one roundtrip to any other core?

I don't actually need a correctness guarantee of atomicity for a snapshot of all 3 members, just in the normal case that all three items are read in the same clock cycle.  I want to avoid the case where the cache line arrives, but then an invalidate request comes in before all 3 objects are read.  That would result in the 3rd access needing to send another request to share the line, making contention even worse.

For example,

```<code>class alignas(std::hardware_destructive_interference_size) Something {
    std::atomic<uint64_t> one;
    std::uint64_t two;
    std::uint64_t three;
};

void bar(std::uint64_t, std::uint64_t, std::uint64_t);

void f1(Something& something) {
    auto one = something.one.load(std::memory_order_relaxed);
    auto two = something.two;
    if (one == 0) {
        bar(one, two, something.three);
    } else {
        bar(one, two, 0);
    }

}

void f2(Something& something) {
    while (true) {
        baz(something.a.exchange(...));
    }
}
</code>```

Can I somehow ensure that one, two and three all get loaded together without multiple RFOs under heavy contention (assume f1 and f2 are running concurrently)?

The target architecture / platform for the purposes of this question is Intel x86 Broadwell, but if there is a technique or compiler intrinsic that allows doing something best-effort like this somewhat portably, that would be great as well.

答:
terminology: A load won't generate an RFO, it doesn't need ownership.  It only sends a request to share the data.  Multiple cores can be reading from the same physical address in parallel, each with a copy of it hot in their L1d cache.

Other cores writing the line will send RFOs which invalidate the shared copy in our cache, though, and yes that could come in after reading one or two elements of a cache line before all have been read.  (I updated your question with a description of the problem in those terms.)

Hadi's SIMD load is a good idea to grab all the data with one instruction.

As far as we know, _mm_load_si128() is in practice atomic for its 8-byte chunks, so it can safely replace the .load(mo_relaxed) of the atomic.  But see Per-element atomicity of vector load/store and gather/scatter? - there's no clear written guarantee of this.

If you used _mm256_loadu_si256(), beware of GCC's default tuning -mavx256-split-unaligned-load:  Why doesn't gcc resolve _mm256_loadu_pd as single vmovupd?  So that's another good reason to use an aligned load, besides needing to avoid a cache-line split.

But we're writing in C, not asm, so we need to worry about some of the other things that std::atomic with mo_relaxed does: specifically that repeated loads from the same address might not give the same value.  You probably need to dereference a volatile __m256i* to kind of simulate what load(mo_relaxed).

You can use atomic_thread_fence() if you want stronger ordering; I think in practice C++11 compilers that support Intel intrinsics will order volatile dereferences wrt. fences the same way as std::atomic loads/stores.  In ISO C++, volatile objects are still subject to data-race UB, but in real implementations that can for example compile a Linux kernel, volatile can be used for multi-threading.  (Linux rolls its own atomics with volatile and inline asm, and this is I think considered supported behaviour by gcc/clang.)  Given what volatile actually does (object in memory matches the C++ abstract machine), it basically just automatically works, despite any rules-lawyer concerns that it's technically UB.  It's UB that compilers can't know or care about because that's the whole point of volatile.

In practice there's good reason to believe that entire aligned 32-byte loads/store on Haswell and later are atomic.  Certainly for reading from L1d into the out-of-order backend, but also even for transferring cache lines between cores.  (e.g. multi-socket K10 can tear on 8-byte boundaries with HyperTransport, so this really is a separate issue).  The only problem for taking advantage of it is the lack of any written guarantee or CPU-vendor-approved way to detect this "feature".

Other than that, for portable code it could help to hoist auto three = something.three; out of the branch; a branch mispredict gives the core much more time to invalidate the line before the 3rd load.

But compilers will probably not respect that source change, and only load it in the case that needs it.  But branchless code would always load it, so maybe we should encourage that with

```<code>    bar(one, two, one == 0 ? something.three : 0);
</code>```

Broadwell can run 2 loads per clock cycle (like all mainstream x86 since Sandybridge and K8); uops typically execute in oldest-ready-first order so it's likely (if this load did have to wait for data from another core) that our 2 load uops will execute in the first cycle possible after the data arrives.

The 3rd load uop will hopefully run in the cycle after that, leaving a very small window for an invalidate to cause a problem.

Or on CPUs with only 1-per clock loads, still having all 3 loads adjacent in the asm reduces the window for invalidations.

But if one == 0 is rare, then three often isn't needed at all, so unconditional loading brings a risk of unnecessary requests for it.  So you have to consider that tradeoff when tuning, if you can't cover all the data with one SIMD load.

As discussed in comments, software prefetch could potentially help to hide some of the inter-core latency.

But you have to prefetch much later than you would for a normal array, so finding places in your code that are often running ~50 to ~100 cycles before f1() is called is a hard problem and can "infect" a lot of other code with details unrelated to its normal operation.  And you need a pointer to the right cache line.

You need the PF to be late enough that the demand load happens a few (tens of) cycles before the prefetched data actually arrives.  This is the opposite of the normal use-case, where L1d is a buffer to prefetch into and hold data from completed prefetches before demand-loads get to them.  But you want load_hit_pre.sw_pf perf events (load hit prefetch), because that means the demand load happened while the data was still in flight, before there's any chance of it being invalidated.

That means tuning is even more brittle and difficult than usual, because instead of a nearly-flat sweet spot for prefetch distance where earlier or later doesn't hurt, earlier hides more latency right up until the point where it allows invalidations, so it's a slope all the way up to a cliff.  (And any too-early prefetches just make overall contention even worse.)

Body:
Assuming that there are three pieces of data that I need from a heavily contended cache line, is there a way to load all three things "atomically" so as to avoid more than one roundtrip to any other core?

I don't actually need a correctness guarantee of atomicity for a snapshot of all 3 members, just in the normal case that all three items are read in the same clock cycle.  I want to avoid the case where the cache line arrives, but then an invalidate request comes in before all 3 objects are read.  That would result in the 3rd access needing to send another request to share the line, making contention even worse.

For example,

class alignas(std::hardware_destructive_interference_size) Something {
    std::atomic<uint64_t> one;
    std::uint64_t two;
    std::uint64_t three;
};

void bar(std::uint64_t, std::uint64_t, std::uint64_t);

void f1(Something& something) {
    auto one = something.one.load(std::memory_order_relaxed);
    auto two = something.two;
    if (one == 0) {
        bar(one, two, something.three);
    } else {
        bar(one, two, 0);
    }

}

void f2(Something& something) {
    while (true) {
        baz(something.a.exchange(...));
    }
}

Can I somehow ensure that one, two and three all get loaded together without multiple RFOs under heavy contention (assume f1 and f2 are running concurrently)?

The target architecture / platform for the purposes of this question is Intel x86 Broadwell, but if there is a technique or compiler intrinsic that allows doing something best-effort like this somewhat portably, that would be great as well.

Body:
terminology: A load won't generate an RFO, it doesn't need ownership.  It only sends a request to share the data.  Multiple cores can be reading from the same physical address in parallel, each with a copy of it hot in their L1d cache.

Other cores writing the line will send RFOs which invalidate the shared copy in our cache, though, and yes that could come in after reading one or two elements of a cache line before all have been read.  (I updated your question with a description of the problem in those terms.)

Hadi's SIMD load is a good idea to grab all the data with one instruction.

As far as we know, _mm_load_si128() is in practice atomic for its 8-byte chunks, so it can safely replace the .load(mo_relaxed) of the atomic.  But see Per-element atomicity of vector load/store and gather/scatter? - there's no clear written guarantee of this.

If you used _mm256_loadu_si256(), beware of GCC's default tuning -mavx256-split-unaligned-load:  Why doesn't gcc resolve _mm256_loadu_pd as single vmovupd?  So that's another good reason to use an aligned load, besides needing to avoid a cache-line split.

But we're writing in C, not asm, so we need to worry about some of the other things that std::atomic with mo_relaxed does: specifically that repeated loads from the same address might not give the same value.  You probably need to dereference a volatile __m256i* to kind of simulate what load(mo_relaxed).

You can use atomic_thread_fence() if you want stronger ordering; I think in practice C++11 compilers that support Intel intrinsics will order volatile dereferences wrt. fences the same way as std::atomic loads/stores.  In ISO C++, volatile objects are still subject to data-race UB, but in real implementations that can for example compile a Linux kernel, volatile can be used for multi-threading.  (Linux rolls its own atomics with volatile and inline asm, and this is I think considered supported behaviour by gcc/clang.)  Given what volatile actually does (object in memory matches the C++ abstract machine), it basically just automatically works, despite any rules-lawyer concerns that it's technically UB.  It's UB that compilers can't know or care about because that's the whole point of volatile.

In practice there's good reason to believe that entire aligned 32-byte loads/store on Haswell and later are atomic.  Certainly for reading from L1d into the out-of-order backend, but also even for transferring cache lines between cores.  (e.g. multi-socket K10 can tear on 8-byte boundaries with HyperTransport, so this really is a separate issue).  The only problem for taking advantage of it is the lack of any written guarantee or CPU-vendor-approved way to detect this "feature".

Other than that, for portable code it could help to hoist auto three = something.three; out of the branch; a branch mispredict gives the core much more time to invalidate the line before the 3rd load.

But compilers will probably not respect that source change, and only load it in the case that needs it.  But branchless code would always load it, so maybe we should encourage that with

    bar(one, two, one == 0 ? something.three : 0);

Broadwell can run 2 loads per clock cycle (like all mainstream x86 since Sandybridge and K8); uops typically execute in oldest-ready-first order so it's likely (if this load did have to wait for data from another core) that our 2 load uops will execute in the first cycle possible after the data arrives.

The 3rd load uop will hopefully run in the cycle after that, leaving a very small window for an invalidate to cause a problem.

Or on CPUs with only 1-per clock loads, still having all 3 loads adjacent in the asm reduces the window for invalidations.

But if one == 0 is rare, then three often isn't needed at all, so unconditional loading brings a risk of unnecessary requests for it.  So you have to consider that tradeoff when tuning, if you can't cover all the data with one SIMD load.

As discussed in comments, software prefetch could potentially help to hide some of the inter-core latency.

But you have to prefetch much later than you would for a normal array, so finding places in your code that are often running ~50 to ~100 cycles before f1() is called is a hard problem and can "infect" a lot of other code with details unrelated to its normal operation.  And you need a pointer to the right cache line.

You need the PF to be late enough that the demand load happens a few (tens of) cycles before the prefetched data actually arrives.  This is the opposite of the normal use-case, where L1d is a buffer to prefetch into and hold data from completed prefetches before demand-loads get to them.  But you want load_hit_pre.sw_pf perf events (load hit prefetch), because that means the demand load happened while the data was still in flight, before there's any chance of it being invalidated.

That means tuning is even more brittle and difficult than usual, because instead of a nearly-flat sweet spot for prefetch distance where earlier or later doesn't hurt, earlier hides more latency right up until the point where it allows invalidations, so it's a slope all the way up to a cliff.  (And any too-early prefetches just make overall contention even worse.)