问:
Flutter: Decoding List<dynamic> to List<String> silently failing
When casting from a Json list object to a list String, instead of failing to cast, the process silently fails without any warnings or errors to identify what is going wrong.

Steps to Reproduce

Take the below factory and model:

```<code>class Topic {
  int? id;
  String name;
  String displayName;
  int? parentId;
  List<String>? contentThemes;
  List<String>? channels;

  Topic({this.id, required this.name, required this.displayName, this.parentId, this.contentThemes, this.channels});

  factory Topic.fromJson(Map<String, dynamic> json) {
    var topic = Topic(
      id: json['id'] as int?,
      name: json['name'] as String,
      displayName: json['displayName'] as String,
      parentId: json['parentId'] as int?,
      contentThemes: json['contentThemes'] as List<String>?,
      channels: json['channels'] as List<String>?,
    );

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

Expected results:

The expectation is that flutter is able to identify that json['contentThemes'] is not a complex object and cast it from List dynamic to List String

OR if it is unable to, it should throw an error to the developer to highlight the failure to cast.

Actual results:
When trying to cast List to List (contentThemes, channels) it stops execution and silently fails to complete the task so the data is never returned.

The work around currently is to treat this as a complex object and do something like this:

```<code>class Topic {
  int? id;
  String name;
  String displayName;
  int? parentId;
  List<String>? contentThemes;
  List<String>? channels;

  Topic({this.id, required this.name, required this.displayName, this.parentId, this.contentThemes, this.channels});

  factory Topic.fromJson(Map<String, dynamic> json) {
    var topic = Topic(
      id: json['id'] as int?,
      name: json['name'] as String,
      displayName: json['displayName'] as String,
      parentId: json['parentId'] as int?,
      contentThemes: (json['channels'] as List?)?.map((item) => item as String)?.toList(),
      channels: (json['contentThemes'] as List?)?.map((item) => item as String)?.toList()
    );

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

Hope this helps anyone else as this was a tricky issue to debug due to the way flutter currently handles this.

答:
Try this:</p>
```<code>channels: List<String>.from(json['contentThemes'].map((x) => x))
</code>```

Body:
When casting from a Json list object to a list String, instead of failing to cast, the process silently fails without any warnings or errors to identify what is going wrong.

Steps to Reproduce

Take the below factory and model:

class Topic {
  int? id;
  String name;
  String displayName;
  int? parentId;
  List<String>? contentThemes;
  List<String>? channels;

  Topic({this.id, required this.name, required this.displayName, this.parentId, this.contentThemes, this.channels});

  factory Topic.fromJson(Map<String, dynamic> json) {
    var topic = Topic(
      id: json['id'] as int?,
      name: json['name'] as String,
      displayName: json['displayName'] as String,
      parentId: json['parentId'] as int?,
      contentThemes: json['contentThemes'] as List<String>?,
      channels: json['channels'] as List<String>?,
    );

    return topic;
  }
}

Expected results:

The expectation is that flutter is able to identify that json['contentThemes'] is not a complex object and cast it from List dynamic to List String

OR if it is unable to, it should throw an error to the developer to highlight the failure to cast.

Actual results:
When trying to cast List to List (contentThemes, channels) it stops execution and silently fails to complete the task so the data is never returned.

The work around currently is to treat this as a complex object and do something like this:

class Topic {
  int? id;
  String name;
  String displayName;
  int? parentId;
  List<String>? contentThemes;
  List<String>? channels;

  Topic({this.id, required this.name, required this.displayName, this.parentId, this.contentThemes, this.channels});

  factory Topic.fromJson(Map<String, dynamic> json) {
    var topic = Topic(
      id: json['id'] as int?,
      name: json['name'] as String,
      displayName: json['displayName'] as String,
      parentId: json['parentId'] as int?,
      contentThemes: (json['channels'] as List?)?.map((item) => item as String)?.toList(),
      channels: (json['contentThemes'] as List?)?.map((item) => item as String)?.toList()
    );

    return topic;
  }
}

Hope this helps anyone else as this was a tricky issue to debug due to the way flutter currently handles this.

Body:
Try this:

channels: List<String>.from(json['contentThemes'].map((x) => x))


来源: stackexchange

问:
Makefile target unexpectadly raising error
My Makefile includes follow target

```<code>   run: $(BIN_FILE)
        if [ -d $(BIN_FILE) ]; then $(error Sorry BIN_FILE is directory); else ./$(BIN_FILE) $(RUN_ARGS); fi
</code>```

But it raises the error no matter whether test passes or not. What is wrong? Why it raises an error even BIN_FILE is not directory? Have directive $(error... any special meaning?

Many thanks.

答:
You can't embed a Make expression like that inside your shell script.  Make performs all expansions of $(...) expressions before the shell even starts, so it sees your $(error ...) command and exits. You would need to emit this error using shell logic instead, doing something like:

```<code>run: $(BIN_FILE)
    if [ -d $(BIN_FILE) ]; then \
        echo "Sorry BIN_FILE is directory"; \
        exit 1; \
    fi
    $(BIN_FILE) $(RUN_ARGS)
</code>```

Or with slightly more compact logic:

```<code>run: $(BIN_FILE)
    [ -d "$(BIN_FILE)" ] && { echo "$(BIN_FILE) is a directory"; exit 1; } ||:
    $(BIN_FILE) $(RUN_ARGS)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My Makefile includes follow target

   run: $(BIN_FILE)
        if [ -d $(BIN_FILE) ]; then $(error Sorry BIN_FILE is directory); else ./$(BIN_FILE) $(RUN_ARGS); fi

But it raises the error no matter whether test passes or not. What is wrong? Why it raises an error even BIN_FILE is not directory? Have directive $(error... any special meaning?

Many thanks.

Body:
You can't embed a Make expression like that inside your shell script.  Make performs all expansions of $(...) expressions before the shell even starts, so it sees your $(error ...) command and exits. You would need to emit this error using shell logic instead, doing something like:

run: $(BIN_FILE)
    if [ -d $(BIN_FILE) ]; then \
        echo "Sorry BIN_FILE is directory"; \
        exit 1; \
    fi
    $(BIN_FILE) $(RUN_ARGS)

Or with slightly more compact logic:

run: $(BIN_FILE)
    [ -d "$(BIN_FILE)" ] && { echo "$(BIN_FILE) is a directory"; exit 1; } ||:
    $(BIN_FILE) $(RUN_ARGS)


问:
Navigating to a page on load in react JS
I am working on user registration setup and stuck on a problem where I am not able to redirect from a page 'localhost:3000/activate/tokenNo.'(Activation.jsx file) on load to my main page (App.jsx file) .

Here is my activation.jsx file :

```<code>import React, { useEffect } from 'react';
import { useNavigate } from "react-router-dom";

const Activate = () => {
    const navigate = useNavigate();

    useEffect(() => {
        navigate('/')
    }, [navigate])

    return (
        <div>Activation Page</div>
    )
}

export default Activate;
</code>```

Here is my App.jsx file :

```<code>import React from 'react';

export const App = () => {
  return <div>Dashboard</div>;
};
export default App ;
</code>```

My activationController.js file :

```<code>exports.activationController = (req,res) => {
    const {token} = req.body
    if(token){
        //Verify the token is valid or not or expired
    jwt.verify(token , process.env.JWT_ACCOUNT_ACTIVATION ,
        (err , decoded) => {
            if(err){
                return res.status(401).json({
                    error: "Expired Token , Signup again"
                })
            }
            else{
                //if valid save to database
                //Get name email password from token
                const {name , email , password} = jwt.decode(token)

                const user = new User({
                    name ,
                    email ,
                    passsword
                })

                user.save((err,user) => {
                    if(err){
                        return res.status(401).json({
                            error: errorHandler(err)
                        })
                    }
                    else{
                        return res.json({
                            success: true ,
                            message: "Signup successful",
                            user
                        })
                    }
                })

            }
        })

    }
    else{
        return res.json({
            message: "error happening please try again"
        })
    }

}
</code>```

In my auth.routes.js

```<code>router.post('/activation', activationController)
</code>```

I recieved an error in my console --> index.tsx:25 No routes matched location "/activate/tokenNo."

My reference folder --> https://github.com/Mohammed-Abdelhady/FULL-MERN-AUTH-Boilerplate

答:
Often we require to perform some extra action on component or page render initially.

Like, Data fetching, etc.

To implement like this we can use the useEffect hook from react and state our execution into it.

I can't see the useNavigate hook in the latest version of react-router-dom so we can use the useHistory hook.

For Example:

```<code>import React, { useEffect } from "react"
import { useHistory } from 'react-router-dom'

const App = () => {
    const history = useHistory();

    useEffect(() => {
        history.push('Page2URL')
    }, [history])

    return (
        <div>Page1</div>
    )
}
</code>```

Body:
I am working on user registration setup and stuck on a problem where I am not able to redirect from a page 'localhost:3000/activate/tokenNo.'(Activation.jsx file) on load to my main page (App.jsx file) .

Here is my activation.jsx file :

import React, { useEffect } from 'react';
import { useNavigate } from "react-router-dom";

const Activate = () => {
    const navigate = useNavigate();

    useEffect(() => {
        navigate('/')
    }, [navigate])

    return (

Activation Page

    )
}

export default Activate;

Here is my App.jsx file :

import React from 'react';

export const App = () => {
  return
Dashboard
;
};
export default App ;

My activationController.js file :

exports.activationController = (req,res) => {
    const {token} = req.body
    if(token){
        //Verify the token is valid or not or expired
    jwt.verify(token , process.env.JWT_ACCOUNT_ACTIVATION ,
        (err , decoded) => {
            if(err){
                return res.status(401).json({
                    error: "Expired Token , Signup again"
                })
            }
            else{
                //if valid save to database
                //Get name email password from token
                const {name , email , password} = jwt.decode(token)

                const user = new User({
                    name ,
                    email ,
                    passsword
                })

                user.save((err,user) => {
                    if(err){
                        return res.status(401).json({
                            error: errorHandler(err)
                        })
                    }
                    else{
                        return res.json({
                            success: true ,
                            message: "Signup successful",
                            user
                        })
                    }
                })

            }
        })

    }
    else{
        return res.json({
            message: "error happening please try again"
        })
    }

}

In my auth.routes.js

router.post('/activation', activationController)

I recieved an error in my console --> index.tsx:25 No routes matched location "/activate/tokenNo."

My reference folder --> https://github.com/Mohammed-Abdelhady/FULL-MERN-AUTH-Boilerplate

Body:
Often we require to perform some extra action on component or page render initially.

Like, Data fetching, etc.

To implement like this we can use the useEffect hook from react and state our execution into it.

I can't see the useNavigate hook in the latest version of react-router-dom so we can use the useHistory hook.

For Example:

import React, { useEffect } from "react"
import { useHistory } from 'react-router-dom'

const App = () => {
    const history = useHistory();

    useEffect(() => {
        history.push('Page2URL')
    }, [history])

    return (
        <div>Page1</div>
    )
}


问:
Get data stored in AsyncStorage instantly without async/await(promise)
config.js

```<code>AsyncStorage.getItem("storedValue").then(value=>{
//return data based on the value from asyncStorage storage
 if(value==="value1"){
  return {
   text:"text1",
   number:"number1"
  }
 }
 else if(value==="value2"){
  return {
   text:"text2",
   number:"number2"
  }
 }
})
</code>```

index.js

```<code>import config from "./config"
//I have to use data from config file here
console.log(config.text) //->getting error
//The problem is that, since fetching from AsyncStorage is asynchronous, data from config is not yet available here

//I have tried SyncStorage npm package for react native. It loads all the asyncStored values into memory upon calling
await SyncStorage.init() //-> called on app initialisation

//And can be used later in place of AsyncStorage.getItem(""), which returns the value directly instead of promise
const value=SyncStorage.get("storedValue")
</code>```

But the problem is, I am accessing the config in index.js(which is the starting file for a react-native project). And I have to initialise SyncStorage here, which is again asynchronous, which means the config file will get loaded before init() happens.

What I am expecting is:

get the value stored in local storage instantly without async/await in index.js
OR

In the app, I will have a button to restart the app. But, should be able to pass a value during the restart, which can be used in config.js or index.js while the app loadsOR

Or use any other package for deep-linking or something like that, so that on app restarting app using deep-link, the value passed should be accessible. It has to work for both android and iOS

Changes that are not possible:

Cannot make any other file other than index.js as starting file because, many other project packages are being initialized here, and in fact, the stored value we are trying to access needs to be passed to these packages while initializing.

Thank you.

答:
Please explain a little further...

Summarising what I understand from your question:

you want to read some value from async storage right away in index

you tried using synch storage for the same

you cannot move your code from index because you parked everything there

Trying to untangle that here my answer:

it is not really best practice to put a lot of code in app.js or index.js so I would try to avoid that as much as possible

sync storage as well as redux are normally just available at runtime and often are loaded from the async storage

async storage needs time and thus also needs to be loaded either with a then promise look or await catch

--> If I was you I would use async storage as normal with await and introduce some sort of splash screen where you do the loading.

Body:
config.js

AsyncStorage.getItem("storedValue").then(value=>{
//return data based on the value from asyncStorage storage
 if(value==="value1"){
  return {
   text:"text1",
   number:"number1"
  }
 }
 else if(value==="value2"){
  return {
   text:"text2",
   number:"number2"
  }
 }
})

index.js

import config from "./config"
//I have to use data from config file here
console.log(config.text) //->getting error
//The problem is that, since fetching from AsyncStorage is asynchronous, data from config is not yet available here

//I have tried SyncStorage npm package for react native. It loads all the asyncStored values into memory upon calling
await SyncStorage.init() //-> called on app initialisation

//And can be used later in place of AsyncStorage.getItem(""), which returns the value directly instead of promise
const value=SyncStorage.get("storedValue")

But the problem is, I am accessing the config in index.js(which is the starting file for a react-native project). And I have to initialise SyncStorage here, which is again asynchronous, which means the config file will get loaded before init() happens.

What I am expecting is:

get the value stored in local storage instantly without async/await in index.js
OR

In the app, I will have a button to restart the app. But, should be able to pass a value during the restart, which can be used in config.js or index.js while the app loadsOR

Or use any other package for deep-linking or something like that, so that on app restarting app using deep-link, the value passed should be accessible. It has to work for both android and iOS

Changes that are not possible:

Cannot make any other file other than index.js as starting file because, many other project packages are being initialized here, and in fact, the stored value we are trying to access needs to be passed to these packages while initializing.

Thank you.


问:
My promise returns the same value every time it's called despite having different data?
So first the getCart function is called in b-navbar.component.ts:

export class BNavbarComponent implements OnInit{
  appUser: any;
  cart$ : Observable<ShoppingCart | null>;

  constructor(private auth : AuthService, private shoppingCartService : ShoppingCartService) {}

  async ngOnInit() {
    this.auth.appUser$.then(dataObservable => {
      dataObservable?.subscribe(data => {
        this.appUser = data
      });
    });

    this.getCart()
  }

  async getCart() {
    this.cart$ = await this.shoppingCartService.getCart()

    this.cart$.subscribe(data => {
      console.log("Nav Observable data: ", data);
    })
  }
```
<p>Which looks in <code>shopping-cart.service.ts</code> and gets a promise of an observable:</p>
<pre class="lang-ts prettyprint-override"><code>export class ShoppingCartService {

  constructor(private db : AngularFireDatabase) { }

  private create(){
    return this.db.list("/shopping-carts").push({
      // dateCreated : new Date().getTime()
      date: "date"
    });
  }

  async getCart(): Promise<Observable<ShoppingCart>>{
    let cartId = await this.getOrCreateCartId();
    let cart = this.db.object("/shopping-carts/" + cartId);

    return new Promise((resolve) => {
      cart.valueChanges().subscribe(x => {
        let newX = x as ShoppingCart
        let items = newX.items
        resolve(of(new ShoppingCart(items)))
      })
    })
  }

  private async getOrCreateCartId() : Promise<string> {
    let cartId = localStorage.getItem("cartId");

    if (cartId) return cartId;

    let result = await this.create();
    localStorage.setItem("cartId", result.key as string);
    return result.key as string;
  }
}
</code>```

Now the issue arises when interpolate the values in my html, since the observable returned in the getCart promise resolves a "static" observable, meaning it terminates the observable when resolved, thus the data is never updated. Please help :))

    Shopping Cart

        {{ cart.totalItemsCount }}

```

答:
Once your promise gets resolved, it doesn't "emit" anything after that. This is one key difference between promises and obsevables. Observables can emit more values even after they emit the first.

So, you should make your getCart return just the observable stream:

```<code>import { map } from 'rxjs';

// rest of your code

async getCart(): Promise<Observable<ShoppingCart>>{
  let cartId = await this.getOrCreateCartId();
  let cart = this.db.object("/shopping-carts/" + cartId);
  return cart.valueChanges()
    .pipe(map(x => {
      let newX = x as ShoppingCart
      let items = newX.items
      return new ShoppingCart(items)
    }))
}
</code>```

This way, your promise resolves to the observable stream instead of a single value.

Body:
So first the getCart function is called in b-navbar.component.ts:

export class BNavbarComponent implements OnInit{
  appUser: any;
  cart$ : Observable<ShoppingCart | null>;

  constructor(private auth : AuthService, private shoppingCartService : ShoppingCartService) {}

  async ngOnInit() {
    this.auth.appUser$.then(dataObservable => {
      dataObservable?.subscribe(data => {
        this.appUser = data
      });
    });

    this.getCart()
  }

  async getCart() {
    this.cart$ = await this.shoppingCartService.getCart()

    this.cart$.subscribe(data => {
      console.log("Nav Observable data: ", data);
    })
  }

Which looks in shopping-cart.service.ts and gets a promise of an observable:

export class ShoppingCartService {

  constructor(private db : AngularFireDatabase) { }

  private create(){
    return this.db.list("/shopping-carts").push({
      // dateCreated : new Date().getTime()
      date: "date"
    });
  }

  async getCart(): Promise<Observable<ShoppingCart>>{
    let cartId = await this.getOrCreateCartId();
    let cart = this.db.object("/shopping-carts/" + cartId);

    return new Promise((resolve) => {
      cart.valueChanges().subscribe(x => {
        let newX = x as ShoppingCart
        let items = newX.items
        resolve(of(new ShoppingCart(items)))
      })
    })
  }

  private async getOrCreateCartId() : Promise<string> {
    let cartId = localStorage.getItem("cartId");

    if (cartId) return cartId;

    let result = await this.create();
    localStorage.setItem("cartId", result.key as string);
    return result.key as string;
  }
}

Now the issue arises when interpolate the values in my html, since the observable returned in the getCart promise resolves a "static" observable, meaning it terminates the observable when resolved, thus the data is never updated. Please help :))

    Shopping Cart

        {{ cart.totalItemsCount }}

Body:
Once your promise gets resolved, it doesn't "emit" anything after that. This is one key difference between promises and obsevables. Observables can emit more values even after they emit the first.

So, you should make your getCart return just the observable stream:

import { map } from 'rxjs';

// rest of your code

async getCart(): Promise<Observable<ShoppingCart>>{
  let cartId = await this.getOrCreateCartId();
  let cart = this.db.object("/shopping-carts/" + cartId);
  return cart.valueChanges()
    .pipe(map(x => {
      let newX = x as ShoppingCart
      let items = newX.items
      return new ShoppingCart(items)
    }))
}

This way, your promise resolves to the observable stream instead of a single value.


问:
Sliding window iterator using rolling in pandas
If it's single row, I can get the iterator as following

```<code>import pandas as pd
import numpy as np

a = np.zeros((100,40))
X = pd.DataFrame(a)

for index, row in X.iterrows():
    print index
    print row
</code>```

Now I want each iterator will return a subset X[0:9, :], X[5:14, :], X[10:19, :] etc. How do I achieve this with rolling (pandas.DataFrame.rolling)?

答:
It can be done with rolling but is inefficient (due to iterating all windows) and requires Pandas 1.1:

```<code>for index, row in enumerate(list(X.rolling(10))[::5]):
</code>```

Bit faster (iteration in C)

```<code>from itertools import islice
for index, row in enumerate(islice(X.rolling(10), None, None, 5)):
</code>```

Body:
If it's single row, I can get the iterator as following

import pandas as pd
import numpy as np

a = np.zeros((100,40))
X = pd.DataFrame(a)

for index, row in X.iterrows():
    print index
    print row

Now I want each iterator will return a subset X[0:9, :], X[5:14, :], X[10:19, :] etc. How do I achieve this with rolling (pandas.DataFrame.rolling)?

Body:
It can be done with rolling but is inefficient (due to iterating all windows) and requires Pandas 1.1:

for index, row in enumerate(list(X.rolling(10))[::5]):

Bit faster (iteration in C)

from itertools import islice
for index, row in enumerate(islice(X.rolling(10), None, None, 5)):


问:
An exception happened when converging configuration
This is the response of logstash -f logstash.conf. I don't know what to do.

Using JAVA_HOME defined java: C:\Program Files\Java\jdk-17.0.2
WARNING, using JAVA_HOME while Logstash distribution comes with a
bundled JDK 2022-02-09T18:48:30.825+03:30 [main] WARN FilenoUtil :
Native subprocess control requires open access to the JDK IO subsystem
Pass '--add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens
java.base/java.io=ALL-UNNAMED' to enable. Sending Logstash logs to
C:/logstash-7.12.0/logs which is now configured via log4j2.properties
[2022-02-09T18:48:44,793][INFO ][logstash.runner          ] Log4j
configuration path used is:
C:\logstash-7.12.0\config\log4j2.properties
[2022-02-09T18:48:44,800][INFO ][logstash.runner          ] Starting
Logstash {"logstash.version"=>"7.12.0", "jruby.version"=>"jruby
9.2.13.0 (2.5.7) 2020-08-03 9a89c94bcc Java HotSpot(TM) 64-Bit Server VM 17.0.2+8-LTS-86 on 17.0.2+8-LTS-86 +indy +jit [mswin32-x86_64]"}
[2022-02-09T18:48:44,879][WARN ][logstash.config.source.multilocal]
Ignoring the 'pipelines.yml' file because modules or command line
options are specified [2022-02-09T18:48:45,593][INFO ][logstash.agent
] Successfully started Logstash API endpoint {:port=>9600}
[2022-02-09T18:48:46,107][INFO ][org.reflections.Reflections]
Reflections took ۲۲ ms to scan ۱ urls, producing ۲۳ keys and ۴۷ values
[2022-02-09T18:48:46,484][ERROR][logstash.plugins.registry] Tried to
load a plugin's code, but failed. {:exception=>#<LoadError: Could not
load FFI Provider: (NotImplementedError) FFI not available:
java.lang.UnsatisfiedLinkError: could not locate stub library in jar
file.  Tried [jni/x86_64-Windows/jffi-۱.۲.dll,
/jni/x86_64-Windows/jffi-۱.۲.dll]
at com.kenai.jffi.internal.StubLoader.getStubLibraryStream(StubLoader.java:450)
at com.kenai.jffi.internal.StubLoader.loadFromJar(StubLoader.java:375)
at com.kenai.jffi.internal.StubLoader.load(StubLoader.java:278)
at com.kenai.jffi.internal.StubLoader.(StubLoader.java:487)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:467)
at com.kenai.jffi.Init.load(Init.java:68)
at com.kenai.jffi.Foreign$InstanceHolder.getInstanceHolder(Foreign.java:49)
at com.kenai.jffi.Foreign$InstanceHolder.(Foreign.java:45)
at com.kenai.jffi.Foreign.getInstance(Foreign.java:103)
at com.kenai.jffi.Type$Builtin.lookupTypeInfo(Type.java:242)
at com.kenai.jffi.Type$Builtin.getTypeInfo(Type.java:237)
at com.kenai.jffi.Type.resolveSize(Type.java:155)
at com.kenai.jffi.Type.size(Type.java:138)
at jnr.ffi.provider.jffi.NativeRuntime$TypeDelegate.size(NativeRuntime.java:178)
at jnr.ffi.provider.AbstractRuntime.(AbstractRuntime.java:48)
at jnr.ffi.provider.jffi.NativeRuntime.(NativeRuntime.java:57)
at jnr.ffi.provider.jffi.NativeRuntime.(NativeRuntime.java:41)
at jnr.ffi.provider.jffi.NativeRuntime$SingletonHolder.(NativeRuntime.java:53)
at jnr.ffi.provider.jffi.NativeRuntime.getInstance(NativeRuntime.java:49)
at jnr.ffi.provider.jffi.Provider.(Provider.java:29)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:347)
at java.base/java.lang.Class.newInstance(Class.java:645)
at jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.getInstance(FFIProvider.java:68)
at jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.(FFIProvider.java:57)
at jnr.ffi.provider.FFIProvider.getSystemProvider(FFIProvider.java:35)
at jnr.ffi.Library.loadLibrary(Library.java:114)
at jnr.posix.POSIXFactory$DefaultLibCProvider$SingletonHolder.(POSIXFactory.java:289)
at jnr.posix.POSIXFactory$DefaultLibCProvider.getLibC(POSIXFactory.java:318)
at jnr.posix.BaseNativePOSIX.(BaseNativePOSIX.java:38)
at jnr.posix.WindowsPOSIX.(WindowsPOSIX.java:134)
at jnr.posix.POSIXFactory.loadWindowsPOSIX(POSIXFactory.java:173)
at jnr.posix.POSIXFactory.loadNativePOSIX(POSIXFactory.java:142)
at jnr.posix.POSIXFactory.loadPOSIX(POSIXFactory.java:93)
at jnr.posix.LazyPOSIX.loadPOSIX(LazyPOSIX.java:38)
at jnr.posix.LazyPOSIX.posix(LazyPOSIX.java:32)
at jnr.posix.LazyPOSIX.isNative(LazyPOSIX.java:402)
at org.jruby.util.io.FilenoUtil.(FilenoUtil.java:42)
at org.jruby.Ruby.(Ruby.java:294)
at org.jruby.Ruby.newInstance(Ruby.java:706)
at org.logstash.Logstash.(Logstash.java:162)
at org.logstash.Logstash.main(Logstash.java:69)

See http://jira.codehaus.org/browse/JRUBY-4583>,
:path=>"logstash/inputs/file", :type=>"input", :name=>"file"}
[2022-02-09T18:48:46,494][ERROR][logstash.agent           ] Failed to
execute action
{:action=>LogStash::PipelineAction::Create/pipeline_id:main,
:exception=>"Java::JavaLang::IllegalStateException", :message=>"Unable
to configure plugins: (PluginLoadingError) Couldn't find any input
plugin named 'file'. Are you sure this is correct? Trying to load the
file input plugin resulted in this error: Could not load FFI Provider:
(NotImplementedError) FFI not available:
java.lang.UnsatisfiedLinkError: could not locate stub library in jar
file.  Tried [jni/x86_64-Windows/jffi-۱.۲.dll,
/jni/x86_64-Windows/jffi-۱.۲.dll]\r\n\tat
com.kenai.jffi.internal.StubLoader.getStubLibraryStream(StubLoader.java:450)\r\n\tat
com.kenai.jffi.internal.StubLoader.loadFromJar(StubLoader.java:375)\r\n\tat
com.kenai.jffi.internal.StubLoader.load(StubLoader.java:278)\r\n\tat
com.kenai.jffi.internal.StubLoader.(StubLoader.java:487)\r\n\tat
java.base/java.lang.Class.forName0(Native Method)\r\n\tat
java.base/java.lang.Class.forName(Class.java:467)\r\n\tat
com.kenai.jffi.Init.load(Init.java:68)\r\n\tat
com.kenai.jffi.Foreign$InstanceHolder.getInstanceHolder(Foreign.java:49)\r\n\tat
com.kenai.jffi.Foreign$InstanceHolder.(Foreign.java:45)\r\n\tat
com.kenai.jffi.Foreign.getInstance(Foreign.java:103)\r\n\tat
com.kenai.jffi.Type$Builtin.lookupTypeInfo(Type.java:242)\r\n\tat
com.kenai.jffi.Type$Builtin.getTypeInfo(Type.java:237)\r\n\tat
com.kenai.jffi.Type.resolveSize(Type.java:155)\r\n\tat
com.kenai.jffi.Type.size(Type.java:138)\r\n\tat
jnr.ffi.provider.jffi.NativeRuntime$TypeDelegate.size(NativeRuntime.java:178)\r\n\tat
jnr.ffi.provider.AbstractRuntime.(AbstractRuntime.java:48)\r\n\tat
jnr.ffi.provider.jffi.NativeRuntime.(NativeRuntime.java:57)\r\n\tat
jnr.ffi.provider.jffi.NativeRuntime.(NativeRuntime.java:41)\r\n\tat
jnr.ffi.provider.jffi.NativeRuntime$SingletonHolder.(NativeRuntime.java:53)\r\n\tat
jnr.ffi.provider.jffi.NativeRuntime.getInstance(NativeRuntime.java:49)\r\n\tat
jnr.ffi.provider.jffi.Provider.(Provider.java:29)\r\n\tat
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method)\r\n\tat
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)\r\n\tat
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)\r\n\tat
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)\r\n\tat
java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)\r\n\tat
java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:347)\r\n\tat
java.base/java.lang.Class.newInstance(Class.java:645)\r\n\tat
jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.getInstance(FFIProvider.java:68)\r\n\tat
jnr.ffi.provider.FFIProvider$SystemProviderSingletonHolder.(FFIProvider.java:57)\r\n\tat
jnr.ffi.provider.FFIProvider.getSystemProvider(FFIProvider.java:35)\r\n\tat
jnr.ffi.Library.loadLibrary(Library.java:114)\r\n\tat
jnr.posix.POSIXFactory$DefaultLibCProvider$SingletonHolder.(POSIXFactory.java:289)\r\n\tat
jnr.posix.POSIXFactory$DefaultLibCProvider.getLibC(POSIXFactory.java:318)\r\n\tat
jnr.posix.BaseNativePOSIX.(BaseNativePOSIX.java:38)\r\n\tat
jnr.posix.WindowsPOSIX.(WindowsPOSIX.java:134)\r\n\tat
jnr.posix.POSIXFactory.loadWindowsPOSIX(POSIXFactory.java:173)\r\n\tat
jnr.posix.POSIXFactory.loadNativePOSIX(POSIXFactory.java:142)\r\n\tat
jnr.posix.POSIXFactory.loadPOSIX(POSIXFactory.java:93)\r\n\tat
jnr.posix.LazyPOSIX.loadPOSIX(LazyPOSIX.java:38)\r\n\tat
jnr.posix.LazyPOSIX.posix(LazyPOSIX.java:32)\r\n\tat
jnr.posix.LazyPOSIX.isNative(LazyPOSIX.java:402)\r\n\tat
org.jruby.util.io.FilenoUtil.(FilenoUtil.java:42)\r\n\tat
org.jruby.Ruby.(Ruby.java:294)\r\n\tat
org.jruby.Ruby.newInstance(Ruby.java:706)\r\n\tat
org.logstash.Logstash.(Logstash.java:162)\r\n\tat
org.logstash.Logstash.main(Logstash.java:69)\r\n\n See
http://jira.codehaus.org/browse/JRUBY-4583",
:backtrace=>["org.logstash.config.ir.CompiledPipeline.(CompiledPipeline.java:119)",
"org.logstash.execution.JavaBasePipelineExt.initialize(JavaBasePipelineExt.java:83)",
"org.logstash.execution.JavaBasePipelineExt$INVOKER$i$1$0$initialize.call(JavaBasePipelineExt$INVOKER$i$1$0$initialize.gen)",
"org.jruby.internal.runtime.methods.JavaMethod$JavaMethodN.call(JavaMethod.java:837)",
"org.jruby.ir.runtime.IRRuntimeHelpers.instanceSuper(IRRuntimeHelpers.java:1169)",
"org.jruby.ir.runtime.IRRuntimeHelpers.instanceSuperSplatArgs(IRRuntimeHelpers.java:1156)",
"org.jruby.ir.targets.InstanceSuperInvokeSite.invoke(InstanceSuperInvokeSite.java:39)",
"C_3a_.logstash_minus_7_dot_12_dot_0.logstash_minus_core.lib.logstash.java_pipeline.RUBY$method$initialize$0(C:/logstash-7.12.0/logstash-core/lib/logstash/java_pipeline.rb:47)",
"org.jruby.internal.runtime.methods.CompiledIRMethod.call(CompiledIRMethod.java:80)",
"org.jruby.internal.runtime.methods.MixedModeIRMethod.call(MixedModeIRMethod.java:70)",
"org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:332)",
"org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:86)",
"org.jruby.RubyClass.newInstance(RubyClass.java:939)",
"org.jruby.RubyClass$INVOKER$i$newInstance.call(RubyClass$INVOKER$i$newInstance.gen)",
"org.jruby.ir.targets.InvokeSite.invoke(InvokeSite.java:207)",
"C_3a_.logstash_minus_7_dot_12_dot_0.logstash_minus_core.lib.logstash.pipeline_action.create.RUBY$method$execute$0(C:/logstash-7.12.0/logstash-core/lib/logstash/pipeline_action/create.rb:52)",
"C_3a_.logstash_minus_7_dot_12_dot_0.logstash_minus_core.lib.logstash.pipeline_action.create.RUBY$method$execute$0$VARARGS(C:/logstash-7.12.0/logstash-core/lib/logstash/pipeline_action/create.rb)",
"org.jruby.internal.runtime.methods.CompiledIRMethod.call(CompiledIRMethod.java:80)",
"org.jruby.internal.runtime.methods.MixedModeIRMethod.call(MixedModeIRMethod.java:70)",
"org.jruby.ir.targets.InvokeSite.invoke(InvokeSite.java:207)",
"C_3a_.logstash_minus_7_dot_12_dot_0.logstash_minus_core.lib.logstash.agent.RUBY$block$converge_state$2(C:/logstash-7.12.0/logstash-core/lib/logstash/agent.rb:389)", "org.jruby.runtime.CompiledIRBlockBody.callDirect(CompiledIRBlockBody.java:138)",
"org.jruby.runtime.IRBlockBody.call(IRBlockBody.java:58)",
"org.jruby.runtime.IRBlockBody.call(IRBlockBody.java:52)",
"org.jruby.runtime.Block.call(Block.java:139)",
"org.jruby.RubyProc.call(RubyProc.java:318)",
"org.jruby.internal.runtime.RubyRunnable.run(RubyRunnable.java:105)",
"java.base/java.lang.Thread.run(Thread.java:833)"]} warning: thread
"Converge PipelineAction::Create" terminated with exception
(report_on_exception is true): LogStash::Error: Don't know how to
handle Java::JavaLang::IllegalStateException for
PipelineAction::Create
create at org/logstash/execution/ConvergeResultExt.java:129
add at org/logstash/execution/ConvergeResultExt.java:57   converge_state at
C:/logstash-7.12.0/logstash-core/lib/logstash/agent.rb:402
[2022-02-09T18:48:46,509][ERROR][logstash.agent           ] An
exception happened when converging configuration
{:exception=>LogStash::Error, :message=>"Don't know how to handle
Java::JavaLang::IllegalStateException for
PipelineAction::Create"}
[2022-02-09T18:48:46,519][FATAL][logstash.runner          ] An
unexpected error occurred! {:error=>#<LogStash::Error: Don't know how
to handle Java::JavaLang::IllegalStateException for
PipelineAction::Create>,
:backtrace=>["org/logstash/execution/ConvergeResultExt.java:129:in
create'", "org/logstash/execution/ConvergeResultExt.java:57:in add'", "C:/logstash-7.12.0/logstash-core/lib/logstash/agent.rb:402:in
`block in converge_state'"]}
[2022-02-09T18:48:46,527][FATAL][org.logstash.Logstash    ] Logstash
stopped processing because of an error: (SystemExit) exit
org.jruby.exceptions.SystemExit: (SystemExit) exit
at org.jruby.RubyKernel.exit(org/jruby/RubyKernel.java:747) ~[jruby-complete-9.2.13.0.jar:?]
at org.jruby.RubyKernel.exit(org/jruby/RubyKernel.java:710) ~[jruby-complete-9.2.13.0.jar:?]
at C_3a_.logstash_minus_7_dot_12_dot_0.lib.bootstrap.environment.(C:\logstash-7.12.0\lib\bootstrap\environment.rb:89)
~[?:?]

答: I found out that I had to use java version 8+ instead of 17.</p>


问:
MockMvc result returns null for GET request in Spring Boot
I have a problem with testing my Spring Boot Controller. I'm trying to test one of Controller put methods, but all I'm getting is Status expected:<200> but was:<400> error message.

My Controller:

```<code>@PutMapping(value = "/update", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> updateFields(@RequestBody List<UpdateModel> model) throws JsonProcessingException {
    return new ResponseEntity<>(vaultService.updateFields(model), HttpStatus.OK);
}
</code>```

My ControllerTest:
The URL is ok, and I have a list just like in the get method in my controller.

```<code>@Test
void updateFieldsTest() throws Exception {
    List<UpdateModel> response = new ArrayList<>();
    UpdateModel updateModel = new UpdateModel();
    response.add(updateModel);
    when(vaultService.updateFields(anyList()))
            .thenReturn(String.valueOf(response));

mockMvc.perform(
        MockMvcRequestBuilders.put("/api/update")
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .accept("application/json"))
        .andExpect(MockMvcResultMatchers.status().isOk());
}
</code>```

And here's an error message:

```<code>MockHttpServletRequest:
      HTTP Method = PUT
      Request URI = /api/update
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json"]
             Body = null
    Session Attrs = {}

Handler:
             Type = hr.ogcs.ltt.api.lttapi.controller.LttController
           Method = hr.ogcs.ltt.api.lttapi.controller.LttController#updateFields(List)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Status expected:<200> but was:<400>
Expected :200
Actual   :400
<Click to see difference>
java.lang.AssertionError: Status expected:<200> but was:<400>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:212)
   at hr.ogcs.ltt.api.apicontroller.ControllerTest.updateFieldsTest(ControllerTest.java:113) <31 internal lines>
   at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)<9 internal lines>
   at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)<48 internal lines>
</code>```

I guess it has to be something with sending the required parameter, but I'm not sure what exactly causes this 400 error.

答:
For anyone interested, I've managed to find a solution, so here it is.

```<code>@Test
@DisplayName("Test updateFieldsTest")
void updateFieldsTest() throws Exception {
    List<UpdateModel> response = new ArrayList<>();
    UpdateModel updateModel = new UpdateModel();
    response.add(updateModel);
    when(vaultService.updateFields(anyList()))
            .thenReturn(String.valueOf(response));

ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(response);

mockMvc.perform(
        MockMvcRequestBuilders.put("/api/update")
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .content(json)
        .accept("application/json"))
        .andExpect(MockMvcResultMatchers.status().isOk());
}
</code>```

If you compare this code with the one in my original post, the difference is in adding the ObjectMapper.

Body:
I have a problem with testing my Spring Boot Controller. I'm trying to test one of Controller put methods, but all I'm getting is Status expected:<200> but was:<400> error message.

My Controller:

@PutMapping(value = "/update", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> updateFields(@RequestBody List<UpdateModel> model) throws JsonProcessingException {
    return new ResponseEntity<>(vaultService.updateFields(model), HttpStatus.OK);
}

My ControllerTest:
The URL is ok, and I have a list just like in the get method in my controller.

@Test
void updateFieldsTest() throws Exception {
    List<UpdateModel> response = new ArrayList<>();
    UpdateModel updateModel = new UpdateModel();
    response.add(updateModel);
    when(vaultService.updateFields(anyList()))
            .thenReturn(String.valueOf(response));

mockMvc.perform(
        MockMvcRequestBuilders.put("/api/update")
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .accept("application/json"))
        .andExpect(MockMvcResultMatchers.status().isOk());
}

And here's an error message:

MockHttpServletRequest:
      HTTP Method = PUT
      Request URI = /api/update
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json"]
             Body = null
    Session Attrs = {}

Handler:
             Type = hr.ogcs.ltt.api.lttapi.controller.LttController
           Method = hr.ogcs.ltt.api.lttapi.controller.LttController#updateFields(List)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Status expected:<200> but was:<400>
Expected :200
Actual   :400
<Click to see difference>
java.lang.AssertionError: Status expected:<200> but was:<400>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:212)
   at hr.ogcs.ltt.api.apicontroller.ControllerTest.updateFieldsTest(ControllerTest.java:113) <31 internal lines>
   at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)<9 internal lines>
   at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)<48 internal lines>

I guess it has to be something with sending the required parameter, but I'm not sure what exactly causes this 400 error.

Body:
For anyone interested, I've managed to find a solution, so here it is.

@Test
@DisplayName("Test updateFieldsTest")
void updateFieldsTest() throws Exception {
    List<UpdateModel> response = new ArrayList<>();
    UpdateModel updateModel = new UpdateModel();
    response.add(updateModel);
    when(vaultService.updateFields(anyList()))
            .thenReturn(String.valueOf(response));

ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(response);

mockMvc.perform(
        MockMvcRequestBuilders.put("/api/update")
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .content(json)
        .accept("application/json"))
        .andExpect(MockMvcResultMatchers.status().isOk());
}

If you compare this code with the one in my original post, the difference is in adding the ObjectMapper.


问:
Why Oracle Rest Service returns 404 Not Found?
I have Apex 21 & ORDS installed.

Apex works properly.

I have the following RESTful service module :

Whever I access the module url, I'm getting the error 404 Not Found.

ORDS is enabled for the schema.

Does anyone know why the module is not working please ?

Thanks.

答:
Whenever I access the module url

Nothing is configured in ORDS to provide a response at the module level, only the TEMPLATE level, and that only if you have a HANDLER defined for the method being used.

You can go to your API, or you can go to the description (OpenAPI Catalog) of the APIs in your module.

Good: GET http://example.com/ords/myschema/test/1

Bad: GET http://example.com/ords/myschema/test

Good: GET http://example.com/ords/open-api-catalog/myschema/test/

Also for anyone else reading this, you can use APEX with ORDS, but you don't HAVE to use APEX with ORDS.

ORDS also has a native IDE for developing REST APIs, as shown in my screenshot. You can read more about this here.

Disclaimer: I'm the product manager at Oracle responsible for Oracle REST Data Services, aka ORDS.


问:
Adding background to entire UISplitViewController
Hey I want to add a background image to my UISplitViewController that spans the entire iPad screen and is visible underneath both my master and detail views.

I've tried this a number of different ways and have yet to be successful. If I place it in the splitView.view it just overlays on top of everything in both sub-view controllers. If I place it in the master view controller I can do things normally there (place a UITableView on top of it, etc), but it then covers everything in the detail view controller. Another route I tried was to place my background image in it's own view controller the put the entire split view controller inside that view controller, but no matter what I set the alpha of my split view controller the background is still black.

If someone could point me towards getting this working it would be awesome, thanks!

答:
Got it working!

First follow along with Apple's example of setting up a UISplitViewController programmatically here: http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/iPadControllers/iPadControllers.html

then add in this line before adding the VC to the window:

```<code>splitVC.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.jpg"]];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Got it working!

First follow along with Apple's example of setting up a UISplitViewController programmatically here: http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/iPadControllers/iPadControllers.html

then add in this line before adding the VC to the window:

splitVC.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.jpg"]];


问:
MERN app login working on localhost but not on Heroku
I have created a MERN app that I deployed on Heroku but I can't login although I enter the correct credentials. When I submit the login form, the request to the login api is successful (I get the desired response) but there is no jwt_token cookie stored in the browser and the user context is not updated with the logged in user.

FRONTEND

App.js

```<code>import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './routes/Home';
import ErrorPage from './routes/ErrorPage';
import LoginPage from './routes/LoginPage';
import RegisterPage from './routes/RegisterPage';
import Tournaments from './routes/Tournaments';
import PlayerStatistics from './routes/PlayerStatistics';
import SettingsPage from './routes/SettingsPage';
import TournamentPlay from './routes/TournamentPlay';
import TournamentCreate from './routes/TournamentCreate';
import MyData from './routes/MyData';
import Header from './components/Header';
import useFindPlayer from './hooks/useFindPlayer';
import { PlayerContext } from './context/PlayerContext';
import ThemeContextProvider from './context/ThemeContextProvider';
import PrivateRoute from './routes/PrivateRoute';
import RedirectLoggedIn from './routes/RedirectLoggedIn';

function App() {
  const { player, setPlayer, isLoading } = useFindPlayer();

  return (
    <div className="App">
      <div>
        <Router>
          <ThemeContextProvider>
            <PlayerContext.Provider value={{ player, setPlayer, isLoading }}>
              {player && <Header />}
              <Routes>
                <Route
                  exact
                  path="/"
                  element={
                    <PrivateRoute>
                      <Home />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/tournaments/:id"
                  element={
                    <PrivateRoute>
                      <TournamentPlay />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/login"
                  element={
                    <RedirectLoggedIn>
                      <LoginPage />
                    </RedirectLoggedIn>
                  }
                />
                <Route
                  exact
                  path="/register"
                  element={
                    <RedirectLoggedIn>
                      <RegisterPage />
                    </RedirectLoggedIn>
                  }
                />
                <Route
                  exact
                  path="/settings"
                  element={
                    <PrivateRoute>
                      <SettingsPage />
                    </PrivateRoute>
                  }
                />
                <Route element={<ErrorPage />} />
                <Route
                  exact
                  path="/tournaments"
                  element={
                    <PrivateRoute>
                      <Tournaments />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/players"
                  element={
                    <PrivateRoute>
                      <PlayerStatistics />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/tournaments/new"
                  element={
                    <PrivateRoute>
                      <TournamentCreate />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/mydata"
                  element={
                    <PrivateRoute>
                      <MyData />
                    </PrivateRoute>
                  }
                />
              </Routes>
            </PlayerContext.Provider>
          </ThemeContextProvider>
        </Router>
      </div>
    </div>
  );
}

export default App;
</code>```

useAuth.js

```<code>import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { PlayerContext } from '../context/PlayerContext';

export default function useAuth() {
  const navigate = useNavigate();
  const { setPlayer } = useContext(PlayerContext);
  const [error, setError] = useState(null);

  const setPlayerContext = async () => {
    return await axios
      .get('/api/auth/player')
      .then((res) => {
        setPlayer(res.data.currentPlayer);
        navigate('/');
      })
      .catch((err) => {
        console.error(err);
        setError(err.response.data);
      });
  };

  const registerPlayer = async (data) => {
    const { username, fullname, password, passwordCheck } = data;

    return axios
      .post('/api/auth/register', {
        username,
        fullname,
        password,
        passwordCheck,
      })
      .then(async () => {
        await setPlayerContext();
        navigate('/');
      })
      .catch((err) => {
        console.error(err);
        setError(err.response.data);
      });
  };

  //login player
  const loginPlayer = async (data) => {
    const { username, password } = data;
    return axios
      .post('/api/auth/login', {
        username,
        password,
      })
      .then(async () => {
        await setPlayerContext();
      })
      .catch((err) => {
        setError(err.response.data);
      });
  };

  const clearError = () => {
    setError(null);
  };

  return {
    registerPlayer,
    loginPlayer,
    clearError,
    error,
  };
}
</code>```

useFindPlayer

```<code>import axios from 'axios';

export default function useFindPlayer() {
  const [player, setPlayer] = useState(null);
  const [isLoading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function findPlayer() {
      await axios
        .get('/api/auth/player')
        .then((res) => {
          setPlayer(res.data.currentPlayer);
          setLoading(false);
        })
        .catch((err) => {
          console.error(err);
          setError(err);
          setLoading(false);
        });
    }
    findPlayer();
  }, []);
  return {
    player,
    setPlayer,
    error,
    setError,
    isLoading,
  };
}
</code>```

BACKEND

server.js

```<code>const express = require('express');
const app = express();
const cors = require('cors');
const PORT = process.env.PORT || 8080;
const mongoose = require('mongoose');
const auth = require('./utils/auth');
const bodyParser = require('body-parser');
const database = findDatabase(process.env.NODE_ENV);
const databaseName = database.split('/')[3].split('?')[0].toUpperCase();
const player = require('./routes/playerRoute');
const game = require('./routes/gameRoute');
const tournament = require('./routes/tournamentRoute');
const userAuth = require('./routes/authRoute');
const cookieParser = require('cookie-parser');
const jwtSecret = process.env.JWT_SECRET;
const path = require('path');

mongoose.connect(database);

function findDatabase(env) {
  switch (env) {
    case 'production':
      return process.env.MONGODB_URI;
    case 'development':
      return process.env.MONGO_DEV_URI;
    case 'demo':
      return process.env.MONGO_DEMO_URI;
    default:
      return process.env.MONGO_DEV_URI;
  }
}

const db = mongoose.connection;
const urlEncodedParser = bodyParser.urlencoded({ extended: false });
db.on('error', () => console.error('Error'));
db.once('open', () => {
  console.log(`Database ${databaseName} connected...`);
});

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json(), urlEncodedParser);
app.use(cookieParser(jwtSecret));

// Authentication
app.post('/api/auth/register', userAuth.registerPlayer);
app.post('/api/auth/login', userAuth.loginPlayer);
app.get('/api/auth/logout', userAuth.logoutPlayer);
app.get('/api/auth/player', userAuth.checkPlayer);

// Players
app.post('/api/players', player.add);
app.get('/api/players', player.list);
app.get('/api/players/stats/:id', player.stats);
app.put('/api/players/:id', player.update);

// Tournaments
app.post('/api/tournaments', tournament.add);
app.get('/api/tournaments/complete/:id', tournament.finalize);
app.get('/api/tournaments/:id', tournament.show);
app.get('/api/tournaments', tournament.list);
app.put('/api/tournaments/:id', tournament.update);
app.delete('/api/tournaments/:id', tournament.cancel);

// Games
app.post('/api/games', game.add);
app.get('/api/games', game.list);
app.get('/api/games/:id', game.getOne);
app.delete('/api/tournaments/:tid/game/:gid', game.delete);

//fix login auth and blank page
if (process.env.NODE_ENV === 'production') {
  const root = require('path').join(__dirname, 'client', 'build');
  app.use(express.static(root));
  app.get('*', (req, res) => {
    res.sendFile('index.html', { root });
  });
} else {
  app.get('/', (req, res) => {
    res.send('API running');
  });
}

app.listen(PORT, () => {
  console.log(`Serving on port ${PORT}`);
});
</code>```

authRoute.js

```<code>const catchAsync = require('../utils/catchAsync');
const jwt = require('jsonwebtoken');
const { promisify } = require('util');

const signToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });
};

const createPlayerToken = async (player, code, req, res) => {
  const token = signToken(player._id);

  let d = new Date();
  d.setDate(d.getDate() + 30);

  res.cookie('jwt_token', token, {
    expires: d,
    httpOnly: true,
    secure:
      req.secure ||
      req.headers['x-forwarded-proto'] === 'https' ||
      req.headers['x-forwarded-proto'] === 'http',
    sameSite: 'none',
  });

  player.password = undefined;
  res.status(code).json({
    status: 'success',
    token,
    data: {
      player,
    },
  });
};

exports.registerPlayer = async (req, res, next) => {
  try {
    let { username, password, passwordCheck, fullname } = req.body;
    if (!username || !password || !passwordCheck)
      return res.status(400).json({ msg: 'Not all fields have been entered.' });

    if (password !== passwordCheck) {
      return res
        .status(400)
        .json({ msg: 'Enter the same password twice for verification.' });
    }

    if (!fullname) {
      fullname = username;
    }

    const newPlayer = await Player.create({
      fullname: fullname,
      username: username,
      password: password,
      passwordCheck: passwordCheck,
    });
    createPlayerToken(newPlayer, 201, req, res);
  } catch (err) {
    console.log(err);
    next(err);
  }
};

exports.loginPlayer = catchAsync(async (req, res, next) => {
  const { username, password } = req.body;

  if (!username || !password) {
    return res
      .status(400)
      .send({ msg: 'Please provide a username and password!' });
  }

  const player = await Player.findOne({ username }).select('+password');
  let correctPassword;
  if (player) {
    correctPassword = await player.correctPassword(password, player.password);
  }
  if (!player || !correctPassword) {
    return res.status(401).send({ msg: 'Incorrect username or password' });
  }
  createPlayerToken(player, 200, req, res);
});

exports.checkPlayer = catchAsync(async (req, res, next) => {
  let currentPlayer;
  if (req.cookies.jwt_token) {
    const token = req.cookies.jwt_token;
    const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
    currentPlayer = await Player.findById(decoded.id);
  } else {
    currentPlayer = null;
  }
  res.status(200).send({ currentPlayer });
});
//log user out
exports.logoutPlayer = catchAsync(async (req, res) => {
  res.cookie('jwt_token', 'loggedout', {
    expires: new Date(Date.now() + 10 * 1000),
    httpOnly: true,
  });
  res.status(200).send('user is logged out');
});
</code>```

答:
When using sameSite=None on a cookie, then you have to use the secure flag. From samesite docs:

Cookies will be sent in all contexts, i.e. in responses to both first-party and cross-origin requests. If SameSite=None is set, the cookie Secure attribute must also be set (or the cookie will be blocked).

Otherwise, the cookie gets blocked.

Body:
I have created a MERN app that I deployed on Heroku but I can't login although I enter the correct credentials. When I submit the login form, the request to the login api is successful (I get the desired response) but there is no jwt_token cookie stored in the browser and the user context is not updated with the logged in user.

FRONTEND

App.js

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './routes/Home';
import ErrorPage from './routes/ErrorPage';
import LoginPage from './routes/LoginPage';
import RegisterPage from './routes/RegisterPage';
import Tournaments from './routes/Tournaments';
import PlayerStatistics from './routes/PlayerStatistics';
import SettingsPage from './routes/SettingsPage';
import TournamentPlay from './routes/TournamentPlay';
import TournamentCreate from './routes/TournamentCreate';
import MyData from './routes/MyData';
import Header from './components/Header';
import useFindPlayer from './hooks/useFindPlayer';
import { PlayerContext } from './context/PlayerContext';
import ThemeContextProvider from './context/ThemeContextProvider';
import PrivateRoute from './routes/PrivateRoute';
import RedirectLoggedIn from './routes/RedirectLoggedIn';

function App() {
  const { player, setPlayer, isLoading } = useFindPlayer();

  return (

        <Router>
          <ThemeContextProvider>
            <PlayerContext.Provider value={{ player, setPlayer, isLoading }}>
              {player && }
              <Routes>
                <Route
                  exact
                  path="/"
                  element={
                    <PrivateRoute>
                      <Home />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/tournaments/:id"
                  element={
                    <PrivateRoute>
                      <TournamentPlay />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/login"
                  element={
                    <RedirectLoggedIn>
                      <LoginPage />
                    </RedirectLoggedIn>
                  }
                />
                <Route
                  exact
                  path="/register"
                  element={
                    <RedirectLoggedIn>
                      <RegisterPage />
                    </RedirectLoggedIn>
                  }
                />
                <Route
                  exact
                  path="/settings"
                  element={
                    <PrivateRoute>
                      <SettingsPage />
                    </PrivateRoute>
                  }
                />
                <Route element={<ErrorPage />} />
                <Route
                  exact
                  path="/tournaments"
                  element={
                    <PrivateRoute>
                      <Tournaments />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/players"
                  element={
                    <PrivateRoute>
                      <PlayerStatistics />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/tournaments/new"
                  element={
                    <PrivateRoute>
                      <TournamentCreate />
                    </PrivateRoute>
                  }
                />
                <Route
                  exact
                  path="/mydata"
                  element={
                    <PrivateRoute>
                      <MyData />
                    </PrivateRoute>
                  }
                />
              </Routes>
            </PlayerContext.Provider>
          </ThemeContextProvider>
        </Router>

  );
}

export default App;

useAuth.js

import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { PlayerContext } from '../context/PlayerContext';

export default function useAuth() {
  const navigate = useNavigate();
  const { setPlayer } = useContext(PlayerContext);
  const [error, setError] = useState(null);

  const setPlayerContext = async () => {
    return await axios
      .get('/api/auth/player')
      .then((res) => {
        setPlayer(res.data.currentPlayer);
        navigate('/');
      })
      .catch((err) => {
        console.error(err);
        setError(err.response.data);
      });
  };

  const registerPlayer = async (data) => {
    const { username, fullname, password, passwordCheck } = data;

    return axios
      .post('/api/auth/register', {
        username,
        fullname,
        password,
        passwordCheck,
      })
      .then(async () => {
        await setPlayerContext();
        navigate('/');
      })
      .catch((err) => {
        console.error(err);
        setError(err.response.data);
      });
  };

  //login player
  const loginPlayer = async (data) => {
    const { username, password } = data;
    return axios
      .post('/api/auth/login', {
        username,
        password,
      })
      .then(async () => {
        await setPlayerContext();
      })
      .catch((err) => {
        setError(err.response.data);
      });
  };

  const clearError = () => {
    setError(null);
  };

  return {
    registerPlayer,
    loginPlayer,
    clearError,
    error,
  };
}

useFindPlayer

import axios from 'axios';

export default function useFindPlayer() {
  const [player, setPlayer] = useState(null);
  const [isLoading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function findPlayer() {
      await axios
        .get('/api/auth/player')
        .then((res) => {
          setPlayer(res.data.currentPlayer);
          setLoading(false);
        })
        .catch((err) => {
          console.error(err);
          setError(err);
          setLoading(false);
        });
    }
    findPlayer();
  }, []);
  return {
    player,
    setPlayer,
    error,
    setError,
    isLoading,
  };
}

BACKEND

server.js

const express = require('express');
const app = express();
const cors = require('cors');
const PORT = process.env.PORT || 8080;
const mongoose = require('mongoose');
const auth = require('./utils/auth');
const bodyParser = require('body-parser');
const database = findDatabase(process.env.NODE_ENV);
const databaseName = database.split('/')[3].split('?')[0].toUpperCase();
const player = require('./routes/playerRoute');
const game = require('./routes/gameRoute');
const tournament = require('./routes/tournamentRoute');
const userAuth = require('./routes/authRoute');
const cookieParser = require('cookie-parser');
const jwtSecret = process.env.JWT_SECRET;
const path = require('path');

mongoose.connect(database);

function findDatabase(env) {
  switch (env) {
    case 'production':
      return process.env.MONGODB_URI;
    case 'development':
      return process.env.MONGO_DEV_URI;
    case 'demo':
      return process.env.MONGO_DEMO_URI;
    default:
      return process.env.MONGO_DEV_URI;
  }
}

const db = mongoose.connection;
const urlEncodedParser = bodyParser.urlencoded({ extended: false });
db.on('error', () => console.error('Error'));
db.once('open', () => {
  console.log(`Database ${databaseName} connected...`);
});

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json(), urlEncodedParser);
app.use(cookieParser(jwtSecret));

// Authentication
app.post('/api/auth/register', userAuth.registerPlayer);
app.post('/api/auth/login', userAuth.loginPlayer);
app.get('/api/auth/logout', userAuth.logoutPlayer);
app.get('/api/auth/player', userAuth.checkPlayer);

// Players
app.post('/api/players', player.add);
app.get('/api/players', player.list);
app.get('/api/players/stats/:id', player.stats);
app.put('/api/players/:id', player.update);

// Tournaments
app.post('/api/tournaments', tournament.add);
app.get('/api/tournaments/complete/:id', tournament.finalize);
app.get('/api/tournaments/:id', tournament.show);
app.get('/api/tournaments', tournament.list);
app.put('/api/tournaments/:id', tournament.update);
app.delete('/api/tournaments/:id', tournament.cancel);

// Games
app.post('/api/games', game.add);
app.get('/api/games', game.list);
app.get('/api/games/:id', game.getOne);
app.delete('/api/tournaments/:tid/game/:gid', game.delete);

//fix login auth and blank page
if (process.env.NODE_ENV === 'production') {
  const root = require('path').join(__dirname, 'client', 'build');
  app.use(express.static(root));
  app.get('*', (req, res) => {
    res.sendFile('index.html', { root });
  });
} else {
  app.get('/', (req, res) => {
    res.send('API running');
  });
}

app.listen(PORT, () => {
  console.log(`Serving on port ${PORT}`);
});

authRoute.js

const catchAsync = require('../utils/catchAsync');
const jwt = require('jsonwebtoken');
const { promisify } = require('util');

const signToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });
};

