问:
C++ - How to bind a callback to a class method without being static?
I have my class:

```<code>class Foo
{
public:
  (...)
private:
    void mycallback(void* buff, wifi_promiscuous_pkt_type_t type);
    void registerMyCallback();
};
</code>```

The mycallback is the callback.

I want to use a method esp_wifi_set_promiscuous_rx_cb to register the mycallback so that when a WiFi packet is detected, this callback method will be executed.

The esp_wifi_set_promiscuous_rx_cb signature is:

```<code>esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb);
</code>```

Where the wifi_promiscuous_cb_t definition is:

```<code>typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type);
</code>```

I want to use the mycallback method inside my class, therefore I simply can't use like this:

```<code>  void Foo::registerMyCallback()
  {
    esp_wifi_set_promiscuous_rx_cb(&mycallback);
  }
</code>```

I know that I could use something similar if I would just make my method as static.
Is there anyway that I bind mycallback to esp_wifi_set_promiscuous_rx_cb without making the callback static?

I have tried the following:

```<code>esp_wifi_set_promiscuous_rx_cb(std::bind(&Foo::mycallback, this, std::placeholders::_1, std::placeholders::_2));
</code>```

But I am still having the following error:

```<code>cannot convert 'std::_Bind_helper<false, void (Foo::Foo::*)(void*, wifi_promiscuous_pkt_type_t),
Foo::Foo*, const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type
to
'wifi_promiscuous_cb_t {aka void (*)(void*, wifi_promiscuous_pkt_type_t)}' for argument '1'
</code>```

答:
Th library you are using is C package.

Thus the only guaranteed way pass a valid function is to pass a C function with C linkage. This function can then call the method on your object.

If you want the callback method to be non static you need to store a pointer (ore reference) to the callback object somewhere that your callback function can find it. (in most C callback functions you can provide a void* object that is passed to your callback, but this interface does not seem to allow this so you will have to save the value yourself).

```<code>Foo*  myCBObject = nullptr;

extern "C" void myCB(void *buf, wifi_promiscuous_pkt_type_t type)
{
    try
    {
        myCBObject->mycallback(buff, type);
    }
    catch(...) {} // Don't allow exceptions to cross C linkage
}

...
// Your code.
void Foo::registerMyCallback()
{
    myCBObject = this;
    esp_wifi_set_promiscuous_rx_cb(myCB);
}
</code>```

Note: You should NOT be registering static member functions with a C library. If this works it is only by chance. There is no guarantee that a static function has the same calling convention of a C function (they usually do but that is not guaranteed).

Body:
I have my class:

class Foo
{
public:
  (...)
private:
    void mycallback(void* buff, wifi_promiscuous_pkt_type_t type);
    void registerMyCallback();
};

The mycallback is the callback.

I want to use a method esp_wifi_set_promiscuous_rx_cb to register the mycallback so that when a WiFi packet is detected, this callback method will be executed.

The esp_wifi_set_promiscuous_rx_cb signature is:

esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb);

Where the wifi_promiscuous_cb_t definition is:

typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type);

I want to use the mycallback method inside my class, therefore I simply can't use like this:

  void Foo::registerMyCallback()
  {
    esp_wifi_set_promiscuous_rx_cb(&mycallback);
  }

I know that I could use something similar if I would just make my method as static.
Is there anyway that I bind mycallback to esp_wifi_set_promiscuous_rx_cb without making the callback static?

I have tried the following:

esp_wifi_set_promiscuous_rx_cb(std::bind(&Foo::mycallback, this, std::placeholders::_1, std::placeholders::_2));

But I am still having the following error:

cannot convert 'std::_Bind_helper<false, void (Foo::Foo::*)(void*, wifi_promiscuous_pkt_type_t),
Foo::Foo*, const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type
to
'wifi_promiscuous_cb_t {aka void (*)(void*, wifi_promiscuous_pkt_type_t)}' for argument '1'

Body:
Th library you are using is C package.

Thus the only guaranteed way pass a valid function is to pass a C function with C linkage. This function can then call the method on your object.

If you want the callback method to be non static you need to store a pointer (ore reference) to the callback object somewhere that your callback function can find it. (in most C callback functions you can provide a void* object that is passed to your callback, but this interface does not seem to allow this so you will have to save the value yourself).

Foo*  myCBObject = nullptr;

extern "C" void myCB(void *buf, wifi_promiscuous_pkt_type_t type)
{
    try
    {
        myCBObject->mycallback(buff, type);
    }
    catch(...) {} // Don't allow exceptions to cross C linkage
}

...
// Your code.
void Foo::registerMyCallback()
{
    myCBObject = this;
    esp_wifi_set_promiscuous_rx_cb(myCB);
}

Note: You should NOT be registering static member functions with a C library. If this works it is only by chance. There is no guarantee that a static function has the same calling convention of a C function (they usually do but that is not guaranteed).


来源: stackexchange

问:
Count values in a dict of lists and join keys and values names for the output using pandas
I need help getting some outputs from a dictionary (python3):

```<code>{'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}
</code>```

Outputs required:

```<code>black horse: 1
brown horse: 1
grey horse: 0
black duck: 1
brown duck: 3
grey duck: 1
</code>```

Can someone offer a solution please?

答:
I guess this can be optimised further but you can try:

```<code>d={'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}

s=pd.Series(d).explode()
import itertools
l=[*map(' '.join,itertools.product(s.index.unique(),s.unique()))]
print(s.reset_index().agg(' '.join,1).value_counts().reindex(l,fill_value=0))
</code>```

