问:
Exception on OnPressed function while using animateTo function In TabbarView
I am Trying to write a code for my project which uses a TabBarView with 4 tabs and has a Global Key so that I can Use the Tab controller anywhere in the app,
however when I tried to Call the animateTo Function using an onpressed Function of Raised Button It Keeps Throwing Errors as follows:

Have Already Done This://Tried Creating a function in the same file as the controller to change the view

```<code>class MyTabsState extends State<MyTabs> with SingleTickerProviderStateMixin {

  static final homePageKey=GlobalKey<MyTabsState>();
  TabController tabcontroller;

  @override
  void initState() {
    super.initState();
    tabcontroller = new TabController(vsync: this, length: 4);
  }

  @override
  void dispose() {
    super.dispose();
    tabcontroller.dispose();

  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: homePageKey,
      bottomNavigationBar: new Material(
          color: mainUiColor,
          child: new TabBar(
              controller: tabcontroller,
              unselectedLabelColor: Colors.grey,
              labelColor: Colors.redAccent,
              tabs: <Tab>[
                new Tab(icon: new Icon(Icons.home)),
                new Tab(icon: new Icon(Icons.photo_album)),
                new Tab(icon: new Icon(Icons.arrow_back)),
                new Tab(icon: new Icon(Icons.favorite)),
              ])),
      body: new TabBarView(controller: tabcontroller, children: <Widget>[
        new First(),
        new PhotoGallery(),
        new Third(),
        new SocialMedia(),
      ]),

    );
  }
  void changePage(){

     tabcontroller.animateTo(2);
  }
}
</code>```

```<code>I/flutter ( 4993): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ I/flutter ( 4993): The following NoSuchMethodError was thrown while handling a gesture: I/flutter ( 4993): The method 'changePage' was called on null. I/flutter ( 4993): Receiver: null I/flutter ( 4993): Tried calling: changePage() I/flutter ( 4993): I/flutter ( 4993): When the exception was thrown, this was the stack: I/flutter ( 4993): #0    Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5) I/flutter ( 4993): #1      _PhotoGalleryState.build.<anonymous closure> (package:myproject/screenTabs/SecondTab.dart:97:52) I/flutter ( 4993):
#2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14) I/flutter ( 4993):
#3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30) I/flutter ( 4993):
#4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24) I/flutter ( 4993): #5      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9) I/flutter ( 4993): #6    TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:211:7) I/flutter ( 4993): #7    GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) I/flutter ( 4993): #8
_WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:225:20) I/flutter ( 4993):
#9      _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22) I/flutter ( 4993):
#10     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) I/flutter ( 4993):
#11     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) I/flutter ( 4993):
#12     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) I/flutter ( 4993):
#16     _invoke1 (dart:ui/hooks.dart:233:10) I/flutter ( 4993): #17     _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5) I/flutter ( 4993): (elided 3 frames from package dart:async) I/flutter ( 4993): I/flutter ( 4993): Handler: onTap I/flutter ( 4993): Recognizer: I/flutter ( 4993):   TapGestureRecognizer#bfc40(debugOwner: GestureDetector, state: ready, won arena, finalPosition: I/flutter ( 4993):   Offset(126.9, 667.6), sent tap down)
</code>```

答: If I were a betting man I'd bet you may be trying to call changePage() on one of the pages listed in your tabBarView. A global key doesn't really make the item available anywhere in the app, you'd have to store it somewhere higher up in the widget tree using an inherited widget or pass it down to its children as a property in order to actually use it. It looks like something you may want to consider looking into is a CupertinoTabScaffold. Then you could wrap that around the main views, and work with it there and have it show up across the entire app. This might be a bit easier than using the current setup. </p>

Body:
I am Trying to write a code for my project which uses a TabBarView with 4 tabs and has a Global Key so that I can Use the Tab controller anywhere in the app,
however when I tried to Call the animateTo Function using an onpressed Function of Raised Button It Keeps Throwing Errors as follows:

Have Already Done This://Tried Creating a function in the same file as the controller to change the view

class MyTabsState extends State<MyTabs> with SingleTickerProviderStateMixin {

  static final homePageKey=GlobalKey<MyTabsState>();
  TabController tabcontroller;

  @override
  void initState() {
    super.initState();
    tabcontroller = new TabController(vsync: this, length: 4);
  }

  @override
  void dispose() {
    super.dispose();
    tabcontroller.dispose();

  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: homePageKey,
      bottomNavigationBar: new Material(
          color: mainUiColor,
          child: new TabBar(
              controller: tabcontroller,
              unselectedLabelColor: Colors.grey,
              labelColor: Colors.redAccent,
              tabs: <Tab>[
                new Tab(icon: new Icon(Icons.home)),
                new Tab(icon: new Icon(Icons.photo_album)),
                new Tab(icon: new Icon(Icons.arrow_back)),
                new Tab(icon: new Icon(Icons.favorite)),
              ])),
      body: new TabBarView(controller: tabcontroller, children: <Widget>[
        new First(),
        new PhotoGallery(),
        new Third(),
        new SocialMedia(),
      ]),

    );
  }
  void changePage(){

     tabcontroller.animateTo(2);
  }
}

I/flutter ( 4993): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ I/flutter ( 4993): The following NoSuchMethodError was thrown while handling a gesture: I/flutter ( 4993): The method 'changePage' was called on null. I/flutter ( 4993): Receiver: null I/flutter ( 4993): Tried calling: changePage() I/flutter ( 4993): I/flutter ( 4993): When the exception was thrown, this was the stack: I/flutter ( 4993): #0    Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5) I/flutter ( 4993): #1      _PhotoGalleryState.build.<anonymous closure> (package:myproject/screenTabs/SecondTab.dart:97:52) I/flutter ( 4993):
#2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14) I/flutter ( 4993):
#3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30) I/flutter ( 4993):
#4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24) I/flutter ( 4993): #5      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9) I/flutter ( 4993): #6    TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:211:7) I/flutter ( 4993): #7    GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) I/flutter ( 4993): #8
_WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:225:20) I/flutter ( 4993):
#9      _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22) I/flutter ( 4993):
#10     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) I/flutter ( 4993):
#11     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) I/flutter ( 4993):
#12     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) I/flutter ( 4993):
#16     _invoke1 (dart:ui/hooks.dart:233:10) I/flutter ( 4993): #17     _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5) I/flutter ( 4993): (elided 3 frames from package dart:async) I/flutter ( 4993): I/flutter ( 4993): Handler: onTap I/flutter ( 4993): Recognizer: I/flutter ( 4993):   TapGestureRecognizer#bfc40(debugOwner: GestureDetector, state: ready, won arena, finalPosition: I/flutter ( 4993):   Offset(126.9, 667.6), sent tap down)


来源: stackexchange

问:
how to convert large column using factor
Im writing a machine learning code for my dataset having hotels column.The hotel column contains 300 hotels name.For data preprocessing,I saw we have to use factor.Is there any easy way to covert it as there are so many values for level?</p>

答:
if you are using read.csv option to load the csv data into a dataframe, then column having string values are by default loaded as a factor column.

Anyway you can use factor() function to convert a column to factor:
df$a <- factor(df$a).

ContentLicense: CC BY-SA 4.0


问:
What is the correct way to pass data to a running thread
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

```<code>C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?
</code>```

So what is the correct way to pass data to a running thread in C# and Java?

答:
Edit: Misread question,

