问:
Hovering data as a text, in inside container
My query is that in my homepage, I want that only daily percent change and
market capitalisation seen on this child container. Hovering data should
only appear as a hover here but not as a printed text like daily percent change, market capitalisation. when I click on this child container,
complete hovering data must appear as a text.

```<code>import dash
import dash_core_components as dcc
from dash import dcc

PATH = ['Sector','Symbol']
HOVER_DATA = ['Name','Country','Currency','Market Capitalization', 'Quarterly Earnings GrowthYOY','Quarterly Revenue GrowthYOY','dailyChange']
value_attribute = 'Market Capitalization']
Country_option = ["India","Australia","USA"]
Hover_Tmp = '<br>Name:%{customdata[0]}'+'<br>Country:%{customdata[1]}'+'<br>Currency:%{customdata[2]}'+'<br>Daily Change: %{customdata[14]}%'+'<br>Market Capitalization:%{value:0.3s}'+'<br>Most Recent Quarter:%{customdata[4]}' +'<br>PE Ratio:%{customdata[5]}%'+'<br>PEG Ratio:%{customdata[6]}%'+'<br>

color_scale = "#32a870", "#cc1819"
input_date = '2022-10-21'

df = pd.read_csv(Data_source,Most Recent Quarter','PE Ratio%','PEG Ratio%','Earnings Share','Dividend Yield','Operating Margin TTM','Return OnAssets TTM','Return OnEquity TTM','Quarterly Earnings GrowthYOY','Quarterly Revenue GrowthYOY','dailyChange','date','Sector','Symbol','DailyChangeTreeMap', 'Condition','Description'])

df['Symbol'] = df['Symbol'].apply(lambda item: link_ref.format(item, item, "{}"))

df = pd.DataFrame(df)

def filter_df(input_date,country_name):
    input_date = datetime.strptime (str(input_date), '%Y-%m-%d')
    df['date'] = pd.to_datetime(df['date'])
    df.fillna(0, inplace=True)

    if country_name:
        df2 = df[(df['date'] == input_date) & (df['Country']==country_name)]
    else:
        df2 = df
    return df2

def create_dropdown(option, id_value):
    return html.Div(
        [dcc.Dropdown(id=id_value, options=option, value=option[0], style = {} ),],
    )

        html.Div(

        print("NOT EMPTY")
        indicator = px.treemap(filtered_df,
                    color=COLOR,
                    color_continuous_scale=color_discrete_map,
                    # path = PATH,
                    path = ['Sector','Symbol','dailyChange',],
                    maxdepth=3,
                    hover_data=HOVER_DATA,

                    custom_data=HOVER_DATA,
                    color_discrete_map=color_discrete_map)

        indicator.update_traces(textfont_size=22,)
</code>```

This is the screenshot of my homepage

I don't want hovering data on this container as a text

I want this hovering data as a text in this inside container

Body:
My query is that in my homepage, I want that only daily percent change and
market capitalisation seen on this child container. Hovering data should
only appear as a hover here but not as a printed text like daily percent change, market capitalisation. when I click on this child container,
complete hovering data must appear as a text.

import dash
import dash_core_components as dcc
from dash import dcc

PATH = ['Sector','Symbol']
HOVER_DATA = ['Name','Country','Currency','Market Capitalization', 'Quarterly Earnings GrowthYOY','Quarterly Revenue GrowthYOY','dailyChange']
value_attribute = 'Market Capitalization']
Country_option = ["India","Australia","USA"]
Hover_Tmp = '
Name:%{customdata[0]}'+'
Country:%{customdata[1]}'+'
Currency:%{customdata[2]}'+'
Daily Change: %{customdata[14]}%'+'
Market Capitalization:%{value:0.3s}'+'
Most Recent Quarter:%{customdata[4]}' +'
PE Ratio:%{customdata[5]}%'+'
PEG Ratio:%{customdata[6]}%'+'

color_scale = "#32a870", "#cc1819"
input_date = '2022-10-21'