```<code>horse brown    1
horse black    1
horse grey     0
duck brown     3
duck black     1
duck grey      1
dtype: int64
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need help getting some outputs from a dictionary (python3):

{'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}

Outputs required:

black horse: 1
brown horse: 1
grey horse: 0
black duck: 1
brown duck: 3
grey duck: 1

Can someone offer a solution please?

Body:
I guess this can be optimised further but you can try:

d={'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}

s=pd.Series(d).explode()
import itertools
l=[*map(' '.join,itertools.product(s.index.unique(),s.unique()))]
print(s.reset_index().agg(' '.join,1).value_counts().reindex(l,fill_value=0))

horse brown    1
horse black    1
horse grey     0
duck brown     3
duck black     1
duck grey      1
dtype: int64


答:
If you are looking to do this in just Python:

You can use Counter from collections module:

```<code>In [622]: from collections import Counter
In [623]: d = {'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}

In [611]: l = [j + ' ' + key for key, value in d.items() for j in value]

In [620]: Counter(l)
Out[620]:
Counter({'brown horse': 1,
     'black horse': 1,
     'brown duck': 3,
     'black duck': 1,
     'grey duck': 1})
</code>```

Title: Count values in a dict of lists and join keys and values names for the output using pandas

Body:
If you are looking to do this in just Python:

You can use Counter from collections module:

In [622]: from collections import Counter
In [623]: d = {'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}

In [611]: l = [j + ' ' + key for key, value in d.items() for j in value]

In [620]: Counter(l)
Out[620]:
Counter({'brown horse': 1,
     'black horse': 1,
     'brown duck': 3,
     'black duck': 1,
     'grey duck': 1})


问:
How to resoponsive django ckeditor
I'm already downloaded ckeditor for my blog web appication.
But when i visit this site by mobile it's look very bad because it's not responsive how can i convert this into responive design...
I am using django 3.5

CKEDITOR_CONFIGS = {

```<code>'default': {
    'toolbar': 'Custom',
    'height':500,
    'width':450,
    'extraPlugins': 'codesnippet',
    'toolbar_Custom': [
        ['Bold', 'Italic','Image', 'Underline'],
        ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
        ['Link', 'Unlink'],
        ['RemoveFormat', 'Source','codesnippet']
    ]
},
'special':
  { 'toolbar': 'Special',
  'wdith':100,
  'toolbar_Special':
  [
  ['CodeSnippet','Youtube'],
  ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'],
  ['Link', 'Unlink',],
  ['Image','Table', 'HorizontalRule'],
  ['TextColor', 'BGColor'],
  ['Smiley', 'SpecialChar'],
  ['Source'],
  ],'extraPlugins': 'codesnippet',
  }
</code>```

}

答:
if u want to do responsive need to change setting in config.js</p>

```<code>CKEDITOR.editorConfig = function (config) {

config.width = "auto";
config.height = "auto";
</code>```

Title: How to resoponsive django ckeditor

Body:
I'm already downloaded ckeditor for my blog web appication.
But when i visit this site by mobile it's look very bad because it's not responsive how can i convert this into responive design...
I am using django 3.5

CKEDITOR_CONFIGS = {

'default': {
    'toolbar': 'Custom',
    'height':500,
    'width':450,
    'extraPlugins': 'codesnippet',
    'toolbar_Custom': [
        ['Bold', 'Italic','Image', 'Underline'],
        ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
        ['Link', 'Unlink'],
        ['RemoveFormat', 'Source','codesnippet']
    ]
},
'special':
  { 'toolbar': 'Special',
  'wdith':100,
  'toolbar_Special':
  [
  ['CodeSnippet','Youtube'],
  ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'],
  ['Link', 'Unlink',],
  ['Image','Table', 'HorizontalRule'],
  ['TextColor', 'BGColor'],
  ['Smiley', 'SpecialChar'],
  ['Source'],
  ],'extraPlugins': 'codesnippet',
  }

}

Body:
if u want to do responsive need to change setting in config.js

CKEDITOR.editorConfig = function (config) {

config.width = "auto";
config.height = "auto";


问:
NSOperation and reloading the parser
I have a parser class that is subclass of NSOperation. It is used to parse the xml and table view is reloaded when the parse is completed. I have a refresh UIBarButtonItem that is used to call the parser and parse the new xml from the link again.

```<code>-(void)refresh {
   [self.queue cancelAllOperations]; //cancel all the current operations
   [self.queue release];
   self.queue=nil;
   self.arrayOfAllPhotos = nil; // The array to load table view
   [self performSelectorOnMainThread:@selector(doItAgain) withObject:nil waitUntilDone:NO];
</code>```

}

```<code>-(void)doItAgain {
   [tableView reloadData];
   NSURL *url = [NSURL URLWithString:@"some url"];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLConnection *aconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
   self.myConnection = aconnection;
   [aconnection release];
</code>```

}

But, as press refresh button, the app crashes with no message. How do I release the NSOperationQueue and start a new parsing again to load data ?

答:
You should be careful after calling cancelAllOperations, its an asynchoronos operation. The simplest way to ensure all operations have been cancelled it to do something like:

```<code>[self.queue cancelAllOperations]
[self.queue waitUntilAllOperationsAreFinished];
</code>```

ContentLicense: CC BY-SA 3.0

Title: NSOperation and reloading the parser

Body:
I have a parser class that is subclass of NSOperation. It is used to parse the xml and table view is reloaded when the parse is completed. I have a refresh UIBarButtonItem that is used to call the parser and parse the new xml from the link again.

-(void)refresh {
   [self.queue cancelAllOperations]; //cancel all the current operations
   [self.queue release];
   self.queue=nil;
   self.arrayOfAllPhotos = nil; // The array to load table view
   [self performSelectorOnMainThread:@selector(doItAgain) withObject:nil waitUntilDone:NO];

}

-(void)doItAgain {
   [tableView reloadData];
   NSURL *url = [NSURL URLWithString:@"some url"];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLConnection *aconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
   self.myConnection = aconnection;
   [aconnection release];

}

But, as press refresh button, the app crashes with no message. How do I release the NSOperationQueue and start a new parsing again to load data ?

Body:
You should be careful after calling cancelAllOperations, its an asynchoronos operation. The simplest way to ensure all operations have been cancelled it to do something like:

[self.queue cancelAllOperations]
[self.queue waitUntilAllOperationsAreFinished];


问:
Update Statement MySQL Consecutive Fields
Having the mysql process below, would it be reasonable to say that always mysql will update first than then second column, if I maintain the order below (given the dependency). or is it recommended that I write 2 separate update queries one for the first column and one for the second?</p>

```<code>CREATE TABLE a (first INT, second INT);
INSERT INTO a VALUES (1,1);
UPDATE a SET first = 2, second = first * 2;
</code>```

答:
It is sequential. So, first gets updated to 2 and then second gets updated to first * 2 = 4.

If your data was 1, 1, after your update, it will be:

```<code>CREATE TABLE a (first INT, second INT);
INSERT INTO a VALUES (1,1);
UPDATE a SET first = 2, second = first * 2;
select * from a;
+-------+--------+
| first | second |
+-------+--------+
|     2 |      4 |
+-------+--------+
</code>```

If you do this:

```<code>truncate table a;
INSERT INTO a VALUES (1,1);
UPDATE a SET second = first * 2, first = 2;
</code>```

you will get

```<code>select * from a;
+-------+--------+
| first | second |
+-------+--------+
|     2 |      2 |
+-------+--------+
</code>```

So, if you want to update the second field (which relies on dependent field), change the order of the second field to be ahead of the dependent field.

Body:
Having the mysql process below, would it be reasonable to say that always mysql will update first than then second column, if I maintain the order below (given the dependency). or is it recommended that I write 2 separate update queries one for the first column and one for the second?

CREATE TABLE a (first INT, second INT);
INSERT INTO a VALUES (1,1);
UPDATE a SET first = 2, second = first * 2;

Body:
It is sequential. So, first gets updated to 2 and then second gets updated to first * 2 = 4.

If your data was 1, 1, after your update, it will be:

CREATE TABLE a (first INT, second INT);
INSERT INTO a VALUES (1,1);
UPDATE a SET first = 2, second = first * 2;
select * from a;
+-------+--------+
| first | second |
+-------+--------+
|     2 |      4 |
+-------+--------+

If you do this:

truncate table a;
INSERT INTO a VALUES (1,1);
UPDATE a SET second = first * 2, first = 2;

you will get

select * from a;
+-------+--------+
| first | second |
+-------+--------+
|     2 |      2 |
+-------+--------+

So, if you want to update the second field (which relies on dependent field), change the order of the second field to be ahead of the dependent field.


问:
Why does the algorithm not accept float numbers?
Task:
There are two teachers. They give grades for a student's work. There's a final grade. It is equal to the teacher's grade if they give the same grade. Or the final grade is -1 if the teachers have made different grades.
I want to teach the computer to see this logic.

Data:

Rate1 - First teacher assessment

Rate2 - Second teacher assessment

Result - Final evaluation

Example:

0,1; 0,1 => 0,1

0,7; 0,7 => 0,7

0,3; 0,2 => -1

My code:

```<code>import pandas
MyData = pandas.read_excel("train.xlsx")
input_data = MyData.drop("Result", axis=1)
target = MyData.Result
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(input_data, target)

</code>```

And after that, I get the next mistake. If all my estimates are integers, this error is absent. But I have to work with fractions.

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-51-433a918946a9> in <module>
----> 1 model.fit(input_data, target)

~\anaconda3\lib\site-packages\sklearn\ensemble\_forest.py in fit(self, X, y, sample_weight)
    319         self.n_outputs_ = y.shape[1]
    320
--> 321         y, expanded_class_weight = self._validate_y_class_weight(y)
    322
    323         if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:

~\anaconda3\lib\site-packages\sklearn\ensemble\_forest.py in _validate_y_class_weight(self, y)
    539
    540     def _validate_y_class_weight(self, y):
--> 541         check_classification_targets(y)
    542
    543         y = np.copy(y)

~\anaconda3\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y)
    167     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
    168                       'multilabel-indicator', 'multilabel-sequences']:
--> 169         raise ValueError("Unknown label type: %r" % y_type)
    170
    171

ValueError: Unknown label type: 'continuous'
</code>```

p.s. My data is here.

How can I work with fractional numbers?

答:
You are trying to pass float values to a classifier. Try instead with Decision Tree Regressor, where you can pass integer values.

Here is an example code:

```<code>import pandas as pd

df = pd.read_csv(r'train.csv')

X = df.iloc[:, :1].values
y = df.iloc[:, 2].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

from sklearn.tree import DecisionTreeRegressor

DTR = DecisionTreeRegressor()

DTR.fit(X_train, y_train)
</code>```

Body:
Task:
There are two teachers. They give grades for a student's work. There's a final grade. It is equal to the teacher's grade if they give the same grade. Or the final grade is -1 if the teachers have made different grades.
I want to teach the computer to see this logic.

Data:

Rate1 - First teacher assessment

Rate2 - Second teacher assessment

Result - Final evaluation

Example:

0,1; 0,1 => 0,1

0,7; 0,7 => 0,7

0,3; 0,2 => -1

My code:

import pandas
MyData = pandas.read_excel("train.xlsx")
input_data = MyData.drop("Result", axis=1)
target = MyData.Result
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(input_data, target)

And after that, I get the next mistake. If all my estimates are integers, this error is absent. But I have to work with fractions.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-51-433a918946a9> in <module>
----> 1 model.fit(input_data, target)

~\anaconda3\lib\site-packages\sklearn\ensemble\_forest.py in fit(self, X, y, sample_weight)
    319         self.n_outputs_ = y.shape[1]
    320
--> 321         y, expanded_class_weight = self._validate_y_class_weight(y)
    322
    323         if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:

~\anaconda3\lib\site-packages\sklearn\ensemble\_forest.py in _validate_y_class_weight(self, y)
    539
    540     def _validate_y_class_weight(self, y):
--> 541         check_classification_targets(y)
    542
    543         y = np.copy(y)

~\anaconda3\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y)
    167     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
    168                       'multilabel-indicator', 'multilabel-sequences']:
--> 169         raise ValueError("Unknown label type: %r" % y_type)
    170
    171

ValueError: Unknown label type: 'continuous'

p.s. My data is here.

How can I work with fractional numbers?

Body:
You are trying to pass float values to a classifier. Try instead with Decision Tree Regressor, where you can pass integer values.

Here is an example code:

import pandas as pd

df = pd.read_csv(r'train.csv')

X = df.iloc[:, :1].values
y = df.iloc[:, 2].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

from sklearn.tree import DecisionTreeRegressor

DTR = DecisionTreeRegressor()

DTR.fit(X_train, y_train)


问:
How can I disable authentication for a specific endpoint?
Many answers to similar questions explains that permitAll() means "allow all authenticated users", and that if you want to skip authentication, you need to do

```<code>@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/chores");
}
</code>```

This does not work for me.

In particular, here is my controller test that I would like to pass.

```<code>@SpringBootTest
@AutoConfigureMockMvc
public class ChoreApplicationTest
{
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void choresShouldBeEmptyAtStart() throws Exception
    {
        this.mockMvc.perform(get("/chores")).
                andExpect(status().isOk());
    }
</code>```

Test results:

```<code>java.lang.AssertionError: Status expected:<200> but was:<401>
Expected :200
Actual   :401
</code>```

Here's how I'm setting up the security:

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web.ignoring().antMatchers("/chores");
        super.configure(web);
    }
}
</code>```

I reckon you can imagine what's in the Chores controller, but for completeness here's the relevant part:

```<code>@RestController
public class ChoreController
{
    private final ChoreRepository repository;

    ChoreController(ChoreRepository repository)
    {
        this.repository = repository;
    }

    @GetMapping("/chores")
    List<Chore> all()
    {
        return this.repository.findAll();
    }
}
</code>```

Here is the request that the test prints in the output:

```<code>MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /chores
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/chores]}
</code>```

So why is my test getting a return code of 401, and how can I fix it?

答:
```<code>@ActiveProfiles("integration-test")
@SpringBootTest
@AutoConfigureMockMvc
public class ChoreApplicationTest{}

