问:
React Redux - dispatch action with react hooks
To clearify I'm pretty newbie with the concept of react-redux. I try to dispatch an async action in the presentational comp. but this does not seem to work out.

Container Component

```<code>const store = configureStore();

const Root: React.FC = () => (
    <Provider store={store}>
        <App />
    </Provider>
);

render(<Root/>, document.getElementById('root'));
</code>```

Presentational Component

```<code>interface AppProps {
    system: SystemState,
    updateSession: typeof updateSession,
    getLanguageThunk: any
}

const App: React.FC<AppProps> = ({system, updateSession, getLanguageThunk}) => {
    useEffect(() => {
        getLanguageThunk().then((res: any) => {
            console.log(res);
            i18n.init().then(
                () => i18n.changeLanguage(res.language));
       });
    }, []
);

    return (
            <div>
                <div className="app">
                    <TabBar/>
                </div>
            </div>
    );
};

const mapStateToProps = (state: AppState) => ({
    system: state.system
});

export default connect(mapStateToProps, { updateSession, getLanguageThunk })(App);
</code>```

But the console everytime logs undefined. So I am doint something wrong here. Maybe some of u can help me out on here.

Redux middleware

```<code>export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
    const language = await getLanguage();
    dispatch(
        updateSession({
            disableSwipe: false,
            language
        })
    )
};

async function getLanguage() {
    try {
        const response = await fetch('http://localhost:3000/language');
        return response.json();
    } catch {
        return { language: 'en_GB' }
    }
}
</code>```

答:
You need to return the language from getLanguageThunk, to be able to use it from promise in the useEffect method

```<code>export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
    const language = await getLanguage();
    dispatch(
        updateSession({
            disableSwipe: false,
            language
        })
    )
    return language;
};
</code>```

Body:
To clearify I'm pretty newbie with the concept of react-redux. I try to dispatch an async action in the presentational comp. but this does not seem to work out.

Container Component

const store = configureStore();

const Root: React.FC = () => (
    <Provider store={store}>
        <App />
    </Provider>
);

render(<Root/>, document.getElementById('root'));

Presentational Component

interface AppProps {
    system: SystemState,
    updateSession: typeof updateSession,
    getLanguageThunk: any
}

const App: React.FC<AppProps> = ({system, updateSession, getLanguageThunk}) => {
    useEffect(() => {
        getLanguageThunk().then((res: any) => {
            console.log(res);
            i18n.init().then(
                () => i18n.changeLanguage(res.language));
       });
    }, []
);

    return (

                    <TabBar/>

    );
};

const mapStateToProps = (state: AppState) => ({
    system: state.system
});

export default connect(mapStateToProps, { updateSession, getLanguageThunk })(App);

But the console everytime logs undefined. So I am doint something wrong here. Maybe some of u can help me out on here.

Redux middleware

export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
    const language = await getLanguage();
    dispatch(
        updateSession({
            disableSwipe: false,
            language
        })
    )
};

async function getLanguage() {
    try {
        const response = await fetch('http://localhost:3000/language');
        return response.json();
    } catch {
        return { language: 'en_GB' }
    }
}

Body:
You need to return the language from getLanguageThunk, to be able to use it from promise in the useEffect method

export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
    const language = await getLanguage();
    dispatch(
        updateSession({
            disableSwipe: false,
            language
        })
    )
    return language;
};


来源: stackexchange

问:
Google VR GvrReticlePointer not working properly
I'm making a VR Menu for my app in unity (5.4), using Google VR (1.30)

So there's the camera in the middle of the scene (MainCamera with "MainCamera" tag and GvrReticlePointer prefab as child)
And then i have another object GvrViewerMain prefab.

In the EventSystem object I have the usual EventSystem script, GvrPointerInputModule (active) and StandaloneInputModule (for the screen UI when I use it, deactivated for the moment).

So when i create the objects to interact to, they activate their scripts to handle the pointer events (these objects are Canvas with a RawImage and a Text as children).

So when I move the pointer over any of these I don't get any interaction... any of you know what should I do?

The script for pointer events is right bc when I use the STD ModuleInput and hover with the mouse they work

It's just like the GvrReticlePointer is not working or not sending the right events

答: Try Adding GvrPointerPhysicsRaycaster.cs to Player game object.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to chain the result of observable to the below observable in rxjs
I am saving user in the database.

Here are the steps I am following

1) Validating the request.

2) hashing the password.

3) then storing the user details in users collection with the hashed password.

So below I have the code in which I am subscribing to hashPassword method, once I get the hashed string, creating the user with the hashed string. subscribing to save method and assigning the result to the observer's next method.

How can I do this zip() or map() operator instead of subscribing again and again.

createUser(req: Request, res: Response): Observable<mongoose.Document> {
    const body = req.body
    const self = this

    return singleObservable(Observable.create((observer: Observer<mongoose.Document>) => {
        const errorMessage = new UserValidator(req).validateRequest()
        if (errorMessage) {
            observer.error(errorMessage)
        } else {
            self.hashPassword(req.body.password).subscribe(new BaseObserver(
                (value) => {
                    const newUser = new this.userModule({ email: req.body.email, username: req.body.username, password: value })
                    this.save(newUser).subscribe(new BaseObserver((value) => {
                        observer.next(value)
                    }, (err) => {
                        observer.error(err)
                    }))
                }, (error) => observer.error(error)))
        }
    }))
}

private hashPassword(password: string): Observable<string> {
    return singleObservable(Observable.create((observer: Observer<string>) => {
        bcrypt.hash(password, 10, (err, result) => {
            result.length > 0 ? observer.next(result) : observer.error(err)
        })
    }))
}

save<T extends mongoose.Document>(model: mongoose.Document): Observable<T> {
    return singleObservable(Observable.create(function (observer: Observer<mongoose.Document>) {
        model.save(function (err, object) {
            emitResult(observer, object, err)
        })
    }))
}

emitResult<T, E>(observer: Observer<T>, result: T | null, err: E) {
    result ? observer.next(result) : observer.error(err);
}

singleObservable<T>(observable: Observable<T>) : Observable<T> {
    return observable.pipe(first())
}

```

答:
I solved my issue using flatMap operator

createUser(req: Request, res: Response): Observable<mongoose.Document> {
    const body = req.body
    const self = this

    const errorMessage = new UserValidator(req).validateRequest()
    if (errorMessage) {
        return throwError(errorMessage)
    } else {
        return self.hashPassword(req.body.password)
        .pipe(flatMap((hashedString) => {
            const newUser = new this.userModule({ email: req.body.email, username: req.body.username, password: hashedString })
            return this.save(newUser)
        }), catchError((err) => throwError(err))
    }
}
```


问:
Unable to install hummus npm module
I was trying to install hummus npm module. But it is giving me a list of errors. Can someone tell me what causes this issue if I have installed before? I am using Windows 7.</p>

```<code>> C:\Users\hmudunuri\Desktop\encryptionapp>npm install hummus
> C:\Users\hmudunuri\Desktop\encryptionapp\node_modules\hummus>
> node-pre-gyp install --fallback-to-build node-pre-gyp ERR! stack
> Error: Failed to execute 'C:\Program   Files\nodejs\node.e
>     xe  C:\Users\hmudunuri\Desktop\encryptionapp\node_modules\npm\node_modules\node-g
>     yp\bin\node-gyp.js configure --fallback-to-build -- module=C:\Users\hmudunuri\Des
>     ktop\encryptionapp\node_modules\hummus\binding\hummus.node -- module_name=hummus
>     -- module_path=C:\Users\hmudunuri\Desktop\encryptionapp\node_modules\hummus\bindi
>     ng' (1)
>     node-pre-gyp ERR! stack     at ChildProcess.<anonymous>  (C:\Users\hmudunuri\Desk
>     top\encryptionapp\node_modules\hummus\node_modules\node-pre- gyp\lib\util\compile    .js:83:29)
>     node-pre-gyp ERR! stack     at emitTwo (events.js:87:13)
>     node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
>     node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:829:16)
>     node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit  (internal/chi
>     ld_process.js:211:5)
>     node-pre-gyp ERR! System Windows_NT 6.1.7601
>     node-pre-gyp ERR! command "C:\\Program Files\\nodejs\\node.exe"   "C:\\Users\\hmud
>     unuri\\Desktop\\encryptionapp\\node_modules\\hummus\\node_modules\\node-pre-
> gyp\    \bin\\node-pre-gyp" "install" "--fallback-to-build"
>     node-pre-gyp ERR! cwd  C:\Users\hmudunuri\Desktop\encryptionapp\node_modules\hummus
>     node-pre-gyp ERR! node -v v4.5.0
>     node-pre-gyp ERR! node-pre-gyp -v v0.6.29
>     node-pre-gyp ERR! not ok
>     Failed to execute 'C:\Program Files\nodejs\node.exe   C:\Users\hmudunuri\Desktop\e
>     ncryptionapp\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js
> configure --
>     fallback-to-build --  module=C:\Users\hmudunuri\Desktop\encryptionapp\node_modules
>     \hummus\binding\hummus.node --module_name=hummus --   module_path=C:\Users\hmudunur
>     i\Desktop\encryptionapp\node_modules\hummus\binding' (1)
>     npm ERR! Windows_NT 6.1.7601
>     npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program   Files\\nodejs\\
>     node_modules\\npm\\bin\\npm-cli.js" "install" "hummus"
>     npm ERR! node v4.5.0
>     npm ERR! npm  v2.15.9
>     npm ERR! code ELIFECYCLE
>     npm ERR! hummus@1.0.60 install: node-pre-gyp install --fallback-to-build
>     npm ERR! Exit status 1 npm ERR!
>     npm ERR! Failed at the hummus@1.0.60 install script  node-pre-gyp install -- fall
>     back-to-build npm ERR! This is most likely a problem with the hummus package,
>     npm ERR! not with npm itself.
>     npm ERR! Tell the author that this fails on your system:
>     npm ERR!     node-pre-gyp install --fallback-to-build
>     npm ERR! You can get information on how to open an issue for this project  with:
>     npm ERR!     npm bugs hummus
>     npm ERR! Or if that isn't available, you can get their info via:
>     npm ERR!
>     npm ERR!     npm owner ls hummus
>     npm ERR! There is likely additional logging output above.
>     npm ERR! Please include the following file with any support request:
>     npm ERR! C:\Users\hmudunuri\Desktop\encryptionapp\npm'
</code>```