C#
What I normally do is create a Global Static Class and then set the values there. That way you can access it from both threads. Not sure if this is the preferred method and there could be cases where locking occurs (correct me if I'm wrong) which should be handled.

I haven't tried it but It should work for for the threadpool/backgroundworker as well.

ContentLicense: CC BY-SA 3.0

Body:
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?

So what is the correct way to pass data to a running thread in C# and Java?


问:
How can I organize my spiders into nested directories in Scrapy?
I have the following directory structure:

```<code>my_project/
  __init__.py
  spiders/
    __init__.py
    my_spider.py
    other_spider.py
  pipeines.py
  # other files
</code>```

Right now I can be in the my_project directory and start my crawl using scrapy crawl my_spider.

What I'd like to achieve is to be able to run scrapy crawl my_spider with this updated structure:

```<code>my_project/
  __init__.py
  spiders/
    __init__.py
    subtopic1/
      __init__.py # <-- I get the same error whether this is present or not
      my_spider.py
    subtopicx/
      other_spider.py
  pipeines.py
  # other files
</code>```

But right now I get this error:

KeyError: 'Spider not found: my_spider'

What is the appropriate way to organize Scrapy spiders into directories?

答:
I know this is long over due but this is the right way to organize your spiders in nested directories. You set the modules location in the settings defined here.

Example:

```<code>SPIDER_MODULES = ['my_project.spiders', 'my_project.spiders.subtopic1', 'my_project.spiders.subtopicx']
</code>```

Body:
I have the following directory structure:

my_project/
  __init__.py
  spiders/
    __init__.py
    my_spider.py
    other_spider.py
  pipeines.py
  # other files

Right now I can be in the my_project directory and start my crawl using scrapy crawl my_spider.

What I'd like to achieve is to be able to run scrapy crawl my_spider with this updated structure:

my_project/
  __init__.py
  spiders/
    __init__.py
    subtopic1/
      __init__.py # <-- I get the same error whether this is present or not
      my_spider.py
    subtopicx/
      other_spider.py
  pipeines.py
  # other files

But right now I get this error:

KeyError: 'Spider not found: my_spider'

What is the appropriate way to organize Scrapy spiders into directories?

Body:
I know this is long over due but this is the right way to organize your spiders in nested directories. You set the modules location in the settings defined here.

Example:

SPIDER_MODULES = ['my_project.spiders', 'my_project.spiders.subtopic1', 'my_project.spiders.subtopicx']


问:
Speed up Mysql queries with Hash Table in OPENSIPS
Dears,

I have got an Opensips server which make queries to an mysql server. I need to optimice these queries at maximum.

One way could be: using mysql table with engine=memory and index=hash, but ¿how to load these type of table at the init of the opensips server?

Another way: ¿is there a function in Opensips server to cache data of previous querys in order to recover them later?

Kind regards,
Tentenpie

答:
Starting with version 2.2, OpenSIPS offers the sql_cacher module.  You can use it in order to cache MySQL tables and achieve direct in-memory lookups for the keys of your choosing through the $sql_cached_value variable.

Cached tables are periodically refreshed according to the reload_interval setting of the module.

If you consider sql_cacher to be too complex for your needs, then you can still maintain a high traffic throughput for your SIP proxy while also doing blocking MySQL queries by making all of these queries asynchronous, using the async(avp_db_query()) construct.


问:
select with index on DataTable?
After I get DataTable from sqlAdapter I'm closing connection.
If I preform SELECT from this DataTable, does the select use the index
I created in the DB?

what code do I need to write for using the index?

答:
All data in the DataTable is respecting database structure/data, you have  exactly what you have in the database.</p>

```<code>        DataRow[] dra = datatable.Select("uid > 2");
        foreach (DataRow dr in dra)
        {
            Console.WriteLine(dr["uid"]);
        }
</code>```

Title: select with index on DataTable?

Body:
All data in the DataTable is respecting database structure/data, you have  exactly what you have in the database.

        DataRow[] dra = datatable.Select("uid > 2");
        foreach (DataRow dr in dra)
        {
            Console.WriteLine(dr["uid"]);
        }


问:
The localStorage is not refreshing in Vuex
I write codes with Vuex to login and logout in my Laravel single page application it's working well but when i login to an account the profiles information (name, address, Email, ...)doesn't show in profile but after i reload the page the profile information loads, and when another user try the profile the data of the last person that login shown to him/her

auth.js:

```<code>export function registerUser(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/register', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('Somthing is wrong!!')
        })
    })
}

export function login(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/login', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('The Email or password is incorrect!')
        })
    })
}

export function getLoggedinUser(){
    const userStr = localStorage.getItem('user');

    if(!userStr){
        return null
    }

    return JSON.parse(userStr);
}
</code>```

store.js:

```<code>import {getLoggedinUser} from './partials/auth';
const user = getLoggedinUser();
export default {
    state: {
        currentUser: user,
        isLoggedIn: !!user,
        loading: false,
        auth_error: null,
        reg_error:null,
        registeredUser: null,
    },
    getters: {
        isLoading(state){
            return state.loading;
        },
        isLoggedin(state){
            return state.isLoggedin;
        },
        currentUser(state){
            return state.currentUser;
        },
        authError(state){
            return state.auth_error;
        },
        regError(state){
            return state.reg_error;
        },
        registeredUser(state){
            return state.registeredUser;
        },

    },
    mutations: {
        login(state){
            state.loading = true;
            state.auth_error = null;
        },
        loginSuccess(state, payload){
            state.auth_error = null;
            state.isLoggedin = true;
            state.loading = false;
            state.currentUser = Object.assign({}, payload.user, {token: payload.access_token});

            localStorage.setItem("user", JSON.stringify(state.currentUser));
        },
        loginFailed(state, payload){
            state.loading = false;
            state.auth_error = payload.error;
        },
        logout(state){
            localStorage.removeItem("user");
            state.isLoggedin = false;
            state.currentUser = null;
        },
        registerSuccess(state, payload){
            state.reg_error = null;
            state.registeredUser = payload.user;
        },
        registerFailed(state, payload){
            state.reg_error = payload.error;
        },
    },
    actions: {
        login(context){
            context.commit("login");
        },
    }
};
</code>```

general.js:

```<code>export function initialize(store, router) {
    router.beforeEach((to, from, next) => {
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        const currentUser = store.state.currentUser;

        if(requiresAuth && !currentUser) {
            next('/login');
        } else if(to.path == '/login' && currentUser) {
            next('/');
        } else {
            next();
        }

        if(to.path == '/register' && currentUser) {
            next('/');
        }

    });

    axios.interceptors.response.use(null, (error) => {
        if (error.resposne.status == 401) {
            store.commit('logout');
            router.push('/login');
        }

        return Promise.reject(error);
    });

    if (store.getters.currentUser) {
        setAuthorization(store.getters.currentUser.token);
    }
}

export function setAuthorization(token) {
    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
}
</code>```

I think that this issue is relate to my localstorage, how can i fix this?
I'm novice at the Vue and don't have any idea what is the problem.

Login Component:

```<code><template>
<main>
    <form @submit.prevent="authenticate">
    <div class="grid-x grid-padding-x">

        <div class="small-10 small-offset-2 cell" v-if="registeredUser">
            <p class="alert success">Welcome {{registeredUser.name}}</p>
        </div>
        <div class="small-10 small-offset-2 cell" v-if="authError">
            <p class="alert error">
                {{authError}}
            </p>
        </div>

        <div class="small-2 cell">
            <label for="email" class="text-right middle">Email:</label>
        </div>
        <div class="small-10 cell">
             <input type="email" v-model="formLogin.email" placeholder="Email address">
        </div>

        <div class="small-2 cell">
            <label for="password" class="text-right middle">Password:</label>
        </div>
        <div class="small-10 cell">
             <input type="password" v-model="formLogin.password" placeholder="Enter password">
        </div>

        <div class="small-10 small-offset-2 cell">
            <div class="gap"></div>
            <input type="submit" value="Login" class="button success expanded">
        </div>
    </div>

    </form>

</main>

</template>

<script>
import {login} from '../../partials/auth';
export default {
    data(){
        return {
            formLogin: {
            email: '',
            password: ''
        },
        error: null
        }
    },
    methods:{
        authenticate(){
            this.$store.dispatch('login');

        login(this.$data.formLogin)
            .then(res => {
                this.$store.commit("loginSuccess", res);
                this.$router.push({path: '/profile'});
            })
            .catch(error => {
                this.$store.commit("loginFailed", {error});
            })
        }
    },
    computed:{
        authError(){
            return this.$store.getters.authError
        },
        registeredUser(){
            return this.$store.getters.registeredUser
        }
    }
}
</script>
</code>```

答:
Localstorage data is once loaded on page load, so when you use setItem, this won't be visible until the next time.

You should store the data to vuex store, and use that as the source. Only set and get the data from localstorage on page loads.

Otherwise use something like: https://github.com/robinvdvleuten/vuex-persistedstate

Body:
I write codes with Vuex to login and logout in my Laravel single page application it's working well but when i login to an account the profiles information (name, address, Email, ...)doesn't show in profile but after i reload the page the profile information loads, and when another user try the profile the data of the last person that login shown to him/her

auth.js:

export function registerUser(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/register', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('Somthing is wrong!!')
        })
    })
}