const createPlayerToken = async (player, code, req, res) => {
  const token = signToken(player._id);

  let d = new Date();
  d.setDate(d.getDate() + 30);

  res.cookie('jwt_token', token, {
    expires: d,
    httpOnly: true,
    secure:
      req.secure ||
      req.headers['x-forwarded-proto'] === 'https' ||
      req.headers['x-forwarded-proto'] === 'http',
    sameSite: 'none',
  });

  player.password = undefined;
  res.status(code).json({
    status: 'success',
    token,
    data: {
      player,
    },
  });
};

exports.registerPlayer = async (req, res, next) => {
  try {
    let { username, password, passwordCheck, fullname } = req.body;
    if (!username || !password || !passwordCheck)
      return res.status(400).json({ msg: 'Not all fields have been entered.' });

    if (password !== passwordCheck) {
      return res
        .status(400)
        .json({ msg: 'Enter the same password twice for verification.' });
    }

    if (!fullname) {
      fullname = username;
    }

    const newPlayer = await Player.create({
      fullname: fullname,
      username: username,
      password: password,
      passwordCheck: passwordCheck,
    });
    createPlayerToken(newPlayer, 201, req, res);
  } catch (err) {
    console.log(err);
    next(err);
  }
};

exports.loginPlayer = catchAsync(async (req, res, next) => {
  const { username, password } = req.body;

  if (!username || !password) {
    return res
      .status(400)
      .send({ msg: 'Please provide a username and password!' });
  }

  const player = await Player.findOne({ username }).select('+password');
  let correctPassword;
  if (player) {
    correctPassword = await player.correctPassword(password, player.password);
  }
  if (!player || !correctPassword) {
    return res.status(401).send({ msg: 'Incorrect username or password' });
  }
  createPlayerToken(player, 200, req, res);
});