@Configuration
@EnableWebSecurity
@Profile("!integration-test")
public class SecurityConfigurer extends WebSecurityConfigurerAdapter{}
</code>```

You can ignore security by this way.

If you are writing integration test, then you can set profile to ignore some specific areas of spring. Example: security.

ActiveProfile can be on configuration file.

Body:
Many answers to similar questions explains that permitAll() means "allow all authenticated users", and that if you want to skip authentication, you need to do

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/chores");
}

This does not work for me.

In particular, here is my controller test that I would like to pass.

@SpringBootTest
@AutoConfigureMockMvc
public class ChoreApplicationTest
{
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void choresShouldBeEmptyAtStart() throws Exception
    {
        this.mockMvc.perform(get("/chores")).
                andExpect(status().isOk());
    }

Test results:

java.lang.AssertionError: Status expected:<200> but was:<401>
Expected :200
Actual   :401

Here's how I'm setting up the security:

@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web.ignoring().antMatchers("/chores");
        super.configure(web);
    }
}

I reckon you can imagine what's in the Chores controller, but for completeness here's the relevant part:

@RestController
public class ChoreController
{
    private final ChoreRepository repository;

    ChoreController(ChoreRepository repository)
    {
        this.repository = repository;
    }

    @GetMapping("/chores")
    List<Chore> all()
    {
        return this.repository.findAll();
    }
}

Here is the request that the test prints in the output:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /chores
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/chores]}

So why is my test getting a return code of 401, and how can I fix it?

Body:
@ActiveProfiles("integration-test")
@SpringBootTest
@AutoConfigureMockMvc
public class ChoreApplicationTest{}

@Configuration
@EnableWebSecurity
@Profile("!integration-test")
public class SecurityConfigurer extends WebSecurityConfigurerAdapter{}

You can ignore security by this way.

If you are writing integration test, then you can set profile to ignore some specific areas of spring. Example: security.

ActiveProfile can be on configuration file.


问:
Duplicate data when working with multiple tables. Clarification needed
I have a very simple table as shown when query returning clean data select * from Income where symbol = 'AAPL' and statementitem = 'Revenues' and periodtype="Annual";

--

When I attempt to put together a report, I get 0 from someplace. How can I remove the 0 to get a clean output? Where do these 0s come from?

```<code>DROP TABLE IF EXISTS _vars;
CREATE TABLE _vars(symbol);
INSERT INTO  _vars(symbol) VALUES ('AAPL');

SELECT distinct a.yearmonth, a.symbol, periodtype,

      case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
      case when a.statementitem = 'Gross Profit' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
      case when a.statementitem = 'Selling General & Admin Expenses' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit

FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol and a.periodtype = 'Annual'
</code>```

答:
Your 1st query contains 3 conditions:

```<code>WHERE symbol = 'AAPL' AND statementitem = 'Revenues' AND periodtype = 'Annual'
</code>```

and the result is 10 rows.

Your 2nd query joins _vars to the table and since _vars contains only 1 row with the column symbol having value 'AAPL' and you also apply the condition:

```<code>and a.periodtype = 'Annual'
</code>```

in the ON clause, you are covering only 2 of the conditions of the 1st query.

You do not apply the condition:

```<code>statementitem = 'Revenues'
</code>```

you are just checking it in:

```<code>case when a.statementitem = 'Revenues' AND .....
</code>```

Checking a condition does not apply it.

This means that you get more rows in the results that are coming from all the rows that do not have 'Revenues' in the column statementitem and the CASE expression returns 0 for these rows in the column Revenue.

Edit:

You should use conditional aggregation:

```<code>SELECT a.yearmonth, a.symbol, a.periodtype,
  COALESCE(MAX(CASE WHEN a.statementitem = 'Revenues' THEN a.value END), 0) Revenue,
  COALESCE(MAX(CASE WHEN a.statementitem = 'Gross Profit' THEN a.value END), 0) GrossProfit,
  COALESCE(MAX(CASE WHEN a.statementitem = 'Selling General & Admin Expenses' THEN a.value END), 0) [Selling General & Admin Expenses]
FROM _vars INNER JOIN Income a
ON a.symbol = _vars.symbol AND a.periodtype = 'Annual'
GROUP BY a.yearmonth, a.symbol, a.periodtype
</code>```

Body:
I have a very simple table as shown when query returning clean data select * from Income where symbol = 'AAPL' and statementitem = 'Revenues' and periodtype="Annual";

--

When I attempt to put together a report, I get 0 from someplace. How can I remove the 0 to get a clean output? Where do these 0s come from?

DROP TABLE IF EXISTS _vars;
CREATE TABLE _vars(symbol);
INSERT INTO  _vars(symbol) VALUES ('AAPL');

SELECT distinct a.yearmonth, a.symbol, periodtype,

      case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
      case when a.statementitem = 'Gross Profit' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
      case when a.statementitem = 'Selling General & Admin Expenses' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit

FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol and a.periodtype = 'Annual'

Body:
Your 1st query contains 3 conditions:

WHERE symbol = 'AAPL' AND statementitem = 'Revenues' AND periodtype = 'Annual'

and the result is 10 rows.

Your 2nd query joins _vars to the table and since _vars contains only 1 row with the column symbol having value 'AAPL' and you also apply the condition:

and a.periodtype = 'Annual'

in the ON clause, you are covering only 2 of the conditions of the 1st query.

You do not apply the condition:

statementitem = 'Revenues'

you are just checking it in:

case when a.statementitem = 'Revenues' AND .....

Checking a condition does not apply it.

This means that you get more rows in the results that are coming from all the rows that do not have 'Revenues' in the column statementitem and the CASE expression returns 0 for these rows in the column Revenue.

Edit:

You should use conditional aggregation:

SELECT a.yearmonth, a.symbol, a.periodtype,
  COALESCE(MAX(CASE WHEN a.statementitem = 'Revenues' THEN a.value END), 0) Revenue,
  COALESCE(MAX(CASE WHEN a.statementitem = 'Gross Profit' THEN a.value END), 0) GrossProfit,
  COALESCE(MAX(CASE WHEN a.statementitem = 'Selling General & Admin Expenses' THEN a.value END), 0) [Selling General & Admin Expenses]
FROM _vars INNER JOIN Income a
ON a.symbol = _vars.symbol AND a.periodtype = 'Annual'
GROUP BY a.yearmonth, a.symbol, a.periodtype


问:
Vuetify Datables - expanded-item slot transition
I'm using Vuetify Datatables and I would like to use a transition on the expanded template. Is there any possibility to use the Vuetify Transition on v-slot:v-slot:expanded-item?

I wasn't able to make the transition work.

Here is my code:

```<code>       <template v-slot:expanded-item="{ headers, item }">
            <td :colspan="headers.length">
                <p>ID Transakce: {{ item.transactionId }}
                <p>Stav {{ item.transactionData.state }}</p>
                <p>Podstav {{ item.transactionData.subState }}</p>
            </td>
    </template>
</code>```

Thanks for you help.

答:
Transition on expanded-item was removed for 2.x version. There are some issues open on github to to bring its back.

By the way there is a tricky solution posted on codepen: https://codepen.io/webifi/pen/ExxmXbJ

Body:
I'm using Vuetify Datatables and I would like to use a transition on the expanded template. Is there any possibility to use the Vuetify Transition on v-slot:v-slot:expanded-item?

I wasn't able to make the transition work.

Here is my code:

       <template v-slot:expanded-item="{ headers, item }">

ID Transakce: {{ item.transactionId }}

Stav {{ item.transactionData.state }}

Podstav {{ item.transactionData.subState }}

    </template>

Thanks for you help.


问:
A non-recoverable sign in failure occurred Google Sigin
I'm trying to use react-native-google-signin in a new project. I'm trying by hours, to solve this issue and I see all topics, threads and issues about it and nothing solve my problem. The error is: A non-recoverable sign in failure occurred

I, created the project in Google Console

I created the consent screen (and interestingly its status is "not published", would that be the error?)

I created the OAuth Android Client Id and passed it to the module like this (I've tried to create a webclient id, I've tried it through firebase, none of the alternatives worked):

GoogleSignin.configure ({
     webClientId: GOOGLE_CLIENT_ID,
     offlineAccess: false,
   });

答:
Make sure you follow the main steps for the Google sign-in integration:

Google Sign-in integration

Please put special focus on the configuration for the Google Api Console Project. You must provide the SHA-1 hash of your signing certificate.

In case you have some doubt about your hash:

For debug hash check in your android/app/build.gradle.
This is the default signing configuration for debug

```<code>signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
</code>```

You can retrieve the the SHA1 hash with this command.
I'm asumming you're in the path of your debug.keystore file. (default android/app/debug.keystore)

keytool -list -v -keystore debug.keystore

password: android

Copy the SHA1 value from the terminal and include in the Console configuration XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX

For release hash you should create your own production keystore and get the SHA1 hash to include in your Console configuration.

Here is some information about retrieve the hash
Authenticating Your Client

Here is some information to generate your own keystore
App Signing

Body:
Make sure you follow the main steps for the Google sign-in integration:

Google Sign-in integration

Please put special focus on the configuration for the Google Api Console Project. You must provide the SHA-1 hash of your signing certificate.

In case you have some doubt about your hash:

For debug hash check in your android/app/build.gradle.
This is the default signing configuration for debug

signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }

You can retrieve the the SHA1 hash with this command.
I'm asumming you're in the path of your debug.keystore file. (default android/app/debug.keystore)

keytool -list -v -keystore debug.keystore

password: android

Copy the SHA1 value from the terminal and include in the Console configuration XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX

For release hash you should create your own production keystore and get the SHA1 hash to include in your Console configuration.

Here is some information about retrieve the hash
Authenticating Your Client

Here is some information to generate your own keystore
App Signing


问:
How do I download the Android SDK without downloading Android Studio?
As of the moment, I am running a Windows 8.1 PC that does not have the storage or the RAM for a IDE like Android Studio or Eclipse. I want to download the Android SDK tools, without the IDE. How can this be accomplished?</p>

答:
Well the folks who are trying to download either on *ix or Ec2 machine would suggest to clean approach in below steps:

```<code>$ mkdir android-sdk
$ cd android-sdk
$ mkdir cmdline-tools
$ cd cmdline-tools
$ wget https://dl.google.com/android/repository/commandlinetools-linux-*.zip
$ unzip commandlinetools-linux-*.zip
</code>```

The king - sdkmanager lives inside

cmdline-tools/tools/bin

, you'd better set in PATH environment variable.

but cmdline-tools should not be set as ANDROID_HOME. Because later, when updating Android SDK, or installing more packages, the other packages will be placed under ANDROID_HOME, but not under cmdline-tools.

The final, complete ANDROID_HOME directory structure should look like below, consist of quite a few sub-directories:

build-tools, cmdline-tools, emulator, licenses, patcher, platform-tools, platforms, tools.
You can easily point out that build-tools and cmdline-tools are siblings, all resides inside the parent ANDROID_HOME.

Add SDK tools directory in PATH environment variable to make executable available globally. Add below line either in ~/.bashrc or ~/.profile file to make it permanent.

In order to edit the ~/.bashrc simply can be editable in vim mode

```<code>$ vim .bashrc
</code>```

Now set your preferred ANDROID_HOME in .bashrc file :

```<code>export ANDROID_HOME=/home/<user>/android-sdk
export PATH=${PATH}:$ANDROID_HOME/cmdline-tools/tools/bin:$ANDROID_HOME/platform-tools
</code>```

here strange thing that we haven't download the platform-tools directory as of now but mentoning it under path but let it be as it will help you avoid remodification on the same file later.

Now go inside the same directory:

```<code>$ cd android-sdk
</code>```

NOTE: well in first attempt sdkmanager command didnt found for me so I close the terminal and again created the connection or you can also refresh the same if it works for you.

after that use the sdkmanager to list and install the packages needed:

```<code>$ sdkmanager "platform-tools" "platforms;android-27" "build-tools;27.0.3"
</code>```

Hence Sdkmanager path is already set it will be accessible from anywhere:

```<code>$ sdkmanager --update