答:
Remove and reinstall hummus.
remove with

```<code>npm remove hummus
</code>```

and install with

```<code>npm install hummus
</code>```

Title: Unable to install hummus npm module

Body:
I was trying to install hummus npm module. But it is giving me a list of errors. Can someone tell me what causes this issue if I have installed before? I am using Windows 7.

> C:\Users\hmudunuri\Desktop\encryptionapp>npm install hummus
> C:\Users\hmudunuri\Desktop\encryptionapp\node_modules\hummus>
> node-pre-gyp install --fallback-to-build node-pre-gyp ERR! stack
> Error: Failed to execute 'C:\Program   Files\nodejs\node.e
>     xe  C:\Users\hmudunuri\Desktop\encryptionapp\node_modules\npm\node_modules\node-g
>     yp\bin\node-gyp.js configure --fallback-to-build -- module=C:\Users\hmudunuri\Des
>     ktop\encryptionapp\node_modules\hummus\binding\hummus.node -- module_name=hummus
>     -- module_path=C:\Users\hmudunuri\Desktop\encryptionapp\node_modules\hummus\bindi
>     ng' (1)
>     node-pre-gyp ERR! stack     at ChildProcess.<anonymous>  (C:\Users\hmudunuri\Desk
>     top\encryptionapp\node_modules\hummus\node_modules\node-pre- gyp\lib\util\compile    .js:83:29)
>     node-pre-gyp ERR! stack     at emitTwo (events.js:87:13)
>     node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
>     node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:829:16)
>     node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit  (internal/chi
>     ld_process.js:211:5)
>     node-pre-gyp ERR! System Windows_NT 6.1.7601
>     node-pre-gyp ERR! command "C:\\Program Files\\nodejs\\node.exe"   "C:\\Users\\hmud
>     unuri\\Desktop\\encryptionapp\\node_modules\\hummus\\node_modules\\node-pre-
> gyp\    \bin\\node-pre-gyp" "install" "--fallback-to-build"
>     node-pre-gyp ERR! cwd  C:\Users\hmudunuri\Desktop\encryptionapp\node_modules\hummus
>     node-pre-gyp ERR! node -v v4.5.0
>     node-pre-gyp ERR! node-pre-gyp -v v0.6.29
>     node-pre-gyp ERR! not ok
>     Failed to execute 'C:\Program Files\nodejs\node.exe   C:\Users\hmudunuri\Desktop\e
>     ncryptionapp\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js
> configure --
>     fallback-to-build --  module=C:\Users\hmudunuri\Desktop\encryptionapp\node_modules
>     \hummus\binding\hummus.node --module_name=hummus --   module_path=C:\Users\hmudunur
>     i\Desktop\encryptionapp\node_modules\hummus\binding' (1)
>     npm ERR! Windows_NT 6.1.7601
>     npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program   Files\\nodejs\\
>     node_modules\\npm\\bin\\npm-cli.js" "install" "hummus"
>     npm ERR! node v4.5.0
>     npm ERR! npm  v2.15.9
>     npm ERR! code ELIFECYCLE
>     npm ERR! hummus@1.0.60 install: node-pre-gyp install --fallback-to-build
>     npm ERR! Exit status 1 npm ERR!
>     npm ERR! Failed at the hummus@1.0.60 install script  node-pre-gyp install -- fall
>     back-to-build npm ERR! This is most likely a problem with the hummus package,
>     npm ERR! not with npm itself.
>     npm ERR! Tell the author that this fails on your system:
>     npm ERR!     node-pre-gyp install --fallback-to-build
>     npm ERR! You can get information on how to open an issue for this project  with:
>     npm ERR!     npm bugs hummus
>     npm ERR! Or if that isn't available, you can get their info via:
>     npm ERR!
>     npm ERR!     npm owner ls hummus
>     npm ERR! There is likely additional logging output above.
>     npm ERR! Please include the following file with any support request:
>     npm ERR! C:\Users\hmudunuri\Desktop\encryptionapp\npm'

Body:
Remove and reinstall hummus.
remove with

npm remove hummus

and install with

npm install hummus


问:
sendto takes much time
I'm trying communicate client-server without tcp's payload. I'm just using tcp's header as payload field which is 20 byte in default. I just realized cpu usage is very high for transfer big files I tried put some timer to every part of code. (I used rdtsc for it.) Result is I build packet's everything in 1000~ tick (I don't touch ipv4 checksum since kernel calculates it automatically); then I looked sendto time, it takes 100000~ tick (100x more than to build the packet). Is there any faster way to send raw tcp packet without sendto or a way to make sendto faster?

I measure sendto time like this:

```<code>timefirst = rdtsc()
sendto()
timesecond = rdtsc()
print timesecond - timefirst
</code>```

I create my send socket with:

```<code>int mysocket = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);
int one = 1;
const int *val = &one;
setsockopt(mysocket, IPPROTO_IP, IP_HDRINCL, val, sizeof(one));
</code>```

Note: I'm talking about packet's time only on my side (sender program and kernel). It's not about about how slow it goes through wire, isp and routers.

答:
Well, to send an IP packet to another place, there's a need to route it and get the MAC address of the target destination, which can involve (not always) an ARP roundtrip to get the MAC address of the router/destination host to compose the ethernet header.

You have not included the amount of delay (well you did, but you didn't specify the duration of a tick) or the wire traffic output seen in the wire to be able to determine these timings...  How do you determine the destination address, is there also a DNS lookup to get the IP address?  That should imply another network roundtrip (the first time) to get the IP address of the destination host.

In other plane, what are you actually measuring? the time it takes to sendto(2) to execute? the time the packet takes to be visible on the wire? the time it takes to reach the destination?  If so, are the source and target machines synchronized? how are they syncrhonzed in that case?

Why don't you actually show your code as the How to create a Minimal, Complete, and Verifiable example page shows?

Title: sendto takes much time

Body:
I'm trying communicate client-server without tcp's payload. I'm just using tcp's header as payload field which is 20 byte in default. I just realized cpu usage is very high for transfer big files I tried put some timer to every part of code. (I used rdtsc for it.) Result is I build packet's everything in 1000~ tick (I don't touch ipv4 checksum since kernel calculates it automatically); then I looked sendto time, it takes 100000~ tick (100x more than to build the packet). Is there any faster way to send raw tcp packet without sendto or a way to make sendto faster?

I measure sendto time like this:

timefirst = rdtsc()
sendto()
timesecond = rdtsc()
print timesecond - timefirst

I create my send socket with:

int mysocket = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);
int one = 1;
const int *val = &one;
setsockopt(mysocket, IPPROTO_IP, IP_HDRINCL, val, sizeof(one));

Note: I'm talking about packet's time only on my side (sender program and kernel). It's not about about how slow it goes through wire, isp and routers.


问:
Using SFINAE to check function std::to_string exists for a type
I want to create a function template that is specialized for types that may have std::to_string applied to them, another for classes for which I have defined a mylib::to_string, and let any types for which it may not fall through to other implementations or specializations.

Example:

```<code>// I only want this to be found if std::to_string exists for ItemType
template<typename ItemType>
void func(ItemType &i)
{
     std::cout << std::to_string(i);
}

// I only want this to be found if mylib::to_string exists for ItemType
template<typename ItemType>
void func(ItemType &i)
{
     std::cout << mylib::to_string(i);
}

// And finally, I'd like to be able to fall through to anything that has a << defined for streams
template<>
void func<MyClass>(MyClass &i)
{
     std::cout << MySpecialConverterFunc(i);
}
</code>```

I always have problems with std::enable_if syntax. How would you add it to the first template?

答:
Avoid SFINAE and write simple code using the ADL rule

You can avoid having to use SFINAE by taking advantage of ADL (Argument Dependent Lookup). What ADL states is that:

If a function and a type are both declared in the same namespace, you don't have to specify the namespace when invoking that function.

For example:

```<code>namespace foo
{
    class MyClass {};
    std::string to_string(MyClass const& x) {
        return "[Element of MyClass]";
    }
}

int main() {
    foo::MyClass x;

    std::cout << to_string(x); // This is legal because x is in namespace foo
}
</code>```

If you write to_string functions in your namespace for your types, then you can write func once in terms of that:

```<code>template<class T>
void func(T const& t) {
    using std::to_string;
    // This calls std::to_string if std::to_string is defined;
    // Otherwise it uses ADL to find the correct to_string function
    std::cout << to_string(t);
}
</code>```

In this example, func can be called with foo::MyClass because there's a to_string function that accepts MyClass in namespace foo:

```<code>int main() {
    func(10); // Prints 10;
    func(3.1415); // Prints 3.1415

    foo::MyClass x;
    func(x); // Prints [Element of MyClass]
}
</code>```

What about types in namespaces I don't own?

In this case, I'd recommend creating an additional namespace and sticking the to_string functions there, and then adding that as a using statement:

```<code>namespace textConvert {
    // Because we use std::to_string here, it automatically gets included
    // When we use textConvert::to_string
    using std::to_string;

    // Convert a vector
    template<class T>
    std::string to_string(std::vector<T> const& vect) {
        using std::to_string;

        std::string str = "[";
        for(auto& elem : vect) {
            str += to_string(elem);
            str += ',';
        }
        str.back() = ']';
        return str;
    }
}
</code>```

Then, we can update func to include textConvert::to_string, and because textConvert uses std::to_string in addition to the various custom conversion functions, both get included!

```<code>template<class T>
void func(T const& t) {
    // This *also* automatically includes std::to_string
    // Because we put using std::to_string inside textConvert
    using textConvert::to_string;

    std::cout << to_string(t);
}
</code>```

Body:
I want to create a function template that is specialized for types that may have std::to_string applied to them, another for classes for which I have defined a mylib::to_string, and let any types for which it may not fall through to other implementations or specializations.