exports.checkPlayer = catchAsync(async (req, res, next) => {
  let currentPlayer;
  if (req.cookies.jwt_token) {
    const token = req.cookies.jwt_token;
    const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
    currentPlayer = await Player.findById(decoded.id);
  } else {
    currentPlayer = null;
  }
  res.status(200).send({ currentPlayer });
});
//log user out
exports.logoutPlayer = catchAsync(async (req, res) => {
  res.cookie('jwt_token', 'loggedout', {
    expires: new Date(Date.now() + 10 * 1000),
    httpOnly: true,
  });
  res.status(200).send('user is logged out');
});


问:
Would it be possible to create a “DIY Anaconda” by just installing all of its libraries to a venv?
I’ll be using Anaconda for university and I dislike how bloated it feels having it on my system. From what I can tell, Anaconda is basically just Python prepackaged with a lot of libraries for data science. Would it be possible for me to just install all of the libraries to a venv? If so, where could I find a list of the libraries?

Sorry if I’m misunderstanding Anaconda by the way :)

答: Miniconda is a minimal version of Anaconda where you can install packages as needed instead of having them all included by default.</p>


问:
Elastic search multiple field match query with condition and boost
I have one field in my elastic search which is visibility_boosters which has two properties country_id and booster_rate.

I want to apply multi match query with these two fields (country_id and booster_rate).