$ sdkmanager --list
Installed packages:=====================] 100% Computing updates...
  Path                 | Version | Description                    | Location
  -------              | ------- | -------                        | -------
  build-tools;27.0.3   | 27.0.3  | Android SDK Build-Tools 27.0.3 | build-tools/27.0.3/
  emulator             | 30.0.12 | Android Emulator               | emulator/
  patcher;v4           | 1       | SDK Patch Applier v4           | patcher/v4/
  platform-tools       | 30.0.1  | Android SDK Platform-Tools     | platform-tools/
  platforms;android-27 | 3       | Android SDK Platform 27        | platforms/android-27/
</code>```

Body:
Well the folks who are trying to download either on *ix or Ec2 machine would suggest to clean approach in below steps:

$ mkdir android-sdk
$ cd android-sdk
$ mkdir cmdline-tools
$ cd cmdline-tools
$ wget https://dl.google.com/android/repository/commandlinetools-linux-*.zip
$ unzip commandlinetools-linux-*.zip

The king - sdkmanager lives inside

cmdline-tools/tools/bin

, you'd better set in PATH environment variable.

but cmdline-tools should not be set as ANDROID_HOME. Because later, when updating Android SDK, or installing more packages, the other packages will be placed under ANDROID_HOME, but not under cmdline-tools.

The final, complete ANDROID_HOME directory structure should look like below, consist of quite a few sub-directories:

build-tools, cmdline-tools, emulator, licenses, patcher, platform-tools, platforms, tools.
You can easily point out that build-tools and cmdline-tools are siblings, all resides inside the parent ANDROID_HOME.

Add SDK tools directory in PATH environment variable to make executable available globally. Add below line either in ~/.bashrc or ~/.profile file to make it permanent.

In order to edit the ~/.bashrc simply can be editable in vim mode

$ vim .bashrc

Now set your preferred ANDROID_HOME in .bashrc file :

export ANDROID_HOME=/home/<user>/android-sdk
export PATH=${PATH}:$ANDROID_HOME/cmdline-tools/tools/bin:$ANDROID_HOME/platform-tools

here strange thing that we haven't download the platform-tools directory as of now but mentoning it under path but let it be as it will help you avoid remodification on the same file later.

Now go inside the same directory:

$ cd android-sdk

NOTE: well in first attempt sdkmanager command didnt found for me so I close the terminal and again created the connection or you can also refresh the same if it works for you.

after that use the sdkmanager to list and install the packages needed:

$ sdkmanager "platform-tools" "platforms;android-27" "build-tools;27.0.3"

Hence Sdkmanager path is already set it will be accessible from anywhere:

$ sdkmanager --update

$ sdkmanager --list
Installed packages:=====================] 100% Computing updates...
  Path                 | Version | Description                    | Location
  -------              | ------- | -------                        | -------
  build-tools;27.0.3   | 27.0.3  | Android SDK Build-Tools 27.0.3 | build-tools/27.0.3/
  emulator             | 30.0.12 | Android Emulator               | emulator/
  patcher;v4           | 1       | SDK Patch Applier v4           | patcher/v4/
  platform-tools       | 30.0.1  | Android SDK Platform-Tools     | platform-tools/
  platforms;android-27 | 3       | Android SDK Platform 27        | platforms/android-27/


答:
Since you tag panda do explode , then pass crosstab count the freq , and flatten the index with join

```<code>s=pd.Series(d).explode()
s=pd.crosstab(s.index,s).stack()
s.index=s.index.map('_'.join)
s.to_dict()
{'duck_black': 1, 'duck_brown': 3, 'duck_grey': 1, 'horse_black': 1, 'horse_brown': 1, 'horse_grey': 0}
</code>```

Body:
I need help getting some outputs from a dictionary (python3):

{'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}

Outputs required:

black horse: 1
brown horse: 1
grey horse: 0
black duck: 1
brown duck: 3
grey duck: 1

Can someone offer a solution please?

Body:
Since you tag panda do explode , then pass crosstab count the freq , and flatten the index with join

s=pd.Series(d).explode()
s=pd.crosstab(s.index,s).stack()
s.index=s.index.map('_'.join)
s.to_dict()
{'duck_black': 1, 'duck_brown': 3, 'duck_grey': 1, 'horse_black': 1, 'horse_brown': 1, 'horse_grey': 0}


问:
is it possible to run a python script without saving it?
I have tried RUN a script that was commented and saved, so. When I uncommented a part of code without save the script, it run but, it takes like if it's still commented. I had to save the script with the part uncommented.</p>

答:
No, it is not possible.

However, you can modify a VS Code setting files.autoSave to auto save a file automatically.
Also, take a look at files.autoSaveDelay setting if it suits your needs.


问:
Query when data is not available in one of the table
I have 2 tables A & B. I used left join on table, but when left table(A) does not have I want query which return right table values with same columns as blank from left table.

I used below query and it is working fine for me. Is there any better way to built same query to improve performance?

```<code>IF EXISTS(SELECT 1 FROM TableA WHERE Project_ID = @Project_ID)
    SELECT
        A.ID, A.Project_ID, A.Column1, A.Column2,
        B.Column
    FROM
        TableA A
    LEFT JOIN
        TableB B ON A.Project_ID = B.Project_ID
    WHERE
        A.Project_ID = @Project_ID
ELSE
    SELECT
        B.ID, B.Project_ID, '' As Column1, '' As Column2, B.Column
    FROM
        TableB
    WHERE
        project_ID = @Project_ID
</code>```

答:
you should use full join:</p>

```<code>SELECT
    ISNULL(A.ID,B.ID) AS ID
   ,ISNULL(A.Project_ID, B.Project_ID) AS Project_ID
   , A.Column1, A.Column2, B.Column

FROM
    TableA A

FULL JOIN
    TableB B ON A.Project_ID = B.Project_ID

WHERE
    isnull(A.Project_ID ,B.Project_ID) =  @Project_ID
</code>```

Body:
I have 2 tables A & B. I used left join on table, but when left table(A) does not have I want query which return right table values with same columns as blank from left table.

I used below query and it is working fine for me. Is there any better way to built same query to improve performance?

IF EXISTS(SELECT 1 FROM TableA WHERE Project_ID = @Project_ID)
    SELECT
        A.ID, A.Project_ID, A.Column1, A.Column2,
        B.Column
    FROM
        TableA A
    LEFT JOIN
        TableB B ON A.Project_ID = B.Project_ID
    WHERE
        A.Project_ID = @Project_ID
ELSE
    SELECT
        B.ID, B.Project_ID, '' As Column1, '' As Column2, B.Column
    FROM
        TableB
    WHERE
        project_ID = @Project_ID

Body:
you should use full join:

SELECT
    ISNULL(A.ID,B.ID) AS ID
   ,ISNULL(A.Project_ID, B.Project_ID) AS Project_ID
   , A.Column1, A.Column2, B.Column

FROM
    TableA A

FULL JOIN
    TableB B ON A.Project_ID = B.Project_ID

WHERE
    isnull(A.Project_ID ,B.Project_ID) =  @Project_ID


问:
Testing whether a value is odd or even
I decided to create simple isEven and isOdd function with a very simple algorithm:

```<code>function isEven(n) {
  n = Number(n);
  return n === 0 || !!(n && !(n%2));
}