df = pd.read_csv(Data_source,Most Recent Quarter','PE Ratio%','PEG Ratio%','Earnings Share','Dividend Yield','Operating Margin TTM','Return OnAssets TTM','Return OnEquity TTM','Quarterly Earnings GrowthYOY','Quarterly Revenue GrowthYOY','dailyChange','date','Sector','Symbol','DailyChangeTreeMap', 'Condition','Description'])

df['Symbol'] = df['Symbol'].apply(lambda item: link_ref.format(item, item, "{}"))

df = pd.DataFrame(df)

def filter_df(input_date,country_name):
    input_date = datetime.strptime (str(input_date), '%Y-%m-%d')
    df['date'] = pd.to_datetime(df['date'])
    df.fillna(0, inplace=True)

    if country_name:
        df2 = df[(df['date'] == input_date) & (df['Country']==country_name)]
    else:
        df2 = df
    return df2

def create_dropdown(option, id_value):
    return html.Div(
        [dcc.Dropdown(id=id_value, options=option, value=option[0], style = {} ),],
    )

        html.Div(

        print("NOT EMPTY")
        indicator = px.treemap(filtered_df,
                    color=COLOR,
                    color_continuous_scale=color_discrete_map,
                    # path = PATH,
                    path = ['Sector','Symbol','dailyChange',],
                    maxdepth=3,
                    hover_data=HOVER_DATA,

                    custom_data=HOVER_DATA,
                    color_discrete_map=color_discrete_map)

        indicator.update_traces(textfont_size=22,)

This is the screenshot of my homepage

I don't want hovering data on this container as a text

I want this hovering data as a text in this inside container


来源: stackexchange

问:
How to remove image plugin from Ckeditor4 in vuejs code
I am trying to remove the image plugin from ckeditor4 in my vue code below is the code.

```<code><ckeditor v-model="description" :config="editorConfig" name="description"></ckeditor>

import CKEditor from 'ckeditor4-vue';

export default {

components: { ckeditor: CKEditor.component },

data: () => ({
formData : {

    description : "",

},

editorConfig: {

    removePlugins: [['Image']]

}

}),
}
</code>```

but the image plugin is not being removed from my ckeditor. I want to keep all other plugins as it is.
kindly suggest the correct way.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to remove the image plugin from ckeditor4 in my vue code below is the code.

<ckeditor v-model="description" :config="editorConfig" name="description"></ckeditor>

import CKEditor from 'ckeditor4-vue';

export default {

components: { ckeditor: CKEditor.component },

data: () => ({
formData : {

    description : "",

},

editorConfig: {

    removePlugins: [['Image']]

}

}),
}

but the image plugin is not being removed from my ckeditor. I want to keep all other plugins as it is.
kindly suggest the correct way.


问:
Exclamation point usage in C# (not equality operator)
I am going through a Udemy tutorial on .NET WebAPI/Entity Framework and the instructor has used exclamation mark syntax I have never seen before. He doesn't explain it, and I am struggling to find an explanation online.

Can anyone fill me in on what these exclamation marks are accomplishing here? I've only used them as equality operators (e.g., "!=" for "not equal to"), but this seems to be something else entirely:

example 1 (before ".User" and after "NameIdentifier)":

```<code>private int GetCurrentUserId() => int.Parse(_httpContextAccessor.HttpContext!.User
            .FindFirstValue(ClaimTypes.NameIdentifier)!);
</code>```

Example two (after "SubmittedBy"):

.Where(i => i.SubmittedBy!.Id == GetCurrentUserId())

I tried omitting the exclamation marks and my requests worked just the same (tested w/ Swagger). I googled my question a few different ways, but couldn't find a phrasing that returned useful results. I hunted down Microsoft's "C# operators and expressions" documentation, but didn't see an explanation of it there.

Body:
I am going through a Udemy tutorial on .NET WebAPI/Entity Framework and the instructor has used exclamation mark syntax I have never seen before. He doesn't explain it, and I am struggling to find an explanation online.

Can anyone fill me in on what these exclamation marks are accomplishing here? I've only used them as equality operators (e.g., "!=" for "not equal to"), but this seems to be something else entirely:

example 1 (before ".User" and after "NameIdentifier)":

private int GetCurrentUserId() => int.Parse(_httpContextAccessor.HttpContext!.User
            .FindFirstValue(ClaimTypes.NameIdentifier)!);

Example two (after "SubmittedBy"):

.Where(i => i.SubmittedBy!.Id == GetCurrentUserId())

I tried omitting the exclamation marks and my requests worked just the same (tested w/ Swagger). I googled my question a few different ways, but couldn't find a phrasing that returned useful results. I hunted down Microsoft's "C# operators and expressions" documentation, but didn't see an explanation of it there.


问:
Can I add a cancel action to iOS keyboard input on Safari?
I have an input field on a webpage. When I'm editing it on iOS, it displays with a "Done" button that submits the input field.

I would like to also display a Cancel action that is similar to an escape key.


问:
Getting the same user in print(user_id)?
Trying to authenticate is seeing what user is currently logged in. I tried authenticating with a different spotify account but I still get mine. Not sure why. I am getting the token info after the user authenticates and get who the current user is but it always results in the same user even if I try to authenticate with a different one.</p>
```<code>from flask import Flask, jsonify, redirect, request, session
from flask_cors import CORS, cross_origin
from flask_session import Session
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import os
from dotenv import load_dotenv
import time
import redis

# load environment variables
load_dotenv()

# run flask app and set up cors
app = Flask(__name__)
# generate random secret key
app.config['SECRET_KEY'] = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = 60 * 60 * 24 * 7
r = redis.Redis(host='localhost', port=6379, db=0)
CORS(app)

# sets up user credentials for spotify api
client_id = os.getenv("SPOTIFY_CLIENT_ID")
client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
redirect_uri = os.getenv("SPOTIFY_REDIRECT_URI")

# get all scopes
scopes = 'user-read-recently-played'

# authenticates user and sends react app to url
@app.route('/authenticate', methods=['GET'])
def authenticate_user():
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, scope=scopes, show_dialog=True)
    auth_url = sp_oauth.get_authorize_url()
    return jsonify({'url': auth_url})

# gets access token from spotify api
@app.route('/callback')
def callback():
    session.clear()
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, scope=scopes)
    code = request.args.get('code')
    token_info = sp_oauth.get_access_token(code)
    sp = spotipy.Spotify(auth=token_info['access_token'])
    user = sp.current_user()
    user_id = user['id']
    print(user_id)
    return redirect('http://localhost:3000/')

if __name__ == '__main__':
    app.run(host='localhost', port=5000, debug=True)
</code>```
```<code>
</code>```

Body:
Trying to authenticate is seeing what user is currently logged in. I tried authenticating with a different spotify account but I still get mine. Not sure why. I am getting the token info after the user authenticates and get who the current user is but it always results in the same user even if I try to authenticate with a different one.

from flask import Flask, jsonify, redirect, request, session
from flask_cors import CORS, cross_origin
from flask_session import Session
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import os
from dotenv import load_dotenv
import time
import redis

# load environment variables
load_dotenv()

# run flask app and set up cors
app = Flask(__name__)
# generate random secret key
app.config['SECRET_KEY'] = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = 60 * 60 * 24 * 7
r = redis.Redis(host='localhost', port=6379, db=0)
CORS(app)

# sets up user credentials for spotify api
client_id = os.getenv("SPOTIFY_CLIENT_ID")
client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
redirect_uri = os.getenv("SPOTIFY_REDIRECT_URI")

# get all scopes
scopes = 'user-read-recently-played'

# authenticates user and sends react app to url
@app.route('/authenticate', methods=['GET'])
def authenticate_user():
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, scope=scopes, show_dialog=True)
    auth_url = sp_oauth.get_authorize_url()
    return jsonify({'url': auth_url})

# gets access token from spotify api
@app.route('/callback')
def callback():
    session.clear()
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, scope=scopes)
    code = request.args.get('code')
    token_info = sp_oauth.get_access_token(code)
    sp = spotipy.Spotify(auth=token_info['access_token'])
    user = sp.current_user()
    user_id = user['id']
    print(user_id)
    return redirect('http://localhost:3000/')

if __name__ == '__main__':
    app.run(host='localhost', port=5000, debug=True)


问:
Mysql connector for python dosent add data into table
The code runs with no errors but doesn't add the data to the table.

db = MySQLdb.connect(host="localhost",
   user="user",
   passwd="pass",
   db="database",
   autocommit=True)
def welcome_new_user():
    pass1 = input("Enter your master password")
    pass2 = input("Enter your master password again")
    if pass1 == pass2:
        cursor.execute("INSERT INTO MasterPass(masterpassword) VALUES (%s)", [pass1])
    else:
        print("Passwords don't match")

x = cursor.execute("SELECT * from MasterPass ")
if x == None:
    print("nope")
    welcome_new_user()
```

it prints pass added but the table still remains empty

Body:
The code runs with no errors but doesn't add the data to the table.

db = MySQLdb.connect(host="localhost",
   user="user",
   passwd="pass",
   db="database",
   autocommit=True)
def welcome_new_user():
    pass1 = input("Enter your master password")
    pass2 = input("Enter your master password again")
    if pass1 == pass2:
        cursor.execute("INSERT INTO MasterPass(masterpassword) VALUES (%s)", [pass1])
    else:
        print("Passwords don't match")

x = cursor.execute("SELECT * from MasterPass ")
if x == None:
    print("nope")
    welcome_new_user()

it prints pass added but the table still remains empty


问:
Including blank lines following region in fold
I'm currently attempting to improve the folding behavior of Matlab files in Vim. I have a syntax file generated and the folding behaves as I want with one exception. Say I have the following code:

```<code>function [out1,out2] = doSomething(arg1,arg2)
    out1 = performSubRoutine(arg1);
    out2 = performSubRoutine(arg2);
end

function output = performSubRoutine(input)
    output = input;
end
</code>```

When I perform the folding I get:

```<code>+---  4 lines: function [out1,out2] = doSomething(arg1,arg2)

+---  3 lines: function output = performSubRoutine(input)
</code>```

Ideally, I would like to have the fold engulf any trailing whitespace.

My region definition from the syntax file is:

```<code>syn region matlabClassBlock
            \transparent fold
            \matchgroup=matlabClass
            \extend start='\<function\>'
            \end='\%([%-+(\*\:(\/\[]\s*\)\@<!\<end\>\%(\s*[-+}\:\*\/()\]]\)\@!.*\($\n^\s*\)*$'re=e
            \contains=ALLBUT,@matlabClassCluster,@matlabProceduralCluster
</code>```

I used the offset specifier "re=e" to say that I want to fold to the end of the match, but I still get the first result.

I must be missing something, because the documentation states that the offset method should work. Any ideas?

ContentLicense: CC BY-SA 3.0

Body:
I'm currently attempting to improve the folding behavior of Matlab files in Vim. I have a syntax file generated and the folding behaves as I want with one exception. Say I have the following code:

function [out1,out2] = doSomething(arg1,arg2)
    out1 = performSubRoutine(arg1);
    out2 = performSubRoutine(arg2);
end

function output = performSubRoutine(input)
    output = input;
end

When I perform the folding I get:

+---  4 lines: function [out1,out2] = doSomething(arg1,arg2)

+---  3 lines: function output = performSubRoutine(input)

Ideally, I would like to have the fold engulf any trailing whitespace.

My region definition from the syntax file is:

syn region matlabClassBlock
            \transparent fold
            \matchgroup=matlabClass
            \extend start='\<function\>'
            \end='\%([%-+(\*\:(\/\[]\s*\)\@<!\<end\>\%(\s*[-+}\:\*\/()\]]\)\@!.*\($\n^\s*\)*$'re=e
            \contains=ALLBUT,@matlabClassCluster,@matlabProceduralCluster

I used the offset specifier "re=e" to say that I want to fold to the end of the match, but I still get the first result.

I must be missing something, because the documentation states that the offset method should work. Any ideas?


问:
Metadata Lock Acquisition - RENAME TABLE multiple in MySQL

DDL statements, LOCK TABLES, and other similar statements try to
reduce the number of possible deadlocks between concurrent DDL
statements by acquiring locks on explicitly named tables in name
order.

What does Name Order mean exactly?

This RENAME TABLE statement renames tbla to something else, and
renames tblc to tbla:

```<code>    RENAME TABLE tbla TO tbld, tblc TO tbla;
</code>```

The statement acquires metadata locks, in order, on tbla, tblc, and
tbld (because tbld follows tblc in name order):

This slightly different statement also renames tbla to something else,
and renames tblc to tbla:

```<code>    RENAME TABLE tbla TO tblb, tblc TO tbla;
</code>```

In this case, the statement acquires metadata locks, in order, on
tbla, tblb, and tblc (because tblb precedes tblc in name order):

https://dev.mysql.com/doc/refman/8.0/en/metadata-locking.html

Body:
DDL statements, LOCK TABLES, and other similar statements try to
reduce the number of possible deadlocks between concurrent DDL
statements by acquiring locks on explicitly named tables in name
order.

What does Name Order mean exactly?

This RENAME TABLE statement renames tbla to something else, and
renames tblc to tbla:

    RENAME TABLE tbla TO tbld, tblc TO tbla;

The statement acquires metadata locks, in order, on tbla, tblc, and
tbld (because tbld follows tblc in name order):

This slightly different statement also renames tbla to something else,
and renames tblc to tbla:

    RENAME TABLE tbla TO tblb, tblc TO tbla;

In this case, the statement acquires metadata locks, in order, on
tbla, tblb, and tblc (because tblb precedes tblc in name order):

https://dev.mysql.com/doc/refman/8.0/en/metadata-locking.html


问:
Interchanging selected rows and columns and plot a spaghetti plot of a R dataframe
I have a R dataframe like this:

Year
Country
Car
Bike
Truck

2010
US
4342
5783
5849

2011
US
8292
4304
4839

2012
US
5839
5930
8483

I need to plot a spaghetti plot for all three types(car,bike,truck) for US. That is: Type as the legend. I understand that I need to interchange columns of Types to rows. But I am unable to do that with out interchanging Year.

In a nutshell, I think I need this kind of table to plot the spaghetti plot.

Year
Type
Country

2010
US
XXXX

2010
US
XXXX

2010
US
XXXX

2011
US
XXXX

2011
US
XXXX

2011
US
XXXX

2012
US
XXXX

2012
US
XXXX

2012
US
XXXX

Please help!


问:
Authentication when adding 3rd party auth with same email to an existing account
Are there any security risks adding 3rd party authentication (Google, FB, etc.) to existing account based on matching email without re-authentication?

Let's say user already have an account with the@email.com, but later:

decides to login/sign-up with FB OAuth which uses the same the@email.com. Should we require user to re-authenticate with existing login credentials before adding FB auth to existing account or just automatically add FB auth as another login option and login user into account?

*All websites I have used, just added 3rd Party auth to existing account with the same email and log them in automatically.

logged in user goes to account setting and choose to add e.g. Google OAuth, which may or may not have the same email address. Should there be any prompt to re-authenticate user with any existing login options attached to account?
e.g. Stackoverflow gives you ability to add Google OAuth from Settings (even with different email) and doesn't require you to authenticate or send any notification emails.


问:
Unknown label type: Continuous MULTIOUTPUT when using nearest neighbours
I am trying to build a supervised predictive ML model to predict world population, fertility, and life_expectancy for 10 random countries for the years 2017 and 2018 but get a Unknown label type: Continuous multioutput error when running the model

I have cleaned the data and prepared the data frames, applying the train_test_split function successfully. I then try to create a KN neighbors model using the sklearn algorithm but get an error.

db is the database I am using to create the model and vizinhos the number of neighbors

The first image is my K nearest algorithmand the test split

enter image description here

The second image is just how data is stored inside test_split, the function that splits the data set

enter image description here

The third image is the error and what causes it

enter image description here

Any help would be greatly appreciated!


问:
redshift immutable varchar to timestamp function
I'm creating auto refresh MV. definition of MV is like create mv newvw auto refresh yes as select col1,cast(col2 as timestamp) col2 from basetbl

col2 in basetbl is varchar
but I want col2 in newvw to be timestamp

I get error saying mutable functions not supported in autorefresh mv

any workaround/udf I can use to solve this?


问:
how to toggle hamburger menu with inside which there is a drop down in Angular 8?
``hi . When I click on the hamburger menu and it opens, when I want to click on the drop down, the menu closes, but I want the menu to remain completely fixed until I click on the hamburger menu.
so that we can open and close the dropdown easily...
**code close and open drop down list **

so that we can open and close the dropdown easily...


问:
metro.config.js customization isn’t working
I have to disable the minifier in metro.config.js, because if I build my application on iOS devices it doesn't work properly.

The development build is ok, but after I upload it to TestFlight it keeps crashing, and I can't think of anything other than the minification.

The bundling just ignores my modifications in metro.config.js, if I add anything to it, it just skips it.

The following message appears in the terminal: "Metro skipped: Project metro.config.js does not match prebuild template."

The default metro.config.js is the following (generated by: npx expo customize metro.config.js ):

```<code>// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require('expo/metro-config');

module.exports = getDefaultConfig(__dirname);

</code>```

This works flawlessly. But if i change it to this:

```<code>// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require('expo/metro-config');

const config = getDefaultConfig(__dirname);

module.exports = config;

</code>```

Then it skips the whole metro config.
Do you have any idea, why this happens?

Thanks for your help!

```<code>"dependencies": {
    "**@expo/metro-config": "^0.5.2**",
    "@expo/webpack-config": "^0.17.0",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-native-community/netinfo": "9.3.0",
    "@react-native-firebase/app": "^16.4.3",
    "@react-native-firebase/messaging": "^16.4.3",
    "@react-navigation/bottom-tabs": "^6.4.0",
    "@react-navigation/drawer": "^6.5.0",
    "@react-navigation/elements": "^1.3.6",
    "@react-navigation/material-top-tabs": "^6.3.0",
    "@react-navigation/native": "^6.0.13",
    "@react-navigation/stack": "^6.3.2",
    "axios": "^1.1.3",
    "date-fns": "^2.29.3",
    "dayjs": "^1.11.6",
    "**expo": "~46.0.19**",
    "expo-av": "~12.0.4",
    "expo-device": "~4.3.0",
    "expo-file-system": "~14.1.0",
    "expo-linking": "~3.2.2",
    "expo-localization": "~13.1.0",
    "expo-location": "~14.3.0",
    "expo-notifications": "~0.16.1",
    "expo-secure-store": "~11.3.0",
    "expo-splash-screen": "~0.16.2",
    "expo-status-bar": "~1.4.0",
    "expo-task-manager": "~10.3.0",
    "i18n-js": "^4.2.0",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "**react-native": "0.69.6**",
    "react-native-gesture-handler": "~2.5.0",
    "react-native-gifted-chat": "^1.0.4",
    "react-native-image-picker": "^4.10.0",
    "react-native-image-zoom-viewer": "^3.0.1",
    "react-native-maps": "0.31.1",
    "react-native-pager-view": "5.4.24",
    "react-native-paper": "^4.12.5",
    "react-native-reanimated": "~2.9.1",
    "react-native-reanimated-carousel": "^3.1.5",
    "react-native-safe-area-context": "4.3.1",
    "react-native-screens": "~3.15.0",
    "react-native-tab-view": "^3.3.0",
    "react-native-vector-icons": "^9.2.0",
    "react-native-web": "~0.18.7",
    "react-redux": "^8.0.5",
    "react-timer-hook": "^3.0.5",
    "redux": "^4.2.0",
    "socket.io-client": "^4.5.3",
    "use-debounce": "^8.0.4",
    "use-elapsed-time": "^3.0.4"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "babel-plugin-module-resolver": "^4.1.0"
  },
</code>```

I have tried to solve this issue based on the official documentation (https://docs.expo.dev/guides/customizing-metro/), but no modification can be accepted. The bundling process always skips the custom file.

I have already tried a lot of workaround, that I found on StackOverflow and Github.

Body:
I have to disable the minifier in metro.config.js, because if I build my application on iOS devices it doesn't work properly.

The development build is ok, but after I upload it to TestFlight it keeps crashing, and I can't think of anything other than the minification.

The bundling just ignores my modifications in metro.config.js, if I add anything to it, it just skips it.

The following message appears in the terminal: "Metro skipped: Project metro.config.js does not match prebuild template."

The default metro.config.js is the following (generated by: npx expo customize metro.config.js ):

// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require('expo/metro-config');

module.exports = getDefaultConfig(__dirname);

This works flawlessly. But if i change it to this:

// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require('expo/metro-config');

const config = getDefaultConfig(__dirname);

module.exports = config;

Then it skips the whole metro config.
Do you have any idea, why this happens?

Thanks for your help!

"dependencies": {
    "**@expo/metro-config": "^0.5.2**",
    "@expo/webpack-config": "^0.17.0",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-native-community/netinfo": "9.3.0",
    "@react-native-firebase/app": "^16.4.3",
    "@react-native-firebase/messaging": "^16.4.3",
    "@react-navigation/bottom-tabs": "^6.4.0",
    "@react-navigation/drawer": "^6.5.0",
    "@react-navigation/elements": "^1.3.6",
    "@react-navigation/material-top-tabs": "^6.3.0",
    "@react-navigation/native": "^6.0.13",
    "@react-navigation/stack": "^6.3.2",
    "axios": "^1.1.3",
    "date-fns": "^2.29.3",
    "dayjs": "^1.11.6",
    "**expo": "~46.0.19**",
    "expo-av": "~12.0.4",
    "expo-device": "~4.3.0",
    "expo-file-system": "~14.1.0",
    "expo-linking": "~3.2.2",
    "expo-localization": "~13.1.0",
    "expo-location": "~14.3.0",
    "expo-notifications": "~0.16.1",
    "expo-secure-store": "~11.3.0",
    "expo-splash-screen": "~0.16.2",
    "expo-status-bar": "~1.4.0",
    "expo-task-manager": "~10.3.0",
    "i18n-js": "^4.2.0",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "**react-native": "0.69.6**",
    "react-native-gesture-handler": "~2.5.0",
    "react-native-gifted-chat": "^1.0.4",
    "react-native-image-picker": "^4.10.0",
    "react-native-image-zoom-viewer": "^3.0.1",
    "react-native-maps": "0.31.1",
    "react-native-pager-view": "5.4.24",
    "react-native-paper": "^4.12.5",
    "react-native-reanimated": "~2.9.1",
    "react-native-reanimated-carousel": "^3.1.5",
    "react-native-safe-area-context": "4.3.1",
    "react-native-screens": "~3.15.0",
    "react-native-tab-view": "^3.3.0",
    "react-native-vector-icons": "^9.2.0",
    "react-native-web": "~0.18.7",
    "react-redux": "^8.0.5",
    "react-timer-hook": "^3.0.5",
    "redux": "^4.2.0",
    "socket.io-client": "^4.5.3",
    "use-debounce": "^8.0.4",
    "use-elapsed-time": "^3.0.4"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "babel-plugin-module-resolver": "^4.1.0"
  },

I have tried to solve this issue based on the official documentation (https://docs.expo.dev/guides/customizing-metro/), but no modification can be accepted. The bundling process always skips the custom file.

I have already tried a lot of workaround, that I found on StackOverflow and Github.


问:
failed to validate StaticLayoutProvider(id='p1075' ... expected an element of Dict(Int, Seq(Any)), got {'A': array([-7.94707039, 3.45521447]),
I am trying to draw network graphs following from this example.

Below is what I am trying to do.

```<code>`data = {
    'source': ['A', 'C', 'B', 'F', 'G'],
    'target': ['B', 'D', 'E', 'C', 'E'],
    'weight': [5, 3, 10, 4, 7]
}
df = pd.DataFrame(data=data)
G = networkx.from_pandas_edgelist(df, 'source', 'target', 'weight')
# Choose a title!
title = 'Graph Network'

# Establish which categories will appear when hovering over each node
HOVER_TOOLTIPS = [("Character", "@index")]
# Create a plot — set dimensions, toolbar, and title
plot = figure(tooltips=HOVER_TOOLTIPS,
              tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
              x_range=Range1d(-10.1, 10.1), y_range=Range1d(-10.1, 10.1), title=title)

network_graph = from_networkx(G, networkx.spring_layout, scale=10, center=(0, 0))

# Set node size and color
network_graph.node_renderer.glyph = Circle(size=15, fill_color='skyblue')

# Set edge opacity and width
network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5, line_width=1)

# Add network graph to the plot
plot.renderers.append(network_graph)

return plot`
</code>```

The error I get is as below;

```<code>failed to validate StaticLayoutProvider(id='p1075', ...).graph_layout: expected an
element of Dict(Int, Seq(Any)), got {'A': array([-7.94707039,  3.45521447]), 'B':
array([-6.60505319,  4.31869148]), 'C': array([ 8.38746457, -6.26423001]), 'D':
array([ 6.7178286 , -6.63523276]), 'E': array([-5.66671517,  5.25260372]), 'F':
array([10.        , -6.53836091]), 'G': array([-4.88645443,  6.41131401])}
</code>```

The error is self-explanatory. The engine expects an integer as a key, but I pass a String into it.

This error is similar to this stack overflow question

However in this case, the error specifies expected an element of Dict(Either(String, Int), Seq(Any)) that both String and Int are allowed. While in my case, the error specifies that only ints are allowed.

And indeed if I simulate the source and target as integers, the graph is drawn successfully.

If it helps, I am using networkx~=2.8.8 and bokeh==3.0.3.

Can anyone help me identify what I am doing wrong.

Body:
I am trying to draw network graphs following from this example.

Below is what I am trying to do.

`data = {
    'source': ['A', 'C', 'B', 'F', 'G'],
    'target': ['B', 'D', 'E', 'C', 'E'],
    'weight': [5, 3, 10, 4, 7]
}
df = pd.DataFrame(data=data)
G = networkx.from_pandas_edgelist(df, 'source', 'target', 'weight')
# Choose a title!
title = 'Graph Network'

# Establish which categories will appear when hovering over each node
HOVER_TOOLTIPS = [("Character", "@index")]
# Create a plot — set dimensions, toolbar, and title
plot = figure(tooltips=HOVER_TOOLTIPS,
              tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
              x_range=Range1d(-10.1, 10.1), y_range=Range1d(-10.1, 10.1), title=title)

network_graph = from_networkx(G, networkx.spring_layout, scale=10, center=(0, 0))

# Set node size and color
network_graph.node_renderer.glyph = Circle(size=15, fill_color='skyblue')

# Set edge opacity and width
network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5, line_width=1)

# Add network graph to the plot
plot.renderers.append(network_graph)

return plot`

The error I get is as below;

failed to validate StaticLayoutProvider(id='p1075', ...).graph_layout: expected an
element of Dict(Int, Seq(Any)), got {'A': array([-7.94707039,  3.45521447]), 'B':
array([-6.60505319,  4.31869148]), 'C': array([ 8.38746457, -6.26423001]), 'D':
array([ 6.7178286 , -6.63523276]), 'E': array([-5.66671517,  5.25260372]), 'F':
array([10.        , -6.53836091]), 'G': array([-4.88645443,  6.41131401])}

The error is self-explanatory. The engine expects an integer as a key, but I pass a String into it.

This error is similar to this stack overflow question

However in this case, the error specifies expected an element of Dict(Either(String, Int), Seq(Any)) that both String and Int are allowed. While in my case, the error specifies that only ints are allowed.

And indeed if I simulate the source and target as integers, the graph is drawn successfully.

If it helps, I am using networkx~=2.8.8 and bokeh==3.0.3.

Can anyone help me identify what I am doing wrong.


问:
Conditional handlebars with plop and react
I am working on a template for a react component with plop.js and I am using conditional handlebars to render some content conditional upon an argument passed along with the command used to generate the content. Here is the conditional content of the template:

{{#ifCond "withStyles"}}import * as styles from "./{{pascalCase name}}.styles";{{/ifCond}}

When I use the line above, it returns "cannot read properties of undefined (reading "replace") which might be due to using {{pascalCase name}} inside the {{ifCond}} so how can we achieve the same thing in a correct way as it seems wrong.

Thanks in advance.


问:
Why does my app designed with kivy doesn't have access to the internet?
Recently I created an application with python by using the kivy module. It is a YouTube to mp3 converter/downloader app. It works absolutely fine and as expected when I run the code on VS. However, once I convert the file from .py to .apk, there is a bug... The issue on the app is that when you paste the link in the input bar and click on the 'submit' button to convert, it doesn't download the video.

I've added some try/except clauses in order to spot the line which is causing an issue to download a vid. I found it on line 70 : it turns out my app cannot browse the streams available for a video. After experimenting with the code on VS, I discovered that an error is happening due to line 70 when my laptop is disconnected from the internet too. That's why I think that the issue is that my app can't access the internet. I uncommented the line granting the internet permission to the app on the buildozer.spec file but it doesn't work anyways and showed the same line was causing a problem.

A snippet from the .py file including the line 70 is below:

```<code>
                try: # browse and select the stream

                    vid = yt.streams.filter(only_audio=True).first() # this is causing the problem

                    try:# download the vid

                        output_file = vid.download(r'''Internal storage/Download''')

                        try: # change the exctension

                            base,ext=os.path.splitext(output_file)
                            new_file = base+'.mp3'
                            os.rename(output_file, new_file)
                            self.verification.text=f'download successful new file created at: {new_file}'

                        except:
                            self.verification.text="download unsuccesful; problem with os module"

                    except:
                        self.verification.text="download unsuccesful; can't download vid"

                except:
                    self.verification.text="download unsuccesful, can't select stream"

</code>```

Body:
Recently I created an application with python by using the kivy module. It is a YouTube to mp3 converter/downloader app. It works absolutely fine and as expected when I run the code on VS. However, once I convert the file from .py to .apk, there is a bug... The issue on the app is that when you paste the link in the input bar and click on the 'submit' button to convert, it doesn't download the video.

I've added some try/except clauses in order to spot the line which is causing an issue to download a vid. I found it on line 70 : it turns out my app cannot browse the streams available for a video. After experimenting with the code on VS, I discovered that an error is happening due to line 70 when my laptop is disconnected from the internet too. That's why I think that the issue is that my app can't access the internet. I uncommented the line granting the internet permission to the app on the buildozer.spec file but it doesn't work anyways and showed the same line was causing a problem.

A snippet from the .py file including the line 70 is below:

                try: # browse and select the stream

                    vid = yt.streams.filter(only_audio=True).first() # this is causing the problem

                    try:# download the vid

                        output_file = vid.download(r'''Internal storage/Download''')

                        try: # change the exctension

                            base,ext=os.path.splitext(output_file)
                            new_file = base+'.mp3'
                            os.rename(output_file, new_file)
                            self.verification.text=f'download successful new file created at: {new_file}'

                        except:
                            self.verification.text="download unsuccesful; problem with os module"

                    except:
                        self.verification.text="download unsuccesful; can't download vid"

                except:
                    self.verification.text="download unsuccesful, can't select stream"


问:
How to add a repository correctly and use it in service
I generated a gateway app with jhipster and generated a jparepository but when I try to use this repository I am getting the following error:

```<code>Description:

Parameter 1 of constructor in com.nosi.gateway.service.ReceiptService required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.
</code>```

This is how I use it in my service:

```<code>@Service
@Transactional
public class ReceiptService {

    private final Logger log = LoggerFactory.getLogger(ReceiptService.class);

    private final ReceiptRepository receiptRepository;
    private final ReceiptRepositoryJpa receiptRepositoryJpa;
    private final ReceiptMapper receiptMapper;

    public ReceiptService(ReceiptRepository receiptRepository, ReceiptRepositoryJpa receiptRepositoryJpa, ReceiptMapper receiptMapper) {
        this.receiptRepository = receiptRepository;
        this.receiptRepositoryJpa = receiptRepositoryJpa;
        this.receiptMapper = receiptMapper;
    }

    /**
     * Save a receipt.
     *
     * @param receiptDTO the entity to save.
     * @return the persisted entity.
     */
    public Mono<ReceiptDTO> save(ReceiptDTO receiptDTO) {
        log.debug("Request to save Receipt : {}", receiptDTO);
        return receiptRepository.save(receiptMapper.toEntity(receiptDTO)).map(receiptMapper::toDto);
    }

    /**
     * Partially update a receipt.
     *
     * @param receiptDTO the entity to update partially.
     * @return the persisted entity.
     */
    public Mono<ReceiptDTO> partialUpdate(ReceiptDTO receiptDTO) {
        log.debug("Request to partially update Receipt : {}", receiptDTO);

        return receiptRepository
            .findById(receiptDTO.getId())
            .map(existingReceipt -> {
                receiptMapper.partialUpdate(existingReceipt, receiptDTO);

                return existingReceipt;
            })
            .flatMap(receiptRepository::save)
            .map(receiptMapper::toDto);
    }

    public Flux<ReceiptDTO> findByCompany(Long companyUserID) {
        log.debug("Request to get all Receipts by a company");
        return receiptRepository.findReceiptsByCompanyId(companyUserID).map(receiptMapper::toDto);
    }

    public List<ReceiptDTO> findByCompanyJpa(Long companyUserID) {
        log.debug("Request to get all Receipts by a company");
        return receiptRepositoryJpa.findReceiptsByCompanyId(companyUserID).stream().map(receiptMapper::toDto).collect(Collectors.toList());
    }
</code>```

Controller:

```<code>@RestController
@RequestMapping("/api")
public class ReceiptResource {

    private final Logger log = LoggerFactory.getLogger(ReceiptResource.class);

    private static final String ENTITY_NAME = "receipt";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final ReceiptService receiptService;

    private final ReceiptRepository receiptRepository;

    private final UserRepository userRepository;

    public ReceiptResource(ReceiptService receiptService, ReceiptRepository receiptRepository, UserRepository userRepository) {
        this.receiptService = receiptService;
        this.receiptRepository = receiptRepository;
        this.userRepository = userRepository;
    }

    /**
     * {@code POST  /receipts} : Create a new receipt.
     *
     * @param receiptDTO the receiptDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new receiptDTO, or with status {@code 400 (Bad Request)} if the receipt has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */

    @PostMapping("/receipts")
    public Mono<ResponseEntity<ReceiptDTO>> createReceipt(@RequestBody ReceiptDTO receiptDTO) throws URISyntaxException {
        log.debug("REST request to save Receipt : {}", receiptDTO);
        if (receiptDTO.getId() != null) {
            throw new BadRequestAlertException("A new receipt cannot already have an ID", ENTITY_NAME, "idexists");
        }
        return receiptService
            .save(receiptDTO)
            .map(result -> {
                try {
                    return ResponseEntity
                        .created(new URI("/api/receipts/" + result.getId()))
                        .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
                        .body(result);
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
            });
    }

    @GetMapping("/receipts/byUserId")
    public Mono<List<ReceiptDTO>> getAllReceiptsByCompanyId(@RequestParam Long companyId) {
        log.debug("REST request to get all Receipts");

        return receiptService.findByCompany(companyId).collectList();
    }

    @GetMapping("/receipts/byUserId")
    public List<ReceiptDTO> getAllReceiptsByCompanyIdJpa(@RequestParam Long companyId) {
        log.debug("REST request to get all Receipts");

        return receiptService.findByCompanyJpa(companyId);
    }
</code>```

Repository

```<code>public interface ReceiptRepositoryJpa extends JpaRepository<Receipt, Long>  {

    List<Receipt> findReceiptsByCompanyId(Long id);

}
</code>```

I also added this to my mainApplication.java

```<code>@SpringBootApplication
@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class })
@EnableJpaRepositories("com.nosi.gateway.repository.jpa")
public class NosiApp {

SOme methods are here generated by jhipster
}
</code>```

Can someone give me a pointer how to fix this? I tried to use autowired in service and annotate my repository with @repository but still the same error.

ADDED POM

```<code> <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-jpamodelgen</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
        </dependency>
</code>```

Also I have this one:

```<code><dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.7.6</version>
</dependency>
</code>```

Body:
I generated a gateway app with jhipster and generated a jparepository but when I try to use this repository I am getting the following error:

Description:

Parameter 1 of constructor in com.nosi.gateway.service.ReceiptService required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

This is how I use it in my service:

@Service
@Transactional
public class ReceiptService {

    private final Logger log = LoggerFactory.getLogger(ReceiptService.class);

    private final ReceiptRepository receiptRepository;
    private final ReceiptRepositoryJpa receiptRepositoryJpa;
    private final ReceiptMapper receiptMapper;

    public ReceiptService(ReceiptRepository receiptRepository, ReceiptRepositoryJpa receiptRepositoryJpa, ReceiptMapper receiptMapper) {
        this.receiptRepository = receiptRepository;
        this.receiptRepositoryJpa = receiptRepositoryJpa;
        this.receiptMapper = receiptMapper;
    }

    /**
     * Save a receipt.
     *
     * @param receiptDTO the entity to save.
     * @return the persisted entity.
     */
    public Mono<ReceiptDTO> save(ReceiptDTO receiptDTO) {
        log.debug("Request to save Receipt : {}", receiptDTO);
        return receiptRepository.save(receiptMapper.toEntity(receiptDTO)).map(receiptMapper::toDto);
    }

    /**
     * Partially update a receipt.
     *
     * @param receiptDTO the entity to update partially.
     * @return the persisted entity.
     */
    public Mono<ReceiptDTO> partialUpdate(ReceiptDTO receiptDTO) {
        log.debug("Request to partially update Receipt : {}", receiptDTO);

        return receiptRepository
            .findById(receiptDTO.getId())
            .map(existingReceipt -> {
                receiptMapper.partialUpdate(existingReceipt, receiptDTO);

                return existingReceipt;
            })
            .flatMap(receiptRepository::save)
            .map(receiptMapper::toDto);
    }

    public Flux<ReceiptDTO> findByCompany(Long companyUserID) {
        log.debug("Request to get all Receipts by a company");
        return receiptRepository.findReceiptsByCompanyId(companyUserID).map(receiptMapper::toDto);
    }

    public List<ReceiptDTO> findByCompanyJpa(Long companyUserID) {
        log.debug("Request to get all Receipts by a company");
        return receiptRepositoryJpa.findReceiptsByCompanyId(companyUserID).stream().map(receiptMapper::toDto).collect(Collectors.toList());
    }

Controller:

@RestController
@RequestMapping("/api")
public class ReceiptResource {

    private final Logger log = LoggerFactory.getLogger(ReceiptResource.class);

    private static final String ENTITY_NAME = "receipt";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final ReceiptService receiptService;

    private final ReceiptRepository receiptRepository;

    private final UserRepository userRepository;

    public ReceiptResource(ReceiptService receiptService, ReceiptRepository receiptRepository, UserRepository userRepository) {
        this.receiptService = receiptService;
        this.receiptRepository = receiptRepository;
        this.userRepository = userRepository;
    }

    /**
     * {@code POST  /receipts} : Create a new receipt.
     *
     * @param receiptDTO the receiptDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new receiptDTO, or with status {@code 400 (Bad Request)} if the receipt has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */

    @PostMapping("/receipts")
    public Mono<ResponseEntity<ReceiptDTO>> createReceipt(@RequestBody ReceiptDTO receiptDTO) throws URISyntaxException {
        log.debug("REST request to save Receipt : {}", receiptDTO);
        if (receiptDTO.getId() != null) {
            throw new BadRequestAlertException("A new receipt cannot already have an ID", ENTITY_NAME, "idexists");
        }
        return receiptService
            .save(receiptDTO)
            .map(result -> {
                try {
                    return ResponseEntity
                        .created(new URI("/api/receipts/" + result.getId()))
                        .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
                        .body(result);
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
            });
    }

    @GetMapping("/receipts/byUserId")
    public Mono<List<ReceiptDTO>> getAllReceiptsByCompanyId(@RequestParam Long companyId) {
        log.debug("REST request to get all Receipts");

        return receiptService.findByCompany(companyId).collectList();
    }

    @GetMapping("/receipts/byUserId")
    public List<ReceiptDTO> getAllReceiptsByCompanyIdJpa(@RequestParam Long companyId) {
        log.debug("REST request to get all Receipts");

        return receiptService.findByCompanyJpa(companyId);
    }

Repository

public interface ReceiptRepositoryJpa extends JpaRepository<Receipt, Long>  {

    List<Receipt> findReceiptsByCompanyId(Long id);

}

I also added this to my mainApplication.java

@SpringBootApplication
@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class })
@EnableJpaRepositories("com.nosi.gateway.repository.jpa")
public class NosiApp {

SOme methods are here generated by jhipster
}

Can someone give me a pointer how to fix this? I tried to use autowired in service and annotate my repository with @repository but still the same error.

ADDED POM

 <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-jpamodelgen</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
        </dependency>

Also I have this one:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.7.6</version>
</dependency>


问:
Feasibility of a desktop app that should overlay another app
I'm looking at developing a desktop app that should overlay Word on windows. I have looked into office plugins, but they are too limited in their functionality. Essentially, I want to achieve something like what is shown in the image below.

These highlighted text segments should move as the user scrolls etc., but do not have to be instant or could be shown when the user has been at one location in the document for more than a second, etc.

Is this possible? The overlay should not interfere with the word functionality, and what framework should one go for in the development Electron? Windows is the main platform where it should work but would be great with an easy port to Mac.

Any resources are much appreciated, and I was thinking it could be built kind of like Loom video. Have already looked at this and trying out this one.


问:
Firebase phone authentication not working after creating .apk file
I initialized a react native app with Expo Bare Workflow, installed the @react-native-firebase/app and @react-native-firebase/auth package and followed all the setup instructions from the rnfirebase.io website. When I'm in development the firebase phone number authentication works fine but when I build using EAS (Expo Application Services) the reCAPTCHA screen doesn't open and I don't get the code of confirmation.

I need help to solve this problem


问:
Spring boot authorization server (1.0.0) intercept and store login_hint as a query param
I Have a situation when a client send and authorize request as such below:
 http://localhost:8080/oauth2/authorize?scope=openid&response_type=code&redirect_uri=https://api.test.local:9443/commonauth&state=b3cefc9d-2096-4a3c-a291-58781a171b5f,OIDC&client_id=client-id&login_hint=BfcZPa4vv_Q6Y_o0VwqTOnUA4pcPJLTNgSTq3vqiouJFY4TaMd6kKxanim2CDhilkQhrvzbv7fanE3-vpyG4dtLky5bLJFpbDYP7eIAtuP7WLe00mlMUpUPzd733V39TsWhf2lOkpP0z2JcdCQvTi7b2W1OFxPoHrNUMCFhj0AnJqaTal3O7l1Oo1-xrlJR3nz_p_EeK-eWK6bMQZqPvon8AHkQMtq8txClqM3aywZtXJ0Jea4fJyVEhvV_tnIXxgYg296_a5HsnnmcPlkVk-1TMZesr07dC2OBh0m02gGcWW-TPunBH5SRTI8BwzgwFBSig8Js_4gkgGwxhTpBo5g

Notice that we have a login_hint query param that we need later on the process

i wrote an interceptor to intercept the query param after the AbstractPreAuthenticatedProcessingFilter

Once storing it in the SecurityContextHolder it seem that i lost it later in the process once getting to the login page

does any have a slick way to store this information (by the way the request.getSession() resulted in the same problem

```<code>public class LoginHintFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(LoginHintFilter.class);

    @Override
    public void doFilterInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse response, final FilterChain chain) throws ServletException, IOException {
        try {
            if (Objects.equals(httpServletRequest.getServletPath(), "/oauth2/authorize")) {
                if (httpServletRequest.getParameter("login_hint") == null) {
                    throw new SecurityLoginHintException("Error No security 'login_hint' found");
                }
                ....
            }
        } catch (SecurityLoginHintException | NoSuchPaddingException | IllegalBlockSizeException |
                 NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) {
            logger.error(e.getMessage());
        }
        try {
            chain.doFilter(httpServletRequest, response);
        } catch (final Exception e) {
            throw e;
        }
    }
}
</code>```
```<code>    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.getConfigurer(OAuth2AuthorizationServerConfigurer.class).oidc(Customizer.withDefaults())
                .and()
                .formLogin().loginPage("/login_kvk").and()
                .addFilterAfter(bsnDecryptionFilter, AbstractPreAuthenticatedProcessingFilter.class)
                .build();
    }