country_id is dynamic and Visibility booster criteria are as below :

0 % => 0 | 5 %  => +2 | 10 % => +4 | 15 % => +6 | 20 % => +8

Like if visibility booster is 5% then boost will be 2, if visibility booster is 10% then boost will be 4.

If both field matched based on that I want to boost that doc.

I have tried below solution but does not work for me.

My Query :

```<code>if ($country && $country != null) {
            $params['body']['query']['bool']['should'][] = [
                "bool" => [
                    "must" => [
                        [ "match" => [ "visibility_boosters.country_id" => $country->id ] ],
                        [ "match" => [ "visibility_boosters.booster_rate" => 5 ] ],
                    ],
                    "boost" => 2.0
                ]
            ];
            $params['body']['query']['bool']['should'][] = [
                "bool" => [
                    "must" => [
                        [ "match" => [ "visibility_boosters.country_id" => $country->id ] ],
                        [ "match" => [ "visibility_boosters.booster_rate" => 10 ] ],
                    ],
                    "boost" => 4.0
                ]
            ];
            $params['body']['query']['bool']['should'][] = [
                "bool" => [
                    "must" => [
                        [ "match" => [ "visibility_boosters.country_id" => $country->id ] ],
                        [ "match" => [ "visibility_boosters.booster_rate" => 15 ] ],
                    ],
                    "boost" => 6.0
                ]
            ];
            $params['body']['query']['bool']['should'][] = [
                "bool" => [
                    "must" => [
                        [ "match" => [ "visibility_boosters.country_id" => $country->id ] ],
                        [ "match" => [ "visibility_boosters.booster_rate" => 20 ] ],
                    ],
                    "boost" => 8.0
                ]
            ];
        }
</code>```