function isOdd(n) {
  return isEven(Number(n) + 1);
}
</code>```

That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.

```<code>// Returns true if:
//
//    n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string

(function (global) {

  function basicTests(n) {

    // Deal with empty string
    if (n === '')
      return false;

    // Convert n to Number (may set to NaN)
    n = Number(n);

    // Deal with NaN
    if (isNaN(n))
      return false;

    // Deal with infinity -
    if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
      return false;

    // Return n as a number
    return n;
  }

  function isEven(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Convert to Number and proceed
    n = Number(n);

    // Return true/false
    return n === 0 || !!(n && !(n%2));
  }
  global.isEven = isEven;

  // Returns true if n is an integer and (n+1) is even
  // Returns false if n is not an integer or (n+1) is not even
  // Empty string evaluates to zero so returns false (zero is even)
  function isOdd(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Return true/false
    return n === 0 || !!(n && (n%2));
  }
  global.isOdd = isOdd;

}(this));
</code>```

Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?

There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.

答:
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)

```<code>function isEven(n) {
   return /^-?\d*[02468]$/.test(n);
}

function isOdd(n) {
   return /^-?\d*[13579]$/.test(n);
}
</code>```

Title: Testing whether a value is odd or even

Body:
I decided to create simple isEven and isOdd function with a very simple algorithm:

function isEven(n) {
  n = Number(n);
  return n === 0 || !!(n && !(n%2));
}

function isOdd(n) {
  return isEven(Number(n) + 1);
}

That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.

// Returns true if:
//
//    n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string

(function (global) {

  function basicTests(n) {

    // Deal with empty string
    if (n === '')
      return false;

    // Convert n to Number (may set to NaN)
    n = Number(n);

    // Deal with NaN
    if (isNaN(n))
      return false;

    // Deal with infinity -
    if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
      return false;

    // Return n as a number
    return n;
  }

  function isEven(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Convert to Number and proceed
    n = Number(n);

    // Return true/false
    return n === 0 || !!(n && !(n%2));
  }
  global.isEven = isEven;

  // Returns true if n is an integer and (n+1) is even
  // Returns false if n is not an integer or (n+1) is not even
  // Empty string evaluates to zero so returns false (zero is even)
  function isOdd(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Return true/false
    return n === 0 || !!(n && (n%2));
  }
  global.isOdd = isOdd;

}(this));

Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?

There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.

Body:
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)

function isEven(n) {
   return /^-?\d*[02468]$/.test(n);
}

function isOdd(n) {
   return /^-?\d*[13579]$/.test(n);
}


问:
Almost all of the constructors and deconstructors in my classes are implicitly defined as deleted?
Variable.h

```<code>#pragma once

#include <unordered_map>

namespace ssu
{
    class GenericArray;

    class Variable
    {
        enum Type
        {
            NONE,

            BOOL,
            STRING,
            INT,
            FLOAT,

            ARRAY,
            DICT,

            TYPE_MAX
        };
    private:
        template<typename Key, typename Value>
        using Dictionary = std::unordered_map<Key, Value>;

        union
        {
            bool _bool;
            std::string _string;
            int64_t _int;
            double _float;

            GenericArray _array;
            Dictionary<std::string, Variable&> _dict;
        };

        Type m_Type;
    private:
        static inline Variable eval();
    public:
        Variable(const bool p_bool);
        Variable(const std::string p_string);
        Variable(const int64_t p_int);
        Variable(const double p_float);
        Variable(const GenericArray p_array);
        Variable(const Dictionary<std::string, Variable&> p_dict);
    };

    class GenericArray
    {
    private:
        struct Block
        {
            Variable m_Data;
            Block* m_Next;
            Block* m_Prev;
        };

        Block* m_First;
        Block* m_Last;

        size_t m_Size = 0;
    public:
        void push_back(Variable p_var);
        void erase(int index);
        void erase(int first, int end);

        Variable& operator[] (int index);
    };
}
</code>```

Variable.cpp

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

namespace ssu
{
    void GenericArray::push_back(Variable p_var)
    {
        Block* block = new Block;
        block->m_Data = p_var;

        if (!m_First || !m_Last)
        {
            m_First = block;
            m_Last = block;
        }
    }
}
</code>```

I am extremely confused by the errors I'm getting. I've tried compiling the code, but it won't build. This never happened before.

In case it matters, the Variable class is intended to be used as a generic type for all of the values in the union. Maybe the recursion between GenericArray and Variable is contributing to the problem?

These are the types of errors I'm getting:

```<code>File    Severity    Code    Line    Description
variable.cpp    Error   C2280   6   'ssu::Variable::~Variable(void)': attempting to reference a deleted function
variable.cpp    Error   E1790   7   the default constructor of "ssu::GenericArray::Block" cannot be referenced -- it is a deleted function
variable.cpp    Error   E1776   8   function "ssu::Variable::operator=(const ssu::Variable &)" (declared implicitly) cannot be referenced -- it is a deleted function
variable.h      Error   C2079   36  'ssu::Variable::_array' uses undefined class 'ssu::GenericArray'
variable.h      Warning C4624   50  'ssu::Variable': destructor was implicitly defined as deleted
variable.h      Warning C4624   60  'ssu::GenericArray::Block': destructor was implicitly defined as deleted
variable.h      Error   C2079   36  'ssu::Variable::_array' uses undefined class 'ssu::GenericArray'
variable.h      Warning C4624   50  'ssu::Variable': destructor was implicitly defined as deleted
variable.h      Warning C4624   60  'ssu::GenericArray::Block': destructor was implicitly defined as deleted
variable.cpp    Error   C2280   7   'ssu::GenericArray::Block::Block(void)': attempting to reference a deleted function
variable.cpp    Error   C2280   8   'ssu::Variable &ssu::Variable::operator =(const ssu::Variable &)': attempting to reference a deleted function
</code>```

答:
Union declaration

Unions cannot contain a non-static data member with a non-trivial special member function (copy constructor, copy-assignment operator, or destructor).

If a union contains a non-static data member with a non-trivial special member function (copy/move constructor, copy/move assignment, or destructor), that function is deleted by default in the union and needs to be defined explicitly by the programmer.

If a union contains a non-static data member with a non-trivial default constructor, the default constructor of the union is deleted by default unless a variant member of the union has a default member initializer.

Such non-static data members with non-trivial default constructors are std::string and Dictionary.

If a class data member has the deleted constructor, the class default constructor is deleted by default.

Body:
Variable.h

#pragma once

#include <unordered_map>

namespace ssu
{
    class GenericArray;

    class Variable
    {
        enum Type
        {
            NONE,

            BOOL,
            STRING,
            INT,
            FLOAT,

            ARRAY,
            DICT,

            TYPE_MAX
        };
    private:
        template<typename Key, typename Value>
        using Dictionary = std::unordered_map<Key, Value>;

        union
        {
            bool _bool;
            std::string _string;
            int64_t _int;
            double _float;

            GenericArray _array;
            Dictionary<std::string, Variable&> _dict;
        };

        Type m_Type;
    private:
        static inline Variable eval();
    public:
        Variable(const bool p_bool);
        Variable(const std::string p_string);
        Variable(const int64_t p_int);
        Variable(const double p_float);
        Variable(const GenericArray p_array);
        Variable(const Dictionary<std::string, Variable&> p_dict);
    };

    class GenericArray
    {
    private:
        struct Block
        {
            Variable m_Data;
            Block* m_Next;
            Block* m_Prev;
        };

        Block* m_First;
        Block* m_Last;

        size_t m_Size = 0;
    public:
        void push_back(Variable p_var);
        void erase(int index);
        void erase(int first, int end);

        Variable& operator[] (int index);
    };
}

Variable.cpp

#include "variable.h"

namespace ssu
{
    void GenericArray::push_back(Variable p_var)
    {
        Block* block = new Block;
        block->m_Data = p_var;

        if (!m_First || !m_Last)
        {
            m_First = block;
            m_Last = block;
        }
    }
}

I am extremely confused by the errors I'm getting. I've tried compiling the code, but it won't build. This never happened before.

In case it matters, the Variable class is intended to be used as a generic type for all of the values in the union. Maybe the recursion between GenericArray and Variable is contributing to the problem?

These are the types of errors I'm getting:

File    Severity    Code    Line    Description
variable.cpp    Error   C2280   6   'ssu::Variable::~Variable(void)': attempting to reference a deleted function
variable.cpp    Error   E1790   7   the default constructor of "ssu::GenericArray::Block" cannot be referenced -- it is a deleted function
variable.cpp    Error   E1776   8   function "ssu::Variable::operator=(const ssu::Variable &)" (declared implicitly) cannot be referenced -- it is a deleted function
variable.h      Error   C2079   36  'ssu::Variable::_array' uses undefined class 'ssu::GenericArray'
variable.h      Warning C4624   50  'ssu::Variable': destructor was implicitly defined as deleted
variable.h      Warning C4624   60  'ssu::GenericArray::Block': destructor was implicitly defined as deleted
variable.h      Error   C2079   36  'ssu::Variable::_array' uses undefined class 'ssu::GenericArray'
variable.h      Warning C4624   50  'ssu::Variable': destructor was implicitly defined as deleted
variable.h      Warning C4624   60  'ssu::GenericArray::Block': destructor was implicitly defined as deleted
variable.cpp    Error   C2280   7   'ssu::GenericArray::Block::Block(void)': attempting to reference a deleted function
variable.cpp    Error   C2280   8   'ssu::Variable &ssu::Variable::operator =(const ssu::Variable &)': attempting to reference a deleted function


问:
How to invoke a @app.route function set up in zappa from outside using boto3?
I have a zappa lambda deployed at arn:aws:lambda:us-east-1:xxxxx:function:xx-xx-prod, which serves a route like so:

```<code>@app.route('/test', methods=['POST'])
def test():
    response = app.response_class(
      response=get_jsonstr({'test': 'OK'}),
      status=200,
      mimetype='application/json'
    )
    return response
</code>```

I want to invoke the above test() function from another lambda function like so:

```<code>client = boto3.client('lambda', region_name='us-east-1')
r = client.invoke(
  FunctionName='arn:aws:lambda:us-east-1:xxxxx:function:xx-xx-prod',
  InvocationType='RequestResponse',
  LogType='None',
  Payload='',
)
print(r)
print(json.loads(r['Payload'].read()))
</code>```

The above call succeeds like so:

```<code>{
  'ResponseMetadata': {
    'RequestId': '37ecc17b-03a9-11e9-9ea0-9dee231dfb79',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'date': 'Wed, 19 Dec 2018 16:14:55 GMT',
      'content-type': 'application/json',
      'content-length': '4',
      'connection': 'keep-alive',
      'x-amzn-requestid': '37ecc17b-03a9-11e9-9ea0-9dee231dfb79',
      'x-amzn-remapped-content-length': '0',
      'x-amz-executed-version': '$LATEST',
      'x-amzn-trace-id': 'root=1-5c1a6e7d-8063e5004eab150d6c967b0;sampled=0'
    },
    'RetryAttempts': 0
  },
  'StatusCode': 200,
  'ExecutedVersion': '$LATEST',
  'Payload': <botocore.response.StreamingBody object at 0x11296ce10>
}
None
</code>```

How do I tell the zappa handler to invoke the test() function?

Update:

I found that I can add a custom handler in zappa_settings.json like so:

"lambda_handler": "lambdafilename.test"

Then, I changed the test() like so:

```<code>@app.route('/test', methods=['POST'])
def test(event=None, context=None):
  return json.dumps({'test': 'OK1'})
</code>```

Now, the invocation returns the expected result:

{"test": "OK1"}

However, with this custom handler, I lose the WSGI functionality that zappa/flask provides.

答:
I had a look into the source code of the Zappa CLI to figure out how the zappa invoke command works internally because that's exactly what we want:
Remotely and programmatically invoke a specific function within your Zappa lambda.

```<code>payload = {'command': '<module_path>.lambda_handler_function'}
client = boto3.client('lambda', region_name='us-east-1')
client.invoke(
  FunctionName='arn:aws:lambda:<arn>:function:<your_zappa_lambda_name>',
  InvocationType='RequestResponse',
  LogType='Tail',
  Payload=json.dumps(payload),
)
</code>```

Keep in mind that your function has to accept the lambda event and context to be a valid entry point.

For more information on how the zappa invoke command works:

if command == 'invoke'

command = {key: function_name}

Body:
I have a zappa lambda deployed at arn:aws:lambda:us-east-1:xxxxx:function:xx-xx-prod, which serves a route like so:

@app.route('/test', methods=['POST'])
def test():
    response = app.response_class(
      response=get_jsonstr({'test': 'OK'}),
      status=200,
      mimetype='application/json'
    )
    return response

I want to invoke the above test() function from another lambda function like so:

client = boto3.client('lambda', region_name='us-east-1')
r = client.invoke(
  FunctionName='arn:aws:lambda:us-east-1:xxxxx:function:xx-xx-prod',
  InvocationType='RequestResponse',
  LogType='None',
  Payload='',
)
print(r)
print(json.loads(r['Payload'].read()))

The above call succeeds like so:

{
  'ResponseMetadata': {
    'RequestId': '37ecc17b-03a9-11e9-9ea0-9dee231dfb79',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'date': 'Wed, 19 Dec 2018 16:14:55 GMT',
      'content-type': 'application/json',
      'content-length': '4',
      'connection': 'keep-alive',
      'x-amzn-requestid': '37ecc17b-03a9-11e9-9ea0-9dee231dfb79',
      'x-amzn-remapped-content-length': '0',
      'x-amz-executed-version': '$LATEST',
      'x-amzn-trace-id': 'root=1-5c1a6e7d-8063e5004eab150d6c967b0;sampled=0'
    },
    'RetryAttempts': 0
  },
  'StatusCode': 200,
  'ExecutedVersion': '$LATEST',
  'Payload': <botocore.response.StreamingBody object at 0x11296ce10>
}
None

How do I tell the zappa handler to invoke the test() function?

Update:

I found that I can add a custom handler in zappa_settings.json like so:

"lambda_handler": "lambdafilename.test"

Then, I changed the test() like so:

@app.route('/test', methods=['POST'])
def test(event=None, context=None):
  return json.dumps({'test': 'OK1'})

Now, the invocation returns the expected result:

{"test": "OK1"}

However, with this custom handler, I lose the WSGI functionality that zappa/flask provides.

Body:
I had a look into the source code of the Zappa CLI to figure out how the zappa invoke command works internally because that's exactly what we want:
Remotely and programmatically invoke a specific function within your Zappa lambda.

payload = {'command': '<module_path>.lambda_handler_function'}
client = boto3.client('lambda', region_name='us-east-1')
client.invoke(
  FunctionName='arn:aws:lambda:<arn>:function:<your_zappa_lambda_name>',
  InvocationType='RequestResponse',
  LogType='Tail',
  Payload=json.dumps(payload),
)

Keep in mind that your function has to accept the lambda event and context to be a valid entry point.

For more information on how the zappa invoke command works:

if command == 'invoke'

command = {key: function_name}


问:
Like expression in JSON Path
I have a JOSN some thing like this

```<code>{
    "Room" :{
    "Book" :
     {
        "name" : "abc"
     },

    "Book1":
     {
       "name" : "xyz"
     },

    "Book3":
    {
      "name" : "abc123"
    },

    "Tv" :
    {
      "name" : "zyc"
    },

    "audio":
    {
      "name" :"sound ++"
    }
    }
}
</code>```

From this JSON I want to filter out all book elements("book","book1","book2") using JSONPATH

As I got to know in in JSONPATH we do not have any "Like" type syntax , but we can do that by using regex.

I tried with this

```<code>$.Room[?(/^.*book.*$/i.test(@.Room))]
</code>```

But this expression return nothing from the JSON.

Can any one help me out in this...

答:
Maybe this link will be helpful for you . Check the table
<code>$..book[?(@.author =~ /.*Tolkien/i)].</code>  This expression brings All books whose author name ends with Tolkien (case-insensitive) --> Modify it for yours </p>

Title: Like expression in JSON Path

Body:
I have a JOSN some thing like this

{
    "Room" :{
    "Book" :
     {
        "name" : "abc"
     },

    "Book1":
     {
       "name" : "xyz"
     },

    "Book3":
    {
      "name" : "abc123"
    },

    "Tv" :
    {
      "name" : "zyc"
    },

    "audio":
    {
      "name" :"sound ++"
    }
    }
}

From this JSON I want to filter out all book elements("book","book1","book2") using JSONPATH

As I got to know in in JSONPATH we do not have any "Like" type syntax , but we can do that by using regex.

I tried with this

$.Room[?(/^.*book.*$/i.test(@.Room))]

But this expression return nothing from the JSON.

Can any one help me out in this...

Body:
Maybe this link will be helpful for you . Check the table
$..book[?(@.author =~ /.*Tolkien/i)].  This expression brings All books whose author name ends with Tolkien (case-insensitive) --> Modify it for yours


问:
update row striping after removing element
I am making a todo-list. And I added row striping on it, which worked.

Now when I delete a task it should update the row striping, which it does not.
After deleting an element instead of being eg. white white beige it should update to white beige white.

I have a tried a lot of things but I couldn't get anything to work. To be fair I am new to all of this and not quite experienced in working with row striping.

Is there even a way to do it?

Here is what I have so far:

loadEvents();

function loadEvents() {
  document.querySelector('form').addEventListener('submit', submit);
  document.querySelector('ul').addEventListener('click', deleteOrTick);
}

function submit(a) {
  a.preventDefault();
  let input = document.querySelector('input');
  if (input.value != '')
    addTask(input.value);
  input.value = '';
}

function addTask(task) {
  let ul = document.querySelector('ul');
  let li = document.createElement('li');
  li.innerHTML = `

${task}

    x
`;
  ul.appendChild(li);
  document.querySelector('.allToDos').style.display = 'block';
}

function deleteOrTick(a) {
  if (a.target.className == 'delete')
    deleteTask(a);
}

function deleteTask(a) {
  let remove = a.target.parentNode;
  let parentNode = remove.parentNode;
  parentNode.removeChild(remove);
  event.stopPropagation();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  list-style-type: none;
}

li {
  font-size: 1.3em;
  color: #2f4f4f;
}

.todo li:nth-child(2n) {
  background: #e0d9c3;
}

.todo {
  width: 500px;
}

.delete {
  cursor: pointer;
}</code>```

  <form action="index.html" method="post">

ToDo-List

Do what you do

      <input type="text" class="form-control" name="task" placeholder="Add a todo" aria-describedby="basic-addon2">

        <button class="btn btn-outline-secondary" type="submit">Add</button>

  </form>

            hi was geht ab

          x

```

答:
deleteTask can be

function deleteTask(event) {
    let remove = event.target.parentNode;
    let parentNode = remove.parentNode;
    remove.parentNode.remove();
    event.stopPropagation();
}
```

Body:
I am making a todo-list. And I added row striping on it, which worked.

Now when I delete a task it should update the row striping, which it does not.
After deleting an element instead of being eg. white white beige it should update to white beige white.

I have a tried a lot of things but I couldn't get anything to work. To be fair I am new to all of this and not quite experienced in working with row striping.

Is there even a way to do it?

Here is what I have so far:

loadEvents();

function loadEvents() {
  document.querySelector('form').addEventListener('submit', submit);
  document.querySelector('ul').addEventListener('click', deleteOrTick);
}

function submit(a) {
  a.preventDefault();
  let input = document.querySelector('input');
  if (input.value != '')
    addTask(input.value);
  input.value = '';
}

function addTask(task) {
  let ul = document.querySelector('ul');
  let li = document.createElement('li');
  li.innerHTML = `