Example:

// I only want this to be found if std::to_string exists for ItemType
template<typename ItemType>
void func(ItemType &i)
{
     std::cout << std::to_string(i);
}

// I only want this to be found if mylib::to_string exists for ItemType
template<typename ItemType>
void func(ItemType &i)
{
     std::cout << mylib::to_string(i);
}

// And finally, I'd like to be able to fall through to anything that has a << defined for streams
template<>
void func<MyClass>(MyClass &i)
{
     std::cout << MySpecialConverterFunc(i);
}

I always have problems with std::enable_if syntax. How would you add it to the first template?

Body:
Avoid SFINAE and write simple code using the ADL rule

You can avoid having to use SFINAE by taking advantage of ADL (Argument Dependent Lookup). What ADL states is that:

If a function and a type are both declared in the same namespace, you don't have to specify the namespace when invoking that function.

For example:

namespace foo
{
    class MyClass {};
    std::string to_string(MyClass const& x) {
        return "[Element of MyClass]";
    }
}

int main() {
    foo::MyClass x;

    std::cout << to_string(x); // This is legal because x is in namespace foo
}

If you write to_string functions in your namespace for your types, then you can write func once in terms of that:

template<class T>
void func(T const& t) {
    using std::to_string;
    // This calls std::to_string if std::to_string is defined;
    // Otherwise it uses ADL to find the correct to_string function
    std::cout << to_string(t);
}

In this example, func can be called with foo::MyClass because there's a to_string function that accepts MyClass in namespace foo:

int main() {
    func(10); // Prints 10;
    func(3.1415); // Prints 3.1415

    foo::MyClass x;
    func(x); // Prints [Element of MyClass]
}

What about types in namespaces I don't own?

In this case, I'd recommend creating an additional namespace and sticking the to_string functions there, and then adding that as a using statement:

namespace textConvert {
    // Because we use std::to_string here, it automatically gets included
    // When we use textConvert::to_string
    using std::to_string;

    // Convert a vector
    template<class T>
    std::string to_string(std::vector<T> const& vect) {
        using std::to_string;

        std::string str = "[";
        for(auto& elem : vect) {
            str += to_string(elem);
            str += ',';
        }
        str.back() = ']';
        return str;
    }
}

Then, we can update func to include textConvert::to_string, and because textConvert uses std::to_string in addition to the various custom conversion functions, both get included!

template<class T>
void func(T const& t) {
    // This *also* automatically includes std::to_string
    // Because we put using std::to_string inside textConvert
    using textConvert::to_string;

    std::cout << to_string(t);
}


问:
SpringBootTest failing with 'IllegalStateException - No ServletContext set'
I have a pretty simple @SpringBootTest :

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {...})
public class MyApplicationTest {

    @Test
    public void anyTest() { ... }
}
</code>```

It was working as expected until we've added @EnableSchedulerLock (from Shedlock) on the MyApplication.java  file.

Since, we're experiencing this issue :

```<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
    ... 46 common frames omitted
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:483)
</code>```

This happends when Spring tries to instanciate its resourceHandlerMapping :

```<code>@Bean
public HandlerMapping resourceHandlerMapping() {
    Assert.state(this.applicationContext != null, "No ApplicationContext set");
    Assert.state(this.servletContext != null, "No ServletContext set");
    ...
</code>```

It's like this @Bean is created before the setServletContext (from WebMvcConfigurationSupport) is called.

答:
As mentioned by Lukas, this error has been fixed in the latest version of Shedlock.

Upgrading Shedlock's version from 2.2.0 to 2.5.0 fixes the issue.

Body:
I have a pretty simple @SpringBootTest :

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {...})
public class MyApplicationTest {

    @Test
    public void anyTest() { ... }
}

It was working as expected until we've added @EnableSchedulerLock (from Shedlock) on the MyApplication.java  file.

Since, we're experiencing this issue :

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
    ... 46 common frames omitted
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:483)

This happends when Spring tries to instanciate its resourceHandlerMapping :

@Bean
public HandlerMapping resourceHandlerMapping() {
    Assert.state(this.applicationContext != null, "No ApplicationContext set");
    Assert.state(this.servletContext != null, "No ServletContext set");
    ...

It's like this @Bean is created before the setServletContext (from WebMvcConfigurationSupport) is called.


问:
How to get values from SVG file using QT
I am in need of a way to get the values inside the svg file in QT using the XMLStreamReader.. How do I do that?

Here's the values inside an SVG file.

And here's what I've tried yet. I'm trying to printout the values if I'm getting something. I'm new to QT by the way.

```<code>xmlFile = new QFile("composition.svg");

if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text))
                qDebug() << ("Load XML File Problem");

xmlReader = new QXmlStreamReader(xmlFile);

//Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
        // Read next element
        QXmlStreamReader::TokenType token = xmlReader->readNext();
        //If token is just StartDocument - go to next
        if(token == QXmlStreamReader::StartDocument) {
                continue;
        }
        //If token is StartElement - read it
        if(token == QXmlStreamReader::StartElement) {

                if(xmlReader->name() == "g") {
                        continue;
                }

                if(xmlReader->name() == "g") {
                    qDebug() << xmlReader->readElementText();
                    //fprintf(stderr, xmlReader->readElementText().toLatin1());
                }
        }
}
</code>```

答:
```<code>while(!xmlReader->atEnd() && !xmlReader->hasError()) {
        // Read next element
        QXmlStreamReader::TokenType token = xmlReader->readNext();
        //If token is just StartDocument - go to next
        if(token == QXmlStreamReader::StartDocument)
                continue;
        //If token is StartElement - read it
        if(token == QXmlStreamReader::StartElement)
        {
            if(xmlReader->name() == "g")
                   continue;
            if(xmlReader->name() == "polygon")
            {
                foreach(const QXmlStreamAttribute &attr, xmlReader->attributes())
                {
                    if (attr.name().toString() == QLatin1String("style"))
                    {
                        qDebug() << attr.value().toLatin1();
                    }
                }
            }
        }
}
</code>```

I needed to loop on the attributes/nodes to get some of its values.

Body:
I am in need of a way to get the values inside the svg file in QT using the XMLStreamReader.. How do I do that?

Here's the values inside an SVG file.

And here's what I've tried yet. I'm trying to printout the values if I'm getting something. I'm new to QT by the way.

xmlFile = new QFile("composition.svg");

if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text))
                qDebug() << ("Load XML File Problem");

xmlReader = new QXmlStreamReader(xmlFile);

//Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
        // Read next element
        QXmlStreamReader::TokenType token = xmlReader->readNext();
        //If token is just StartDocument - go to next
        if(token == QXmlStreamReader::StartDocument) {
                continue;
        }
        //If token is StartElement - read it
        if(token == QXmlStreamReader::StartElement) {

                if(xmlReader->name() == "g") {
                        continue;
                }

                if(xmlReader->name() == "g") {
                    qDebug() << xmlReader->readElementText();
                    //fprintf(stderr, xmlReader->readElementText().toLatin1());
                }
        }
}

Body:
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
        // Read next element
        QXmlStreamReader::TokenType token = xmlReader->readNext();
        //If token is just StartDocument - go to next
        if(token == QXmlStreamReader::StartDocument)
                continue;
        //If token is StartElement - read it
        if(token == QXmlStreamReader::StartElement)
        {
            if(xmlReader->name() == "g")
                   continue;
            if(xmlReader->name() == "polygon")
            {
                foreach(const QXmlStreamAttribute &attr, xmlReader->attributes())
                {
                    if (attr.name().toString() == QLatin1String("style"))
                    {
                        qDebug() << attr.value().toLatin1();
                    }
                }
            }
        }
}

I needed to loop on the attributes/nodes to get some of its values.


问:
Joining most recent record based on the date in another record
I have two tables - let's call them week and contract, like so:

```<code>Week                                    Contract
emp_id | starting   | data1 |  ...   emp_id | from_date  | data2 | ...
-------|------------|-------|--      -------|------------|-------|--
12     | 2019-01-08 | abcd  |        12     | 2018-08-01 | efgh  |
12     | 2019-01-15 | abcd  |        13     | 2018-10-02 | efgh  |
12     | 2019-01-22 | abcd  |        13     | 2019-01-15 | ijkl  |
13     | 2019-01-08 | abcd  |        13     | 2019-03-19 | mnop  |
13     | 2019-01-15 | abcd  |        14     | 2017-02-02 | efgh  |
13     | 2019-01-22 | abcd  |        15     | 2018-01-19 | efgh  |
</code>```

The week.starting field is a date (datetime with time set to midnight) that's at fairly regular intervals. The specific combination of (emp_id, starting) is unique. The from_date field is also a date that records the starting period where the contract record applies. This can be in the future, so we can't just do a MAX(from) and get the right contract for each employee. Currently, (emp_id, from_date) is unique, but I don't want to rely on this. week.starting and contract.from_date can be identical.

I want a query that returns the entire week record, and for each, the record for whatever contract was active at the time - that is, the record where from_date is largest while still less than or equal to week.starting. Getting this contract if I have a specific week in mind is a pretty straightforward greatest n-per-group problem:

```<code>SELECT * FROM contract
WHERE contract.emp_id = @emp_id AND contract.from_date <= @starting
ORDER BY contract.from_date DESC
LIMIT 1
</code>```

But I can't work out how to do this as part of a query to get every record in week. My specific combination of obstacles means I haven't been able to find an answer, despite this being a common set of problems. I don't appear to be able to pass week.starting into a subquery, and I don't appear to be able to use LIMIT in a join either. My best attempt so far ended up joining all contracts that were less than a given week.

What query will return the result I'm looking for?

```<code>emp_id | starting   | from_date  | data1 | data2 | ...
-------|------------|------------|-------|-------|--
12     | 2019-01-08 | 2018-08-01 | abcd  | efgh  |
12     | 2019-01-15 | 2018-08-01 | abcd  | efgh  |
12     | 2019-01-22 | 2018-08-01 | abcd  | efgh  |
13     | 2019-01-08 | 2018-10-02 | abcd  | efgh  |
13     | 2019-01-15 | 2019-01-15 | abcd  | ijkl  |
13     | 2019-01-22 | 2019-01-15 | abcd  | ijkl  |
</code>```

答:
You should be able to use a window function to order the contracts in time after filtering future contracts and assign a rank. Then you can pick the latest with the top rank.

Have not tested this but should look something like:

```<code>select * from (
    select w.*, c.from_date, c.data2,
        row_number() over (partition by c.emp_id, w.starting order by c.from_date desc) as latest
    from week w
    join contract c on c.emp_id = w.emp_id and c.from_date <= w.starting
) as sub where latest = 1
</code>```

Body:
I have two tables - let's call them week and contract, like so:

Week                                    Contract
emp_id | starting   | data1 |  ...   emp_id | from_date  | data2 | ...
-------|------------|-------|--      -------|------------|-------|--
12     | 2019-01-08 | abcd  |        12     | 2018-08-01 | efgh  |
12     | 2019-01-15 | abcd  |        13     | 2018-10-02 | efgh  |
12     | 2019-01-22 | abcd  |        13     | 2019-01-15 | ijkl  |
13     | 2019-01-08 | abcd  |        13     | 2019-03-19 | mnop  |
13     | 2019-01-15 | abcd  |        14     | 2017-02-02 | efgh  |
13     | 2019-01-22 | abcd  |        15     | 2018-01-19 | efgh  |

The week.starting field is a date (datetime with time set to midnight) that's at fairly regular intervals. The specific combination of (emp_id, starting) is unique. The from_date field is also a date that records the starting period where the contract record applies. This can be in the future, so we can't just do a MAX(from) and get the right contract for each employee. Currently, (emp_id, from_date) is unique, but I don't want to rely on this. week.starting and contract.from_date can be identical.

I want a query that returns the entire week record, and for each, the record for whatever contract was active at the time - that is, the record where from_date is largest while still less than or equal to week.starting. Getting this contract if I have a specific week in mind is a pretty straightforward greatest n-per-group problem:

SELECT * FROM contract
WHERE contract.emp_id = @emp_id AND contract.from_date <= @starting
ORDER BY contract.from_date DESC
LIMIT 1

But I can't work out how to do this as part of a query to get every record in week. My specific combination of obstacles means I haven't been able to find an answer, despite this being a common set of problems. I don't appear to be able to pass week.starting into a subquery, and I don't appear to be able to use LIMIT in a join either. My best attempt so far ended up joining all contracts that were less than a given week.

What query will return the result I'm looking for?

emp_id | starting   | from_date  | data1 | data2 | ...
-------|------------|------------|-------|-------|--
12     | 2019-01-08 | 2018-08-01 | abcd  | efgh  |
12     | 2019-01-15 | 2018-08-01 | abcd  | efgh  |
12     | 2019-01-22 | 2018-08-01 | abcd  | efgh  |
13     | 2019-01-08 | 2018-10-02 | abcd  | efgh  |
13     | 2019-01-15 | 2019-01-15 | abcd  | ijkl  |
13     | 2019-01-22 | 2019-01-15 | abcd  | ijkl  |

Body:
You should be able to use a window function to order the contracts in time after filtering future contracts and assign a rank. Then you can pick the latest with the top rank.

Have not tested this but should look something like:

select * from (
    select w.*, c.from_date, c.data2,
        row_number() over (partition by c.emp_id, w.starting order by c.from_date desc) as latest
    from week w
    join contract c on c.emp_id = w.emp_id and c.from_date <= w.starting
) as sub where latest = 1


问:
Windowed/ sliding mean filter accounting for valid members at boundary
Is there a similar function to scipy.ndimage's uniform_filter or convolve (similar problem with Numpy Two-Dimensional Moving Average), but the average is calculated using only the values in the input array (disregard count of fill values for corner and edge cells). A similar function wherein the fill value can be set to np.nan and the resulting average is calculated as np.nanmean?

My initial code loops over the array to get the neighbors and calculate the resulting mean, but this method takes too long. I have tried both uniform_filter or convolve, but the results are not what I needed since the resulting corner and edge values are too low (due to filling the edges with 0).

For example, if I have the array:

a = np.ones((4,5))
```