export function login(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/login', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('The Email or password is incorrect!')
        })
    })
}

export function getLoggedinUser(){
    const userStr = localStorage.getItem('user');

    if(!userStr){
        return null
    }

    return JSON.parse(userStr);
}

store.js:

import {getLoggedinUser} from './partials/auth';
const user = getLoggedinUser();
export default {
    state: {
        currentUser: user,
        isLoggedIn: !!user,
        loading: false,
        auth_error: null,
        reg_error:null,
        registeredUser: null,
    },
    getters: {
        isLoading(state){
            return state.loading;
        },
        isLoggedin(state){
            return state.isLoggedin;
        },
        currentUser(state){
            return state.currentUser;
        },
        authError(state){
            return state.auth_error;
        },
        regError(state){
            return state.reg_error;
        },
        registeredUser(state){
            return state.registeredUser;
        },

    },
    mutations: {
        login(state){
            state.loading = true;
            state.auth_error = null;
        },
        loginSuccess(state, payload){
            state.auth_error = null;
            state.isLoggedin = true;
            state.loading = false;
            state.currentUser = Object.assign({}, payload.user, {token: payload.access_token});

            localStorage.setItem("user", JSON.stringify(state.currentUser));
        },
        loginFailed(state, payload){
            state.loading = false;
            state.auth_error = payload.error;
        },
        logout(state){
            localStorage.removeItem("user");
            state.isLoggedin = false;
            state.currentUser = null;
        },
        registerSuccess(state, payload){
            state.reg_error = null;
            state.registeredUser = payload.user;
        },
        registerFailed(state, payload){
            state.reg_error = payload.error;
        },
    },
    actions: {
        login(context){
            context.commit("login");
        },
    }
};

general.js:

export function initialize(store, router) {
    router.beforeEach((to, from, next) => {
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        const currentUser = store.state.currentUser;

        if(requiresAuth && !currentUser) {
            next('/login');
        } else if(to.path == '/login' && currentUser) {
            next('/');
        } else {
            next();
        }

        if(to.path == '/register' && currentUser) {
            next('/');
        }

    });

    axios.interceptors.response.use(null, (error) => {
        if (error.resposne.status == 401) {
            store.commit('logout');
            router.push('/login');
        }

        return Promise.reject(error);
    });

    if (store.getters.currentUser) {
        setAuthorization(store.getters.currentUser.token);
    }
}

export function setAuthorization(token) {
    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
}

I think that this issue is relate to my localstorage, how can i fix this?
I'm novice at the Vue and don't have any idea what is the problem.

Login Component:

<template>

    <form @submit.prevent="authenticate">

Welcome {{registeredUser.name}}

                {{authError}}

            Email:

             <input type="email" v-model="formLogin.email" placeholder="Email address">

            Password:

             <input type="password" v-model="formLogin.password" placeholder="Enter password">

            <input type="submit" value="Login" class="button success expanded">

    </form>

</template>


问:
Using predict.lm based on a model.matrix with different contrasts in R
The aim is to predict new observations based on a multiple regression model.

The model includes two factors ("ec" with effect coding, "dc" with dummy coding) and a numeric variable ("num") plus an interaction term of "ec" and "num".

However, the predict.lm function based on new data fails.

```<code># Dependent variable

y <- rnorm(12, 50, 10)

# Independent variables

# Dummy coding

dc <- factor(x=c("Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel"))

contrasts(dc) <- contr.treatment(3, 1)

# Effect coding

ec <- factor(x=c("A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D"))

contrasts(ec) <- contr.sum(4)

num <- rnorm(12, 10, 2)

# Design matrix

df <- data.frame(dc = dc, ec = ec, num = num)

lm_dm <- model.matrix(~ 1 + ec + dc * num, df)

lm <- lm(y ~ 0 + lm_dm)

# prediction

newdata <- data.frame(dc = c("Schlecht", "Gut", "Gut"), ec = c("C", "D", "B"), num = c(9, 8, 12))

predict.lm(lm, newdata)
</code>```

How can I use the estimated model to conduct a new prediction?

答:
The issue is that the model is estimated using an exterior matrix rather than with the data argument. Instead we may do

```<code>mod <- lm(y ~ 1 + ec + dc * num, data = df)
predict.lm(mod, newdata)
#        1        2        3
# 24.19016 71.26768 59.50670
</code>```

Sticking to not using this is complicated. For instance, the variables in your version of mod have names lm_dmec1, lm_dmdc3, which we would need to match. Further, in the process of supplying lm_dm as a whole we lose information that ec and dc are factors; for this reason we cannot use dc and ec as factors in your newdata; instead we must have dummy variables for all the levels. Thus, the best alternative seems to be to perform the prediction manually:

```<code>model.matrix(~ 1 + ec + dc * num, newdata) %*% coef(mod)
#       [,1]
# 1 57.08853
# 2 31.90847
# 3 47.81049
</code>```

Body:
The aim is to predict new observations based on a multiple regression model.

The model includes two factors ("ec" with effect coding, "dc" with dummy coding) and a numeric variable ("num") plus an interaction term of "ec" and "num".

However, the predict.lm function based on new data fails.

# Dependent variable

y <- rnorm(12, 50, 10)

# Independent variables

# Dummy coding

dc <- factor(x=c("Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel"))

contrasts(dc) <- contr.treatment(3, 1)

# Effect coding

ec <- factor(x=c("A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D"))

contrasts(ec) <- contr.sum(4)

num <- rnorm(12, 10, 2)

# Design matrix

df <- data.frame(dc = dc, ec = ec, num = num)

lm_dm <- model.matrix(~ 1 + ec + dc * num, df)

lm <- lm(y ~ 0 + lm_dm)

# prediction

newdata <- data.frame(dc = c("Schlecht", "Gut", "Gut"), ec = c("C", "D", "B"), num = c(9, 8, 12))

predict.lm(lm, newdata)

How can I use the estimated model to conduct a new prediction?

Body:
The issue is that the model is estimated using an exterior matrix rather than with the data argument. Instead we may do

mod <- lm(y ~ 1 + ec + dc * num, data = df)
predict.lm(mod, newdata)
#        1        2        3
# 24.19016 71.26768 59.50670

Sticking to not using this is complicated. For instance, the variables in your version of mod have names lm_dmec1, lm_dmdc3, which we would need to match. Further, in the process of supplying lm_dm as a whole we lose information that ec and dc are factors; for this reason we cannot use dc and ec as factors in your newdata; instead we must have dummy variables for all the levels. Thus, the best alternative seems to be to perform the prediction manually:

model.matrix(~ 1 + ec + dc * num, newdata) %*% coef(mod)
#       [,1]
# 1 57.08853
# 2 31.90847
# 3 47.81049


问:
Bouncycastle fails in android API < 21
i am trying to run some spongycastle code in android:

```<code>    try {
        Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
        ECGenParameterSpec spec = new ECGenParameterSpec("P-256");
        KeyPairGenerator generator = KeyPairGenerator.getInstance("ECDSA", "SC");
        generator.initialize(spec, new SecureRandom());
        KeyPair keyPair = generator.generateKeyPair();
        ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
        ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
        String publicKeyStr = publicKey.getW().getAffineX().toString() + ":" + publicKey.getW().getAffineY().toString();
        Log.d(TAG, publicKeyStr);
        Calendar c = Calendar.getInstance();
        Date d0 = c.getTime();
        c.add(Calendar.DATE, 1);
        Date expiry = c.getTime();
        String token = Jwts.builder()
                .setIssuedAt(d0)
                .setSubject("00000000-0000-0000-0000-000000000001")
                .setExpiration(expiry)
                .signWith(privateKey, SignatureAlgorithm.ES256).compact();
        Log.d(TAG, token);
    } catch (Exception e) {
        Log.d(TAG, e.toString());
    }
</code>```

in API version 21+, it works as expected.