${task}

    x
`;
  ul.appendChild(li);
  document.querySelector('.allToDos').style.display = 'block';
}

function deleteOrTick(a) {
  if (a.target.className == 'delete')
    deleteTask(a);
}

function deleteTask(a) {
  let remove = a.target.parentNode;
  let parentNode = remove.parentNode;
  parentNode.removeChild(remove);
  event.stopPropagation();
}

ul {
  list-style-type: none;
}

li {
  font-size: 1.3em;
  color: #2f4f4f;
}

.todo li:nth-child(2n) {
  background: #e0d9c3;
}

.todo {
  width: 500px;
}

.delete {
  cursor: pointer;
}

  <form action="index.html" method="post">

ToDo-List

Do what you do

      <input type="text" class="form-control" name="task" placeholder="Add a todo" aria-describedby="basic-addon2">

        <button class="btn btn-outline-secondary" type="submit">Add</button>

  </form>

            hi was geht ab

          x


问:
iterative reweighted least squares
I am trying to manually implement the irls logistic regression (Chapter 4.3.3 in Bishop - Pattern Recognition And Machine Learning) in python.

For updating the weights, I am using

However I am not getting satisfying results, also my weights are growing unbounded in each iteration.

I've written this code so far:

```<code>def y(X, w):
    return sigmoid(X.dot(w))

def R(y):
    R = np.identity(y.size)
    R = R*(y*(1-y))
    return R

def irls(X, t):
    w = np.ones(X.shape[1])
    w = w.reshape(w.size, 1)
    t = np.array(list(map(lambda x: 1 if x else 0, t)))
    t = t.reshape(t.size, 1)

    #after 3 iterations matrix is singular
    for i in range(3):
        y_ = y(X,w)
        w = w - np.linalg.inv(X.T.dot(R(y_)).dot(X)).dot((X.T).dot(y_-t))
    return w
</code>```

where X is my design matrix (64 features and 74 samples) and t is my target vector comprising Boolean values (data is from https://archive.ics.uci.edu/ml/datasets/Mice+Protein+Expression).

Any help is appreciated pointing out where I went wrong.

答: So the answer is as simple as setting the initial weight vector w = np.zeros(X.shape[1)

Title: iterative reweighted least squares

Body:
I am trying to manually implement the irls logistic regression (Chapter 4.3.3 in Bishop - Pattern Recognition And Machine Learning) in python.

For updating the weights, I am using

However I am not getting satisfying results, also my weights are growing unbounded in each iteration.

I've written this code so far:

def y(X, w):
    return sigmoid(X.dot(w))

def R(y):
    R = np.identity(y.size)
    R = R*(y*(1-y))
    return R

def irls(X, t):
    w = np.ones(X.shape[1])
    w = w.reshape(w.size, 1)
    t = np.array(list(map(lambda x: 1 if x else 0, t)))
    t = t.reshape(t.size, 1)

    #after 3 iterations matrix is singular
    for i in range(3):
        y_ = y(X,w)
        w = w - np.linalg.inv(X.T.dot(R(y_)).dot(X)).dot((X.T).dot(y_-t))
    return w

where X is my design matrix (64 features and 74 samples) and t is my target vector comprising Boolean values (data is from https://archive.ics.uci.edu/ml/datasets/Mice+Protein+Expression).

Any help is appreciated pointing out where I went wrong.


问:
Transparent background on react-navigation not applying correctly
I am currently trying to make a linear gradient background on my app and it works as intended but on the right header there's some container that I can't access. Any ideas? I tried changing the headerRightContainerStyle but that only affects the button on the right and not that empty space. It's weird how only the right side is affected too because the header's left side is the effect I desire

Image: https://ibb.co/cYKj1XV

Code:

```<code>...
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      title: "Users Page",
      headerStyle: {
        backgroundColor: "transparent",
      },
      headerRightContainerStyle: {
        backgroundColor: "red",
      },
      headerRight: () => <Button title="Next" color={colors.blue} />,
    });
  }, []);

  return (
    <LinearGradient
      colors={gradientColorsBackground}
      style={styles.gradientBackground}
    >
      <SafeAreaView style={styles.container}>
        <KeyboardAvoidingView
          style={styles.keyboardAvoidingContainer}
          behavior="padding"
        >
          <KeyboardAwareFlatList
            style={styles.usersList}
            data={users}
            keyExtractor={(item) => `${item.id}`}
            renderItem={({ item }) => <Person name={item.name} id={item.id} />}
          />
          <TextInput
            style={styles.input}
            autoFocus={false}
            blurOnSubmit={false}
            placeholder="Type people's names"
            onSubmitEditing={({ nativeEvent: { text } }) => addUser(text)}
            autoCorrect={false}
          />
        </KeyboardAvoidingView>
      </SafeAreaView>
    </LinearGradient>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: "100%",
  },
  gradientBackground: {
    flex: 1,
    width: "100%",
    height: "100%",
    alignItems: "center",
  },
  input: {
    height: 50,
    backgroundColor: "orange",
    width: "100%",
    borderStyle: "solid",
    borderWidth: 3,
  },
  keyboardAvoidingContainer: {
    flex: 1,
  },
  usersList: {
    flex: 1,
    width: "100%",
    backgroundColor: colors.blue,
  },
});
...
</code>```

答:
Use this code to make header color transparent

```<code> headerStyle:{ position: 'absolute', backgroundColor: 'transparent', zIndex: 100, top: 0, left: 0, right: 0 }
</code>```

check snack here https://snack.expo.io/lMGBTKXJK

Body:
I am currently trying to make a linear gradient background on my app and it works as intended but on the right header there's some container that I can't access. Any ideas? I tried changing the headerRightContainerStyle but that only affects the button on the right and not that empty space. It's weird how only the right side is affected too because the header's left side is the effect I desire

Image: https://ibb.co/cYKj1XV

Code:

...
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      title: "Users Page",
      headerStyle: {
        backgroundColor: "transparent",
      },
      headerRightContainerStyle: {
        backgroundColor: "red",
      },
      headerRight: () => <Button title="Next" color={colors.blue} />,
    });
  }, []);

  return (
    <LinearGradient
      colors={gradientColorsBackground}
      style={styles.gradientBackground}
    >
      <SafeAreaView style={styles.container}>
        <KeyboardAvoidingView
          style={styles.keyboardAvoidingContainer}
          behavior="padding"
        >
          <KeyboardAwareFlatList
            style={styles.usersList}
            data={users}
            keyExtractor={(item) => `${item.id}`}
            renderItem={({ item }) => <Person name={item.name} id={item.id} />}
          />
          <TextInput
            style={styles.input}
            autoFocus={false}
            blurOnSubmit={false}
            placeholder="Type people's names"
            onSubmitEditing={({ nativeEvent: { text } }) => addUser(text)}
            autoCorrect={false}
          />
        </KeyboardAvoidingView>
      </SafeAreaView>
    </LinearGradient>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: "100%",
  },
  gradientBackground: {
    flex: 1,
    width: "100%",
    height: "100%",
    alignItems: "center",
  },
  input: {
    height: 50,
    backgroundColor: "orange",
    width: "100%",
    borderStyle: "solid",
    borderWidth: 3,
  },
  keyboardAvoidingContainer: {
    flex: 1,
  },
  usersList: {
    flex: 1,
    width: "100%",
    backgroundColor: colors.blue,
  },
});
...

Body:
Use this code to make header color transparent

 headerStyle:{ position: 'absolute', backgroundColor: 'transparent', zIndex: 100, top: 0, left: 0, right: 0 }

check snack here https://snack.expo.io/lMGBTKXJK


问:
Convert a rigid transformation so that the rotation center is not the origin
Given a rotation matrix R, what is the equivalent transformation so that some point c (the new rotation center) is unchanged under the transformation y = R * c, i.e., change R so that the rotation center is at c rather than the origin. One limitation is that I cannot act on the actual vector to be used, only edit the original transformation (this is because that part is buried in an external library and I cannot change it).

I have something that works but it violates the above limitation:

import numpy as np

# R is a given rotation matrix, v is an arbitrary vector and cen is the desired center

theta = np.pi / 2
cen = np.array([0.5, 0.5])
v = np.array([0, 0])
R = Rot(theta) # ordinary rotation matrix

y = R @ (v - center ) + cen

# y = [0, 1] which is the expected result since we have a right angle triangle
# with vertices at (0, 0) (0.5, 0.5) and (0, 1)
```

I also tried implementing a calculation similar to here but the result I'm getting is not correct

How can I achive the same result but keeping the form y = R*v (or using a rigid transform y = R*v + t) but not changing v like I did?

答:
While writing the question I came upon the (obvious) solution which is just expanding the solution I wrote before and rearranging. In case someone needs this as well the new transformations should be:

y = R_new*v + t_new

where R_new = R, t_new = (I - R)*cen and I is the identity.

Body:
Given a rotation matrix R, what is the equivalent transformation so that some point c (the new rotation center) is unchanged under the transformation y = R * c, i.e., change R so that the rotation center is at c rather than the origin. One limitation is that I cannot act on the actual vector to be used, only edit the original transformation (this is because that part is buried in an external library and I cannot change it).

I have something that works but it violates the above limitation:

import numpy as np

# R is a given rotation matrix, v is an arbitrary vector and cen is the desired center

theta = np.pi / 2
cen = np.array([0.5, 0.5])
v = np.array([0, 0])
R = Rot(theta) # ordinary rotation matrix

y = R @ (v - center ) + cen

# y = [0, 1] which is the expected result since we have a right angle triangle
# with vertices at (0, 0) (0.5, 0.5) and (0, 1)