<p>Calculating the mean value from a moving 3x3 array should also result to:</p>

<pre class="lang-py prettyprint-override"><code>array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])
</code>```

uniform_filter gives:

uniform_filter(a, size=3, mode='constant', cval=0.0)

array([[0.44444444, 0.66666667, 0.66666667, 0.66666667, 0.44444444],
       [0.66666667, 1.        , 1.        , 1.        , 0.66666667],
       [0.66666667, 1.        , 1.        , 1.        , 0.66666667],
       [0.44444444, 0.66666667, 0.66666667, 0.66666667, 0.44444444]])
```

<p>I have tried setting cval=np.nan but the resulting values of the cell edges are nan.</p>

<p>For another array, b</p>

<pre class="lang-py prettyprint-override"><code>array([[1., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
</code>```

I want to obtain an array, using a 3x3 averaging-window, as

array([[0.25      , 0.16666667, 0.        ],
       [0.16666667, 0.11111111, 0.        ],
       [0.        , 0.        , 0.        ]])
```

The values are calculated as shown in this
illustration

答:
Get the windowed summations and divide by the valid members in each window. We can use scipy.signal.convolve2d to get both and hence have a solution like so -

```<code>from scipy.signal import convolve2d

def windowed_average(a, kernel_size, mode='same'):
    k = np.ones((kernel_size,kernel_size),dtype=int)
    window_sum = convolve2d(a,k,mode)
    window_count = convolve2d(np.ones(a.shape, dtype=bool),k,mode)
    return window_sum/window_count
</code>```

Alternative #1

Alternatively, if you want to make use of uniform_filter to get the windowed summations, we can do so and that might be more efficient as well, like so -

```<code>from scipy.ndimage import uniform_filter

n = kernel_size**2
window_sum = uniform_filter(a, kernel_size, mode='constant', cval=0.0)*n
</code>```

Sample runs -

```<code>In [54]: a
Out[54]:
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

In [55]: windowed_average(a, kernel_size=3)
Out[55]:
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

In [56]: b
Out[56]:
array([[1., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])

In [57]: windowed_average(b, kernel_size=3)
Out[57]:
array([[0.25      , 0.16666667, 0.        ],
       [0.16666667, 0.11111111, 0.        ],
       [0.        , 0.        , 0.        ]])
</code>```

Body:
Is there a similar function to scipy.ndimage's uniform_filter or convolve (similar problem with Numpy Two-Dimensional Moving Average), but the average is calculated using only the values in the input array (disregard count of fill values for corner and edge cells). A similar function wherein the fill value can be set to np.nan and the resulting average is calculated as np.nanmean?

My initial code loops over the array to get the neighbors and calculate the resulting mean, but this method takes too long. I have tried both uniform_filter or convolve, but the results are not what I needed since the resulting corner and edge values are too low (due to filling the edges with 0).

For example, if I have the array:

a = np.ones((4,5))

Calculating the mean value from a moving 3x3 array should also result to:

array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

uniform_filter gives:

uniform_filter(a, size=3, mode='constant', cval=0.0)

array([[0.44444444, 0.66666667, 0.66666667, 0.66666667, 0.44444444],
       [0.66666667, 1.        , 1.        , 1.        , 0.66666667],
       [0.66666667, 1.        , 1.        , 1.        , 0.66666667],
       [0.44444444, 0.66666667, 0.66666667, 0.66666667, 0.44444444]])

I have tried setting cval=np.nan but the resulting values of the cell edges are nan.

For another array, b

array([[1., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])

I want to obtain an array, using a 3x3 averaging-window, as

array([[0.25      , 0.16666667, 0.        ],
       [0.16666667, 0.11111111, 0.        ],
       [0.        , 0.        , 0.        ]])

The values are calculated as shown in this
illustration

Body:
Get the windowed summations and divide by the valid members in each window. We can use scipy.signal.convolve2d to get both and hence have a solution like so -

from scipy.signal import convolve2d

def windowed_average(a, kernel_size, mode='same'):
    k = np.ones((kernel_size,kernel_size),dtype=int)
    window_sum = convolve2d(a,k,mode)
    window_count = convolve2d(np.ones(a.shape, dtype=bool),k,mode)
    return window_sum/window_count

Alternative #1

Alternatively, if you want to make use of uniform_filter to get the windowed summations, we can do so and that might be more efficient as well, like so -

from scipy.ndimage import uniform_filter

n = kernel_size**2
window_sum = uniform_filter(a, kernel_size, mode='constant', cval=0.0)*n

Sample runs -

In [54]: a
Out[54]:
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

In [55]: windowed_average(a, kernel_size=3)
Out[55]:
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

In [56]: b
Out[56]:
array([[1., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])

In [57]: windowed_average(b, kernel_size=3)
Out[57]:
array([[0.25      , 0.16666667, 0.        ],
       [0.16666667, 0.11111111, 0.        ],
       [0.        , 0.        , 0.        ]])


问:
How to keep continuous ImageView and hide the other views?
I am working with a designer for the first time.

And he wants me to implement this complex screen transition.

The current Screen doesn't move. But the new screen come from the right side and then it is stacked.

The problem is this. The ImageView which is animation must run in all the screens continuously(no move) and repeat the animation. So, when the new screen comes from the right side. The ImageView must be alive. But the rest are hidden by the new screen.

At first, I thought I need to make MainActivity which has screen star animation with white or transparent background. And then, use half-transparent background color(pink) for the fragments.

However, I checked the video that designer sent me. And I found out that the texts and images, buttons are hidden and just the star keeps moving.

The way I am implementing is totally wrong because you can see everything in the previous screen, not only the star but also the texts and buttons and also the color becomes thicker.

How can I solve this problem?

答:
Well, It's kind of difficult feature to implement.

You can use FrameLayout or just put the view as the most front view with half transparency(maybe around 15% opacity).

Then, it looks like it's behind of all the views.


问:
Why does Xlim and Ylim not work as expected
Why does the xlim and ylim not work as expected? It should show y-lim from 1-4 and xlim from 1-3. This is not the case. Any idea why?

答:
The data you plot seem to be text data. Try converting data into numbers. For example

x = [float(row.split(' ')[0]) for row in data]
y = [float(row.split(' ')[1]) for row in data]
```

You can use int instead of float if input data are integers.

Body:
The data you plot seem to be text data. Try converting data into numbers. For example

x = [float(row.split(' ')[0]) for row in data]
y = [float(row.split(' ')[1]) for row in data]

You can use int instead of float if input data are integers.


问:
laravel 5.8 access other table's property in one to many relation
I have 3 tables

hotel

province

city

the hotel has a relation to the city and the city has a relation to the province.
city id will save in the city field in the hotel table.
how can I access city name and province name in the Hotel model?

in hotel model I wrote this :

```<code>  public function city(){
        return $this->belongsTo(City::class);
    }
</code>```

and in the city model I have this:

```<code>   public function hotel(){
        return $this->hasMany(Hotel::class);
    }

    public function province(){
        return $this->belongsTo(Province::class);
    }
</code>```

and in province

```<code>  public function cities(){
        return $this->hasMany(City::class);
    }
</code>```

答:
```<code>public function provinces()
{
    return $this->hasManyThrough('App\Province', 'App\City');
}
</code>```

In hotel model and you can access province name by using in the controller like

```<code>$hotel = Hotel::find(1);
dd($hotel->provinces);
</code>```

and use that variable in the blade

Body:
I have 3 tables

hotel

province

city

the hotel has a relation to the city and the city has a relation to the province.
city id will save in the city field in the hotel table.
how can I access city name and province name in the Hotel model?

in hotel model I wrote this :

  public function city(){
        return $this->belongsTo(City::class);
    }

and in the city model I have this:

   public function hotel(){
        return $this->hasMany(Hotel::class);
    }

    public function province(){
        return $this->belongsTo(Province::class);
    }

and in province

  public function cities(){
        return $this->hasMany(City::class);
    }

Body:
public function provinces()
{
    return $this->hasManyThrough('App\Province', 'App\City');
}

In hotel model and you can access province name by using in the controller like

$hotel = Hotel::find(1);
dd($hotel->provinces);

and use that variable in the blade


问:
How to create the split 1/2 login screen in vue such that one side contains fields and the other side is image?
https://vuestic.epicmax.co/#/auth/login
I want something which looks as if in above link.</p>

答:
As you're using Vuetify you can use the container, layout and flex columns to create that:

```<code><v-container>
    <v-layout row wrap>
      <!-- xs12 and sm12 to make it responsive = 12 columns on mobile and 6 columns from medium to XL layouts -->
      <v-flex xs12 sm12 md6>
        <!-- Login form here -->
      </v-flex>
      <v-flex xs12 sm12 md6>
        <!-- artwork here -->
      </v-flex>
    </v-layout>
  </v-container>
</code>```

Check more details about how to use the grid system here: https://vuetifyjs.com/en/framework/grid

Body:
As you're using Vuetify you can use the container, layout and flex columns to create that:

<v-container>
    <v-layout row wrap>
      <!-- xs12 and sm12 to make it responsive = 12 columns on mobile and 6 columns from medium to XL layouts -->
      <v-flex xs12 sm12 md6>
        <!-- Login form here -->
      </v-flex>
      <v-flex xs12 sm12 md6>
        <!-- artwork here -->
      </v-flex>
    </v-layout>
  </v-container>

Check more details about how to use the grid system here: https://vuetifyjs.com/en/framework/grid


问:
Remove complete string with special character
In a sentence, I want to remove a complete string which contains special characters.

Input is ["i am in jersey1&2","this code is %bdn2*nn"]

Expected output is ["i am in","this code is"]

```<code>import re

Dsp = ["i am in jersey1&2","this code is %bdn2*nn"]

Dsp1 = []

for i in Dsp:
    Dsp = [re.sub('^\W+$'," ",j) for j in i]
    Dsp1.append("".join(Dsp))
</code>```

I got

```<code>Dsp1 = ["i am in jersey12","this code is bdn2nn"]
</code>```

but the expected output is

```<code>Dsp1 = ["i am in", "this code is"]
</code>```

答:
You're expecting re.sub to match and replace on word level, where words are substrings delimited by whitespace within a string. Regular expressions will match on a character level, unless you manage to tell them otherwise (which is a bit complicated) or you split the strings on whitespace before applying a special-character matching regex:

```<code>Dsp = ["i am in jersey1&2","this code is %bdn2*nn"]
Dsp1 = []

for sentence in Dsp:
  cleaned_sentence = []
  for word in sentence.split(' '):
    if not re.search(r'\W'):
      cleaned_sentence.append(word)
  DSP1.append(' '.join(cleaned_sentence))

print(DSP1)
# ['i am in', 'this code is']
</code>```

Body:
In a sentence, I want to remove a complete string which contains special characters.

Input is ["i am in jersey1&2","this code is %bdn2*nn"]

Expected output is ["i am in","this code is"]

import re

Dsp = ["i am in jersey1&2","this code is %bdn2*nn"]

Dsp1 = []

for i in Dsp:
    Dsp = [re.sub('^\W+$'," ",j) for j in i]
    Dsp1.append("".join(Dsp))

I got

Dsp1 = ["i am in jersey12","this code is bdn2nn"]

but the expected output is

Dsp1 = ["i am in", "this code is"]

Body:
You're expecting re.sub to match and replace on word level, where words are substrings delimited by whitespace within a string. Regular expressions will match on a character level, unless you manage to tell them otherwise (which is a bit complicated) or you split the strings on whitespace before applying a special-character matching regex:

Dsp = ["i am in jersey1&2","this code is %bdn2*nn"]
Dsp1 = []

for sentence in Dsp:
  cleaned_sentence = []
  for word in sentence.split(' '):
    if not re.search(r'\W'):
      cleaned_sentence.append(word)
  DSP1.append(' '.join(cleaned_sentence))

print(DSP1)
# ['i am in', 'this code is']


问:
Grab the first and last element for every sequence
I have a file with 3 types of sequences and their positions that are reoccurring as such:

```<code>seq1 2
seq1 5
seq1 10
seq3 15
seq3 34
seq3 60
seq2 100
seq2 110
seq2 200
seq3 210
seq3 250
seq3 300
seq1 310
seq1 330
seq1 400
</code>```

The second value is always unique denoting a position and is sorted, hence why the sequences are scattered.

For every time a sequence starts, I want to grab the minimum and max of that sequence. Output should be (seq min max)

```<code>seq1 2 10
seq3 15 60
seq2 100 200
seq3 210 300
seq1 310 400
</code>```

Is it possible to do this in bash with awk or anything else?

答:
Another awk</p>

```<code>$ awk ' { if(NR>1 && p!=$1) { print p,min,max; max=min=""} min=min?min:$2; max=$2; p=$1 }
END { print p,min,max } ' adrian.txt
seq1 2 10
seq3 15 60
seq2 100 200
seq3 210 300
seq1 310 400

$
</code>```

Body:
I have a file with 3 types of sequences and their positions that are reoccurring as such:

seq1 2
seq1 5
seq1 10
seq3 15
seq3 34
seq3 60
seq2 100
seq2 110
seq2 200
seq3 210
seq3 250
seq3 300
seq1 310
seq1 330
seq1 400

The second value is always unique denoting a position and is sorted, hence why the sequences are scattered.

For every time a sequence starts, I want to grab the minimum and max of that sequence. Output should be (seq min max)

seq1 2 10
seq3 15 60
seq2 100 200
seq3 210 300
seq1 310 400

Is it possible to do this in bash with awk or anything else?

Body:
Another awk

$ awk ' { if(NR>1 && p!=$1) { print p,min,max; max=min=""} min=min?min:$2; max=$2; p=$1 }
END { print p,min,max } ' adrian.txt
seq1 2 10
seq3 15 60
seq2 100 200
seq3 210 300
seq1 310 400

$


问:
Why is blue circle not spinning in the center of itself
Why is the blue circle not rotating in the center of its own axis?
Below you can find my previous code.

Here you can see my CSS with the proportionate SVG:

circle {
  animation: grow 2s infinite;
  transform-origin: center;
}

@keyframes grow {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.5);
  }
  100% {
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg"
     width="80"
     height="110"
     version="1.1">
     <rect width="70"
           height="100"
           x="5"
           y="5"
           fill="white"
           stroke="red"
           stroke-width="10"
           rx="5"/>
     <circle cx="40" cy="105" r="3" fill="blue"/>
</svg></code>```

答:
You need transform-box: fill-box;

circle {
  animation: grow 2s infinite;
  transform-origin: center;
  transform-box: fill-box;
}
@keyframes grow {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.5);
  }
  100% {
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg
  xmlns="http://www.w3.org/2000/svg"
  width="80"
  height="110"
  version="1.1"
>
  <rect
    width="70"
    height="100"
    x="5"
    y="5"
    fill="white"
    stroke="red"
    stroke-width="10"
    rx="5"
  />
  <circle cx="40" cy="105" r="3" fill="blue" />
</svg></code>```

Body:
Why is the blue circle not rotating in the center of its own axis?
Below you can find my previous code.

Here you can see my CSS with the proportionate SVG:

circle {
  animation: grow 2s infinite;
  transform-origin: center;
}

@keyframes grow {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.5);
  }
  100% {
    transform: scale(1);
  }
}

<svg xmlns="http://www.w3.org/2000/svg"
     width="80"
     height="110"
     version="1.1">
     <rect width="70"
           height="100"
           x="5"
           y="5"
           fill="white"
           stroke="red"
           stroke-width="10"
           rx="5"/>
     <circle cx="40" cy="105" r="3" fill="blue"/>
</svg>

Body:
You need transform-box: fill-box;

circle {
  animation: grow 2s infinite;
  transform-origin: center;
  transform-box: fill-box;
}
@keyframes grow {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.5);
  }
  100% {
    transform: scale(1);
  }
}

<svg
  xmlns="http://www.w3.org/2000/svg"
  width="80"
  height="110"
  version="1.1"
>
  <rect
    width="70"
    height="100"
    x="5"
    y="5"
    fill="white"
    stroke="red"
    stroke-width="10"
    rx="5"
  />
  <circle cx="40" cy="105" r="3" fill="blue" />
</svg>


问:
How to handle the longclick in android
I want to make a layout visible by using long click, and invisible by clicking again, it is not working for me.
please help me with this.
The code is given below.
when I click once the layout is visible when I click again the layout need to be gone, but still it is visible.</p>

```<code>     public class ReminderstestExplaination extends Fragment {

    RecyclerView testexplntion_recycle;
    CustomRecyclerview customRecyclerview;
    LinearLayout reminderpage_addbutton,extraremlay,del_editlay;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.remindertest_explaination,container,false);

        extraremlay = v.findViewById (R.id.extraremlay);

        extraremlay.setOnLongClickListener (new View.OnLongClickListener () {
                                                @Override
                                                public boolean onLongClick(View view) {

                                                    del_editlay.setVisibility (View.VISIBLE);

                                                    return true;

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

答:
Do this , keep track of the visibility using a boolean variable and change it every time long click is done.

```<code>public class ReminderstestExplaination extends Fragment {
boolean isVisible = false;
RecyclerView testexplntion_recycle;
CustomRecyclerview customRecyclerview;
LinearLayout reminderpage_addbutton,extraremlay,del_editlay;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.remindertest_explaination,container,false);

    extraremlay = v.findViewById (R.id.extraremlay);

    extraremlay.setOnLongClickListener (new View.OnLongClickListener () {
                                            @Override
                                            public boolean onLongClick(View view) {

                                               if(isVisible) {
                                                isVisible = false;
                                               del_editlay.setVisibility
                                              (View.INVISIBLE);
                                              }
                                               }
                                               else {
                                             isVisible = true;
                                             del_editlay.setVisibility
                                              (View.VISIBLE);}

                                                return true;

                                            }
                                        });
</code>```

}

Title: How to handle the longclick in android

Body:
I want to make a layout visible by using long click, and invisible by clicking again, it is not working for me.
please help me with this.
The code is given below.
when I click once the layout is visible when I click again the layout need to be gone, but still it is visible.

     public class ReminderstestExplaination extends Fragment {

    RecyclerView testexplntion_recycle;
    CustomRecyclerview customRecyclerview;
    LinearLayout reminderpage_addbutton,extraremlay,del_editlay;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.remindertest_explaination,container,false);

        extraremlay = v.findViewById (R.id.extraremlay);

        extraremlay.setOnLongClickListener (new View.OnLongClickListener () {
                                                @Override
                                                public boolean onLongClick(View view) {

                                                    del_editlay.setVisibility (View.VISIBLE);

                                                    return true;

                                                }
                                            });
}

Body:
Do this , keep track of the visibility using a boolean variable and change it every time long click is done.

public class ReminderstestExplaination extends Fragment {
boolean isVisible = false;
RecyclerView testexplntion_recycle;
CustomRecyclerview customRecyclerview;
LinearLayout reminderpage_addbutton,extraremlay,del_editlay;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.remindertest_explaination,container,false);

    extraremlay = v.findViewById (R.id.extraremlay);

    extraremlay.setOnLongClickListener (new View.OnLongClickListener () {
                                            @Override
                                            public boolean onLongClick(View view) {

                                               if(isVisible) {
                                                isVisible = false;
                                               del_editlay.setVisibility
                                              (View.INVISIBLE);
                                              }
                                               }
                                               else {
                                             isVisible = true;
                                             del_editlay.setVisibility
                                              (View.VISIBLE);}

                                                return true;

                                            }
                                        });

}


问:
How to make slide animation with a fixed screen and new screen?
I made three xml files for the transition.

enter_from_right.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="0%" />
</set>
</code>```

none.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="100%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="0%" />
</set>
</code>```

exit_to_right.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toXDelta="100%"
        android:toYDelta="0%" />
</set>
</code>```

However, It just works fine in Activities not in Fragments.

When I click the back button, the backward transition(pop) works fine. But it doesn't work properly when I call the new fragment. It just blinks when the screen changes.

I tried changing the duration to 50 of none.xml. And I see the new screen comes in from the right side. And also tried with 10000. But it just delays the changing time.

I am using navigation component. And I defined like this:

```<code>        <action
            android:id="@+id/action_initFragment_to_settingFragment"
            app:destination="@id/settingFragment"
            app:enterAnim="@anim/enter_from_right"
            app:exitAnim="@anim/none"
            app:popExitAnim="@anim/exit_to_right"
            app:popEnterAnim="@anim/none"/>
</code>```

What's wrong with it?
I think this is because of Z index. Is there any way to give Z index attribute?

答:
This happened because of the z index. Activities have different depth. However, I guess Fragments have the same depth. So, When A Fragment is switched to B Fragment, They are on the same depth and transition is not shown properly.

The solution is giving Z index to the screen programmatically like below:

```<code>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ViewCompat.setTranslationZ(view, 1F)
    }
</code>```

1F in here, it is the index of depth.

The interesting thing is the higher value creates the bigger shadow. If you give 100F, then it creates huge shadow underneath. And I can't see any shadows visibly when the value is 1F.

Body:
I made three xml files for the transition.

enter_from_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="0%" />
</set>

none.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="100%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="0%" />
</set>

exit_to_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toXDelta="100%"
        android:toYDelta="0%" />
</set>

However, It just works fine in Activities not in Fragments.

When I click the back button, the backward transition(pop) works fine. But it doesn't work properly when I call the new fragment. It just blinks when the screen changes.

I tried changing the duration to 50 of none.xml. And I see the new screen comes in from the right side. And also tried with 10000. But it just delays the changing time.

I am using navigation component. And I defined like this:

        <action
            android:id="@+id/action_initFragment_to_settingFragment"
            app:destination="@id/settingFragment"
            app:enterAnim="@anim/enter_from_right"
            app:exitAnim="@anim/none"
            app:popExitAnim="@anim/exit_to_right"
            app:popEnterAnim="@anim/none"/>

What's wrong with it?
I think this is because of Z index. Is there any way to give Z index attribute?

Body:
This happened because of the z index. Activities have different depth. However, I guess Fragments have the same depth. So, When A Fragment is switched to B Fragment, They are on the same depth and transition is not shown properly.

The solution is giving Z index to the screen programmatically like below:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ViewCompat.setTranslationZ(view, 1F)
    }

1F in here, it is the index of depth.

The interesting thing is the higher value creates the bigger shadow. If you give 100F, then it creates huge shadow underneath. And I can't see any shadows visibly when the value is 1F.


问:
TensorFlow input function for reading sparse data (in libsvm format)

I'm new to TensorFlow and trying to use the Estimator API for some simple classification experiments. I have a sparse dataset in libsvm format. The following input function works for small datasets:

def libsvm_input_function(file):

    def input_function():

        indexes_raw = []
        indicators_raw = []
        values_raw = []
        labels_raw = []
        i=0

        for line in open(file, "r"):
            data = line.split(" ")
            label = int(data[0])
            for fea in data[1:]:
                id, value = fea.split(":")
                indexes_raw.append([i,int(id)])
                indicators_raw.append(int(1))
                values_raw.append(float(value))
            labels_raw.append(label)
            i=i+1

        indexes = tf.SparseTensor(indices=indexes_raw,
                              values=indicators_raw,
                              dense_shape=[i, num_features])

        values = tf.SparseTensor(indices=indexes_raw,
                             values=values_raw,
                             dense_shape=[i, num_features])

        labels = tf.constant(labels_raw, dtype=tf.int32)

        return {"indexes": indexes, "values": values}, labels

    return input_function
```

However, for a dataset of a few GB size I get the following error:

ValueError: Cannot create a tensor proto whose content is larger than 2GB.

How can I avoid this error? How should I write an input function to read medium-sized sparse datasets (in libsvm format)?

答:
I have been using tensorflow.contrib.libsvm. Here's an example (i am using eager execution with generators)

```<code>import os
import tensorflow as tf
import tensorflow.contrib.libsvm as libsvm

def all_libsvm_files(folder_path):
    for file in os.listdir(folder_path):
        if file.endswith(".libsvm"):
            yield os.path.join(folder_path, file)

def load_libsvm_dataset(path_to_folder):
    return tf.data.TextLineDataset(list(all_libsvm_files(path_to_folder)))

def libsvm_iterator(path_to_folder):
    dataset = load_libsvm_dataset(path_to_folder)
    iterator = dataset.make_one_shot_iterator()
    next_element = iterator.get_next()
    yield libsvm.decode_libsvm(tf.reshape(next_element, (1,)),
                               num_features=666,
                               dtype=tf.float32,
                               label_dtype=tf.float32)
</code>```

libsvm_iterator gives you a feature-label pair back on each iteration, from multiple files inside a folder that you specify.

Body:
I'm new to TensorFlow and trying to use the Estimator API for some simple classification experiments. I have a sparse dataset in libsvm format. The following input function works for small datasets:

def libsvm_input_function(file):

    def input_function():

        indexes_raw = []
        indicators_raw = []
        values_raw = []
        labels_raw = []
        i=0

        for line in open(file, "r"):
            data = line.split(" ")
            label = int(data[0])
            for fea in data[1:]:
                id, value = fea.split(":")
                indexes_raw.append([i,int(id)])
                indicators_raw.append(int(1))
                values_raw.append(float(value))
            labels_raw.append(label)
            i=i+1

        indexes = tf.SparseTensor(indices=indexes_raw,
                              values=indicators_raw,
                              dense_shape=[i, num_features])

        values = tf.SparseTensor(indices=indexes_raw,
                             values=values_raw,
                             dense_shape=[i, num_features])

        labels = tf.constant(labels_raw, dtype=tf.int32)

        return {"indexes": indexes, "values": values}, labels

    return input_function

However, for a dataset of a few GB size I get the following error:

ValueError: Cannot create a tensor proto whose content is larger than 2GB.

How can I avoid this error? How should I write an input function to read medium-sized sparse datasets (in libsvm format)?

Body:
I have been using tensorflow.contrib.libsvm. Here's an example (i am using eager execution with generators)

import os
import tensorflow as tf
import tensorflow.contrib.libsvm as libsvm

def all_libsvm_files(folder_path):
    for file in os.listdir(folder_path):
        if file.endswith(".libsvm"):
            yield os.path.join(folder_path, file)

def load_libsvm_dataset(path_to_folder):
    return tf.data.TextLineDataset(list(all_libsvm_files(path_to_folder)))

def libsvm_iterator(path_to_folder):
    dataset = load_libsvm_dataset(path_to_folder)
    iterator = dataset.make_one_shot_iterator()
    next_element = iterator.get_next()
    yield libsvm.decode_libsvm(tf.reshape(next_element, (1,)),
                               num_features=666,
                               dtype=tf.float32,
                               label_dtype=tf.float32)

libsvm_iterator gives you a feature-label pair back on each iteration, from multiple files inside a folder that you specify.


问:
player dies when he touches the floor
I made a game following a YouTube tutorial https://www.youtube.com/playlist?list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6 I am on episode 8 and when I start the game the end game text comes up and I assume it is because the player touches the ground I cannot see any difference between the coding that I have produced and the YouTuber

GAME MANAGER:
    using UnityEngine;

```<code>public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
// Start is called before the first frame update
public void EndGame ()
{
    if (gameHasEnded == false)
    {
        gameHasEnded = true;
        Debug.Log("GAME OVER");

    }

}
}
</code>```

PLAYER COLLISIONS:
    using UnityEngine;

```<code>public class PlayerCollision : MonoBehaviour
{

public PlayerMovement movement;

void OnCollisionEnter (Collision collisionInfo)
{
    if (collisionInfo.collider.tag == "Block")
    {
        movement.enabled = false;
    }   FindObjectOfType<GameManager>().EndGame();
}
}
</code>```

PLAYER MOVEMENT:

```<code>using UnityEngine;

public class PlayerMovement : MonoBehaviour
{   //to substitute rigidbody to rb
public Rigidbody rb;

public float forwardForce = 2000f;

public float sidewaysForce = 500f;

// Update is called once per frame
void FixedUpdate()
{
    //add forward force
    rb.AddForce(0, 0, forwardForce * Time.deltaTime);
    //only exectued if condition is met
    if ( Input.GetKey("d") )
    {
        rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0,
ForceMode.VelocityChange);

    }

    if (Input.GetKey("a"))
    {
        rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0,
ForceMode.VelocityChange);

    }
    if (rb.position.y < -1f)
    {
       FindObjectOfType<GameManager>().EndGame();
    }

}
}
</code>```

答:
The problem is here:

```<code>void OnCollisionEnter (Collision collisionInfo)
{
    if (collisionInfo.collider.tag == "Block")
    {
        movement.enabled = false;
    }   FindObjectOfType<GameManager>().EndGame();// <--- It is outside the if
}
</code>```

Should be like this:

```<code>void OnCollisionEnter (Collision collisionInfo)
{
    if (collisionInfo.collider.tag == "Block")
    {
        movement.enabled = false;
        FindObjectOfType<GameManager>().EndGame();
    }
}
</code>```

It ended the game whenever you collided with something, instead of doing it when it is a block only.

Title: player dies when he touches the floor

Body:
I made a game following a YouTube tutorial https://www.youtube.com/playlist?list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6 I am on episode 8 and when I start the game the end game text comes up and I assume it is because the player touches the ground I cannot see any difference between the coding that I have produced and the YouTuber

GAME MANAGER:
    using UnityEngine;

public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
// Start is called before the first frame update
public void EndGame ()
{
    if (gameHasEnded == false)
    {
        gameHasEnded = true;
        Debug.Log("GAME OVER");

    }

}
}

PLAYER COLLISIONS:
    using UnityEngine;

public class PlayerCollision : MonoBehaviour
{

public PlayerMovement movement;

void OnCollisionEnter (Collision collisionInfo)
{
    if (collisionInfo.collider.tag == "Block")
    {
        movement.enabled = false;
    }   FindObjectOfType<GameManager>().EndGame();
}
}

PLAYER MOVEMENT:

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{   //to substitute rigidbody to rb
public Rigidbody rb;

public float forwardForce = 2000f;

public float sidewaysForce = 500f;

// Update is called once per frame
void FixedUpdate()
{
    //add forward force
    rb.AddForce(0, 0, forwardForce * Time.deltaTime);
    //only exectued if condition is met
    if ( Input.GetKey("d") )
    {
        rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0,
ForceMode.VelocityChange);

    }

    if (Input.GetKey("a"))
    {
        rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0,
ForceMode.VelocityChange);

    }
    if (rb.position.y < -1f)
    {
       FindObjectOfType<GameManager>().EndGame();
    }

}
}