</code>```
```<code>@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
   return http.formLogin().loginPage("/login").and().authorizeRequests().requestMatchers(DEFAULT_WHITELIST).permitAll().anyRequest().authenticated().and().build();
}
</code>```

Body:
I Have a situation when a client send and authorize request as such below:
 http://localhost:8080/oauth2/authorize?scope=openid&response_type=code&redirect_uri=https://api.test.local:9443/commonauth&state=b3cefc9d-2096-4a3c-a291-58781a171b5f,OIDC&client_id=client-id&login_hint=BfcZPa4vv_Q6Y_o0VwqTOnUA4pcPJLTNgSTq3vqiouJFY4TaMd6kKxanim2CDhilkQhrvzbv7fanE3-vpyG4dtLky5bLJFpbDYP7eIAtuP7WLe00mlMUpUPzd733V39TsWhf2lOkpP0z2JcdCQvTi7b2W1OFxPoHrNUMCFhj0AnJqaTal3O7l1Oo1-xrlJR3nz_p_EeK-eWK6bMQZqPvon8AHkQMtq8txClqM3aywZtXJ0Jea4fJyVEhvV_tnIXxgYg296_a5HsnnmcPlkVk-1TMZesr07dC2OBh0m02gGcWW-TPunBH5SRTI8BwzgwFBSig8Js_4gkgGwxhTpBo5g

Notice that we have a login_hint query param that we need later on the process

i wrote an interceptor to intercept the query param after the AbstractPreAuthenticatedProcessingFilter

Once storing it in the SecurityContextHolder it seem that i lost it later in the process once getting to the login page

does any have a slick way to store this information (by the way the request.getSession() resulted in the same problem

public class LoginHintFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(LoginHintFilter.class);

    @Override
    public void doFilterInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse response, final FilterChain chain) throws ServletException, IOException {
        try {
            if (Objects.equals(httpServletRequest.getServletPath(), "/oauth2/authorize")) {
                if (httpServletRequest.getParameter("login_hint") == null) {
                    throw new SecurityLoginHintException("Error No security 'login_hint' found");
                }
                ....
            }
        } catch (SecurityLoginHintException | NoSuchPaddingException | IllegalBlockSizeException |
                 NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) {
            logger.error(e.getMessage());
        }
        try {
            chain.doFilter(httpServletRequest, response);
        } catch (final Exception e) {
            throw e;
        }
    }
}

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.getConfigurer(OAuth2AuthorizationServerConfigurer.class).oidc(Customizer.withDefaults())
                .and()
                .formLogin().loginPage("/login_kvk").and()
                .addFilterAfter(bsnDecryptionFilter, AbstractPreAuthenticatedProcessingFilter.class)
                .build();
    }

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
   return http.formLogin().loginPage("/login").and().authorizeRequests().requestMatchers(DEFAULT_WHITELIST).permitAll().anyRequest().authenticated().and().build();
}


问:
Console mouse events in Windows 10
The purpose of this program is to use the mouse on the output console.

I used this code in C and it worked on Windows 7. What should I change to make it work on Windows 10?  The mouse doesn't react on Windows 10.
Maybe a library is missing? Maybe library windows is not supported by Windows 10?

```<code>#include <windows.h>
#include <stdio.h>
#include <conio.h>

