答:
Inheritance would be the C++03 way

```<code>template< template <int A,char B,bool> typename T>
struct Add_true {
    template <int A,char B>
    struct type : T<A,B,true> {};
};
</code>```

In both C++11 and C++03, type is the name of a new template. The difference is only is only in what the specializations mean. For alias templates, they stand exactly for the thing being aliased, while here they are new types. However, derived to base conversions should allow treating the C++03 type specialization almost exactly as if they were the thing they "alias".

Title: How to transform template to template pre C++11

Body:
Inheritance would be the C++03 way

template< template <int A,char B,bool> typename T>
struct Add_true {
    template <int A,char B>
    struct type : T<A,B,true> {};
};

In both C++11 and C++03, type is the name of a new template. The difference is only is only in what the specializations mean. For alias templates, they stand exactly for the thing being aliased, while here they are new types. However, derived to base conversions should allow treating the C++03 type specialization almost exactly as if they were the thing they "alias".


来源: stackexchange

问:
Do every pin of a micro controller associated with a register?
I'm a beginner in the embedded system development world.
I would like some clarifications on the following questions.

Is every pin of a microcontroller (from here after referred to as mc) associated with a register?

Is it an one to one relationship?

How are ports (or groups of pins) assigned inside the mc?

Is it only possible to set a single pin low or high only?

答:
Not all pins but all IOs (Input/Output) have a specific register.

Each IO has a specific group of registers. Bu also some registers may include specific bits which effects an IO or all IOs.

It depends of design of micro controller.

Yes it is.

I strongly recommend you to read some embedded hardware/software books(for example Newness Know It All books for embedded systems) and datasheets.

ContentLicense: CC BY-SA 4.0


问:
Ssh certificate authentication using certificate of type ssh-rsa-cert-v01
I have created a certificate using ssh-keygen and I couldn't find appropriate method in maverick latest package to establish a connection ..although maverick provides that feature. Where could I
load my private keys and certificates? As I couldn't use keystore, which is for maintaining certificates of type X.509.Kindly let me know of the method for authenticating ssh-rsa-cert-v01 type certificates..</p>

答:
You need to load the certificate just as you would any public key. That means loading the certificate file that ends with "-cert.pub"

```<code>    SshPublicKey publicKey = SshKeyUtils.getPublicKey(
          new File("user_key-cert.pub"));
    SshPrivateKey privateKey = SshKeyUtils.getPrivateKey(
          new File("user_key"), "xxx"));

    SshKeyPair pair = new SshKeyPair();
    pair.setPrivateKey(privateKey);
    pair.setPublicKey(publicKey);
</code>```

You can then present that for authentication as you would any normal SSH key.

```<code>    // Create SshClient
    SshClient ssh = SshConnector.createInstance()
           .connect(new SocketTransport("host", 22), "user"));
    ssh.authenticate(new PublicKeyAuthentication(pair));
</code>```

Body:
You need to load the certificate just as you would any public key. That means loading the certificate file that ends with "-cert.pub"

    SshPublicKey publicKey = SshKeyUtils.getPublicKey(
          new File("user_key-cert.pub"));
    SshPrivateKey privateKey = SshKeyUtils.getPrivateKey(
          new File("user_key"), "xxx"));

    SshKeyPair pair = new SshKeyPair();
    pair.setPrivateKey(privateKey);
    pair.setPublicKey(publicKey);

You can then present that for authentication as you would any normal SSH key.

    // Create SshClient
    SshClient ssh = SshConnector.createInstance()
           .connect(new SocketTransport("host", 22), "user"));
    ssh.authenticate(new PublicKeyAuthentication(pair));


问:
SQL syntax near WHERE?
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?</p>

```<code>protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}
</code>```

答:
So your SQL statement is:
"INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES (blah) WHERE SubmissionId =" + x;

The problem is definitely the WHERE.  WHERE isn't valid for INSERT - See the MSDN documentation for the Insert command.  Since you're filtering by SubmissionId, you probably want to do an UPDATE instead.

As for a better way of finding the problem, learning to use the MSDN documentation is a good step.  A quick Google search for "msdn t-sql insert" will give you the page I linked to earlier in this answer.  Documentation, experience, Google and Stack Overflow.  That's how you find solutions :)

ContentLicense: CC BY-SA 3.0

Title: SQL syntax near WHERE?

Body:
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?

protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}


问:
Angular doesn't have node dependencies after update
Updated from Angular 5 to 9. I got the following error in browser devtools:

Uncaught ReferenceError: global is not defined

I saw the following post addressing the issue:

Upgrading to angular-6.x gives "Uncaught ReferenceError: global is not defined"

So I tried to implement the accepted answer's solution and put the following script in my index.html file  tag:

```<code>  <script>
    var global = global || window;
    var Buffer = Buffer || [];
    var process = process || {
      env: { DEBUG: undefined },
      version: []
    };
  </script>
</code>```

However, this gave the following error in browser devtools:

default-encoding.js:6 Uncaught TypeError: process.version.split is not
  a function

It seems like Angular didn't ship a implementation of process and Buffer to the frontend. Any suggestions how to fix this?

答:
Via https://stackoverflow.com/a/50313953/976676:

This is an incompatibility with Angular v6. They removed support
  (shim) of process and global variables in browser.

For further clarification: https://github.com/angular/angular-cli/issues/9827#issuecomment-369578814

Body:
Updated from Angular 5 to 9. I got the following error in browser devtools:

Uncaught ReferenceError: global is not defined

I saw the following post addressing the issue:

Upgrading to angular-6.x gives "Uncaught ReferenceError: global is not defined"

So I tried to implement the accepted answer's solution and put the following script in my index.html file  tag:

However, this gave the following error in browser devtools:

default-encoding.js:6 Uncaught TypeError: process.version.split is not
  a function

It seems like Angular didn't ship a implementation of process and Buffer to the frontend. Any suggestions how to fix this?


问:
Pandas to datetime check format
I have several csv files which all have a column with a date which is either in DD/MM/YYYY format or MM/DD/YYYY format.

At the moment I manually check the file and convert it the column to pandas datetime using the code below.

```<code>df["date"] = pd.to_datetime(df["date"], dayfirst=True, errors='coerce')
</code>```

In cases of different date format I change dayfirst=True/False.
I have to coerce errors as some rows contain dirty data.
I would like to automate this process so that I only upload the file and pandas will automatically decide if the column is in MM/DD or DD/MM format.

Any tips and suggestions are appreciated.

答:
Okay, I have found something that is working:</p>

```<code>for df in df_list:
    df_test=df["Date"].str.split("/", expand=True)
    df_test[0] = pd.to_numeric(df_test[0], errors="coerce")
    df_test[1] = pd.to_numeric(df_test[1], errors="coerce")
    a=df_test[0].max()
    b=df_test[1].max()
    if b > a:
        df["Date"] = pd.to_datetime(df["Creation Date"],dayfirst=False, errors='coerce')
    elif a > b:
        df["Date"] = pd.to_datetime(df["Creation Date"],dayfirst=True, errors='coerce')
</code>```

Title: Pandas to datetime check format

Body:
I have several csv files which all have a column with a date which is either in DD/MM/YYYY format or MM/DD/YYYY format.

At the moment I manually check the file and convert it the column to pandas datetime using the code below.

df["date"] = pd.to_datetime(df["date"], dayfirst=True, errors='coerce')

In cases of different date format I change dayfirst=True/False.
I have to coerce errors as some rows contain dirty data.
I would like to automate this process so that I only upload the file and pandas will automatically decide if the column is in MM/DD or DD/MM format.

Any tips and suggestions are appreciated.

Body:
Okay, I have found something that is working:

for df in df_list:
    df_test=df["Date"].str.split("/", expand=True)
    df_test[0] = pd.to_numeric(df_test[0], errors="coerce")
    df_test[1] = pd.to_numeric(df_test[1], errors="coerce")
    a=df_test[0].max()
    b=df_test[1].max()
    if b > a:
        df["Date"] = pd.to_datetime(df["Creation Date"],dayfirst=False, errors='coerce')
    elif a > b:
        df["Date"] = pd.to_datetime(df["Creation Date"],dayfirst=True, errors='coerce')


问:
How can I create an array whose length is specified by a const argument?
I have a function:

```<code>void f(const size_t &len){
    double arr[len];
}

</code>```

but it doesn't work, because I got message from len, that "expression must have a constant value". How can I solve this problem, if I don't want to create a global variable len?

答:
C++ does not support variable-length arrays. If len is a compile time constant, I'd advise you to use std::array with a template, like so:

```<code>template<size_t len>
void f(){
    std::array<double, len> arr;
    //use arr
}
</code>```

And you would use it like that:

```<code>int main()
{
    f<5>();
}
</code>```