Body:
The problem is here:

void OnCollisionEnter (Collision collisionInfo)
{
    if (collisionInfo.collider.tag == "Block")
    {
        movement.enabled = false;
    }   FindObjectOfType<GameManager>().EndGame();// <--- It is outside the if
}

Should be like this:

void OnCollisionEnter (Collision collisionInfo)
{
    if (collisionInfo.collider.tag == "Block")
    {
        movement.enabled = false;
        FindObjectOfType<GameManager>().EndGame();
    }
}

It ended the game whenever you collided with something, instead of doing it when it is a block only.


问:
Generate PDF when clicking on a link
MY PROBLEM STATEMENT IS,

I have a set of links in a webpage,which was created in javascript.

Now what I want is if anybody clicks the link it should go to that
   corresponding page and a pdf file should generate automatically. In
   Ubuntu OS there is an option to generate PDF of any page, but how would I use it
   to generate automatically, if need with some condition also.

答:
It is server side task to generate PDF or whatever. While javascript is client side technique (in your case).

So you need to use some server side technology. So you should let us know what language do you use: PHP, C#, Ruby, Python etc. So we will suggest some ready out of box library.

Title: Generate PDF when clicking on a link


问:
Array is not storing objects from database
I m retriving data from database and want to store that data in the form of objects in my arraylist that furthermore can be use in display custom tables.