HANDLE hStdin;
DWORD fdwSaveOldMode;

DWORD cNumRead, fdwMode, i;
INPUT_RECORD irInBuf[128];

VOID MouseEventProc(MOUSE_EVENT_RECORD mer)
{
    switch(mer.dwEventFlags)
    {
        case 0:

            if(mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
            {
                mer.dwMousePosition.X;
                mer.dwMousePosition.Y;
                printf("left button press   posX  %d\n", mer.dwMousePosition.X);
            }
            else if(mer.dwButtonState == RIGHTMOST_BUTTON_PRESSED)
            {
                printf("right button press \n");
            }
            else
            {
                printf("button press\n");
            }
            break;
    }
}

int main(VOID)
{
    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    if (hStdin == INVALID_HANDLE_VALUE) ErrorExit("GetStdHandle");

    if (! GetConsoleMode(hStdin, &fdwSaveOldMode) ) ErrorExit("GetConsoleMode");

    fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
    if (! SetConsoleMode(hStdin, fdwMode) ) ErrorExit("SetConsoleMode");

    while(1)
    {
        if (! ReadConsoleInput(
                hStdin,
                irInBuf,
                1,
                &cNumRead) ) ErrorExit("ReadConsoleInput");

        i=0;
        switch(irInBuf[i].EventType)
        {
            case MOUSE_EVENT: // mouse input
                MouseEventProc(irInBuf[i].Event.MouseEvent);
                break;
        }
    }

    SetConsoleMode(hStdin,fdwSaveOldMode);

    return 0;
}
</code>```

I'm lost because it is very important to me.

Title: Console mouse events in Windows 10

Body:
The purpose of this program is to use the mouse on the output console.

I used this code in C and it worked on Windows 7. What should I change to make it work on Windows 10?  The mouse doesn't react on Windows 10.
Maybe a library is missing? Maybe library windows is not supported by Windows 10?

#include <windows.h>
#include <stdio.h>
#include <conio.h>

HANDLE hStdin;
DWORD fdwSaveOldMode;

DWORD cNumRead, fdwMode, i;
INPUT_RECORD irInBuf[128];

VOID MouseEventProc(MOUSE_EVENT_RECORD mer)
{
    switch(mer.dwEventFlags)
    {
        case 0:

            if(mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
            {
                mer.dwMousePosition.X;
                mer.dwMousePosition.Y;
                printf("left button press   posX  %d\n", mer.dwMousePosition.X);
            }
            else if(mer.dwButtonState == RIGHTMOST_BUTTON_PRESSED)
            {
                printf("right button press \n");
            }
            else
            {
                printf("button press\n");
            }
            break;
    }
}

int main(VOID)
{
    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    if (hStdin == INVALID_HANDLE_VALUE) ErrorExit("GetStdHandle");

    if (! GetConsoleMode(hStdin, &fdwSaveOldMode) ) ErrorExit("GetConsoleMode");

    fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
    if (! SetConsoleMode(hStdin, fdwMode) ) ErrorExit("SetConsoleMode");

    while(1)
    {
        if (! ReadConsoleInput(
                hStdin,
                irInBuf,
                1,
                &cNumRead) ) ErrorExit("ReadConsoleInput");

        i=0;
        switch(irInBuf[i].EventType)
        {
            case MOUSE_EVENT: // mouse input
                MouseEventProc(irInBuf[i].Event.MouseEvent);
                break;
        }
    }

    SetConsoleMode(hStdin,fdwSaveOldMode);

    return 0;
}

I'm lost because it is very important to me.


问:
How to receive data from python Thread in a greenlet without blocking all greenlets?
We have an existing codebase that is heavily Thread based which we're trying to expose through flask-socketio. I can't find a mechanism to have a greenlet wait for data from a Thread without blocking all of gevent or through a polling loop.

I thought maybe I could use an unbounded gevent Queue and call put from the Thread but that didn't seem to work. Also, the application is not performant enough with long polling so we can't use threads for socketio.

Is there a mechanism to receive data from the Thread in a greenlet without the greenlet blocking all of gevent?


问:
Laravel, how to run legacy & jetstream process login when using google callback
We trying to migrate an old manager (legacy) to Laravel,
we made all a process using Jetstream to log, and Fortify::authenticateThrough to run some necessary code for always running legacy manager (because there is a lot of interface to migrate, and we migrating step by step old interface).

I tried to include login with google email, all good for Jetstream (using Socialite)

In Jetstream Provider, we having something like :

```<code>public function boot()
    {
        $this->configurePermissions();

        Jetstream::deleteUsersUsing(DeleteUser::class);

        // Legacy operations for sessions
        Fortify::authenticateThrough(function (Request $request) {
            return array_filter([
                config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class,
                Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null,
                LegacyPrepareAuthenticatedSession::class,
                AttemptToAuthenticate::class,
                PrepareAuthenticatedSession::class,
            ]);
        });
    }
</code>```

I follow a tuto for using Socialite, and on callback google, we having :

```<code>public function handleGoogleCallback(Request $request)
    {
        try {
            $user = Socialite::driver('google')->user();
            $finduser = User::where('google_id', $user->id)->first();
            if($finduser){
                $test = Auth::login($finduser);

                // Legacy operations for sessions
                // we tried this but it don't lunch LegacyPrepareAuthenticatedSession

                $test = (new Pipeline(app()))->send($request)->through(array_filter([
                config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class,
                Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null,
                LegacyPrepareAuthenticatedSession::class,
                AttemptToAuthenticate::class,
                PrepareAuthenticatedSession::class,
            ]));
                return redirect('/lecacy');
            }else{
                die('user not find');
            }
            //catch exceptions
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
</code>```

LegacyPrepareAuthenticatedSession start some session variable necessary for legacy manager.

I can't find a way to lunch the LegacyPrepareAuthenticatedSession on callback google

I would like find a way to use what jetstream lunch for keeping the same pipeline between the login with jetstream and google auth.

Is there a way to lunch it when log with google ?

Thanks a lot.

Body:
We trying to migrate an old manager (legacy) to Laravel,
we made all a process using Jetstream to log, and Fortify::authenticateThrough to run some necessary code for always running legacy manager (because there is a lot of interface to migrate, and we migrating step by step old interface).

I tried to include login with google email, all good for Jetstream (using Socialite)

In Jetstream Provider, we having something like :

public function boot()
    {
        $this->configurePermissions();

        Jetstream::deleteUsersUsing(DeleteUser::class);

        // Legacy operations for sessions
        Fortify::authenticateThrough(function (Request $request) {
            return array_filter([
                config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class,
                Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null,
                LegacyPrepareAuthenticatedSession::class,
                AttemptToAuthenticate::class,
                PrepareAuthenticatedSession::class,
            ]);
        });
    }

I follow a tuto for using Socialite, and on callback google, we having :

public function handleGoogleCallback(Request $request)
    {
        try {
            $user = Socialite::driver('google')->user();
            $finduser = User::where('google_id', $user->id)->first();
            if($finduser){
                $test = Auth::login($finduser);

                // Legacy operations for sessions
                // we tried this but it don't lunch LegacyPrepareAuthenticatedSession

                $test = (new Pipeline(app()))->send($request)->through(array_filter([
                config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class,
                Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null,
                LegacyPrepareAuthenticatedSession::class,
                AttemptToAuthenticate::class,
                PrepareAuthenticatedSession::class,
            ]));
                return redirect('/lecacy');
            }else{
                die('user not find');
            }
            //catch exceptions
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }

LegacyPrepareAuthenticatedSession start some session variable necessary for legacy manager.

I can't find a way to lunch the LegacyPrepareAuthenticatedSession on callback google

I would like find a way to use what jetstream lunch for keeping the same pipeline between the login with jetstream and google auth.

Is there a way to lunch it when log with google ?

Thanks a lot.


问:
guildBanAdd and messageDelete event not triggering, Discord.js v14
my guildBanAdd event on discord.js v14 doesn't trigger whenever I ban a user, same as the messageDelete event. Do I need to give my bot any specific permission aside the adminstrator permission it has or is there an Intent that is missing in the client
other events such as interactionCreate and messageCreate works just fine
`

```<code>module.exports = {
  name: "guildBanAdd",
  async execute(guild, user, client) {
    console.log('I was called: guildBanAdd');
  },
};
</code>```

`

`

```<code>module.exports = {
  name: "messageDelete",
  async execute(message, client) {
    console.log(`delete logs: ${message}`);
  },
};

</code>```

`

my client Intents
`

```<code>const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
});
</code>```

`

I have also enabled all three Privileged Gateway Intents on the discord application dashboard as well.
Thank you.

I tried banning a user and expected something to be logged but nothing showed, I also tried deleting a user content and nothing showed

Body:
my guildBanAdd event on discord.js v14 doesn't trigger whenever I ban a user, same as the messageDelete event. Do I need to give my bot any specific permission aside the adminstrator permission it has or is there an Intent that is missing in the client
other events such as interactionCreate and messageCreate works just fine
`

module.exports = {
  name: "guildBanAdd",
  async execute(guild, user, client) {
    console.log('I was called: guildBanAdd');
  },
};

`

`

module.exports = {
  name: "messageDelete",
  async execute(message, client) {
    console.log(`delete logs: ${message}`);
  },
};

`

my client Intents
`

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
});

`

I have also enabled all three Privileged Gateway Intents on the discord application dashboard as well.
Thank you.

I tried banning a user and expected something to be logged but nothing showed, I also tried deleting a user content and nothing showed


问:
Can Selenium select specific characters or words within an element's text?
Can Selenium (specifically when run from Python) select specific characters or words within an element's text without any more detailed markup? Just a plain string.
I would like to select specific words found by matching string to a variable.

I see that I can use sequence action.click_and_hold().perform() ... action.release() The question is how to get to the initial and the end positions? The command action.move_to_element_with_offset can potentially do it, but uses coordinates instead position a need span in a characters. I guess in theory it possible to calculate these coordinates using width characters and heights of lines, but that seems to be something unnecessarily cumbersome. Unless I can easily do the opposite action - get coordinate from a character in a specific position in the text. I am a newbie with Selenium. I could not find any commands that can do what I need. I will be surprised if this functionality just does not exist in Selenium. It seems to me that this should be needed for testing. If so, is there some common workaround for this (for example, running JavaScript from Selenium)?


问:
InstaGrapi not adding caption
I am using instagrapi to post on instagram and it was working fine, until it stopped adding captions but still posting

```<code>caption1 = "Sunny days out with the family"
client.photo_upload(path="D:/insta/instagram1.jpg", caption=caption1)
</code>```

This is my code (strings changed and i have repeated it with sleep intervals inbetween and different captions and photos)
This worked fine until it randomly stopped adding captions

Title: InstaGrapi not adding caption

Body:
I am using instagrapi to post on instagram and it was working fine, until it stopped adding captions but still posting

caption1 = "Sunny days out with the family"
client.photo_upload(path="D:/insta/instagram1.jpg", caption=caption1)

This is my code (strings changed and i have repeated it with sleep intervals inbetween and different captions and photos)
This worked fine until it randomly stopped adding captions


问:
I want to enable or disable fields for some users from admin panel
This is template

```<code><div class="container mt-3">
      <h5 class="card-title">Kindly enter the details. All details are required</h5>
      <form class="row g-3" method="post" action="{% url 'home' %}" enctype="multipart/form-data">
        {% csrf_token %}
        <div class="col-md-4">
          <label for="name" class="form-label">Full Name</label>
          <input type="text" class="form-control" id="name" name="name" required>
        </div>
        <div class="col-md-4">
          <label for="parentage" class="form-label">Father's Name</label>
          <input type="text" class="form-control" id="parentage" name="father" required >
        </div>
        <div class="col-md-4">
          <label for="mothername" class="form-label">Mother's Name</label>
          <input type="text" class="form-control" id="mothername" name="mother" required>
        </div>
        <div class="col-md-4">
          <label for="phonenumber" class="form-label">Phone number</label>
          <input type="tel" class="form-control" id="phonenumber" name="pnumber" required>
        </div>
        <div class="col-md-4">
          <label for="ephonenumber" class="form-label">Emergency contact number</label>
          <input type="tel" class="form-control" id="ephonenumber" name="enumber" required>
        </div>
        <div class="col-md-4">
          <label for="dob" class="form-label">Date of Birth</label>
          <input type="date" class="form-control" id="dob" name="dob" required>
        </div>

        <div class="col-12">
          <label for="inputAddress" class="form-label">Address</label>
          <input type="text" class="form-control" id="inputAddress" placeholder="" name="address" required>
        </div>
        <div class="col-md-6">
          <label for="photo" class="form-label">Upload a photo</label>
          <input type="file" class="form-control" id="photo"  name="photo" accept="image/*,.pdf" required>
        </div>
        <div class="col-md-4">
          <label for="schoolname" class="form-label">School Name</label>
          <input type="text" class="form-control" id="schoolname" name="sname" required >
        </div>
        <div class="col-md-4">
          <label for="inputState" class="form-label">Role</label>
          <select id="select" class="form-select" name="role" required>
            <option selected>Choose...</option>
            <option value="student">Student</option>
            <option value="teacher">Teacher</option>
          </select>
        </div>

        <div  id="show">

        </div>

        <div class="col-12">
          <button type="submit" class="btn btn-primary">Submit</button>
        </div>
      </form>

</div>
</code>```

This is models.py

```<code>class Student(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,null=True)
fullname= models.CharField(max_length=50)
father = models.CharField(max_length=30)
mother = models.CharField(max_length=30)
phno=models.IntegerField()
ephno = models.IntegerField()
dob=models.DateField()
address=models.CharField(max_length=100)
photo= models.ImageField(upload_to='photos/')
role=models.CharField(max_length=20)
rollNumber = models.IntegerField()
standard = models.CharField( max_length=10)

def __str__(self):
    return self.fullname
</code>```

This is admin.py

```<code>class studentAdmin(ExportActionMixin,admin.ModelAdmin):
list_display=('fullname', 'father',"mother",'phno','ephno',"dob",'address','photo','role','rollNumber','standard')
</code>```

admin.site.register(Student,studentAdmin)

```<code>class teacherAdmin(ExportActionMixin,admin.ModelAdmin):
    list_display=('fullname', 'father',"mother",'phno','ephno',"dob",'address','photo','role')
    list_filter =['user']
admin.site.register(Teacher,teacherAdmin)
</code>```

I want admin to enable or disable form fields and model fields from the admin panel.
Is there any way to do the same? For some users, I want to for example keep the mother's name and for some, I want to hide to it

Body:
This is template

Kindly enter the details. All details are required

      <form class="row g-3" method="post" action="{% url 'home' %}" enctype="multipart/form-data">
        {% csrf_token %}

          Full Name
          <input type="text" class="form-control" id="name" name="name" required>

          Father's Name
          <input type="text" class="form-control" id="parentage" name="father" required >

          Mother's Name
          <input type="text" class="form-control" id="mothername" name="mother" required>

          Phone number
          <input type="tel" class="form-control" id="phonenumber" name="pnumber" required>

          Emergency contact number
          <input type="tel" class="form-control" id="ephonenumber" name="enumber" required>

          Date of Birth
          <input type="date" class="form-control" id="dob" name="dob" required>

          Address
          <input type="text" class="form-control" id="inputAddress" placeholder="" name="address" required>

          Upload a photo
          <input type="file" class="form-control" id="photo"  name="photo" accept="image/*,.pdf" required>

          School Name
          <input type="text" class="form-control" id="schoolname" name="sname" required >

          Role
          <select id="select" class="form-select" name="role" required>
            <option selected>Choose...</option>
            <option value="student">Student</option>
            <option value="teacher">Teacher</option>
          </select>

          <button type="submit" class="btn btn-primary">Submit</button>

      </form>

This is models.py

class Student(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,null=True)
fullname= models.CharField(max_length=50)
father = models.CharField(max_length=30)
mother = models.CharField(max_length=30)
phno=models.IntegerField()
ephno = models.IntegerField()
dob=models.DateField()
address=models.CharField(max_length=100)
photo= models.ImageField(upload_to='photos/')
role=models.CharField(max_length=20)
rollNumber = models.IntegerField()
standard = models.CharField( max_length=10)

def __str__(self):
    return self.fullname

This is admin.py

class studentAdmin(ExportActionMixin,admin.ModelAdmin):
list_display=('fullname', 'father',"mother",'phno','ephno',"dob",'address','photo','role','rollNumber','standard')

admin.site.register(Student,studentAdmin)

class teacherAdmin(ExportActionMixin,admin.ModelAdmin):
    list_display=('fullname', 'father',"mother",'phno','ephno',"dob",'address','photo','role')
    list_filter =['user']
admin.site.register(Teacher,teacherAdmin)

I want admin to enable or disable form fields and model fields from the admin panel.
Is there any way to do the same? For some users, I want to for example keep the mother's name and for some, I want to hide to it


问:
How to bookmark and retrieve bookmarks in android java
Well I am using pdf viewer by bartsek but when I try to retrieve bookmarks using the bookmark function it gives me wierd characters
Here is the code

```<code>pdfview.getTableofContents.toString()
</code>```

Wierd characters

How can I achieve this

I want a list of bookmarks and a way of bookmarking pages
I have no idea about it

Body:
Well I am using pdf viewer by bartsek but when I try to retrieve bookmarks using the bookmark function it gives me wierd characters
Here is the code

pdfview.getTableofContents.toString()

Wierd characters

How can I achieve this

I want a list of bookmarks and a way of bookmarking pages
I have no idea about it


问:
Fail reading files from cyberduck when publishing website
I have got domain name, got webhotel. The next i am trying to do is publishing my website, that i have build in Rider IDE, .net core. When i am doing this, the only thing that show on my the website(internet) is the files from my Rider program.

MARK: The Rider file is just an test program for lower upload time.

First i make an "custom publish server" in Rider, right click my project. Then click "publish" and fill the form.

The details behind "Remote server" where i set up the SFTP linked to my web hotell, host, username, password. This is fine and connection is good.

Then i run the new "publish" file to get it to cyberduck.

Everything seems to be good so far, the files are getting transferred over to cyberduck, and its green lights.

But when i then check the website on internet, it just show all the files as an dictonary.

I really appreciate any help!!!


问:
Send email from Gmail to Outlook where csv attachment has selected domain
I am sending one email from my gmail account to my outlook email account, and it also has one csv attachment. Whic has only one line B@whp.co.in

while sending this email, outlook does not recieve any email.

And I am also not receving any email failure reply too.

If I change email address from B@whp.co.in to B@xwhp.co.in into attached csv file than email get's deliver to outout emailID

Can someone help me to understand this issue.

Thanks,
Alpesh


问:
warn - Invalid next.config.js options detected ( npm run build )
```<code>> build
> next build

warn  - Invalid next.config.js options detected:
  - The root value has an unexpected property, webpackDevMiddleware, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, configOrigin, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, webpack5, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The value at .amp.canonicalBase must be 1 character or more but it was 0 characters.
  - The value at .assetPrefix must be 1 character or more but it was 0 characters.
  - The value at .experimental.outputFileTracingRoot must be 1 character or more but it was 0 characters.
  - The value at .i18n must be an object but it was null.

See more info here: https://nextjs.org/docs/messages/invalid-next-config
info  - Linting and checking validity of types ...Failed to compile.
</code>```

info  - Linting and checking validity of types ...Failed to compile.
enter image description here

warn  - Invalid next.config.js options detected:
enter image description here

Body:
> build
> next build

warn  - Invalid next.config.js options detected:
  - The root value has an unexpected property, webpackDevMiddleware, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, configOrigin, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The root value has an unexpected property, webpack5, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).
  - The value at .amp.canonicalBase must be 1 character or more but it was 0 characters.
  - The value at .assetPrefix must be 1 character or more but it was 0 characters.
  - The value at .experimental.outputFileTracingRoot must be 1 character or more but it was 0 characters.
  - The value at .i18n must be an object but it was null.

See more info here: https://nextjs.org/docs/messages/invalid-next-config
info  - Linting and checking validity of types ...Failed to compile.

info  - Linting and checking validity of types ...Failed to compile.
enter image description here

warn  - Invalid next.config.js options detected:
enter image description here


问:
Make the clock tick in (java/ javaFX)
I am a student, I am creating a clock for an application, I added a Label in scene builder assigned the clock to it and added the following java code:

 public void initialize() throws FileNotFoundException, InterruptedException {

   var now = LocalTime.now();
   DateTimeFormatter dft =DateTimeFormatter.ofPattern("HH:mm:ss");

labelclock.setText(LocalTime.now().format(dft));

```
<p>I want to make the clock tick and tried in many ways but it didn't work.</p>
<p>I also tried creating the clock in another way and got the same result.</p>
<pre class="lang-java prettyprint-override"><code> public void setTime() {

       while (true) {

       time = timeFormat.format(calendar.getInstance().getTime());
       labelclock.setText(time);
         try {
          Thread.sleep(1000);
              } catch (InterruptedException e) {
          e.printStackTrace();
              }
             }
            }

</code>```

Title: Make the clock tick in (java/ javaFX)

Body:
I am a student, I am creating a clock for an application, I added a Label in scene builder assigned the clock to it and added the following java code:

 public void initialize() throws FileNotFoundException, InterruptedException {

   var now = LocalTime.now();
   DateTimeFormatter dft =DateTimeFormatter.ofPattern("HH:mm:ss");

labelclock.setText(LocalTime.now().format(dft));

I want to make the clock tick and tried in many ways but it didn't work.

I also tried creating the clock in another way and got the same result.

 public void setTime() {

       while (true) {

       time = timeFormat.format(calendar.getInstance().getTime());
       labelclock.setText(time);
         try {
          Thread.sleep(1000);
              } catch (InterruptedException e) {
          e.printStackTrace();
              }
             }
            }


问:
How to implement Github login in a SwiftUI app, ready for both Mac and iOS?
I made this quick  solution below. But it raise error on both platforms. I would avoid to use

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
</code>```

method if possible, and manipulate window object, because that is quite different on Mac and iOS. Do you think finetuning this solution could help to implement a Github authentication with help of an embedded browser?

Can this ASWebAuthenticationSession based solution, using an embedded browser realy receive Github response, with the code parameter?

Button(action: {
    let authURL = URL(string: "https://github.com/login/oauth/authorize")!
    let callbackURL = URL(string: "myapp://callback")!
    let session = ASWebAuthenticationSession(url: authURL, callbackURLScheme: callbackURL.scheme) { (callBackURL, error) in
        let queryItems = URLComponents(string: callbackURL.absoluteString)?.queryItems
        let code = queryItems?.first(where: { $0.name == "code" })?.value
        print("code: \(code ?? "na")")
    }
    session.presentationContextProvider = {
        return UIApplication.shared.windows.first!
    }
    session.start()
}) {
    Text("Login")
}
```

Body:
I made this quick  solution below. But it raise error on both platforms. I would avoid to use

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

method if possible, and manipulate window object, because that is quite different on Mac and iOS. Do you think finetuning this solution could help to implement a Github authentication with help of an embedded browser?

Can this ASWebAuthenticationSession based solution, using an embedded browser realy receive Github response, with the code parameter?

Button(action: {
    let authURL = URL(string: "https://github.com/login/oauth/authorize")!
    let callbackURL = URL(string: "myapp://callback")!
    let session = ASWebAuthenticationSession(url: authURL, callbackURLScheme: callbackURL.scheme) { (callBackURL, error) in
        let queryItems = URLComponents(string: callbackURL.absoluteString)?.queryItems
        let code = queryItems?.first(where: { $0.name == "code" })?.value
        print("code: \(code ?? "na")")
    }
    session.presentationContextProvider = {
        return UIApplication.shared.windows.first!
    }
    session.start()
}) {
    Text("Login")
}


问:
How to underline errors in CodeMirror using a custom linter?
I am currently building a code editor with a custom mode.
This is how it is defined:

```<code>    let codeMirror = CodeMirror.fromTextArea(textArea,
      {
        mode: "customMode",
        lint: true,
        theme: customtheme
       }
</code>```

I then create a custom linter, defined as:

```<code>
  CodeMirror.registerHelper("lint", "customMode", function (text) {
    // the "myLint()" function returns an array of error objects
    // each object has a "from", "to", "severity", and "message" property
    let errorsArray = myLint(text)
    return errorsArray ;
});
</code>```

If run the command

```<code>console.log(CodeMirror.lint.customMode(code));

</code>```

An array of error objects is printed to the console, each with a “to”, “from”, “severity” and “message” property. What I’m wondering is, how do I use this function so that these errors can be underlined in red in the code editor?

Body:
I am currently building a code editor with a custom mode.
This is how it is defined:

    let codeMirror = CodeMirror.fromTextArea(textArea,
      {
        mode: "customMode",
        lint: true,
        theme: customtheme
       }

I then create a custom linter, defined as:

  CodeMirror.registerHelper("lint", "customMode", function (text) {
    // the "myLint()" function returns an array of error objects
    // each object has a "from", "to", "severity", and "message" property
    let errorsArray = myLint(text)
    return errorsArray ;
});

If run the command

console.log(CodeMirror.lint.customMode(code));

An array of error objects is printed to the console, each with a “to”, “from”, “severity” and “message” property. What I’m wondering is, how do I use this function so that these errors can be underlined in red in the code editor?