Do note, that the 5 in my example is a compile-time constant. If you do not know the size of your array at compile time, use a std::vector. You'd do this like this:

```<code>void f(const size_t len){
    std::vector<double> arr(len);
    //use arr
}

int main()
{
    size_t variableLength = 0;
    std::cin >> variableLength;
    f(variableLenght);
}
</code>```

Body:
I have a function:

void f(const size_t &len){
    double arr[len];
}

but it doesn't work, because I got message from len, that "expression must have a constant value". How can I solve this problem, if I don't want to create a global variable len?

Body:
C++ does not support variable-length arrays. If len is a compile time constant, I'd advise you to use std::array with a template, like so:

template<size_t len>
void f(){
    std::array<double, len> arr;
    //use arr
}

And you would use it like that:

int main()
{
    f<5>();
}

Do note, that the 5 in my example is a compile-time constant. If you do not know the size of your array at compile time, use a std::vector. You'd do this like this:

void f(const size_t len){
    std::vector<double> arr(len);
    //use arr
}

int main()
{
    size_t variableLength = 0;
    std::cin >> variableLength;
    f(variableLenght);
}


问:
Spring Boot - Get Data from DB and store it in list and parse it to JSON using jackson
I'm trying to get data from multiple tables and put it in Array List of class, and then convert it to JSON Object.
But when i'm trying to parse it to json using Jackson Object Mapper all the lists are converted as below
Using ObjectMapper().writeValueAsString for deserialization from class objects to json

```<code>```{
"College": [
{
"institution": [
                {
                    "instId": "T34",
                    "Country": "India",
                    "Code": "T33"
                },
                {
                    "instId": "T22",
                    "Country": "India",
                    "Code": "T22"
                }
                ],
"Rating": [
                {
                    "star": "4"
                    "comments": "good"
                },
                {
                    "star": "2"
                    "comments": "ok"
                },
}
]
}```
</code>```

But i want the result as below

```<code>{
"College": [
{
"institution": [
                {
                    "instId": "T34",
                    "Country": "India",
                    "Code": "T33"
                }
                ],
"Rating": [
                {
                    "star": "4"
                    "comments": "good"
                }
            ]

},
{
"institution": [
                {
                    "instId": "T22",
                    "Country": "India",
                    "Code": "T22"
                }
                ],
"Rating": [
                {
                    "star": "2"
                    "comments": "ok"
                }
            ]

}
]
}
</code>```

The above is just an example.

Please help in getting the desired output.

Below are the class files used.

public class AllCollege{
List<College> college = new ArrayList<>();

public List<College> getCollege() {
        return college;
    }

    public void setCollege(List<College> college) {
        this.college = college;
    }

}

public class College{

private List<Institution> institution = new ArrayList<>();
private List<Rating> rating = new ArrayList<>();

    public List<Institution> getInstitution() {
        return institution;
    }

    public void setInstitution(List<Institution> institution) {
        this.institution = institution;
    }

    public List<Rating> getRating() {
        return rating;
    }

    public void setRating(List<Rating> rating) {
        this.rating = rating;
    }

}

public class Institution {

    private String instId;
    private String country;
    private String code;

    public String getInstId() {
        return instId;
    }
    public void setInstId(String instId) {
        this.instId = instId;
    }

    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
}

public class Rating {

    private String star;
    private String comments;

    public String getStar() {
        return star;
    }
    public void setStar(String star) {
        this.star = star;
    }

    public String getComments() {
        return comments;
    }
    public void setComments(String comments) {
        this.comments = comments;
    }

}
```

<p>Below is where the data from tables is set into ArrayList and then converted to json string.</p>

<pre class="lang-java prettyprint-override"><code>session = sessionFactory.openSession();
String sql = "from institution";
Query<InstDto> query = session.createQuery(sql);
List<Institution> configdtoList =query.list();
College alc = new College();
alc.setInstitution(configdtoList);
.
.
.
similarly Rating table.
List<College> clist = new new ArrayList<>();
clist.add(alc);
AllCollege ac = new AllCollege();
ac.setCollege(clist);

String responseJson = new ObjectMapper().writeValueAsString(ac)
</code>```

答: I have created an HashMap contains the List<AllCollege> as value and then used json parser which worked as expected.

Body:
I'm trying to get data from multiple tables and put it in Array List of class, and then convert it to JSON Object.
But when i'm trying to parse it to json using Jackson Object Mapper all the lists are converted as below
Using ObjectMapper().writeValueAsString for deserialization from class objects to json

```{
"College": [
{
"institution": [
                {
                    "instId": "T34",
                    "Country": "India",
                    "Code": "T33"
                },
                {
                    "instId": "T22",
                    "Country": "India",
                    "Code": "T22"
                }
                ],
"Rating": [
                {
                    "star": "4"
                    "comments": "good"
                },
                {
                    "star": "2"
                    "comments": "ok"
                },
}
]
}```

But i want the result as below

{
"College": [
{
"institution": [
                {
                    "instId": "T34",
                    "Country": "India",
                    "Code": "T33"
                }
                ],
"Rating": [
                {
                    "star": "4"
                    "comments": "good"
                }
            ]

},
{
"institution": [
                {
                    "instId": "T22",
                    "Country": "India",
                    "Code": "T22"
                }
                ],
"Rating": [
                {
                    "star": "2"
                    "comments": "ok"
                }
            ]

}
]
}

The above is just an example.

Please help in getting the desired output.

Below are the class files used.

public class AllCollege{
List<College> college = new ArrayList<>();

public List<College> getCollege() {
        return college;
    }

    public void setCollege(List<College> college) {
        this.college = college;
    }

}

public class College{

private List<Institution> institution = new ArrayList<>();
private List<Rating> rating = new ArrayList<>();

    public List<Institution> getInstitution() {
        return institution;
    }

    public void setInstitution(List<Institution> institution) {
        this.institution = institution;
    }

    public List<Rating> getRating() {
        return rating;
    }

    public void setRating(List<Rating> rating) {
        this.rating = rating;
    }

}

public class Institution {

    private String instId;
    private String country;
    private String code;

    public String getInstId() {
        return instId;
    }
    public void setInstId(String instId) {
        this.instId = instId;
    }

    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
}

public class Rating {

    private String star;
    private String comments;

    public String getStar() {
        return star;
    }
    public void setStar(String star) {
        this.star = star;
    }

    public String getComments() {
        return comments;
    }
    public void setComments(String comments) {
        this.comments = comments;
    }

}

Below is where the data from tables is set into ArrayList and then converted to json string.

session = sessionFactory.openSession();
String sql = "from institution";
Query<InstDto> query = session.createQuery(sql);
List<Institution> configdtoList =query.list();
College alc = new College();
alc.setInstitution(configdtoList);
.
.
.
similarly Rating table.
List<College> clist = new new ArrayList<>();
clist.add(alc);
AllCollege ac = new AllCollege();
ac.setCollege(clist);

String responseJson = new ObjectMapper().writeValueAsString(ac)


问:
Is it possible to create a method using these interfaces as parameters?
I'm not sure how to word my issue so that it's clear. But I'll try my best sorry:

I have 4 interfaces:

```<code>        interface OnGetViewPagerListener {
            void onSuccessViewPager(Response<Feed> response);
            void onFailedViewPager();
        }

        interface OnNextPageViewPagerListener {
            void onSuccessViewPagerNextPage(Response<Feed> response);
            void onFailedViewPagerNextPage();
        }

        interface OnGetGridViewListener{
            void onSuccessGridView(Response<Feed> response);
            void onFailedGridView();
        }

        interface OnNextPageGridViewListener{
            void onSuccessGridViewNextPage(Response<Feed> response);
            void onFailedGridViewNextPage();
        }
</code>```

And I'm implementing these interfaces into my class MainRepo. Inside each of these methods, contains a network call:

Main Repo Class

```<code>@Override
public void getPostsViewPager(OnGetViewPagerListener onGetViewPagerListener, String url) {

        //Network Call

        RetrofitInterfaces.IGetTop service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.IGetTop.class);
        Call<Feed> call = service.listRepos(url);
        call.enqueue(new Callback<Feed>() {
            @Override
            public void onResponse(@NonNull Call<Feed> call, @NonNull Response<Feed> response) {
                onGetViewPagerListener.onSuccessViewPager(response);
            }
            @Override
            public void onFailure(@NonNull Call<Feed> call, @NonNull Throwable t) {
                onGetViewPagerListener.onFailedViewPager();
            }
        });
}
</code>```

Is it possible to create a method with the networkcall, and with parameters where I could use any of the 4 interfaces?

```<code>private makeNetworkCall(interface canUseAnyOfThe4InterfacesHere, String url){
    //Network call
}
</code>```

In case this is confusing, here is my code:

https://pastebin.com/y8kq9ZjQ

And as you can see, I don't want to have to type out each network call every time I use each interface.

答: I think closed class hierarchy can meet your needs. Here more about it </p>

Body:
I'm not sure how to word my issue so that it's clear. But I'll try my best sorry:

I have 4 interfaces:

        interface OnGetViewPagerListener {
            void onSuccessViewPager(Response<Feed> response);
            void onFailedViewPager();
        }

        interface OnNextPageViewPagerListener {
            void onSuccessViewPagerNextPage(Response<Feed> response);
            void onFailedViewPagerNextPage();
        }

        interface OnGetGridViewListener{
            void onSuccessGridView(Response<Feed> response);
            void onFailedGridView();
        }

        interface OnNextPageGridViewListener{
            void onSuccessGridViewNextPage(Response<Feed> response);
            void onFailedGridViewNextPage();
        }

And I'm implementing these interfaces into my class MainRepo. Inside each of these methods, contains a network call:

Main Repo Class

@Override
public void getPostsViewPager(OnGetViewPagerListener onGetViewPagerListener, String url) {

        //Network Call

        RetrofitInterfaces.IGetTop service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.IGetTop.class);
        Call<Feed> call = service.listRepos(url);
        call.enqueue(new Callback<Feed>() {
            @Override
            public void onResponse(@NonNull Call<Feed> call, @NonNull Response<Feed> response) {
                onGetViewPagerListener.onSuccessViewPager(response);
            }
            @Override
            public void onFailure(@NonNull Call<Feed> call, @NonNull Throwable t) {
                onGetViewPagerListener.onFailedViewPager();
            }
        });
}