I also tried implementing a calculation similar to here but the result I'm getting is not correct

How can I achive the same result but keeping the form y = R*v (or using a rigid transform y = R*v + t) but not changing v like I did?


问:
Share on LinkedIn button
I've found tons of examples to create share on linkedIn this site and others but I'm starting to learn that this approach isn't available anymore?

```<code><?php

$obj_id = get_queried_object_id();
$actual_link = get_permalink( $obj_id );

$pageTitle = urlencode(get_the_title());
$pageUrl = urlencode(get_permalink());
?>

<a id="linkedIn"  href="http://www.linkedin.com/shareArticle?mini=true&url=<?php the_permalink(); ?>&title=<?php print($pageTitle); ?>">
</code>```

It outputs as -

```<code>href="https://www.linkedin.com/shareArticle?mini=true&url=http://localhost:8888/identity-library/ungated-html/&title=Three Questions with Senior Engineering Manager, Maggie Way"
</code>```

But it doesnt work

答:
So, I just noticed, the URL you are trying to share starts with http://localhost:8888....  That needs to be a real URL, that LinkedIn can see, for it to populate any information about it, or in fact, for LinkedIn to consider that URL worthwhile to share.  Try wikipedia.org, and it works.

But, then -- &title=YourTitle as a GET parameter is still broken, and does not populate in the share preview display.  Here is the solution to that: for now, if you want the URL you are sharing on LinkedIn to have preview values for title, image, etc., is to use og: Open Graph tags, as defined in the Open Graph Protocol.

First, you'll want to update your URL...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

This URL fits the new Official LinkedIn Sharing Documentation.

According to the documentation, these are the options you have available...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Want to see that you're doing things right?  Check out the LinkedIn Post Inspector.

Still not sure?  I have coded up a demo website with 30 different social share services, and the share link for LinkedIn certainly works for me!  Check it out: SortWords.com.

Title: Share on LinkedIn button

Body:
I've found tons of examples to create share on linkedIn this site and others but I'm starting to learn that this approach isn't available anymore?

<?php

$obj_id = get_queried_object_id();
$actual_link = get_permalink( $obj_id );

$pageTitle = urlencode(get_the_title());
$pageUrl = urlencode(get_permalink());
?>

<a id="linkedIn"  href="http://www.linkedin.com/shareArticle?mini=true&url=<?php the_permalink(); ?>&title=<?php print($pageTitle); ?>">

It outputs as -

href="https://www.linkedin.com/shareArticle?mini=true&url=http://localhost:8888/identity-library/ungated-html/&title=Three Questions with Senior Engineering Manager, Maggie Way"

But it doesnt work

Body:
So, I just noticed, the URL you are trying to share starts with http://localhost:8888....  That needs to be a real URL, that LinkedIn can see, for it to populate any information about it, or in fact, for LinkedIn to consider that URL worthwhile to share.  Try wikipedia.org, and it works.

But, then -- &title=YourTitle as a GET parameter is still broken, and does not populate in the share preview display.  Here is the solution to that: for now, if you want the URL you are sharing on LinkedIn to have preview values for title, image, etc., is to use og: Open Graph tags, as defined in the Open Graph Protocol.

First, you'll want to update your URL...

https://www.linkedin.com/sharing/share-offsite/?url={url}

This URL fits the new Official LinkedIn Sharing Documentation.

According to the documentation, these are the options you have available...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Want to see that you're doing things right?  Check out the LinkedIn Post Inspector.

Still not sure?  I have coded up a demo website with 30 different social share services, and the share link for LinkedIn certainly works for me!  Check it out: SortWords.com.


问:
E-mail Notifications
In a .net system I'm building, there is a need for automated e-mail notifications. These should be editable by an admin. What's the easiest way to do this? SQL table and WYSIWIG for editing?

The queue is a great idea. I've been throwing around that type of process for awhile with my old company.

答:
Are you just talking about the interface and storage, or the implementation of sending the emails as well?

Yes, a SQL table with FROM, TO, Subject, Body should work for storage and, heck, a textbox or even maybe a RichText box should work for editing.

Or is this a web interface?

For actually sending it, check out the System.Web.Mail namespace, it's pretty self explanatory and easy to use :)

Title: E-mail Notifications

LastEditorDisplayName: Jeff Atwood

ContentLicense: CC BY-SA 2.5


问:
Where to start with Entity Framework
Anyone know a good book or post about how to start in EF? I have seen the DnrTV any other place?</p>

答: Jason's DotNet Architecture Blog has a tutorial that gets you started with the basics, using the MS SQL Server AdventureWorks sample database.</p>

OwnerDisplayName: Jedi Master Spooky

Title: Where to start with Entity Framework

OwnerDisplayName: Yngvar


问:
How to use TinyMCE custom button, with custom dialog, to add content?
TinyMCE editor lets you assign a custom button to its editor toolbar. I did that and hooked it up to a Flickr account, so a custom dialog box appears with a selection of images.

I want the user to be able to then click any image and have the URL of that image added to the original input, from where the custom TinyMCE button was clicked.

This is the TinyMCE custom button code I have:

```<code>setup : function(ed) {
    // Add a custom button
    ed.addButton('flickr', {
        title : 'Add Flickr Image',
        image : 'styles/media_icons/flickr.png',
        onclick : function() {
            // Add your own code to execute something on click

            $("div.mediaLibraryPopup .box").load("scripts/loadMediaLibrary.php");
            $("div.mediaLibraryPopup").fadeIn("slow").addClass(container);

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

Then, when you click on an image, I have this jQuery to handle that event:

```<code>$("div.mediaLibraryPopup img").live("click", function() {
    var url = $(this).attr("src");
    $("div.mediaLibraryPopup").fadeOut("slow");
});
</code>```

I've been reading the TinyMCE documentation and working with it for hours, and I can't figure out how to pass that URL variable back to the TinyMCE "ed" event so that it can add it to the input.

Since I'll be using this on multiple inputs, I can't just hard-code the input class, either. Any thoughts?

答:
I think you need to insert The URL on the Current Cursor Location in the Editor. if that is the case then you can use this command to insert the content:

```<code>tinyMCE.execCommand('mceInsertContent',false,'Your Content Goes Here...');
</code>```

Hope this helps :)

Body:
TinyMCE editor lets you assign a custom button to its editor toolbar. I did that and hooked it up to a Flickr account, so a custom dialog box appears with a selection of images.

I want the user to be able to then click any image and have the URL of that image added to the original input, from where the custom TinyMCE button was clicked.

This is the TinyMCE custom button code I have:

setup : function(ed) {
    // Add a custom button
    ed.addButton('flickr', {
        title : 'Add Flickr Image',
        image : 'styles/media_icons/flickr.png',
        onclick : function() {
            // Add your own code to execute something on click

            $("div.mediaLibraryPopup .box").load("scripts/loadMediaLibrary.php");
            $("div.mediaLibraryPopup").fadeIn("slow").addClass(container);

        }
    });
}

Then, when you click on an image, I have this jQuery to handle that event:

$("div.mediaLibraryPopup img").live("click", function() {
    var url = $(this).attr("src");
    $("div.mediaLibraryPopup").fadeOut("slow");
});

I've been reading the TinyMCE documentation and working with it for hours, and I can't figure out how to pass that URL variable back to the TinyMCE "ed" event so that it can add it to the input.

Since I'll be using this on multiple inputs, I can't just hard-code the input class, either. Any thoughts?

Body:
I think you need to insert The URL on the Current Cursor Location in the Editor. if that is the case then you can use this command to insert the content:

tinyMCE.execCommand('mceInsertContent',false,'Your Content Goes Here...');

Hope this helps :)


问:
Time complexity of function with nested loops
I am trying to understand how to determine big-O and I've found this algorithm and I'm not really sure about my calculations with this one.

```<code>Compute(A,n,x):
begin
  l=0;
  r=n-1;
  while true do
     while l<r and A[l] < x do
         l=l+1;
     end
     while l<r and A[r] >= x do
         r=r-1;
     end
     if l>=r then
        return
     end
     tmp = A[l];
     A[l]=A[r];
     A[r]=tmp;
     l=l+1;
     r=r-1;
  end
end
</code>```

My guess would be O(n*log(n)), but don't have any proper reason why. The way I was thinking...

The inner loops will both have O(n), so I can add those two, still having O(n). And the outer loop will end depending on l, r, which both can grow in the inner loops, so the complexity should be lower than n, but the log(n) is basically just a guess.

Could anyone help me understand, how to approach this in a right way?

Edit: As pointed out in the comments, changed r=0 to r=n-1. My bad.

答:
If you change initial value of r to n-1 (seems it is silly mistake), you will get O(n) procedure similar to Hoare partition (part of Quicksort algorithm).

Just look - left index moves only right, right index moves only left, and loop works until they meet.

r=0; has no sense  - routine stops immediately

Body:
I am trying to understand how to determine big-O and I've found this algorithm and I'm not really sure about my calculations with this one.

Compute(A,n,x):
begin
  l=0;
  r=n-1;
  while true do
     while l<r and A[l] < x do
         l=l+1;
     end
     while l<r and A[r] >= x do
         r=r-1;
     end
     if l>=r then
        return
     end
     tmp = A[l];
     A[l]=A[r];
     A[r]=tmp;
     l=l+1;
     r=r-1;
  end
end

My guess would be O(n*log(n)), but don't have any proper reason why. The way I was thinking...

The inner loops will both have O(n), so I can add those two, still having O(n). And the outer loop will end depending on l, r, which both can grow in the inner loops, so the complexity should be lower than n, but the log(n) is basically just a guess.

Could anyone help me understand, how to approach this in a right way?

Edit: As pointed out in the comments, changed r=0 to r=n-1. My bad.