These query applies to only one match query, if one query match then it is boosting the doc. I want that if both condition matched then based on visibility criteria boost that doc.

答:
The best way to get the query is right behind the Kibana search.
Do to Kibana discover, and select your index.
Add filters with conditions you require. you can also add search patterns for the required data and click Refresh. Once your data is showed in page, Go to Inspect in top right corner. Go to Request. Look for query in JSON format, You get the query you wanted, and use it wherever u need for API or other integrated systems.</p>

Body:
I have one field in my elastic search which is visibility_boosters which has two properties country_id and booster_rate.

I want to apply multi match query with these two fields (country_id and booster_rate).

country_id is dynamic and Visibility booster criteria are as below :

0 % => 0 | 5 %  => +2 | 10 % => +4 | 15 % => +6 | 20 % => +8

Like if visibility booster is 5% then boost will be 2, if visibility booster is 10% then boost will be 4.

If both field matched based on that I want to boost that doc.

I have tried below solution but does not work for me.

My Query :

if ($country && $country != null) {
            $params['body']['query']['bool']['should'][] = [
                "bool" => [
                    "must" => [
                        [ "match" => [ "visibility_boosters.country_id" => $country->id ] ],
                        [ "match" => [ "visibility_boosters.booster_rate" => 5 ] ],
                    ],
                    "boost" => 2.0
                ]
            ];
            $params['body']['query']['bool']['should'][] = [
                "bool" => [
                    "must" => [
                        [ "match" => [ "visibility_boosters.country_id" => $country->id ] ],
                        [ "match" => [ "visibility_boosters.booster_rate" => 10 ] ],
                    ],
                    "boost" => 4.0
                ]
            ];
            $params['body']['query']['bool']['should'][] = [
                "bool" => [
                    "must" => [
                        [ "match" => [ "visibility_boosters.country_id" => $country->id ] ],
                        [ "match" => [ "visibility_boosters.booster_rate" => 15 ] ],
                    ],
                    "boost" => 6.0
                ]
            ];
            $params['body']['query']['bool']['should'][] = [
                "bool" => [
                    "must" => [
                        [ "match" => [ "visibility_boosters.country_id" => $country->id ] ],
                        [ "match" => [ "visibility_boosters.booster_rate" => 20 ] ],
                    ],
                    "boost" => 8.0
                ]
            ];
        }