Is it possible to create a method with the networkcall, and with parameters where I could use any of the 4 interfaces?

private makeNetworkCall(interface canUseAnyOfThe4InterfacesHere, String url){
    //Network call
}

In case this is confusing, here is my code:

https://pastebin.com/y8kq9ZjQ

And as you can see, I don't want to have to type out each network call every time I use each interface.


问:
How to get the path of image android?
I am selecting an image of the gallery from my app,
using

ACTION_GET_CONTENT

Now I want the path of this image:

But i get it like this:

content://com.android.providers.media.documents/document/image%3A5793

How can i get the path?

I tried this to get path:

```<code>Uri uri = data.getData();
Log.e("Path is: "+uri);
</code>```

答:
The answer is don't try and get the path because in Android 10 and later you won't be able to get it or use it.

You can get a FileDescriptor or input/output Stream that can be used in most methods that need to access the file contents.

See https://developer.android.com/training/data-storage/ for more details, since it is a picture then using Media store is probably best.

Title: How to get the path of image android?

Body:
I am selecting an image of the gallery from my app,
using

ACTION_GET_CONTENT

Now I want the path of this image:

But i get it like this:

content://com.android.providers.media.documents/document/image%3A5793

How can i get the path?

I tried this to get path:

Uri uri = data.getData();
Log.e("Path is: "+uri);


问:
TypeError: this.props.persistor.subscribe is not a function Redux Persist
I'm incorporating redux-persist into my react app, and am getting the following error:
TypeError: this.props.persistor.subscribe is not a function

I am following the same documentation described in the following link: https://www.npmjs.com/package/redux-persist

store.js

```<code>import {applyMiddleware,createStore,combineReducers} from "redux"
import {createLogger} from "redux-logger"
import thunk from "redux-thunk"
import promise from "redux-promise-middleware"
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web and AsyncStorage for react-native

import reducer from "./Reducers"
const middleware = applyMiddleware(promise(),thunk,createLogger())
const persistConfig = {
  key: 'root',
  storage,
}
const persistedReducer = persistReducer(persistConfig, reducer)

export default () => {
  let store = createStore(persistedReducer,middleware)
  let persistor = persistStore(store)
  return { store, persistor }
}.js:
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux'
import store from "./store"
import persistor from "./store"

import { PersistGate } from 'redux-persist/integration/react'

ReactDOM.render(
    <PersistGate loading={null} persistor={persistor}>
        <Provider store={store}>
                <MuiThemeProvider>
                    <App />
                </MuiThemeProvider>
        </Provider>
    </PersistGate>,

    document.getElementById('root'));
registerServiceWorker();
</code>```

答:
Just export your store and persitor like this:

```<code>export default {store, persistor};
</code>```

Then on you reducer import it like this (where the store and persistor are defined):

```<code>import Store from 'yourModuleName'
</code>```

Lastly, call your persistor and store and put PersistGate inside the Provider like this:

```<code><Provider store={Store.store}>
     <PersistGate loading={null} persistor={Store.persistor}>
         <MuiThemeProvider>
            <App />
         </MuiThemeProvider>
     </PersistGate>,
</Provider>

</code>```

Body:
I'm incorporating redux-persist into my react app, and am getting the following error:
TypeError: this.props.persistor.subscribe is not a function

I am following the same documentation described in the following link: https://www.npmjs.com/package/redux-persist

store.js

import {applyMiddleware,createStore,combineReducers} from "redux"
import {createLogger} from "redux-logger"
import thunk from "redux-thunk"
import promise from "redux-promise-middleware"
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web and AsyncStorage for react-native

import reducer from "./Reducers"
const middleware = applyMiddleware(promise(),thunk,createLogger())
const persistConfig = {
  key: 'root',
  storage,
}
const persistedReducer = persistReducer(persistConfig, reducer)

export default () => {
  let store = createStore(persistedReducer,middleware)
  let persistor = persistStore(store)
  return { store, persistor }
}.js:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux'
import store from "./store"
import persistor from "./store"

import { PersistGate } from 'redux-persist/integration/react'

ReactDOM.render(
    <PersistGate loading={null} persistor={persistor}>
        <Provider store={store}>
                <MuiThemeProvider>
                    <App />
                </MuiThemeProvider>
        </Provider>
    </PersistGate>,

    document.getElementById('root'));
registerServiceWorker();

Body:
Just export your store and persitor like this:

export default {store, persistor};

Then on you reducer import it like this (where the store and persistor are defined):

import Store from 'yourModuleName'

Lastly, call your persistor and store and put PersistGate inside the Provider like this:

<Provider store={Store.store}>
     <PersistGate loading={null} persistor={Store.persistor}>
         <MuiThemeProvider>
            <App />
         </MuiThemeProvider>
     </PersistGate>,
</Provider>


问:
Comparing a bit to a boolean
Say I have a set of flags, encoded in a uint16_t flags. For example, AMAZING_FLAG = 0x02.
Now, I have a function. This function needs to check if I want to change the flag, because if I want to do that, I need to write to flash. And that is expensive. Therefore, I want a check which tells me if flags & AMAZING_FLAG is equal to doSet. This is the first idea:

```<code>setAmazingFlag(bool doSet)
{
    if ((flags & AMAZING_FLAG) != (doSet ? AMAZING_FLAG : 0)) {
        // Really expensive thing
        // Update flags
    }
}
</code>```

This is not an intuitive if statement.
I feel like there should be a better way, something like:

```<code>if ((flags & AMAZING_FLAG) != doSet){

}
</code>```

But this does not actually work, true seems to be equal to 0x01.

So, is there a neat way to compare a bit to a boolean?

答:
To convert any non-zero number to 1 (true), there is an old trick: apply the ! (not) operator twice.

```<code>if (!!(flags & AMAZING_FLAG) != doSet){
</code>```

Title: Comparing a bit to a boolean

Body:
Say I have a set of flags, encoded in a uint16_t flags. For example, AMAZING_FLAG = 0x02.
Now, I have a function. This function needs to check if I want to change the flag, because if I want to do that, I need to write to flash. And that is expensive. Therefore, I want a check which tells me if flags & AMAZING_FLAG is equal to doSet. This is the first idea:

setAmazingFlag(bool doSet)
{
    if ((flags & AMAZING_FLAG) != (doSet ? AMAZING_FLAG : 0)) {
        // Really expensive thing
        // Update flags
    }
}

This is not an intuitive if statement.
I feel like there should be a better way, something like:

if ((flags & AMAZING_FLAG) != doSet){

}

But this does not actually work, true seems to be equal to 0x01.

So, is there a neat way to compare a bit to a boolean?

Body:
To convert any non-zero number to 1 (true), there is an old trick: apply the ! (not) operator twice.