in API version 18, it works in debug.  in release, it fails in function generator.generateKeyPair() with java.lang.IllegalArgumentException: Invalid point.

in API version 16, it fails in function Jwts.builder().signWith() with io.jsonwebtoken.security.SignatureException: Invalid Elliptic Curve PrivateKey. can't recognise key type in ECDSA based signer.

any idea what i am doing wrong?

edit:  i have apparently fixed the problem by switching from spongycastle to bouncycastle.

in my build.gradle i changed this:

```<code>implementation 'com.madgag.spongycastle:core:1.58.0.0'
implementation 'com.madgag.spongycastle:prov:1.58.0.0'
</code>```

to this:

```<code>implementation 'org.bouncycastle:bcpkix-jdk15on:1.60'
</code>```

and in my code i got rid of this line:

```<code>Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
</code>```

and added these lines:

```<code>import org.bouncycastle.jce.provider.BouncyCastleProvider;

Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
Security.insertProviderAt(new BouncyCastleProvider(), 1);
</code>```

and i changed the provider from "SC" to "BC".

and now my code works as i would like, for all versions of the android API.

my concern now is the comment at this link...

Spongy Castle: is it obsolete?

...by the author of spongycastle:

Why might Spongy Castle not be obsolete?

...

even on post-Android 3.0 devices, device manufacturers are not above
  carelessly bundling libraries, it's possible that Bouncy Castle may
  still be bundled on some obscure devices.

what does that mean exactly?  could it cause my code above to malfunction on certain devices?

答:
use bouncy castle:</p>

```<code>dependencies {
    // https://mvnrepository.com/artifact/org.bouncycastle
    implementation "org.bouncycastle:bcprov-jdk15on:1.60"
    implementation "org.bouncycastle:bcpkix-jdk15on:1.60"
}
</code>```

Title: Bouncycastle fails in android API < 21

Body:
i am trying to run some spongycastle code in android:

    try {
        Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
        ECGenParameterSpec spec = new ECGenParameterSpec("P-256");
        KeyPairGenerator generator = KeyPairGenerator.getInstance("ECDSA", "SC");
        generator.initialize(spec, new SecureRandom());
        KeyPair keyPair = generator.generateKeyPair();
        ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
        ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
        String publicKeyStr = publicKey.getW().getAffineX().toString() + ":" + publicKey.getW().getAffineY().toString();
        Log.d(TAG, publicKeyStr);
        Calendar c = Calendar.getInstance();
        Date d0 = c.getTime();
        c.add(Calendar.DATE, 1);
        Date expiry = c.getTime();
        String token = Jwts.builder()
                .setIssuedAt(d0)
                .setSubject("00000000-0000-0000-0000-000000000001")
                .setExpiration(expiry)
                .signWith(privateKey, SignatureAlgorithm.ES256).compact();
        Log.d(TAG, token);
    } catch (Exception e) {
        Log.d(TAG, e.toString());
    }

in API version 21+, it works as expected.

in API version 18, it works in debug.  in release, it fails in function generator.generateKeyPair() with java.lang.IllegalArgumentException: Invalid point.

in API version 16, it fails in function Jwts.builder().signWith() with io.jsonwebtoken.security.SignatureException: Invalid Elliptic Curve PrivateKey. can't recognise key type in ECDSA based signer.

any idea what i am doing wrong?

edit:  i have apparently fixed the problem by switching from spongycastle to bouncycastle.

in my build.gradle i changed this:

implementation 'com.madgag.spongycastle:core:1.58.0.0'
implementation 'com.madgag.spongycastle:prov:1.58.0.0'

to this:

implementation 'org.bouncycastle:bcpkix-jdk15on:1.60'

and in my code i got rid of this line:

Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());

and added these lines:

import org.bouncycastle.jce.provider.BouncyCastleProvider;

Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
Security.insertProviderAt(new BouncyCastleProvider(), 1);

and i changed the provider from "SC" to "BC".

and now my code works as i would like, for all versions of the android API.

my concern now is the comment at this link...

Spongy Castle: is it obsolete?

...by the author of spongycastle:

Why might Spongy Castle not be obsolete?

...

even on post-Android 3.0 devices, device manufacturers are not above
  carelessly bundling libraries, it's possible that Bouncy Castle may
  still be bundled on some obscure devices.

what does that mean exactly?  could it cause my code above to malfunction on certain devices?

Body:
use bouncy castle:

dependencies {
    // https://mvnrepository.com/artifact/org.bouncycastle
    implementation "org.bouncycastle:bcprov-jdk15on:1.60"
    implementation "org.bouncycastle:bcpkix-jdk15on:1.60"
}


问:
Why does URL Rewrite module makes CLR stop in IIS 8.5?

Windows server 2012 R2

IIS 8.5

Simple one-file index.html website

In the Application pool selected .NET CLR 4.0

In this step website works. Then I install the URL Rewrite module for IIS. Don't add any rules for URL Rewrite, but when I open web-site in browser, the application pool for this site stops.

The error message:

```<code>HTTP Error 503. The service is unavailable.
</code>```

The log from

```<code>%SystemDrive%\Windows\System32\LogFiles\HTTPERR

#Software: Microsoft HTTP API 2.0
#Version: 1.0
#Date: 2019-04-29 13:34:12
#Fields: date time c-ip c-port s-ip s-port cs-version cs-method cs-uri sc-status s-siteid s-reason s-queuename
2019-04-29 13:34:12 127.0.0.1 49200 127.0.0.1 80 HTTP/1.1 GET / 503 5 AppOffline test.com29 13:34:12 127.0.0.1 49200 127.0.0.1 80 HTTP/1.1 GET / 503 5 AppOffline test.com
</code>```

This catalog has no log files:

```<code>%SystemDrive%\inetpub\logs\LogFiles
</code>```

When one uninstall URL Rewrite module, the pool of website starts to work normally.

Why doest URL Rewrite module makes CLR stop?

UPDATE

Event Log message:

```<code>The Module DLL C:\Windows\system32\inetsrv\rewrite.dll failed to load.  The data is the error.
</code>```

Then I added to applicationHost config bitness32

```<code>C:\Windows\System32\inetsrv\config\applicationHost

<add name="RewriteModule" image="%SystemRoot%\system32\inetsrv\rewrite.dll" preCondition="bitness32" />
</code>```

With bitness32 it doesn't stop the pool but I get this error in the browser:

```<code>HTTP Error 500.0 - Internal Server Error
Module "RewriteModule" could not be found
</code>```

答:
In event log I found the same message. I.e. The Module DLL C:\Windows\system32\inetsrv\rewrite.dll failed to load.  The data is the error.

For me the solution that worked was to replace the "rewrite.dll". In 2 of our other server it was working fine and they were installed in 2017. So I just copied the "rewrite.dll" from that server and replace it on my new server.

For me the older version(v7.1.1952.0) of the dll works, but new version ( v7.1.1993.2351), which comes with the latest setup, doesn't work.

BTW you need to stop the IIS before you replace the dll and start again.

Body:
Windows server 2012 R2

IIS 8.5

Simple one-file index.html website

In the Application pool selected .NET CLR 4.0

In this step website works. Then I install the URL Rewrite module for IIS. Don't add any rules for URL Rewrite, but when I open web-site in browser, the application pool for this site stops.

The error message:

HTTP Error 503. The service is unavailable.

The log from

%SystemDrive%\Windows\System32\LogFiles\HTTPERR

#Software: Microsoft HTTP API 2.0
#Version: 1.0
#Date: 2019-04-29 13:34:12
#Fields: date time c-ip c-port s-ip s-port cs-version cs-method cs-uri sc-status s-siteid s-reason s-queuename
2019-04-29 13:34:12 127.0.0.1 49200 127.0.0.1 80 HTTP/1.1 GET / 503 5 AppOffline test.com29 13:34:12 127.0.0.1 49200 127.0.0.1 80 HTTP/1.1 GET / 503 5 AppOffline test.com

This catalog has no log files:

%SystemDrive%\inetpub\logs\LogFiles

When one uninstall URL Rewrite module, the pool of website starts to work normally.

Why doest URL Rewrite module makes CLR stop?

UPDATE

Event Log message:

The Module DLL C:\Windows\system32\inetsrv\rewrite.dll failed to load.  The data is the error.

Then I added to applicationHost config bitness32

C:\Windows\System32\inetsrv\config\applicationHost

<add name="RewriteModule" image="%SystemRoot%\system32\inetsrv\rewrite.dll" preCondition="bitness32" />

With bitness32 it doesn't stop the pool but I get this error in the browser:

HTTP Error 500.0 - Internal Server Error
Module "RewriteModule" could not be found


问:
Deducing the template parameter of a templated class argument: const issue
I think the problem is fairly common, so there should be a known solution. I came up with one, but I'm not really satisfied, so I'm asking here, hoping someone can help.

Say I have a function, whose signature is

```<code>template<typename T>
void foo(const MyArray<const T>& x);
</code>```

The const in the template parameter is to prevent me from changin the array content, since (for reasons beyond this question), the accessors ([] and ()) of MyArray<T> are always marked const, and return references to T (hence, the const ensure safety, since MyArray<T>::operator[] returns T&, while MyArray<const T>::operator[] returns const T&).

Great. However, templates with different template arguments are non related, so I can't bind a reference to MyClass<T> to a reference of MyClass<const T>, meaning I can't do this

```<code>MyArray<double> ar(/*blah*/);
foo(ar);
</code>```

Notice that, without a reference, the code above would work provided that there is a copy constructor that lets me create MyArray<const T> from MyArray<T>. However, I don't want to remove the reference, since the array construction would happen a lot of times, and, despite relatively cheap, its cost would add up.

So the question: how can I call foo with an MyArray<T>?

My only solution so far is the following:

```<code>MyArray<T> ar(/*blah*/);
foo(reinterpret_cast<MyArray<const T>>(ar));
</code>```

(actually in my code I hid the reinterpret cast in an inlined function with more verbose name, but the end game is the same). The class MyArray does not have a specialization for const T that makes it not reinterpretable, so the cast should be 'safe'. But this is not really a nice solution to read. An alternative, would be to duplicate foo's signature, to have a version taking MyArray<T>, which implementation does the cast and calls the const version. The problem with this is code duplication (and I have quite a few functions foo that need to be duplicated).

Perhaps some extra template magic on the signature of foo? The goal is to pass both MyArray<T> and MyArray<const T>, while still retaining const-correctness (i.e., make the compiler bark if I accidentally change the input in the function body).

Edit 1: The class MyArray (whose implementation is not under my control), has const accessors, since it stores pointers. So calling v[3] will modify the values in the array, but not the members stored in the class (namely a pointer and some smart-pointer-like metadata). In other words, the object is de facto not modified by accessors, though the array is. It's a semantic distinction. Not sure why they went this direction (I have an idea, but too long to explain).

Edit 2: I accepted one of the two answers (though they were somewhat similar). I am not sure (for reasons long to explain) that the wrapper class is doable in my case (maybe, I have to think about it). I am also puzzled by the fact that, while

```<code>template<typename T>
void foo(const MyArray<const T>& x);
MyArray<int> a;
foo(a);
</code>```

does not compile, the following does

```<code>void foo(const MyArray<const int>& x);
MyArray<int> a;
foo(a);
</code>```

Note: MyArray does offer a templated "copy constructor" with signature

```<code>template<typename S>
MyArray(const MyArray<S>&);
</code>```

so it can create MyArray<const T> from MyArray<T>. I am puzzled why it works when T is explicit, while it doesn't if T is a template parameter.

答:
Since you are not allowed to change MyArray, one option is to use an adapter class.

```<code>template <typename T>
class ConstMyArrayView {
   public:
    // Not an explicit constructor!
    ConstMyArrayView(const MyArray<T>& a) : a_(a) {}
    const T& operator[](size_t i) const { return a_[i]; }
   private:
     const MyArray<T>& a_;
};

template<typename T>
void foo(const ConstMyArrayView<T>& x);

MyArray<T> x;
foo(x);
</code>```

But in the end, if you can change MyArray to match the const-correctness you want, or switch to a class that does, that'll be the better option.

Body:
I think the problem is fairly common, so there should be a known solution. I came up with one, but I'm not really satisfied, so I'm asking here, hoping someone can help.

Say I have a function, whose signature is

template<typename T>
void foo(const MyArray<const T>& x);

The const in the template parameter is to prevent me from changin the array content, since (for reasons beyond this question), the accessors ([] and ()) of MyArray<T> are always marked const, and return references to T (hence, the const ensure safety, since MyArray<T>::operator[] returns T&, while MyArray<const T>::operator[] returns const T&).

Great. However, templates with different template arguments are non related, so I can't bind a reference to MyClass<T> to a reference of MyClass<const T>, meaning I can't do this

MyArray<double> ar(/*blah*/);
foo(ar);

Notice that, without a reference, the code above would work provided that there is a copy constructor that lets me create MyArray<const T> from MyArray<T>. However, I don't want to remove the reference, since the array construction would happen a lot of times, and, despite relatively cheap, its cost would add up.

So the question: how can I call foo with an MyArray<T>?

My only solution so far is the following:

MyArray<T> ar(/*blah*/);
foo(reinterpret_cast<MyArray<const T>>(ar));

(actually in my code I hid the reinterpret cast in an inlined function with more verbose name, but the end game is the same). The class MyArray does not have a specialization for const T that makes it not reinterpretable, so the cast should be 'safe'. But this is not really a nice solution to read. An alternative, would be to duplicate foo's signature, to have a version taking MyArray<T>, which implementation does the cast and calls the const version. The problem with this is code duplication (and I have quite a few functions foo that need to be duplicated).

Perhaps some extra template magic on the signature of foo? The goal is to pass both MyArray<T> and MyArray<const T>, while still retaining const-correctness (i.e., make the compiler bark if I accidentally change the input in the function body).

Edit 1: The class MyArray (whose implementation is not under my control), has const accessors, since it stores pointers. So calling v[3] will modify the values in the array, but not the members stored in the class (namely a pointer and some smart-pointer-like metadata). In other words, the object is de facto not modified by accessors, though the array is. It's a semantic distinction. Not sure why they went this direction (I have an idea, but too long to explain).

Edit 2: I accepted one of the two answers (though they were somewhat similar). I am not sure (for reasons long to explain) that the wrapper class is doable in my case (maybe, I have to think about it). I am also puzzled by the fact that, while

template<typename T>
void foo(const MyArray<const T>& x);
MyArray<int> a;
foo(a);

does not compile, the following does

void foo(const MyArray<const int>& x);
MyArray<int> a;
foo(a);

Note: MyArray does offer a templated "copy constructor" with signature

template<typename S>
MyArray(const MyArray<S>&);

so it can create MyArray<const T> from MyArray<T>. I am puzzled why it works when T is explicit, while it doesn't if T is a template parameter.

Body:
Since you are not allowed to change MyArray, one option is to use an adapter class.

template <typename T>
class ConstMyArrayView {
   public:
    // Not an explicit constructor!
    ConstMyArrayView(const MyArray<T>& a) : a_(a) {}
    const T& operator[](size_t i) const { return a_[i]; }
   private:
     const MyArray<T>& a_;
};

template<typename T>
void foo(const ConstMyArrayView<T>& x);

MyArray<T> x;
foo(x);

But in the end, if you can change MyArray to match the const-correctness you want, or switch to a class that does, that'll be the better option.


问:
How to get all the key-values underlying between two given keys in a sorted hashmap?
I have a HashMap with Time as key. I sorted the HashMap.
Now I want to get all the key-values between two keys i.e. time values.</p>

答:
Here's some example code. A TreeMap implements the interface NavigableMap, so make sure you use that as your variable type, to harness the full power of a TreeMap:

```<code>NavigableMap<Integer, String> map = new TreeMap<>();
// code to fill my map with values from 1 to 20, key=int, value=String.valueOf(int)
IntStream.rangeClosed(1,20).forEach(i->map.put(i, String.valueOf(i)));
</code>```

NavigableMap has a method .subMap(start, end) and an overload .subMap(start, startInclusive, end, endInclusive) for selecting a partial view of the map, and it sounds like this is what you need.

```<code>NavigableMap<Integer, String> subMap = map.subMap(5, false, 10, false);
</code>```