These query applies to only one match query, if one query match then it is boosting the doc. I want that if both condition matched then based on visibility criteria boost that doc.


问:
can't interact with popup chrome extention using Selenium in Python
I'm writing a script to automate a task on chrome,I'm using Python and Selenium,the problem is that the task requires clicking on a button in a chrome extension popup to finish the task but I can't initiate the click() class on a chrome extension popup using selenium.

Do you have any idea on how we can solve such a problem ?

答:
Alright, since no one answered my question I will answer how I solved this issue
all  I did is that I used the Pynput library to interact with the chrome extension by simulating keyboard clicks.
to toggle between pages and elements I had to use the Tab button which converts to
keyboard = Controller() keyboard.press(Key,tab) keyoard.release(Key,tab)
in python code and added some delay between each activity so it can run smoothly without any issues.
it might not be the best solution but at least it works now


问:
Python exception handling - line number
I'm using python to evaluate some measured data. Because of many possible results it is difficult to handle or possible combinations. Sometimes an error happens during the evaluation. It is usually an index error because I get out of range from measured data.

It is very difficult to find out on which place in code the problem happened. It would help a lot if I knew on which line the error was raised. If I use following code:

```<code>try:
    result = evaluateData(data)
except Exception, err:
    print ("Error: %s.\n" % str(err))
</code>```