if (!!(flags & AMAZING_FLAG) != doSet){


问:
Simulate click with setTimeout in Javascript
How would I simulate a click event with setTimeout? Something like:</p>

```<code><script>
    window.onload=setTimeout(document.getElementById('mk1').click(),1000);
</script>

<a id="mk1" href="some url">click me</a>
</code>```

答: document.getElementById('mk1').click() is evaluating when the script first runs.  You need to make it into a function and pass that as the first parameter.

Body:
How would I simulate a click event with setTimeout? Something like:

click me


问:
How can keep or save the selected value?
I am working with Spring boot, security and Thymeleaf:
I have a table with the data from a database, I have created filters, when I select a value, the table show the data filtered, so I want to implement multiple filters and keep the value selected when I change the page. So I had the idea to create variables where I can keep the selected values:

```<code>private Optional <TRACKING_CARD> typeSelected;

private Optional <STATUS> statusSelected;

private Optional <Boolean> flagStaff;
</code>```

and when I select the values:

```<code>typeSelected = filter.getType();
statusSelected = filter.getStatus();
flagStaff = filter.getFlag();
</code>```

But the problem is that the variables are global, so if more than one user is logged in the same time, they share the value of the variables.

How can solve this?

Thanks

答:
you can not persist data like this way. If you want to share the data among the others you can declare the variable static which is to be alive and same instance will be shared.

In your case, you don't need to worry about it as each request will have separate filters.

Body:
I am working with Spring boot, security and Thymeleaf:
I have a table with the data from a database, I have created filters, when I select a value, the table show the data filtered, so I want to implement multiple filters and keep the value selected when I change the page. So I had the idea to create variables where I can keep the selected values:

private Optional <TRACKING_CARD> typeSelected;

private Optional <STATUS> statusSelected;

private Optional <Boolean> flagStaff;

and when I select the values:

typeSelected = filter.getType();
statusSelected = filter.getStatus();
flagStaff = filter.getFlag();

But the problem is that the variables are global, so if more than one user is logged in the same time, they share the value of the variables.

How can solve this?

Thanks


问:
How to generate daily/weekly/monthly/annual aggregate values from a database
I am working on an API with Django Rest Framework. I want to generate daily/weekly/monthly/annual aggregate values for total bookings that have happened.

I have added an image to give an idea of how the aggregated weekly data may look. Here is simplified model. Most of the queries I attempted failed to achieve what I wanted.

```<code>class Booking(models.Model):
    trans_date = models.DateTime(auto_now_add=True)
    amount_paid = models.DecimalField(decimal_places=2, max_digits=20)
    trans_date = models.DateField(auto_now=True)
</code>```

Here is a query I attempted;

```<code>weekly_agg = Booking.objects.annotate(week=ExtractWeek('trans_date')).values('trans_date').annotate(count=Count('id')).values('trans_date','count')
</code>```

答:
Maybe it's help you to aggregate data:
https://hakibenita.com/django-group-by-sql</p>

Body:
I am working on an API with Django Rest Framework. I want to generate daily/weekly/monthly/annual aggregate values for total bookings that have happened.

I have added an image to give an idea of how the aggregated weekly data may look. Here is simplified model. Most of the queries I attempted failed to achieve what I wanted.

class Booking(models.Model):
    trans_date = models.DateTime(auto_now_add=True)
    amount_paid = models.DecimalField(decimal_places=2, max_digits=20)
    trans_date = models.DateField(auto_now=True)

Here is a query I attempted;

weekly_agg = Booking.objects.annotate(week=ExtractWeek('trans_date')).values('trans_date').annotate(count=Count('id')).values('trans_date','count')


问:
Populating a static array using multiple threads
I am trying to populate a static array using multiple threads. The suggested usage of join() in https://stackoverflow.com/a/1492077/10418317 seems to be imposing a specific order on the threads. I want them to run in parallel if they can so as to speed up the whole process

     Assigment

```<code>    public class Assigment {

    public static int minPrime;
    public static int maxPrime;
    public static int[] masterMin = new int[10];
    public static int[] masterMax = new int[10];
    public static void main(String[] args) {
    // TODO code application logic here

    for(int i = 1; i < 11;i++){
     Thread thread = new Thread(new NumGenerator(i));
     thread.start();
     System.out.println("Thread " + i + " generating nums");

    }

    Arrays.sort(masterMin);
     Arrays.sort(masterMax);
     minPrime = masterMin[0];
     maxPrime = masterMax[9];
     System.out.println("<------------------------------>");
     System.out.println("Max Prime is " + maxPrime);
     System.out.println("Min Prime is " + minPrime);
 }

}
</code>```

NumGenerator

```<code>public class NumGenerator implements Runnable {
int[] numbers;
int thrnum;
public NumGenerator(int thrnum){
    this.thrnum = thrnum;
}
@Override
public void run(){
Random rand = new Random();
 numbers = new int[3000];

for(int i = 0; i<3000; i++){
    numbers[i] = rand.nextInt(899999)+1;

     }
Searcher searcher = new Searcher(numbers);
Assigment.masterMax[thrnum-1] = searcher.max;
Assigment.masterMin[thrnum-1] = searcher.min;

}
</code>```

I am trying to sort the array after every thread has completed inputting into it and then print out the first and the last i.e the smallest and the largest values.The problem is that the arrays masterMin and masterMax seem to be still having all zero entries after the supposed population through Assigment.masterMin[thrnum-1] = searcher.min; Searcher is another class which is actually giving me non-zero values for search.max and search.max as expected.

答:
As pointed by @jhamon threads have not completed. But the approach give by @Sree is not ideal as shutting down a Executor just for the sake of waiting for the threads to complete is not the best of the approaches. You can try the following :

```<code>ExecutorService executor = Executors.newFixedThreadPool( 10 );
List<Callable<Object>> calls = new ArrayList<>();
for(int i = 1; i < 11;i++){
        calls.add(Executors.callable(new NumGenerator(i)));
    System.out.println("Thread " + i + " generating nums");
}
List<Future<Object>> futures = svc.invokeAll(calls);
</code>```

invokeAll() will not return until all the tasks are completed (either by failing or completing successful execution).

Body:
I am trying to populate a static array using multiple threads. The suggested usage of join() in https://stackoverflow.com/a/1492077/10418317 seems to be imposing a specific order on the threads. I want them to run in parallel if they can so as to speed up the whole process

     Assigment

    public class Assigment {

    public static int minPrime;
    public static int maxPrime;
    public static int[] masterMin = new int[10];
    public static int[] masterMax = new int[10];
    public static void main(String[] args) {
    // TODO code application logic here

    for(int i = 1; i < 11;i++){
     Thread thread = new Thread(new NumGenerator(i));
     thread.start();
     System.out.println("Thread " + i + " generating nums");

    }

    Arrays.sort(masterMin);
     Arrays.sort(masterMax);
     minPrime = masterMin[0];
     maxPrime = masterMax[9];
     System.out.println("<------------------------------>");
     System.out.println("Max Prime is " + maxPrime);
     System.out.println("Min Prime is " + minPrime);
 }

}

NumGenerator

public class NumGenerator implements Runnable {
int[] numbers;
int thrnum;
public NumGenerator(int thrnum){
    this.thrnum = thrnum;
}
@Override
public void run(){
Random rand = new Random();
 numbers = new int[3000];

for(int i = 0; i<3000; i++){
    numbers[i] = rand.nextInt(899999)+1;

     }
Searcher searcher = new Searcher(numbers);
Assigment.masterMax[thrnum-1] = searcher.max;
Assigment.masterMin[thrnum-1] = searcher.min;

}

I am trying to sort the array after every thread has completed inputting into it and then print out the first and the last i.e the smallest and the largest values.The problem is that the arrays masterMin and masterMax seem to be still having all zero entries after the supposed population through Assigment.masterMin[thrnum-1] = searcher.min; Searcher is another class which is actually giving me non-zero values for search.max and search.max as expected.

Body:
As pointed by @jhamon threads have not completed. But the approach give by @Sree is not ideal as shutting down a Executor just for the sake of waiting for the threads to complete is not the best of the approaches. You can try the following :

ExecutorService executor = Executors.newFixedThreadPool( 10 );
List<Callable<Object>> calls = new ArrayList<>();
for(int i = 1; i < 11;i++){
        calls.add(Executors.callable(new NumGenerator(i)));
    System.out.println("Thread " + i + " generating nums");
}
List<Future<Object>> futures = svc.invokeAll(calls);

invokeAll() will not return until all the tasks are completed (either by failing or completing successful execution).


问:
Oracle JDBC ojdbc6 Jar as a Maven Dependency
I cannot seem to get Maven to bundle the ojdbc6.jar file into my project's war file.  I have it working within the POM file when specifying a dependency directly for Hibernate tools.  But it won't get bundled with the project's war file, and therefore my project won't run on Tomcat.

I have tried every solution I can find out there on the net, including those specified for this question here:

Find Oracle JDBC driver in Maven repository

Most recently, I did the following:

Download the jar file to my machine

Run the following command to install the jar into my local repository:

```<code>mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true
</code>```

(I've tried all kinds of variants of that command, too.)

Finally, I put the dependency into my pom file:

```<code><dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>
</code>```

I run a clean build, but it fails:

```<code>mvn -U clean package

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building jazztwo 0.0.1
[INFO] ------------------------------------------------------------------------
Downloading: http://repo1.maven.org/maven2/com/oracle/ojdbc6/11.2.0.3/ojdbc6-11.2.0.3.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.700s
[INFO] Finished at: Tue Mar 27 15:06:14 PDT 2012
[INFO] Final Memory: 3M/81M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project jazztwo: Could not resolve dependencies for project edu.berkeley:jazztwo:war:0.0.1: Could not find artifact com.oracle:ojdbc6:jar:11.2.0.3 in central (http://repo1.maven.org/maven2) -> [Help 1]
</code>```

Why doesn't this work?  I'm ready to throw expensive computer parts across the room.  This has wasted so much time. (Thank you, Oracle.  How much did we pay you again?)

Is it because I'm on a Mac, perhaps?

答: Go to the C drive->user->PcName->find .m2 and Paste the downloaded ojdbc jar file there, Server will automatically pick this.</p>

Body:
I cannot seem to get Maven to bundle the ojdbc6.jar file into my project's war file.  I have it working within the POM file when specifying a dependency directly for Hibernate tools.  But it won't get bundled with the project's war file, and therefore my project won't run on Tomcat.

I have tried every solution I can find out there on the net, including those specified for this question here:

Find Oracle JDBC driver in Maven repository

Most recently, I did the following:

Download the jar file to my machine

Run the following command to install the jar into my local repository:

mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true

(I've tried all kinds of variants of that command, too.)

Finally, I put the dependency into my pom file:

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>

I run a clean build, but it fails:

mvn -U clean package

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building jazztwo 0.0.1
[INFO] ------------------------------------------------------------------------
Downloading: http://repo1.maven.org/maven2/com/oracle/ojdbc6/11.2.0.3/ojdbc6-11.2.0.3.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.700s
[INFO] Finished at: Tue Mar 27 15:06:14 PDT 2012
[INFO] Final Memory: 3M/81M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project jazztwo: Could not resolve dependencies for project edu.berkeley:jazztwo:war:0.0.1: Could not find artifact com.oracle:ojdbc6:jar:11.2.0.3 in central (http://repo1.maven.org/maven2) -> [Help 1]

Why doesn't this work?  I'm ready to throw expensive computer parts across the room.  This has wasted so much time. (Thank you, Oracle.  How much did we pay you again?)

Is it because I'm on a Mac, perhaps?


问:
How to join two figures with different sizes in matplotlib?
I have two different figures from matplotlib.
The first one shows cell sizes through time :

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mahotas
import random

fig,ax_curves = plt.subplots(figsize=(8,6))

for cell in range(1,11):

    ax_curves.set_ylim(0,100)
    ax_curves.set_xlim(0,25)
    ax_curves.set_xticks(np.arange(0,21))

    ax_curves.plot(np.arange(0,21), random.sample(range(40, 61), 21), label = str(cell))
    ax_curves.legend(loc='right',frameon=False)
    ax_curves.spines['right'].set_visible(False)
    ax_curves.spines['top'].set_visible(False)
    ax_curves.set_title('Curves')

plt.show()
</code>```

The second one shows images of these cells at different time points :

```<code>fig, ax_images =plt.subplots(10,5,figsize=(9, 16))
columns = 5
rows = 10

for column in range(0, columns):

    cell = 1

    for row in range(0,rows):

        ax_images[row, column].axes.get_xaxis().set_visible(False)

        ax_images[row, column].tick_params(
                    axis='y',
                    which='both',
                    left=False,
                    right=False,
                    labelleft=False)

        ax_images[row, 0].set_ylabel('Cell ' + str(cell), rotation = 0, color=tab10.colors[row])
        ax_images[row, 0].yaxis.set_label_coords(-0.4,0.5)

        if column == 0:
            plt.figtext(0.14 , 0.9, '0 hour',fontsize = 20)
            img = mahotas.imread('path/to/image_t0.tif')
        if column == 1:
            plt.figtext(0.28, 0.9, '5 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t5.tif')
        if column == 2:
            plt.figtext(0.44 , 0.9, '10 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t10.tif')
        if column == 3:
            plt.figtext(0.60, 0.9, '15 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t15.tif')
        if column == 4:
            plt.figtext(0.76 , 0.9, '20 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t20.tif')

        ax_images[row, column].imshow(img)

        cell = cell + 1

plt.figtext(0.5,0.95,'Cell size through time', fontsize = 20, horizontalalignment='center')
plt.show()
</code>```

I would like to "gather" those two figures (the first on the left and the second on the right fro example). I tried for several hours with GrisSpec or add_subplot but I failed... Please, could you let me know if you have any clue to solve this problem ?

Kindly yours !

答:
You can use the add_axes method of a Matplotlib's Figure:

Here I've just a Q&D example that you definitely have to tweak (a lot) to get exactly what you want

```<code>In [54]: f = plt.figure(figsize=(13,4))
    ...: f.add_axes((0.10,0.10, 0.25, 0.85));

In [55]: for y in np.linspace(0.87, 0.10, 10):
    ...:     for x in np.linspace(0.40, 0.85, 5):
    ...:         # LL corner, width, height in figure coordinates, 0 ≤ x,y,h,w ≤ 1
    ...:         f.add_axes((x, y, 0.09, 0.08))
</code>```

Body:
I have two different figures from matplotlib.
The first one shows cell sizes through time :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mahotas
import random

fig,ax_curves = plt.subplots(figsize=(8,6))

for cell in range(1,11):

    ax_curves.set_ylim(0,100)
    ax_curves.set_xlim(0,25)
    ax_curves.set_xticks(np.arange(0,21))

    ax_curves.plot(np.arange(0,21), random.sample(range(40, 61), 21), label = str(cell))
    ax_curves.legend(loc='right',frameon=False)
    ax_curves.spines['right'].set_visible(False)
    ax_curves.spines['top'].set_visible(False)
    ax_curves.set_title('Curves')

plt.show()

The second one shows images of these cells at different time points :

fig, ax_images =plt.subplots(10,5,figsize=(9, 16))
columns = 5
rows = 10

for column in range(0, columns):

    cell = 1

    for row in range(0,rows):

        ax_images[row, column].axes.get_xaxis().set_visible(False)

        ax_images[row, column].tick_params(
                    axis='y',
                    which='both',
                    left=False,
                    right=False,
                    labelleft=False)

        ax_images[row, 0].set_ylabel('Cell ' + str(cell), rotation = 0, color=tab10.colors[row])
        ax_images[row, 0].yaxis.set_label_coords(-0.4,0.5)

        if column == 0:
            plt.figtext(0.14 , 0.9, '0 hour',fontsize = 20)
            img = mahotas.imread('path/to/image_t0.tif')
        if column == 1:
            plt.figtext(0.28, 0.9, '5 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t5.tif')
        if column == 2:
            plt.figtext(0.44 , 0.9, '10 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t10.tif')
        if column == 3:
            plt.figtext(0.60, 0.9, '15 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t15.tif')
        if column == 4:
            plt.figtext(0.76 , 0.9, '20 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t20.tif')

        ax_images[row, column].imshow(img)

        cell = cell + 1

plt.figtext(0.5,0.95,'Cell size through time', fontsize = 20, horizontalalignment='center')
plt.show()

I would like to "gather" those two figures (the first on the left and the second on the right fro example). I tried for several hours with GrisSpec or add_subplot but I failed... Please, could you let me know if you have any clue to solve this problem ?

Kindly yours !

Body:
You can use the add_axes method of a Matplotlib's Figure:

Here I've just a Q&D example that you definitely have to tweak (a lot) to get exactly what you want

In [54]: f = plt.figure(figsize=(13,4))
    ...: f.add_axes((0.10,0.10, 0.25, 0.85));

In [55]: for y in np.linspace(0.87, 0.10, 10):
    ...:     for x in np.linspace(0.40, 0.85, 5):
    ...:         # LL corner, width, height in figure coordinates, 0 ≤ x,y,h,w ≤ 1
    ...:         f.add_axes((x, y, 0.09, 0.08))


答:
You need to create a Dynamic Array (On the free store). using one of the memory allocation functions.

```<code>double* arr = new double[len];
</code>```

But you have to keep track of the memory release yourself!! so you have to Save your pointer as a global variable or as a class member to delete it later using

```<code>delete[] arr;
arr = nullptr;
</code>```

This is how Dynamic arrays are managed in c++, but static arrays are created on the stack of an instruction block and they are destroyed automatically.And theire size must be defined at compile time not at run time.

Title: How can I create an array whose length is specified by a const argument?

Body:
I have a function:

void f(const size_t &len){
    double arr[len];
}

but it doesn't work, because I got message from len, that "expression must have a constant value". How can I solve this problem, if I don't want to create a global variable len?

Body:
You need to create a Dynamic Array (On the free store). using one of the memory allocation functions.

double* arr = new double[len];

But you have to keep track of the memory release yourself!! so you have to Save your pointer as a global variable or as a class member to delete it later using

delete[] arr;
arr = nullptr;

This is how Dynamic arrays are managed in c++, but static arrays are created on the stack of an instruction block and they are destroyed automatically.And theire size must be defined at compile time not at run time.


问:
How to disable font scaling ( dynamic types from accessibility) for text inputs in react native?
How to disable font scaling (dynamic types - accessibility) for  text inputs in react native? </p>

<p>I have disabled dynamic types for text in the app by adding this code, but I still see that font in TextInputs are scaling: </p>

```<code> Text.defaultProps = Text.defaultProps || {}; //Disable dynamic type in IOS
 Text.defaultProps.allowFontScaling = false;
</code>```

答:
Okay, I found the solution, it can be done the same way as it was done with Text:

```<code>TextInput.defaultProps = Text.defaultProps || {}; //Disable dynamic type in IOS
TextInput.defaultProps.allowFontScaling = false;
</code>```

Body:
How to disable font scaling (dynamic types - accessibility) for  text inputs in react native?

I have disabled dynamic types for text in the app by adding this code, but I still see that font in TextInputs are scaling:

 Text.defaultProps = Text.defaultProps || {}; //Disable dynamic type in IOS
 Text.defaultProps.allowFontScaling = false;

Body:
Okay, I found the solution, it can be done the same way as it was done with Text:

TextInput.defaultProps = Text.defaultProps || {}; //Disable dynamic type in IOS
TextInput.defaultProps.allowFontScaling = false;


答:
It took me a while to see it (so you can ignore my comment) but that was mainly due to bad formatting. Please paste your FIX messages with a visible separator between the fields, e.g. a pipe |

You are sending a Heartbeat message (35=0) with field 108/HeartBtInt. This tag is only allowed on a Logon message (35=A).

This is also explained in the Reject message (35=3) that you get:

```<code>8=FIX.4.4|9=138|35=3|34=2|49=CfhDemoxxxxx|52=20200220-00:14:00.564|56=xxxxxxx|45=2|58=Tag not defined for this message type|371=108|372=0|373=2|10=154|

...
58      Text        Tag not defined for this message type
371     RefTagID    108
372     RefMsgType  0
...
</code>```

So 371/RefTagID tells you that tag 108 is not defined for the 372/RefMsgType of 0.

Edit: in general it seems you are putting wrong tags on every message. You also put tags 141, 553 and 554 on a HeartBeat but these belong to a Logon message also.

Title: FIX Message: "Tag not defined for this message type" upon Logon

Body:
Below is the output snippet I get while I try to logon to Cfh I am following this doument

8=FIX.4.4|9=119|35=0|34=2|49=xxxxxxx|52=20200220-00:14:00.478|56=CfhDemoxxxxx|108=30|141=Y|553=xxxxxxx|554=xxxxxx|10=227|
8=FIX.4.4|9=138|35=3|34=2|49=CfhDemoxxxxx|52=20200220-00:14:00.564|56=xxxxxxx|45=2|58=Tag not defined for this message type|371=108|372=0|373=2|10=154|
8=FIX.4.4|9=113|35=1|34=3|49=CfhDemoxxxxx|52=20200220-00:14:06.564|56=xxxxxxxx|112=2439c450-1914-42ad-83c6-ad4b5ed17501|10=146|
8=FIX.4.4|9=160|35=0|34=3|49=xxxxxxx|52=20200220-00:14:06.740|56=CfhDemoxxxx|108=30|112=2439c450-1914-42ad-83c6-ad4b5ed17501|141=Y|553=xxxxxxxx|554=xxxxxxx|10=135|
8=FIX.4.4|9=138|35=3|34=4|49=CfhDemoxxxx|52=20200220-00:14:06.826|56=xxxxxxx|45=3|58=Tag not defined for this message type|371=108|372=0|373=2|10=164|
8=FIX.4.4|9=119|35=5|34=4|49=xxxxxxx|52=20200220-00:14:23.476|56=CfhDemoxxxxx|108=30|141=Y|553=xxxxxxx|554=xxxxxxB|10=237|
8=FIX.4.4|9=138|35=3|34=5|49=CfhDemoxxxxx|52=20200220-00:14:23.563|56=xxxxxxx|45=4|58=Tag not defined for this message type|371=108|372=5|373=2|10=168|

Body:
It took me a while to see it (so you can ignore my comment) but that was mainly due to bad formatting. Please paste your FIX messages with a visible separator between the fields, e.g. a pipe |

You are sending a Heartbeat message (35=0) with field 108/HeartBtInt. This tag is only allowed on a Logon message (35=A).

This is also explained in the Reject message (35=3) that you get:

8=FIX.4.4|9=138|35=3|34=2|49=CfhDemoxxxxx|52=20200220-00:14:00.564|56=xxxxxxx|45=2|58=Tag not defined for this message type|371=108|372=0|373=2|10=154|

...
58      Text        Tag not defined for this message type
371     RefTagID    108
372     RefMsgType  0
...

So 371/RefTagID tells you that tag 108 is not defined for the 372/RefMsgType of 0.

Edit: in general it seems you are putting wrong tags on every message. You also put tags 141, 553 and 554 on a HeartBeat but these belong to a Logon message also.


问:
Animation, remove blink when a view.visibility(gone) and another view take the space
I'm dealing with animations, and I'm new with it. I've got this structure in XML file:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:focusable="true"
        android:orientation="vertical"
        android:padding="10dp"
        android:background="@color/colorAccent"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/textViewT"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Some Text"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@color/colorPrimaryDark"
            android:gravity="center"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Something"
            android:textSize="12sp"
            android:textColor="@color/colorPrimary"
            android:gravity="center"/>

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingStart="10dp"
        android:paddingEnd="10dp"
        android:scrollbars="vertical" />
</code>```

Animation:

```<code><set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">

<translate
    android:duration="300"
    android:fromYDelta="0"
    android:toYDelta="-100%"/>
</code>```

And my MainActivity looks:

```<code>public class MainActivity extends AppCompatActivity {

MyRecyclerViewAdapter adapter;
boolean animationOnOff;
LinearLayout ll;
Animation animScroll;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> animalNames = new ArrayList<>();
    animalNames.add("Horse");
    ....

    animationOnOff = true;
    ll = findViewById(R.id.linearLayout1);
    animScroll = AnimationUtils.loadAnimation(this, R.anim.total_gasto_hide);
    animScroll.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            ll.animate().alpha(0).setDuration(0).withEndAction(new Runnable() {
                @Override
                public void run() {
                    ll.setVisibility(View.GONE);
                }
            });
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    RecyclerView recyclerView = findViewById(R.id.list);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new MyRecyclerViewAdapter(this, animalNames);
    recyclerView.setAdapter(adapter);
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(dy > 0) {
                if(animationOnOff) {
                    ll.startAnimation(animScroll);
                    animationOnOff = false;
                }
            } else {

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

This code should take the linearLayout1 up and disapear after 300ms with a visibility(view.GONE), so far so good. The problem is that the recyclerview is not getting stick with this animation, and when the linearLayout1 is gone the recycler instantly get the position of the view gone (Doing some kind of blink effect). Gif below:

So my question is, how can I do it to eliminate this blink effect and achieve a smooth interpolation effect when the linearLayout1 is gone?

答: Android can handle the animation for you by default. Just add android:animateLayoutChanges="true" to your parent LinearLayout and the visibility will be animated.

Body:
I'm dealing with animations, and I'm new with it. I've got this structure in XML file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:focusable="true"
        android:orientation="vertical"
        android:padding="10dp"
        android:background="@color/colorAccent"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/textViewT"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Some Text"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@color/colorPrimaryDark"
            android:gravity="center"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Something"
            android:textSize="12sp"
            android:textColor="@color/colorPrimary"
            android:gravity="center"/>

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingStart="10dp"
        android:paddingEnd="10dp"
        android:scrollbars="vertical" />

Animation:

<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">

<translate
    android:duration="300"
    android:fromYDelta="0"
    android:toYDelta="-100%"/>

And my MainActivity looks:

public class MainActivity extends AppCompatActivity {

MyRecyclerViewAdapter adapter;
boolean animationOnOff;
LinearLayout ll;
Animation animScroll;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> animalNames = new ArrayList<>();
    animalNames.add("Horse");
    ....

    animationOnOff = true;
    ll = findViewById(R.id.linearLayout1);
    animScroll = AnimationUtils.loadAnimation(this, R.anim.total_gasto_hide);
    animScroll.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            ll.animate().alpha(0).setDuration(0).withEndAction(new Runnable() {
                @Override
                public void run() {
                    ll.setVisibility(View.GONE);
                }
            });
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    RecyclerView recyclerView = findViewById(R.id.list);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new MyRecyclerViewAdapter(this, animalNames);
    recyclerView.setAdapter(adapter);
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(dy > 0) {
                if(animationOnOff) {
                    ll.startAnimation(animScroll);
                    animationOnOff = false;
                }
            } else {

            }
        }
    });
}
}

This code should take the linearLayout1 up and disapear after 300ms with a visibility(view.GONE), so far so good. The problem is that the recyclerview is not getting stick with this animation, and when the linearLayout1 is gone the recycler instantly get the position of the view gone (Doing some kind of blink effect). Gif below:

So my question is, how can I do it to eliminate this blink effect and achieve a smooth interpolation effect when the linearLayout1 is gone?


问:
"The located assembly's manifest definition does not match the assembly reference"
I have deployed an .NET WebAPI app (compiled against .NET 4.5.2, and running locally) into an Azure App Service.

The error thrown there is

Could not load file or assembly 'System.Web.Mvc, Version=4.0.40804.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

I have checked that the System.Web.Mvc.dll in the App service's bin directory has a size of 505504 bytes - the very same size as my local System.Web.Mvc.dll, which is version 4.0.40804.0, changed 2014-09-25, and working locally without issue. The only difference I can tell is that I have .NET 4.5.2 installed locally, not 4.6.1, like Azure does.

The entry in my Web.config is

```<code>  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="4.0.40804.0" />
  </dependentAssembly>
</code>```

but I have already tried

```<code>  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
</code>```

which doesn't work either.

How do I have to edit that entry for my application to find the System.Web.Mvc.dll?

For reference, the full error message is:

Server Error in '/' Application.

Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Mvc' could not be loaded.

WRN: Assembly binding logging is turned OFF.
  To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
  Note: There is some performance penalty associated with assembly bind failure logging.
  To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[FileLoadException: Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

[FileLoadException: Could not load file or assembly 'System.Web.Mvc, Version=4.0.40804.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
     System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
     System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
     System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
     System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
     System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +21
     System.Reflection.Assembly.Load(String assemblyString) +28
     System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'System.Web.Mvc, Version=4.0.40804.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
     System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +738
     System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217
     System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
     System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
     System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +92
     System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +290
     System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
     System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): Could not load file or assembly 'System.Web.Mvc, Version=4.0.40804.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
     System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9947380
     System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
     System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0

答:
I had the same error regarding the version of System.Web.Mvc.

In my case, there was no NuGet package inconsistency between projects, but there was a web.config file in my Views folder with the following line:

```<code><host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</code>```

Changing this version number to match the currently installed NuGet package fixed the issue.

Body:
I have deployed an .NET WebAPI app (compiled against .NET 4.5.2, and running locally) into an Azure App Service.

The error thrown there is

Could not load file or assembly 'System.Web.Mvc, Version=4.0.40804.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

I have checked that the System.Web.Mvc.dll in the App service's bin directory has a size of 505504 bytes - the very same size as my local System.Web.Mvc.dll, which is version 4.0.40804.0, changed 2014-09-25, and working locally without issue. The only difference I can tell is that I have .NET 4.5.2 installed locally, not 4.6.1, like Azure does.

The entry in my Web.config is

  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="4.0.40804.0" />
  </dependentAssembly>

but I have already tried

  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>

which doesn't work either.

How do I have to edit that entry for my application to find the System.Web.Mvc.dll?

For reference, the full error message is:

Server Error in '/' Application.

Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Mvc' could not be loaded.

WRN: Assembly binding logging is turned OFF.
  To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
  Note: There is some performance penalty associated with assembly bind failure logging.
  To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[FileLoadException: Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

[FileLoadException: Could not load file or assembly 'System.Web.Mvc, Version=4.0.40804.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
     System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
     System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
     System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
     System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
     System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +21
     System.Reflection.Assembly.Load(String assemblyString) +28
     System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'System.Web.Mvc, Version=4.0.40804.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
     System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +738
     System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217
     System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
     System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
     System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +92
     System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +290
     System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
     System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): Could not load file or assembly 'System.Web.Mvc, Version=4.0.40804.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
     System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9947380
     System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
     System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0

Body:
I had the same error regarding the version of System.Web.Mvc.

In my case, there was no NuGet package inconsistency between projects, but there was a web.config file in my Views folder with the following line:

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

Changing this version number to match the currently installed NuGet package fixed the issue.


问:
APEXExport don't exported application with correct name
I'm trying to export my apex applications with APEXExport class, but the sql file is always generated with the name "???" instead of "f"+application id+".sql". When I try to export all workspace applications it replace always the file "???" by latest exported application, so i can't have different application files.

Any ideas could help me, Thanks.

答:
Well, how exactly do you do that? I'm exporting Apex applications daily, no problem. Though, one-by-one.

Here's my MS Windows .bat script, see if it helps. It

exports Apex applications

creates ZIP file name by using DATE value so that I could keep daily backups

ZIPs all exported .sql files

deletes .sql files

```<code>@ECHO OFF

echo Export APEX applications

E:
cd E:\apex_4.2_instalacija\utilities

@ECHO ON

REM Archive
java oracle.apex.APEXExport -db db_serv:1521:orcl -user archive -password xyz -applicationid 126
REM Human resources
java oracle.apex.APEXExport -db db_serv:1521:orcl -user humres  -password xyz -applicationid 139
REM Etc. - list all applications you're exporting

@ECHO OFF

copy f????.sql E:\Apex_backup\f????_50_%date:~10,4%_%date:~7,2%_%date:~4,2%.sql
del f????.sql

E:
cd E:\Apex_backup

REM Today's date in YYYY_MM_DD format
for /F "tokens=1-4 delims=. " %%i in ('date /t') do set yyyy_mm_dd=%%l_%%k_%%j

REM ZIP file name: APEX_YYYY_MM_DD.ZIP
set ime_zipa=apex_%yyyy_mm_dd%.zip

"C:\Program Files\7-Zip\7z" a -tzip %ime_zipa% E:\apex_backup\f*%yyyy_mm_dd%*.sql

dir %ime_zipa%

REM Delete exported .sql files
del f*%yyyy_mm_dd%*.sql
</code>```

Body:
Well, how exactly do you do that? I'm exporting Apex applications daily, no problem. Though, one-by-one.

Here's my MS Windows .bat script, see if it helps. It

exports Apex applications

creates ZIP file name by using DATE value so that I could keep daily backups

ZIPs all exported .sql files

deletes .sql files

@ECHO OFF

echo Export APEX applications

E:
cd E:\apex_4.2_instalacija\utilities

@ECHO ON

REM Archive
java oracle.apex.APEXExport -db db_serv:1521:orcl -user archive -password xyz -applicationid 126
REM Human resources
java oracle.apex.APEXExport -db db_serv:1521:orcl -user humres  -password xyz -applicationid 139
REM Etc. - list all applications you're exporting

@ECHO OFF

copy f????.sql E:\Apex_backup\f????_50_%date:~10,4%_%date:~7,2%_%date:~4,2%.sql
del f????.sql

E:
cd E:\Apex_backup

REM Today's date in YYYY_MM_DD format
for /F "tokens=1-4 delims=. " %%i in ('date /t') do set yyyy_mm_dd=%%l_%%k_%%j

REM ZIP file name: APEX_YYYY_MM_DD.ZIP
set ime_zipa=apex_%yyyy_mm_dd%.zip

"C:\Program Files\7-Zip\7z" a -tzip %ime_zipa% E:\apex_backup\f*%yyyy_mm_dd%*.sql

dir %ime_zipa%

REM Delete exported .sql files
del f*%yyyy_mm_dd%*.sql


问:
Firefox : window.print() block window.history.back() function
I've got a problem when I want to go back with window.location.back() after using window.print().

When I click on my Print button, I'm redirected to a new page with the document to print and the print pop-in appear. On Chrome and IE, when we click on print into the pop-in, window.location.back() is triggered but not in Firefox ...

```<code>timeout(function () {
   window.print()
   window.history.back();
}, 500);
</code>```

I've tried some possible solution like window.onafterprint or window.onbeforeprint events,
window.location.go(-1), but none works on Firefox.

Also, if I remove the window.print() line, window.location.back() works fine.

I've got no other solutions, could you help me ?

答:
Are you sure you don't mean setTimeout?

Using Firefox, with the following html code:

<!DOCTYPE html>

    ```Nothing here```

```

seem to work just fine.

500ms after loading, the print dialog shows, then, it goes back in history.

Body:
I've got a problem when I want to go back with window.location.back() after using window.print().

When I click on my Print button, I'm redirected to a new page with the document to print and the print pop-in appear. On Chrome and IE, when we click on print into the pop-in, window.location.back() is triggered but not in Firefox ...

timeout(function () {
   window.print()
   window.history.back();
}, 500);

I've tried some possible solution like window.onafterprint or window.onbeforeprint events,
window.location.go(-1), but none works on Firefox.

Also, if I remove the window.print() line, window.location.back() works fine.

I've got no other solutions, could you help me ?

Body:
Are you sure you don't mean setTimeout?

Using Firefox, with the following html code:

<!DOCTYPE html>
<html>
<head>
    <script>
        setTimeout(function(){
            window.print();
            window.history.back();
        }, 500);
    </script>
</head>
<body>
    <pre>Nothing here</pre>
</body>
</html>

seem to work just fine.

500ms after loading, the print dialog shows, then, it goes back in history.


问:
Mat Select displaying empty options with Observable
I am creating mat-select options using results from Observable but the options are not rendering. When it simple array it is rendering.

Following is the example i build - See here

答:
In your example you are using from observable. Instead use of observable, it will convert your simple array to observable that will work with async pipe.

```<code>ngOnInit(): void {
    this.toppingList = of(['a', 'b']);
  }
</code>```

Difference between of and from when passing an array-like structure (including strings):

```<code>Observable.of([1, 2, 3]).subscribe(x => console.log(x));
</code>```

would print the whole array at once.

On the other hand,

```<code>Observable.from([1, 2, 3]).subscribe(x => console.log(x));
</code>```

prints the elements 1 by 1.

For strings the behaviour is the same, but at character level.

Body:
In your example you are using from observable. Instead use of observable, it will convert your simple array to observable that will work with async pipe.

ngOnInit(): void {
    this.toppingList = of(['a', 'b']);
  }

Difference between of and from when passing an array-like structure (including strings):

Observable.of([1, 2, 3]).subscribe(x => console.log(x));

would print the whole array at once.

On the other hand,

Observable.from([1, 2, 3]).subscribe(x => console.log(x));

prints the elements 1 by 1.

For strings the behaviour is the same, but at character level.


问:
Odoo 8: How can I send context to python method?

I want to send context to python method.

In xml, I have this code :

```<code><?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="view_mim_wizardfor" model="ir.ui.view">
        <field name="name">mim.wizard.inherit</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.view_order_form"/>
        <field name="arch" type="xml">

        <notebook position="before">
        <field name="entete"/>
        <field name="purchase_order_id" context="{'show_state': True}"/>
    </notebook>
            <group name="sale_total" position="after">
                <button name="action_mim_wizard"
                    attrs="{'invisible': [('state','not in',('draft','sent'))]}"
                    type="object" string="Ajout avancé"
                    class="oe_link oe_edit_only"/>
            </group>
        </field>
    </record>
</data>
</code>```

and I python I have this :

```<code>def name_get(self, cr, uid, ids, context=None):
    if context is None:
        context = {}
    res = []
    for record in self.browse(cr, uid, ids, context=context):
        _logger.info('==============context============================%s', context)
        name = record.name
        if context.get('show_state', False):
            name = '%s %s' % (name, record.state)
        res.append((record.id, name))
        _logger.info('==============name_get============================name_get==============')
    return res
</code>```

I don't get the 'show_state' in context, I don't know why.

Can you help me?

答:
I hope you are accessing this context on the purchase order (As per field purchase_order_id)

Try to check this, self._context.get('show_state')

Body:
I want to send context to python method.

In xml, I have this code :

<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="view_mim_wizardfor" model="ir.ui.view">
        <field name="name">mim.wizard.inherit</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.view_order_form"/>
        <field name="arch" type="xml">

        <notebook position="before">
        <field name="entete"/>
        <field name="purchase_order_id" context="{'show_state': True}"/>
    </notebook>
            <group name="sale_total" position="after">
                <button name="action_mim_wizard"
                    attrs="{'invisible': [('state','not in',('draft','sent'))]}"
                    type="object" string="Ajout avancé"
                    class="oe_link oe_edit_only"/>
            </group>
        </field>
    </record>
</data>

and I python I have this :

def name_get(self, cr, uid, ids, context=None):
    if context is None:
        context = {}
    res = []
    for record in self.browse(cr, uid, ids, context=context):
        _logger.info('==============context============================%s', context)
        name = record.name
        if context.get('show_state', False):
            name = '%s %s' % (name, record.state)
        res.append((record.id, name))
        _logger.info('==============name_get============================name_get==============')
    return res

I don't get the 'show_state' in context, I don't know why.

Can you help me?


问:
How to fetch data from API using id in reactJS?
How do I pass an ID from one API to another, and fetch the require data?

This is my code:

handleClick(e){
    fetch("http://api.com/product_sub_categories?category_id")
    .then(res => res.json())
    .then(
      (result) => {
        this.setState({
          isLoaded: true,
          product_sub_categories: result.product_sub_categories
        });
      },
      (error) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    )
}
```

答:
You can do using back tick.</p>

```<code>handleClick(e){
  fetch(`${BASE_PATH}/product_sub_categories?category_id=${e.target.value}`)
  .then(res => res.json())
  .then(
    (result) => {
      this.setState({
        isLoaded: true,
        product_sub_categories: result.product_sub_categories
      });
    },
    (error) => {
      this.setState({
        isLoaded: true,
        error
      });
    }
  )
}
</code>```

Body:
You can do using back tick.

handleClick(e){
  fetch(`${BASE_PATH}/product_sub_categories?category_id=${e.target.value}`)
  .then(res => res.json())
  .then(
    (result) => {
      this.setState({
        isLoaded: true,
        product_sub_categories: result.product_sub_categories
      });
    },
    (error) => {
      this.setState({
        isLoaded: true,
        error
      });
    }
  )
}


问:
Tomcat 7 Access Log with Client Certificate Subject Name
I am trying to include client certificate information in my tomcat access log file.

I've reviewed this post: https://serverfault.com/questions/624790/tomcat-log-the-equivalent-of-ssl-client-s-dn but this only returns a reference to the cert and I can't actually extract any properties.

My logfile pattern looks like this:

```<code>pattern="... [%{javax.servlet.request.X509Certificate}r]"
</code>```

This is returning: [[Ljava.security.cert.X509Certificate;@667a078]

Is there a way to access the certificate properties such as this:

```<code>pattern="... [%{javax.servlet.request.X509Certificate.SubjectName}r]"
</code>```

I'd like to be able to extract certificate information without any code modification.

答:
I had the same Problem. The only way I figured out is to Override AccessLogValve.

Create a simple maven java project

<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-catalina</artifactId>
  <version>x.x.x</version>
  <scope>provided</scope>
</dependency>

Override AccessLogValve and implement

  @Override
  public void log(Request request, Response response, long time) {

Read your principal from the X509Certificate from the request (unfortunately i cannot share this code)
request.setUserPrincipal(xyz)

pack the jar

copy it to your tomcat lib folder

confix server.xml to use your Valve, replace Valve class with yours

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"-->

Body:
I am trying to include client certificate information in my tomcat access log file.

I've reviewed this post: https://serverfault.com/questions/624790/tomcat-log-the-equivalent-of-ssl-client-s-dn but this only returns a reference to the cert and I can't actually extract any properties.

My logfile pattern looks like this:

pattern="... [%{javax.servlet.request.X509Certificate}r]"

This is returning: [[Ljava.security.cert.X509Certificate;@667a078]

Is there a way to access the certificate properties such as this:

pattern="... [%{javax.servlet.request.X509Certificate.SubjectName}r]"

I'd like to be able to extract certificate information without any code modification.


问:
select data on click of checkbox in table
I have a table with checkboxes and I want to capture the data in the table rows on click of each of the checkboxes. I have a functional call (click)="checkConditions($event, data)" which is called on click of each checkbox.

Here data gives me all the data of the row which I want to get an array variable. The issue is that on click of the first checkbox it works fine. I get the data and I push it in an empty array but if I click the second checkbox, I lose the original data and only have the latest data. I have tried this.checkedInstruments.push(...data);

it gives me an error "Found non-callable @@iterator" in angular 8.

Can anyone help?

答: Yogesh, I can see the array checkedInstruments is getting initialized again with empty array and hence you have only the latest data and not the previous one. Try declaring the checkedInstruments array at class level and check again.</p>


问:
How to generate build files in next js
I am learning basic next js. If we run npm run build create-react-app will generate a build folder index.html and bundle files. In nextjs. It doesn't create any build files. How will I deploy nextjs project on the server?

答:
First, after creating the app, customise the package.json file as your own, like-

```<code> "scripts": {
     "dev": "next dev",
     "build": "next build",
     "start": "next server.js"
}
</code>```

then, use yarn dev to run your project in the server default,

http://localhost:3000/

Title: How to generate build files in next js

Body:
First, after creating the app, customise the package.json file as your own, like-

 "scripts": {
     "dev": "next dev",
     "build": "next build",
     "start": "next server.js"
}

then, use yarn dev to run your project in the server default,

http://localhost:3000/