This is a live view of the map I created before, but it contains only the mappings between keys 5 and 10, exclusive. Let's check whether that works as expected:

```<code>subMap.forEach(
    (k, v) -> System.out.printf("Key: %d, value: '%s'%n", k, v)
);
</code>```

Output:

Key: 6, value: '6'

  Key: 7, value: '7'

  Key: 8, value: '8'

  Key: 9, value: '9'

As you can see, the map remains sorted, but is limited to the specified range.

Body:
Here's some example code. A TreeMap implements the interface NavigableMap, so make sure you use that as your variable type, to harness the full power of a TreeMap:

NavigableMap<Integer, String> map = new TreeMap<>();
// code to fill my map with values from 1 to 20, key=int, value=String.valueOf(int)
IntStream.rangeClosed(1,20).forEach(i->map.put(i, String.valueOf(i)));

NavigableMap has a method .subMap(start, end) and an overload .subMap(start, startInclusive, end, endInclusive) for selecting a partial view of the map, and it sounds like this is what you need.

NavigableMap<Integer, String> subMap = map.subMap(5, false, 10, false);

This is a live view of the map I created before, but it contains only the mappings between keys 5 and 10, exclusive. Let's check whether that works as expected:

subMap.forEach(
    (k, v) -> System.out.printf("Key: %d, value: '%s'%n", k, v)
);

Output:

Key: 6, value: '6'

  Key: 7, value: '7'

  Key: 8, value: '8'

  Key: 9, value: '9'

As you can see, the map remains sorted, but is limited to the specified range.