I have tried the solutions from prev related queries but couldn't solve my problem.

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;

public class Appointment {

public int no;
public String patient;
public String doctor;
public String disease;
public String scheduleDay;

public void setNo(int no){
    this.no = no;}

public void setPatient(String patient){
    this.patient = patient;}

public void setDoctor(String doctor){

    this.doctor = doctor;}

public void setDisease(String disease){

    this.disease = disease;}

public void setScheduleDay(String scheduleDay){

    this.scheduleDay = scheduleDay;}

public int getNo(){
    return no;}
public String getPatient(){
    return patient;}
public String getDoctor(){
    return doctor;}
public String getDisease(){
    return disease;}
public String getScheduleDay(){
    return scheduleDay;}

public Appointment(){
    no = 0;
    patient = "not set";
    doctor = "not set";
    disease = "not set";
    scheduleDay = "not set";
}

public Appointment(int no, String patient, String doctor, String
disease, String scheduleDay){
    setNo(no);
    setPatient(patient);
    setDoctor(doctor);
    setDisease(disease);
    setScheduleDay(scheduleDay);
}

public Appointment (Appointment ap){
    no = ap.no;
    patient = ap.patient;
    doctor = ap.doctor;
    disease = ap.disease;
    scheduleDay = ap.scheduleDay;
}

public ArrayList<Appointment> appointmentArr() throws
ClassNotFoundException, SQLException {

 String url = "jdbc:ucanaccess://D:/MC140202550/MC140202550.accdb";
 Connection con = DriverManager.getConnection(url);
 Statement st = con.createStatement();
 String sql = "select * from  Patient, Doctor where Patient.Disease =
Doctor.Specialization";

 ResultSet rs = st.executeQuery(sql);
 ArrayList<Appointment> appointments = new ArrayList<>();

while(rs.next()==true){
    Appointment ap = new Appointment();
     ap.setPatient(rs.getString(1));
     ap.setDoctor(rs.getString(6));
     ap.setDisease(rs.getString(4));
     ap.setScheduleDay(rs.getString(8));
     int i = 1;
     ap.setNo(i);
     i++;
   appointments.add(ap);
   System.out.println(ap.getNo() + " " + ap.getPatient() + " " +
ap.getDoctor() + " " + ap.getDisease() + " " + ap.getScheduleDay());

}
st.executeQuery(sql);

 con.close();
 st.close();
 st.close();

return appointments;
}
}
</code>```

I want to call this Appointment class in another main class and print the objects stored in array.

```<code>public class Main{
public static void main(String args[]){
Main main=new Main();

Appointment ap = new Appointment();
}
}
</code>```

答:
you need to call appointmentArr() from main method and assign it into a variable, then print it. for example:

```<code>public class Main{
   public static void main(String args[]){

    Appointment ap = new Appointment();
    List<Appointment> list = ap.appointmentArr();
    // now you can iterate over list and print it.
    for(Appointment ap: list){
        System.out.println(ap.getNo() + " " + ap.getPatient() + " " +
                ap.getDoctor() + " " + ap.getDisease() + " " + ap.getScheduleDay());
    }

   }
}
</code>```

Body:
I m retriving data from database and want to store that data in the form of objects in my arraylist that furthermore can be use in display custom tables.

I have tried the solutions from prev related queries but couldn't solve my problem.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;

public class Appointment {

public int no;
public String patient;
public String doctor;
public String disease;
public String scheduleDay;

public void setNo(int no){
    this.no = no;}

public void setPatient(String patient){
    this.patient = patient;}

public void setDoctor(String doctor){

    this.doctor = doctor;}

public void setDisease(String disease){

    this.disease = disease;}

public void setScheduleDay(String scheduleDay){

    this.scheduleDay = scheduleDay;}

public int getNo(){
    return no;}
public String getPatient(){
    return patient;}
public String getDoctor(){
    return doctor;}
public String getDisease(){
    return disease;}
public String getScheduleDay(){
    return scheduleDay;}

public Appointment(){
    no = 0;
    patient = "not set";
    doctor = "not set";
    disease = "not set";
    scheduleDay = "not set";
}

public Appointment(int no, String patient, String doctor, String
disease, String scheduleDay){
    setNo(no);
    setPatient(patient);
    setDoctor(doctor);
    setDisease(disease);
    setScheduleDay(scheduleDay);
}

public Appointment (Appointment ap){
    no = ap.no;
    patient = ap.patient;
    doctor = ap.doctor;
    disease = ap.disease;
    scheduleDay = ap.scheduleDay;
}

public ArrayList<Appointment> appointmentArr() throws
ClassNotFoundException, SQLException {

 String url = "jdbc:ucanaccess://D:/MC140202550/MC140202550.accdb";
 Connection con = DriverManager.getConnection(url);
 Statement st = con.createStatement();
 String sql = "select * from  Patient, Doctor where Patient.Disease =
Doctor.Specialization";

 ResultSet rs = st.executeQuery(sql);
 ArrayList<Appointment> appointments = new ArrayList<>();

while(rs.next()==true){
    Appointment ap = new Appointment();
     ap.setPatient(rs.getString(1));
     ap.setDoctor(rs.getString(6));
     ap.setDisease(rs.getString(4));
     ap.setScheduleDay(rs.getString(8));
     int i = 1;
     ap.setNo(i);
     i++;
   appointments.add(ap);
   System.out.println(ap.getNo() + " " + ap.getPatient() + " " +
ap.getDoctor() + " " + ap.getDisease() + " " + ap.getScheduleDay());

}
st.executeQuery(sql);

 con.close();
 st.close();
 st.close();

return appointments;
}
}

I want to call this Appointment class in another main class and print the objects stored in array.

public class Main{
public static void main(String args[]){
Main main=new Main();

Appointment ap = new Appointment();
}
}

Body:
you need to call appointmentArr() from main method and assign it into a variable, then print it. for example:

public class Main{
   public static void main(String args[]){

    Appointment ap = new Appointment();
    List<Appointment> list = ap.appointmentArr();
    // now you can iterate over list and print it.
    for(Appointment ap: list){
        System.out.println(ap.getNo() + " " + ap.getPatient() + " " +
                ap.getDoctor() + " " + ap.getDisease() + " " + ap.getScheduleDay());
    }

   }
}


问:
SilkTest Identify/Locator Spy Window not seeing any objects in web browser window
SilkTest Locator spy is unable to recognize any of my web applications. It will see the main html page but no of the dom elements that lie Under it. It is weird because it used to work but im not sure if a setting change can cause this. I tried uninstalling and reinstalling silktest and I get the same problems.</p>

答:
Try after adding 'application configuration' for all apps to spy objects in silkTest with locator spy.

Locator spy identifies only those applications which are added in application configurations.


问:
JS — how to append Array of Objects with files to FormData?
I'm developing admin dashboard with Vue, Laravel & Axios.
And I have some problems with trying to upload files to api.

I replaced some real data to type of data

On Client-side I have Array of Objects:

```<code>[
    {
        id: random_generated_id,
        img: {obj},
        img_is_fullwidth: boolean,
        site_url: string,
        description: string
    },
    {
        id: random_generated_id
        img: {obj},
        img_is_fullwidth: boolean,
        site_url: string,
        description: string
    }
    ...
]
</code>```

Objects can be added to Array:

```<code>addObject() {
    this.array.push({
        id: new Date().valueOf(),
        img: null,
        img_is_fullwidth: null,
        site_url: null,
        description: null
    })
}
</code>```

```<code><div v-for="(content, index) in array" :key="content.index">
    <input type="file" :ref="'content' + content.id" v-on:change="handleFileUpload(content.id)">

    <label class="checkbox">
        <input type="checkbox" v-model="content.img_is_fullwidth">
        is fullwidth?
    </label>

    <input type="text" v-model="content.site_url" required>

    <input type="text" v-model="content.description" required>