Unfortunately this only tells me that there is and index error. I would like to know more details about the exception (line in code, variable etc.) to find out what happened. Is it possible?

Thank you.

答:
All the solutions answer the OPs problem, however, if one is holding onto a specific error instance and the last traceback stack won't do it they will not suffice —a corner scenario example given below.

In this case, the magic attribute __traceback__ of a raised exception instance may be used. This is a system traceback object (exposed as types.TracebackType, see Types) not the module. This traceback instance behaves just one like would expect (but it is always nice to check):

```<code>from collections import deque
from typing import (List, )
errors: List[Exception] = deque([], 5)

def get_raised(error_cls: type, msg: str) -> Exception:
# for debugging, an exception instance that is not raised
# ``__traceback__`` has ``None``
    try:
        raise error_cls(msg)
    except Exception as error:
        return error

error = get_raised(NameError, 'foo')
errors.append(error)

error = get_raised(ValueError, 'bar')
errors.append(error)

try:
    raise get_raised(TypeError, 'bar')
except Exception as error:
    errors.append(error)
</code>```

Now, I can check out the first error's details:

```<code>import types

traceback = errors[0].__traceback__  # inadvisable name due to module
line_no: int = traceback.tb_lineno
frame: types.FrameType = traceback.tb_frame
previous: Union[type(None), types.TracebackType] = traceback.tb_next
filename: str = frame.f_code.co_filename
</code>```

The traceback's previous is None for the second error despite a preceding error as expected, but for the third wherein an error is raised twice it is not.

This below is just a test which makes no sense contextually. A case were it is useful if when an exception is raised in a view of a webapp (a 500 status kind of incident) that gets caught and stored for the admit to inspect akin to Setry.io (but for free). Here is a minimal example where the home page / will raise an error, that gets caught and the route errors will list them. This is using Pyramid in a very concentrated way (multifile is way better) with no logging or authentication and the error logging could be better for the admin to inspect similar to Sentry.io.

```<code>from pyramid.config import Configurator
from waitress import serve
from collections import deque
# just for typehinting:
from pyramid.request import Request
from pyramid.traversal import DefaultRootFactory
from pyramid.router import Router
import types
from typing import (List, )

def home_view(context: DefaultRootFactory, request: Request) -> dict:
    raise NotImplementedError('I forgot to fill this')
    return {'status': 'ok'}  # never reached.

def caught_view(error: Exception, request: Request) -> dict:
    """
    Exception above is just type hinting.
    This is controlled by the context argument in
    either the ``add_exception_view`` method of config,
    or the ``exception_view_config`` decorator factory (callable class)
    """
    # this below is a simplification as URLDecodeError is an attack (418)
    request.response.status = 500
    config.registry.settings['error_buffer'].append(error)
    #logging.exception(error) # were it set up.
    #slack_admin(format_error(error))  # ditto
    return {'status': 'error',  'message': 'The server crashed!!'}

def format_error(error: Exception) -> str:
    traceback = error.__traceback__  # inadvisable name due to module
    frame: types.FrameType = traceback.tb_frame
    return f'{type(error).__name__}: {error}' +\
           f'at line {traceback.tb_lineno} in file {frame.f_code.co_filename}'

def error_view(context: DefaultRootFactory, request: Request) -> dict:
    print(request.registry.settings['error_buffer'])
    return {'status': 'ok',
            'errors':list(map(format_error, request.registry.settings['error_buffer']))
           }

with Configurator(settings=dict()) as config:
    config.add_route('home', '/')
    config.add_route('errors', '/errors')
    config.add_view(home_view, route_name='home', renderer='json')
    config.add_view(error_view, route_name='errors', renderer='json')
    config.add_exception_view(caught_view, context=Exception, renderer='json')
    config.registry.settings['error_buffer']: List[Exception] = deque([], 5)
    # not in config.registry.settings, not JSON serialisable
    # config.add_request_method
    app  : Router = config.make_wsgi_app()

port = 6969
serve(app, port=port)
</code>```

Title: Python exception handling - line number

Body:
I'm using python to evaluate some measured data. Because of many possible results it is difficult to handle or possible combinations. Sometimes an error happens during the evaluation. It is usually an index error because I get out of range from measured data.

It is very difficult to find out on which place in code the problem happened. It would help a lot if I knew on which line the error was raised. If I use following code:

try:
    result = evaluateData(data)
except Exception, err:
    print ("Error: %s.\n" % str(err))

Unfortunately this only tells me that there is and index error. I would like to know more details about the exception (line in code, variable etc.) to find out what happened. Is it possible?

Thank you.

Body:
All the solutions answer the OPs problem, however, if one is holding onto a specific error instance and the last traceback stack won't do it they will not suffice —a corner scenario example given below.

In this case, the magic attribute __traceback__ of a raised exception instance may be used. This is a system traceback object (exposed as types.TracebackType, see Types) not the module. This traceback instance behaves just one like would expect (but it is always nice to check):

from collections import deque
from typing import (List, )
errors: List[Exception] = deque([], 5)

def get_raised(error_cls: type, msg: str) -> Exception:
# for debugging, an exception instance that is not raised
# ``__traceback__`` has ``None``
    try:
        raise error_cls(msg)
    except Exception as error:
        return error

error = get_raised(NameError, 'foo')
errors.append(error)

error = get_raised(ValueError, 'bar')
errors.append(error)