问:
Iterate over another url with a for loop in django
I'm setting up a button that save API datas into my database and I'm trying to find a way to get the description out of every products but they are not included with the main url that get all products by city: (https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr), they are only included if we use this link which call a product by its id: (https://www.test-headout.com/api/public/v1/product/get/508).

So I was adviced to first hit the Listing API to get all products. Iterate over the list and get id and hit the product/get API to get the description.

This is what I've tried so far but I don't get how to do the iteration part:

My Django views:

```<code>def api_data(request):
    response = requests.get("https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
      headers={
        "Headout-Auth": HEADOUT_TEST_API_KEY
      }
    ).json()

    if (request.GET.get('mybtn')):
        for item in response['items']:  # for loop
            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                #description=response['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url'],
            )

    return render(request, "form.html")
</code>```

How can I do this?

Based on @ralf answer this is what I came out with
:

```<code>def api_data(request):
    if (request.GET.get('mybtn')):
        url_1 = requests.get("https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
          headers={
            "Headout-Auth": HEADOUT_TEST_API_KEY
          }
        )

        base_url_2 = requests.get("https://www.test-headout.com/api/public/v1/product/get/",
          headers={
            "Headout-Auth": HEADOUT_TEST_API_KEY
          }
        )

        resp_data = url_1.json()

        for item in resp_data['items']:
            url = '{}{}'.format(base_url_2, item['id'])
            resp_data = url.json()

            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                description=response['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")
</code>```

答:
I don't want to add even more code to my other answer, so here goes a new one. So here is how your code should probably look, based on your updated question code:</p>

```<code>def api_data(request):
    if request.GET.get('mybtn'):    # this should probably be compared to something ???
        resp_1 = requests.get(
            "https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
            headers={
                "Headout-Auth": HEADOUT_TEST_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"

        for item in resp_1_data['items']:
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'])

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_TEST_API_KEY
                })
            resp_2_data = resp_2.json()

            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                description=resp_2_data['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")
</code>```

Body:
I'm setting up a button that save API datas into my database and I'm trying to find a way to get the description out of every products but they are not included with the main url that get all products by city: (https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr), they are only included if we use this link which call a product by its id: (https://www.test-headout.com/api/public/v1/product/get/508).

So I was adviced to first hit the Listing API to get all products. Iterate over the list and get id and hit the product/get API to get the description.

This is what I've tried so far but I don't get how to do the iteration part:

My Django views:

def api_data(request):
    response = requests.get("https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
      headers={
        "Headout-Auth": HEADOUT_TEST_API_KEY
      }
    ).json()

    if (request.GET.get('mybtn')):
        for item in response['items']:  # for loop
            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                #description=response['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url'],
            )

    return render(request, "form.html")

How can I do this?

Based on @ralf answer this is what I came out with
:

def api_data(request):
    if (request.GET.get('mybtn')):
        url_1 = requests.get("https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
          headers={
            "Headout-Auth": HEADOUT_TEST_API_KEY
          }
        )

        base_url_2 = requests.get("https://www.test-headout.com/api/public/v1/product/get/",
          headers={
            "Headout-Auth": HEADOUT_TEST_API_KEY
          }
        )

        resp_data = url_1.json()

        for item in resp_data['items']:
            url = '{}{}'.format(base_url_2, item['id'])
            resp_data = url.json()

            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                description=response['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")

Body:
I don't want to add even more code to my other answer, so here goes a new one. So here is how your code should probably look, based on your updated question code:

def api_data(request):
    if request.GET.get('mybtn'):    # this should probably be compared to something ???
        resp_1 = requests.get(
            "https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr",
            headers={
                "Headout-Auth": HEADOUT_TEST_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"

        for item in resp_1_data['items']:
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'])

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_TEST_API_KEY
                })
            resp_2_data = resp_2.json()

            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                description=resp_2_data['contentListHtml'][0]['html'],
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")


问:
FadeOut one element and fadeIn another element on hover
I'm trying to achieve an effect where on the hover of an element A, an element B is fadeOut and an element C is fadeIn, both inside the element A.

That's what I tried:

$('.button').hover(function() {
 info = $(this).find('.info');
 download = $(this).find('.download');

 info.stop().fadeOut(150, function() {
  download.stop().fadeIn(150);
 })
}, function() {
 download.stop().fadeOut(150, function() {
  info.stop().fadeIn(150);
 })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  background-color: orange;
  padding: 10px;
  width: 250px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-bottom: 10px;
}

.download {
  display: none;
  font-size: 17px;
}</code>```

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

```

Hovering one element at a time seems working fine but when you try to hover more elements concurrently the animation it starts to break.

Any solution? Other approaches are accepted. Thanks.

答:
You are inadvertently creating global variables for info and download by omitting the var, let, or const keywords. That means every function call is using and overwriting those variables. You need to create local variables in each function.

$('.button').hover(function() {
  var info = $(this).find('.info');
  var download = $(this).find('.download');

  download.stop();
  info.stop().fadeOut(150, function() {
    download.stop().fadeIn(150);
  })
}, function() {
  var info = $(this).find('.info');
  var download = $(this).find('.download');

  info.stop();
  download.stop().fadeOut(150, function() {
    info.stop().fadeIn(150);
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  background-color: orange;
  padding: 10px;
  width: 250px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-bottom: 10px;
}

.download {
  display: none;
  font-size: 17px;
}</code>```

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

```

Body:
I'm trying to achieve an effect where on the hover of an element A, an element B is fadeOut and an element C is fadeIn, both inside the element A.

That's what I tried:

$('.button').hover(function() {
 info = $(this).find('.info');
 download = $(this).find('.download');

 info.stop().fadeOut(150, function() {
  download.stop().fadeIn(150);
 })
}, function() {
 download.stop().fadeOut(150, function() {
  info.stop().fadeIn(150);
 })
})

.button {
  background-color: orange;
  padding: 10px;
  width: 250px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-bottom: 10px;
}

.download {
  display: none;
  font-size: 17px;
}

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

Hovering one element at a time seems working fine but when you try to hover more elements concurrently the animation it starts to break.

Any solution? Other approaches are accepted. Thanks.

Body:
You are inadvertently creating global variables for info and download by omitting the var, let, or const keywords. That means every function call is using and overwriting those variables. You need to create local variables in each function.

$('.button').hover(function() {
  var info = $(this).find('.info');
  var download = $(this).find('.download');

  download.stop();
  info.stop().fadeOut(150, function() {
    download.stop().fadeIn(150);
  })
}, function() {
  var info = $(this).find('.info');
  var download = $(this).find('.download');

  info.stop();
  download.stop().fadeOut(150, function() {
    info.stop().fadeIn(150);
  })
})

.button {
  background-color: orange;
  padding: 10px;
  width: 250px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-bottom: 10px;
}

.download {
  display: none;
  font-size: 17px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button">
  <div class="info">
    <i class="fas fa-download"></i> <strong>Mega Limited</strong> 1GB
  </div>
  <div class="download">Download</div>
</div>

<div class="button">
  <div class="info">
    <i class="fas fa-download"></i> <strong>Mega Limited</strong> 1GB
  </div>
  <div class="download">Download</div>
</div>

<div class="button">
  <div class="info">
    <i class="fas fa-download"></i> <strong>Mega Limited</strong> 1GB
  </div>
  <div class="download">Download</div>
</div>

<div class="button">
  <div class="info">
    <i class="fas fa-download"></i> <strong>Mega Limited</strong> 1GB
  </div>
  <div class="download">Download</div>
</div>


问:
java.sql.SQLException: no such column: after accepting sql query
I am developing a system that manages stock for a project and am trying to get a list of stock items that are close to their expiration date

This is what the table is created as:

```<code>Query_Statement.executeUpdate("CREATE TABLE STOCK_PURCHASE ( SP_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "USER_ID INTEGER,STOCK_ID INTEGER,SUPPLIER_ID INTEGER,SP_ENTRY_DATE TEXT,"
                    + "SP_PURCHASE_PRICE REAL, SP_SELLBY_DATE TEXT, SP_QUANTITY REAL,"
                    + "FOREIGN KEY (USER_ID) REFERENCES USER (USER_ID),"
                    + "FOREIGN KEY (STOCK_ID) REFERENCES STOCK (STOCK_ID),"
                    + "FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER (SUPPLIER_ID))");
</code>```

This is the function to get that I use:

```<code>public ArrayList<String> GetExpiredStock(){
    Connection dbConnection = null;
    ResultSet list = null;
    ArrayList<String> ls = new ArrayList<String>();

    LocalDate currentDate = LocalDate.now();
    //System.out.println(today);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");

        Statement Query_Statement = dbConnection.createStatement();
        Query_Statement.setQueryTimeout(10);

        list = Query_Statement.executeQuery("SELECT SP_ENTRY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works

        while (list.next()) {
            try {
            LocalDate expDate = LocalDate.parse(list.getString("SP_SELLBY_DATE"), formatter);
            LocalDate monthAway = expDate.minusMonths(1);
            System.out.println(currentDate);
            if(currentDate.isAfter(monthAway)) {
                int id = list.getInt("STOCK_ID");
                ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);

                ls.add(ids.getString("STOCK_NAME") + "\t\t" +
                        list.getString("SP_SELLBY_DATE") + getStockQuant(list.getInt("STOCK_ID"),
                                currentDate));

            }
            }catch(SQLException e) {
                System.err.println(e);
                continue;

            }
        }

    } catch (SQLException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            if (dbConnection != null)
                dbConnection.close();
        } catch (SQLException e) {
            System.err.println(e);
        }
    }

    return ls;
}
</code>```

I expect it to get the expiration date. However it keeps saying:

```<code>java.sql.SQLException: no such column: 'SP_SELLBY_DATE'
</code>```

Edit:

I changed the code to look like this:

```<code>    public ArrayList<String> GetExpiredStock(){
    Connection dbConnection = null;
    ResultSet list = null;
    ArrayList<String> ls = new ArrayList<String>();

    LocalDate currentDate = LocalDate.now();
    //System.out.println(today);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");

        Statement Query_Statement = dbConnection.createStatement();
        Query_Statement.setQueryTimeout(10);

        list = Query_Statement.executeQuery("SELECT SP_SELLBY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works

        while (list.next()) {
            try {
            String da = list.getString("SP_SELLBY_DATE");
            int id = list.getInt("STOCK_ID");
            System.out.println("Executed on id = " + id);
            LocalDate expDate = LocalDate.parse(da, formatter);
            LocalDate monthAway = expDate.minusMonths(1);
            System.out.println(currentDate);
            if(currentDate.isAfter(monthAway)) {

                ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);

                ls.add(ids.getString("STOCK_NAME") + "\t\t" +
                        da + "\t\t"+  getStockQuant(id,
                                currentDate));

            }
            }catch(SQLException e) {
                System.err.println(e);
                continue;

            }
        }

    } catch (SQLException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            if (dbConnection != null)
                dbConnection.close();
        } catch (SQLException e) {
            System.err.println(e);
        }
    }

    return ls;
</code>```

But it still fails after the first iteration

答:
Your SQL query doesn't have the required column, add it :</p>

```<code>SELECT SP_ENTRY_DATE, STOCK_ID, SP_SELLBY_DATE FROM STOCK_PURCHASE
</code>```

Body:
I am developing a system that manages stock for a project and am trying to get a list of stock items that are close to their expiration date

This is what the table is created as:

Query_Statement.executeUpdate("CREATE TABLE STOCK_PURCHASE ( SP_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "USER_ID INTEGER,STOCK_ID INTEGER,SUPPLIER_ID INTEGER,SP_ENTRY_DATE TEXT,"
                    + "SP_PURCHASE_PRICE REAL, SP_SELLBY_DATE TEXT, SP_QUANTITY REAL,"
                    + "FOREIGN KEY (USER_ID) REFERENCES USER (USER_ID),"
                    + "FOREIGN KEY (STOCK_ID) REFERENCES STOCK (STOCK_ID),"
                    + "FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER (SUPPLIER_ID))");

This is the function to get that I use:

public ArrayList<String> GetExpiredStock(){
    Connection dbConnection = null;
    ResultSet list = null;
    ArrayList<String> ls = new ArrayList<String>();

    LocalDate currentDate = LocalDate.now();
    //System.out.println(today);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");

        Statement Query_Statement = dbConnection.createStatement();
        Query_Statement.setQueryTimeout(10);

        list = Query_Statement.executeQuery("SELECT SP_ENTRY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works

        while (list.next()) {
            try {
            LocalDate expDate = LocalDate.parse(list.getString("SP_SELLBY_DATE"), formatter);
            LocalDate monthAway = expDate.minusMonths(1);
            System.out.println(currentDate);
            if(currentDate.isAfter(monthAway)) {
                int id = list.getInt("STOCK_ID");
                ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);

                ls.add(ids.getString("STOCK_NAME") + "\t\t" +
                        list.getString("SP_SELLBY_DATE") + getStockQuant(list.getInt("STOCK_ID"),
                                currentDate));

            }
            }catch(SQLException e) {
                System.err.println(e);
                continue;

            }
        }

    } catch (SQLException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            if (dbConnection != null)
                dbConnection.close();
        } catch (SQLException e) {
            System.err.println(e);
        }
    }

    return ls;
}

I expect it to get the expiration date. However it keeps saying:

java.sql.SQLException: no such column: 'SP_SELLBY_DATE'

Edit:

I changed the code to look like this:

    public ArrayList<String> GetExpiredStock(){
    Connection dbConnection = null;
    ResultSet list = null;
    ArrayList<String> ls = new ArrayList<String>();

    LocalDate currentDate = LocalDate.now();
    //System.out.println(today);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");

        Statement Query_Statement = dbConnection.createStatement();
        Query_Statement.setQueryTimeout(10);

        list = Query_Statement.executeQuery("SELECT SP_SELLBY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works

        while (list.next()) {
            try {
            String da = list.getString("SP_SELLBY_DATE");
            int id = list.getInt("STOCK_ID");
            System.out.println("Executed on id = " + id);
            LocalDate expDate = LocalDate.parse(da, formatter);
            LocalDate monthAway = expDate.minusMonths(1);
            System.out.println(currentDate);
            if(currentDate.isAfter(monthAway)) {

                ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);

                ls.add(ids.getString("STOCK_NAME") + "\t\t" +
                        da + "\t\t"+  getStockQuant(id,
                                currentDate));

            }
            }catch(SQLException e) {
                System.err.println(e);
                continue;

            }
        }

    } catch (SQLException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            if (dbConnection != null)
                dbConnection.close();
        } catch (SQLException e) {
            System.err.println(e);
        }
    }

    return ls;

But it still fails after the first iteration

Body:
Your SQL query doesn't have the required column, add it :

SELECT SP_ENTRY_DATE, STOCK_ID, SP_SELLBY_DATE FROM STOCK_PURCHASE


问:
Vue js vee validate password confirmation with custom components
I use vee-validate in my project with custom components with no problems.

But now for a Password Confirmation input field, I'm not able to make it work properly.

I have custom components for the input fields, somethink like <base-input-field>.

If I add a ref="password" attribute in my custom component (<base-input-field ref="password">), it will not reference the <input> inside my custom component, but the
 wrapper that encapsulates the <input> html component.

Code example:

```<code>            <!-- Password -->
            <div class="row">
              <base-text-field
                ref="password"
                name="password"
                type="password"
                :error="isVisible && errors.first('password')"
                v-validate="{
                  required: true,
                  min: 6,
                  max: 30,
                }"
                v-model.trim="password"
                required
              />
            </div>

            <!-- Confirm Password -->
            <div class="row">
              <base-text-field
                name="password_conf"
                type="password"
                :error="isVisible && errors.first('password_conf')"
                v-validate="{
                  required: true,
                  confirmed: 'password',
                }"
                :data-vv-as="password"
                v-model.trim="password_conf"
                required
              />
            </div>
</code>```

答:
Follow the requirements in this page and you should be fine:

emit input event when the value in your component changes

have name and value defined in component via $_veeValidate.  Or, use data-vv-name and data-vv-value-path (details here).

Since you didn't provide the code in base-text-field I can't really give you any further example of how it should work for you.

Body:
I use vee-validate in my project with custom components with no problems.

But now for a Password Confirmation input field, I'm not able to make it work properly.

I have custom components for the input fields, somethink like <base-input-field>.

If I add a ref="password" attribute in my custom component (<base-input-field ref="password">), it will not reference the <input> inside my custom component, but the
 wrapper that encapsulates the <input> html component.

Code example:

              <base-text-field
                ref="password"
                name="password"
                type="password"
                :error="isVisible && errors.first('password')"
                v-validate="{
                  required: true,
                  min: 6,
                  max: 30,
                }"
                v-model.trim="password"
                required
              />

              <base-text-field
                name="password_conf"
                type="password"
                :error="isVisible && errors.first('password_conf')"
                v-validate="{
                  required: true,
                  confirmed: 'password',
                }"
                :data-vv-as="password"
                v-model.trim="password_conf"
                required
              />


问:
How to prevent Validator from targeting an unrelated ModelAttribute?
I am using custom validator of Spring framework to validate the user input for an Employee entity. If there are no errors, I want to directly go to an html page for user to create a new LeaveRecord.

Controller:

    @Autowired
    private EmployeeValidator eValidator;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(eValidator);
    }

    @RequestMapping(path = "/authenticate", method = RequestMethod.POST)
    public ModelAndView authenticate(@Valid @ModelAttribute Employee user, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return new ModelAndView("redirect:/");
        }

        ModelAndView mav = new ModelAndView("LeaveForm");
        mav.addObject("leave", new LeaveRecord());
        return mav;
    }