</div>

<button @click.prevent="addContent">Add content</button>
</code>```

And I'm using random ids to attach image file to object by:

<input class="file-input" type="file" :ref="'content' + content.id" v-on:change="handleFileUpload(content.id)">
```

```handleFileUpload(itemId) {
   var itemIndex = this.array.findIndex(i => i.id === itemId)
   this.array[itemIndex].img = this.$refs['content' + itemId][0].files[0]
}
```

<p>So the problem is when I'm trying to post this data to api with axios,
I get error: </p>

<pre class="lang-php prettyprint-override"><code>Trying to get property 'img' of non-object
</code>```

It's happened cause I'm using JSON.stringify() and image object transforms to image array:

```<code>let fd = new FormData()
fd.append('array', JSON.stringify(this.array))
</code>```

Part of Laravel Controller:

$array = json_decode($request->array, true);

foreach ($array as $content) {

    $newContent = new WorkContent;

    $contentImg = $content->img;

    $contentName = uniqid();
    $contentExt = $contentImg->getClientOriginalExtension();
    $contentPath = $contentImg->storeAs('works/'.$request->client.'/'.$request->slug, $contentName.'.'.$contentExt);

    $newContent->img_url = $contentPath;

    if ($content->img_is_fullwidth == 'true') {
        $newContent->img_is_fullwidth = true;
    } else if ($content->img_is_fullwidth == 'false') {
        $newContent->img_is_fullwidth = false;
    }

    $newContent->site_url = $content->site_url;
    $newContent->description = $content->description;

    $newContent->save();

    $work->contents()->attach($newContent);
}
```