try:
    raise get_raised(TypeError, 'bar')
except Exception as error:
    errors.append(error)

Now, I can check out the first error's details:

import types

traceback = errors[0].__traceback__  # inadvisable name due to module
line_no: int = traceback.tb_lineno
frame: types.FrameType = traceback.tb_frame
previous: Union[type(None), types.TracebackType] = traceback.tb_next
filename: str = frame.f_code.co_filename

The traceback's previous is None for the second error despite a preceding error as expected, but for the third wherein an error is raised twice it is not.

This below is just a test which makes no sense contextually. A case were it is useful if when an exception is raised in a view of a webapp (a 500 status kind of incident) that gets caught and stored for the admit to inspect akin to Setry.io (but for free). Here is a minimal example where the home page / will raise an error, that gets caught and the route errors will list them. This is using Pyramid in a very concentrated way (multifile is way better) with no logging or authentication and the error logging could be better for the admin to inspect similar to Sentry.io.

from pyramid.config import Configurator
from waitress import serve
from collections import deque
# just for typehinting:
from pyramid.request import Request
from pyramid.traversal import DefaultRootFactory
from pyramid.router import Router
import types
from typing import (List, )

def home_view(context: DefaultRootFactory, request: Request) -> dict:
    raise NotImplementedError('I forgot to fill this')
    return {'status': 'ok'}  # never reached.

def caught_view(error: Exception, request: Request) -> dict:
    """
    Exception above is just type hinting.
    This is controlled by the context argument in
    either the ``add_exception_view`` method of config,
    or the ``exception_view_config`` decorator factory (callable class)
    """
    # this below is a simplification as URLDecodeError is an attack (418)
    request.response.status = 500
    config.registry.settings['error_buffer'].append(error)
    #logging.exception(error) # were it set up.
    #slack_admin(format_error(error))  # ditto
    return {'status': 'error',  'message': 'The server crashed!!'}

def format_error(error: Exception) -> str:
    traceback = error.__traceback__  # inadvisable name due to module
    frame: types.FrameType = traceback.tb_frame
    return f'{type(error).__name__}: {error}' +\
           f'at line {traceback.tb_lineno} in file {frame.f_code.co_filename}'

def error_view(context: DefaultRootFactory, request: Request) -> dict:
    print(request.registry.settings['error_buffer'])
    return {'status': 'ok',
            'errors':list(map(format_error, request.registry.settings['error_buffer']))
           }

with Configurator(settings=dict()) as config:
    config.add_route('home', '/')
    config.add_route('errors', '/errors')
    config.add_view(home_view, route_name='home', renderer='json')
    config.add_view(error_view, route_name='errors', renderer='json')
    config.add_exception_view(caught_view, context=Exception, renderer='json')
    config.registry.settings['error_buffer']: List[Exception] = deque([], 5)
    # not in config.registry.settings, not JSON serialisable
    # config.add_request_method
    app  : Router = config.make_wsgi_app()

port = 6969
serve(app, port=port)


问:
Flutter/Dart how to check key in multidimensional json exists or not
I get response json like this from server :

```<code>{
  gender": {
    "label": "Wanita"
  }
}
</code>```

but sometime i get response like this :

```<code>{
  gender": []
}
</code>```

how to handle if key "label" in gender not exist?

答:
After parsing the server response into a Dart map by using something like jsonDecode provided by the native dart:convert package, you should be able to check the type of the value with the particular key. As you stated, the response will be a list instead of a map if there is no label key, therefore this should do the trick.

import 'dart:convert';

Map response = jsonDecode(rawResponse);

if(response['gender'] is List) {
    print('no label');
}
```
<p>In case it returns an empty object, you would check if the key exists in the corresponding object like</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:convert';

Map response = jsonDecode(rawResponse);

if(response['gender'].containsKey('label')) {
    print('has label');
}
</code>```

Body:
I get response json like this from server :

{
  gender": {
    "label": "Wanita"
  }
}

but sometime i get response like this :

{
  gender": []
}

how to handle if key "label" in gender not exist?

Body:
After parsing the server response into a Dart map by using something like jsonDecode provided by the native dart:convert package, you should be able to check the type of the value with the particular key. As you stated, the response will be a list instead of a map if there is no label key, therefore this should do the trick.

import 'dart:convert';

Map response = jsonDecode(rawResponse);

if(response['gender'] is List) {
    print('no label');
}

In case it returns an empty object, you would check if the key exists in the corresponding object like

import 'dart:convert';

Map response = jsonDecode(rawResponse);

if(response['gender'].containsKey('label')) {
    print('has label');
}


问:
WPF Styles in a BASE class
I am working in WPF .Net 6 I have a Master.exe application and many DLLs, each of which contains functionality for every entity: Customers.dll | Bookings.dll | Vehicles.dll etc.  In the each DLL I have WPF/XAML windows, view models, models, etc like a mini complete and isolated application.

I have also created a Base.dll that has the abstract classes that the models and viewmodels inherit.  This works fine for a bit of shared code among all the dlls.

Similarly I want a one stop shop for uniform styling across all of the XAML windows.

The question now is; can I have XAML resources and styles in the Base.dll that are used by  all the XAML windows in the other dlls?

答:
Sure. Create a WPF Custom Control Library project and define your common XAML resources in one or several resource dictionaries in this project, e.g.:

```<code><!-- Dictionary1.xaml in WpfControlLibrary1.dll: -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="CommonBrush" Color="Red" />
</ResourceDictionary>
</code>```

Then add a reference to this project from the project where you intend to use the common resources and merge the resource dictionary:

```<code><ResourceDictionary>
    <Style x:Key="ButtonStyle" TargetType="Button">
        <Setter Property="Foreground" Value="{StaticResource CommonBrush}" />
    </Style>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/WpfControlLibrary1;component/Dictionary1.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</code>```

Title: WPF Styles in a BASE class

Body:
Sure. Create a WPF Custom Control Library project and define your common XAML resources in one or several resource dictionaries in this project, e.g.:

<!-- Dictionary1.xaml in WpfControlLibrary1.dll: -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="CommonBrush" Color="Red" />
</ResourceDictionary>

Then add a reference to this project from the project where you intend to use the common resources and merge the resource dictionary:

<ResourceDictionary>
    <Style x:Key="ButtonStyle" TargetType="Button">
        <Setter Property="Foreground" Value="{StaticResource CommonBrush}" />
    </Style>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/WpfControlLibrary1;component/Dictionary1.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>


问:
How to convert curl request to HttpClient
I have a curl request that looks like this:

```<code>curl -i -XPOST 'http://my_url:port/write?db=myDb' -u user:xxxxx --data-binary 'FieldName,host=M.233 value=52.666 timestamp'
</code>```

I'm trying to post this request using HttpClient. I'm not sure how exactly I should call it. This is what I tried to do:

```<code>public async void  TestHttpClient()
{
    var client = new HttpClient();
    var credentials = Encoding.ASCII.GetBytes("user:xxxxx");
    var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
    client.DefaultRequestHeaders.Authorization = header;
    client.BaseAddress = new Uri("http://my_url:port/write?db=myDb");
    var result = await client.PostAsync(..);
}
</code>```

Which parameters should I write for PostAsync()?

How to convert --data-binary and FieldName,host=M.233 value=52.666 timestamp from curl to HttpClient?

答:
To get pass the --data-binary flag I did have to add Content-Transfer-Encoding to request content header, see following example:

curl:

```<code>curl -v -X POST \
    -H "Authorization: Bearer token" \
    --header "Content-Type: application/json" \
    --data-binary "@example.json" \
    https://example.com/data
</code>```

C#:

```<code>using var httpClient = new HttpClient
{
    BaseAddress = "https://example.com/"
};
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
const string Uri = "data";
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); // In case data is json (ex: --header "Content-Type: application/json"):
stringContent.Headers.Add("Content-Transfer-Encoding", "binary"); // For data-binary flag: --data-binary "@example.json"
var request = new HttpRequestMessage(HttpMethod.Post, Uri) { Content = stringContent };
var response = await httpClient.SendAsync(request, cancellationToken);
</code>```

Body:
I have a curl request that looks like this:

curl -i -XPOST 'http://my_url:port/write?db=myDb' -u user:xxxxx --data-binary 'FieldName,host=M.233 value=52.666 timestamp'

I'm trying to post this request using HttpClient. I'm not sure how exactly I should call it. This is what I tried to do:

public async void  TestHttpClient()
{
    var client = new HttpClient();
    var credentials = Encoding.ASCII.GetBytes("user:xxxxx");
    var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
    client.DefaultRequestHeaders.Authorization = header;
    client.BaseAddress = new Uri("http://my_url:port/write?db=myDb");
    var result = await client.PostAsync(..);
}

Which parameters should I write for PostAsync()?

How to convert --data-binary and FieldName,host=M.233 value=52.666 timestamp from curl to HttpClient?

Body:
To get pass the --data-binary flag I did have to add Content-Transfer-Encoding to request content header, see following example:

curl:

curl -v -X POST \
    -H "Authorization: Bearer token" \
    --header "Content-Type: application/json" \
    --data-binary "@example.json" \
    https://example.com/data

C#:

using var httpClient = new HttpClient
{
    BaseAddress = "https://example.com/"
};
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
const string Uri = "data";
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); // In case data is json (ex: --header "Content-Type: application/json"):
stringContent.Headers.Add("Content-Transfer-Encoding", "binary"); // For data-binary flag: --data-binary "@example.json"
var request = new HttpRequestMessage(HttpMethod.Post, Uri) { Content = stringContent };
var response = await httpClient.SendAsync(request, cancellationToken);


问:
Trying to do a flutter pub get and got Process finished with exit code 66
```<code>Running "flutter pub get" in mobile...
Because mobile depends on charts_flutter from path which doesn't exist (could not find package charts_flutter at "../mobile-dependencies/pub.dartlang.org/charts_flutter-0.12.0"), version solving failed.
pub get failed (66; Because mobile depends on charts_flutter from path which doesn't exist (could not find package charts_flutter at "../mobile-dependencies/pub.dartlang.org/charts_flutter-0.12.0"), version solving failed.)
Process finished with exit code 66

/Users/H025712/development/flutter/bin/flutter --no-color pub get
Running "flutter pub get" in mobile...
Because mobile depends on charts_flutter from path which doesn't exist (could not find package charts_flutter at "../mobile-dependencies/pub.dartlang.org/charts_flutter-0.12.0"), version solving failed.
pub get failed (66; Because mobile depends on charts_flutter from path which doesn't exist (could not find package charts_flutter at "../mobile-dependencies/pub.dartlang.org/charts_flutter-0.12.0"), version solving failed.)
</code>```

答: Check your pubspec.yaml is well ordered, I had badly composed dev_dependencies and it failed me