```

<p>Validator:</p>

```@Component
public class EmployeeValidator implements Validator{

    private LeaveServiceIF lService;

    @Autowired
    public void setlService(LeaveServiceIF lService) {
        this.lService = lService;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return Employee.class.equals(clazz);
    }

    @Override
    public void validate(Object obj, Errors e) {
        Employee emp = (Employee) obj;
        if (lService.authenticate(emp.getEmpId(), emp.getPwd()) == null) {
            e.rejectValue(null, "invalidEmpIdOrPwd");
        }
    }
}
```

<p>Dependencies (pom.xml):</p>

```<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>
    </dependencies>
```

<p>However when there are no errors for the Employee entity, I will get the following exception.</p>

```java.lang.IllegalStateException: Invalid target for Validator [sg.edu.nus.laps.validator.EmployeeValidator@3404e5c4]: LeaveRecord [lType=null, startDate=null, endDate=null, numOfDays=0.0, reason=null, lStatus=null, employee=null]
    at org.springframework.validation.DataBinder.assertValidators(DataBinder.java:542) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.validation.DataBinder.addValidators(DataBinder.java:553) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at sg.edu.nus.laps.controller.LeaveController.initBinder(LeaveController.java:38) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_212]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_212]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_212]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_212]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.annotation.InitBinderDataBinderFactory.initBinder(InitBinderDataBinderFactory.java:68) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.bind.support.DefaultDataBinderFactory.createBinder(DefaultDataBinderFactory.java:60) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.annotation.ModelFactory.updateBindingResult(ModelFactory.java:214) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.annotation.ModelFactory.updateModel(ModelFactory.java:200) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.getModelAndView(RequestMappingHandlerAdapter.java:1001) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:897) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_212]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_212]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_212]
```

It seems like the EmployeeValidator is targeting the LeaveRecord entity that I am passing to the html view, thus causing the exception.

Is there a way to prevent this, or am I doing it correctly?

答:
Looks like something might be wrong with your Validator class. Can you show us the code?

This might help:

Prevent "IllegalStateException: Invalid target for Validator" error

Body:
I am using custom validator of Spring framework to validate the user input for an Employee entity. If there are no errors, I want to directly go to an html page for user to create a new LeaveRecord.

Controller:

    @Autowired
    private EmployeeValidator eValidator;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(eValidator);
    }

    @RequestMapping(path = "/authenticate", method = RequestMethod.POST)
    public ModelAndView authenticate(@Valid @ModelAttribute Employee user, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return new ModelAndView("redirect:/");
        }

        ModelAndView mav = new ModelAndView("LeaveForm");
        mav.addObject("leave", new LeaveRecord());
        return mav;
    }

Validator:

@Component
public class EmployeeValidator implements Validator{

    private LeaveServiceIF lService;

    @Autowired
    public void setlService(LeaveServiceIF lService) {
        this.lService = lService;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return Employee.class.equals(clazz);
    }

    @Override
    public void validate(Object obj, Errors e) {
        Employee emp = (Employee) obj;
        if (lService.authenticate(emp.getEmpId(), emp.getPwd()) == null) {
            e.rejectValue(null, "invalidEmpIdOrPwd");
        }
    }
}

Dependencies (pom.xml):

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>
    </dependencies>

However when there are no errors for the Employee entity, I will get the following exception.

java.lang.IllegalStateException: Invalid target for Validator [sg.edu.nus.laps.validator.EmployeeValidator@3404e5c4]: LeaveRecord [lType=null, startDate=null, endDate=null, numOfDays=0.0, reason=null, lStatus=null, employee=null]
    at org.springframework.validation.DataBinder.assertValidators(DataBinder.java:542) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.validation.DataBinder.addValidators(DataBinder.java:553) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at sg.edu.nus.laps.controller.LeaveController.initBinder(LeaveController.java:38) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_212]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_212]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_212]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_212]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.annotation.InitBinderDataBinderFactory.initBinder(InitBinderDataBinderFactory.java:68) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.bind.support.DefaultDataBinderFactory.createBinder(DefaultDataBinderFactory.java:60) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.annotation.ModelFactory.updateBindingResult(ModelFactory.java:214) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.method.annotation.ModelFactory.updateModel(ModelFactory.java:200) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.getModelAndView(RequestMappingHandlerAdapter.java:1001) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:897) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) ~[tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_212]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_212]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.17.jar:9.0.17]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_212]

It seems like the EmployeeValidator is targeting the LeaveRecord entity that I am passing to the html view, thus causing the exception.

Is there a way to prevent this, or am I doing it correctly?


问:
Calling Ansible adhoc commands/playbooks in python script
How to run Ansible playbooks and commands from python script

Is this suggesgted way?
https://docs.ansible.com/ansible/latest/dev_guide/developing_api.html#python-api-example

Called ansible playbook/adhoc commands runs smoothly inside python script

答:
Ansible doesn't recommend using that method. Quoting directly from the link you shared:

This API is intended for internal Ansible use. Ansible may make
  changes to this API at any time that could break backward
  compatibility with older versions of the API. Because of this,
  external use is not supported by Ansible.

Another option would be to use the subprocess library to call your command using the command line syntax (as opposed to the API).