So, the question is:
Any ideas how to solve the problem?

答:
Found solution by myself:</p>

```<code>$contentArray = json_decode($r->contents, true);

$contentImgs = $r->contentImgs;

        $imgIndex = 0;

        for ($i = 0; $i < sizeof($contentArray); $i++) {
            if($contentArray[$i]['img'] !== null) {
                $contentArray[$i]['img'] = $r->contentImgs[$imgIndex];
            }
        }

        foreach ($contentArray as $content) {
            $newContent = new WorkContent;

            $contentImg = $content['img'];

            if ($contentImg !== null) {
                $contentName = uniqid();
                $contentExt = $contentImg->getClientOriginalExtension();
                $contentPath = $contentImg->storeAs('works/'.$r->client.'/'.$r->slug, $contentName.'.'.$contentExt);

                $newContent->img_url = $contentPath;
            }

            if ($content['img_is_fullwidth'] == 'true') {
                $newContent->img_is_fullwidth = true;
            } else if ($content['img_is_fullwidth'] == 'false') {
                $newContent->img_is_fullwidth = false;
            }

            $newContent->site_url = $content['site_url'];
            $newContent->description = $content['description'];

            $newContent->work_id = $w->id;

            $newContent->save();
        }
</code>```

Body:
I'm developing admin dashboard with Vue, Laravel & Axios.
And I have some problems with trying to upload files to api.

I replaced some real data to type of data

On Client-side I have Array of Objects:

[
    {
        id: random_generated_id,
        img: {obj},
        img_is_fullwidth: boolean,
        site_url: string,
        description: string
    },
    {
        id: random_generated_id
        img: {obj},
        img_is_fullwidth: boolean,
        site_url: string,
        description: string
    }
    ...
]

Objects can be added to Array:

addObject() {
    this.array.push({
        id: new Date().valueOf(),
        img: null,
        img_is_fullwidth: null,
        site_url: null,
        description: null
    })
}

    <input type="file" :ref="'content' + content.id" v-on:change="handleFileUpload(content.id)">

        <input type="checkbox" v-model="content.img_is_fullwidth">
        is fullwidth?

    <input type="text" v-model="content.site_url" required>

    <input type="text" v-model="content.description" required>

<button @click.prevent="addContent">Add content</button>

And I'm using random ids to attach image file to object by:

<input class="file-input" type="file" :ref="'content' + content.id" v-on:change="handleFileUpload(content.id)">

handleFileUpload(itemId) {
   var itemIndex = this.array.findIndex(i => i.id === itemId)
   this.array[itemIndex].img = this.$refs['content' + itemId][0].files[0]
}

So the problem is when I'm trying to post this data to api with axios,
I get error:

Trying to get property 'img' of non-object

It's happened cause I'm using JSON.stringify() and image object transforms to image array:

let fd = new FormData()
fd.append('array', JSON.stringify(this.array))

Part of Laravel Controller:

$array = json_decode($request->array, true);

foreach ($array as $content) {

    $newContent = new WorkContent;

    $contentImg = $content->img;

    $contentName = uniqid();
    $contentExt = $contentImg->getClientOriginalExtension();
    $contentPath = $contentImg->storeAs('works/'.$request->client.'/'.$request->slug, $contentName.'.'.$contentExt);

    $newContent->img_url = $contentPath;

    if ($content->img_is_fullwidth == 'true') {
        $newContent->img_is_fullwidth = true;
    } else if ($content->img_is_fullwidth == 'false') {
        $newContent->img_is_fullwidth = false;
    }

    $newContent->site_url = $content->site_url;
    $newContent->description = $content->description;

    $newContent->save();

    $work->contents()->attach($newContent);
}

So, the question is:
Any ideas how to solve the problem?

Body:
Found solution by myself:

$contentArray = json_decode($r->contents, true);

$contentImgs = $r->contentImgs;

        $imgIndex = 0;

        for ($i = 0; $i < sizeof($contentArray); $i++) {
            if($contentArray[$i]['img'] !== null) {
                $contentArray[$i]['img'] = $r->contentImgs[$imgIndex];
            }
        }

        foreach ($contentArray as $content) {
            $newContent = new WorkContent;

            $contentImg = $content['img'];

            if ($contentImg !== null) {
                $contentName = uniqid();
                $contentExt = $contentImg->getClientOriginalExtension();
                $contentPath = $contentImg->storeAs('works/'.$r->client.'/'.$r->slug, $contentName.'.'.$contentExt);

                $newContent->img_url = $contentPath;
            }

            if ($content['img_is_fullwidth'] == 'true') {
                $newContent->img_is_fullwidth = true;
            } else if ($content['img_is_fullwidth'] == 'false') {
                $newContent->img_is_fullwidth = false;
            }

            $newContent->site_url = $content['site_url'];
            $newContent->description = $content['description'];

            $newContent->work_id = $w->id;

            $newContent->save();
        }