问:
Google SignIn with expo: signInWithGoogleAsync not being invoked
Im following this tutorial https://github.com/nathvarun/Expo-Google-Login-Firebase and below is my code. However the signInWithGoogleAsync() function is not getting invoked it seems. Clicking the button does nothing. Could it be because of stack Navigator?

There is no issue with firebase as email login is working

Below is my LoginScreen.js

```<code>import { useNavigation } from '@react-navigation/core'
import React, { useEffect, useState, Component } from 'react'
import { Button, KeyboardAvoidingView, StyleSheet, Text,TextInput, TouchableOpacity, View } from 'react-native'
import { auth } from '../firebase'
import * as GoogleSignIn from 'expo-google-sign-in';

class LoginScreen extends Component {
signInWithGoogleAsync = async() => {
try {
  const result = await Google.logInAsync({
    behavior:'web',
    iosClientId: 'lorem ipsum',
    scopes: ['profile', 'email'],
  });

  if (result.type === 'success') {
    return result.accessToken;
  } else {
    return { cancelled: true };
  }
} catch (e) {
  return { error: true };
}
};
render(){
return (
<KeyboardAvoidingView
  style={styles.container}
  behavior="padding"
>
  <View style={styles.inputContainer}>
   <Button
    title='sign'
    onPress={()=>this.signInWithGoogleAsync()} />
  </View>
</KeyboardAvoidingView>
 );
 }
}

export default LoginScreen
</code>```

here's the App.js:

```<code>import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import LoginScreen from './screens/LoginScreen';
import HomeScreen from './screens/HomeScreen';
import * as firebase from "firebase/compat";

const Stack = createNativeStackNavigator();

export default class App extends React.Component {
 render(){
 return (
<NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen options={{ headerShown: false }} name="Login" component={LoginScreen} />
    <Stack.Screen name="Home" component={HomeScreen} />
  </Stack.Navigator>
</NavigationContainer>
);
}
}

const styles = StyleSheet.create({
 container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
registerRootComponent(App);
</code>```

答:
You are importing everythin as GoogleSignIn and then below doing await Google.logInAsync so you'd have to change that to await GoogleSignIn.loadInAsync. 9th line

Also, look at the docs, it doesn't look like logInAsync is a function https://docs.expo.dev/versions/latest/sdk/google-sign-in/

Body:
Im following this tutorial https://github.com/nathvarun/Expo-Google-Login-Firebase and below is my code. However the signInWithGoogleAsync() function is not getting invoked it seems. Clicking the button does nothing. Could it be because of stack Navigator?

There is no issue with firebase as email login is working

Below is my LoginScreen.js

import { useNavigation } from '@react-navigation/core'
import React, { useEffect, useState, Component } from 'react'
import { Button, KeyboardAvoidingView, StyleSheet, Text,TextInput, TouchableOpacity, View } from 'react-native'
import { auth } from '../firebase'
import * as GoogleSignIn from 'expo-google-sign-in';

class LoginScreen extends Component {
signInWithGoogleAsync = async() => {
try {
  const result = await Google.logInAsync({
    behavior:'web',
    iosClientId: 'lorem ipsum',
    scopes: ['profile', 'email'],
  });

  if (result.type === 'success') {
    return result.accessToken;
  } else {
    return { cancelled: true };
  }
} catch (e) {
  return { error: true };
}
};
render(){
return (
<KeyboardAvoidingView
  style={styles.container}
  behavior="padding"
>
  <View style={styles.inputContainer}>
   <Button
    title='sign'
    onPress={()=>this.signInWithGoogleAsync()} />
  </View>
</KeyboardAvoidingView>
 );
 }
}

export default LoginScreen

here's the App.js:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import LoginScreen from './screens/LoginScreen';
import HomeScreen from './screens/HomeScreen';
import * as firebase from "firebase/compat";

const Stack = createNativeStackNavigator();

export default class App extends React.Component {
 render(){
 return (
<NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen options={{ headerShown: false }} name="Login" component={LoginScreen} />
    <Stack.Screen name="Home" component={HomeScreen} />
  </Stack.Navigator>
</NavigationContainer>
);
}
}

const styles = StyleSheet.create({
 container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
registerRootComponent(App);


来源: stackexchange

问:
How to make a fill parent+wrap_content (in that order) Android
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

```<code> LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1
</code>```

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

```<code><RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>
</code>```

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

```<code><RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>
</code>```

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance

答:
I had debug your code .. try this:   </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity = "center_vertical" >

    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_centerHorizontal = "true"

    />

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_below = "@+id/image"
        android:layout_centerHorizontal = "true"
    />

</RelativeLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

 LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

<RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

<RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance

Body:
I had debug your code .. try this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity = "center_vertical" >

    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_centerHorizontal = "true"

    />

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_below = "@+id/image"
        android:layout_centerHorizontal = "true"
    />

</RelativeLayout>


问:
remove eventListener from for loop
I'm trying to remove the event listener that I've added in for loop but it didn't work

Is there a way to do this with pure js?

```<code>for (let i = 0; i < drumPads.length; i++) {
    drumPads[i].addEventListener("click", func)
    function func() {
      display.innerHTML = music[i][0];
      sound.src = music[i][1];
      sound.play();
    }
}
</code>```

答:
Your function func should be defined outside the loop.

In your code the function func is block scoped and hence this wont be refering to the same memory when the user enters with "on" and "off" condition.

You can pass the index and some custom data from the target to the listner function by setting dataset of the target.

let drumPads = document.getElementsByClassName("drum-pads");

function Power(a) {
  for (let i = 0; i < drumPads.length; i++) {
    if (a === 'on') {
      drumPads[i].dataset.index = i;
      drumPads[i].addEventListener("click", func);
    } else {
      drumPads[i].removeEventListener("click", func);
    }
  }
}

function func(e) {
  const targetIndex = e.currentTarget.dataset.index;
  console.log('Triggered listner', targetIndex);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <button class="drum-pads">drum-pads 1</button>
  <button class="drum-pads">drum-pads 2</button>
  <button class="drum-pads">drum-pads 3</button>
  <button class="drum-pads">drum-pads 4</button>
</div>
<div>
  <button onclick="Power('on')">Toggle On</button>
  <button onclick="Power('off')">Toggle Off</button>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: remove eventListener from for loop

Body:
I'm trying to remove the event listener that I've added in for loop but it didn't work

Is there a way to do this with pure js?

for (let i = 0; i < drumPads.length; i++) {
    drumPads[i].addEventListener("click", func)
    function func() {
      display.innerHTML = music[i][0];
      sound.src = music[i][1];
      sound.play();
    }
}

Body:
Your function func should be defined outside the loop.

In your code the function func is block scoped and hence this wont be refering to the same memory when the user enters with "on" and "off" condition.

You can pass the index and some custom data from the target to the listner function by setting dataset of the target.

let drumPads = document.getElementsByClassName("drum-pads");

function Power(a) {
  for (let i = 0; i < drumPads.length; i++) {
    if (a === 'on') {
      drumPads[i].dataset.index = i;
      drumPads[i].addEventListener("click", func);
    } else {
      drumPads[i].removeEventListener("click", func);
    }
  }
}

function func(e) {
  const targetIndex = e.currentTarget.dataset.index;
  console.log('Triggered listner', targetIndex);
}

<div>
  <button class="drum-pads">drum-pads 1</button>
  <button class="drum-pads">drum-pads 2</button>
  <button class="drum-pads">drum-pads 3</button>
  <button class="drum-pads">drum-pads 4</button>
</div>
<div>
  <button onclick="Power('on')">Toggle On</button>
  <button onclick="Power('off')">Toggle Off</button>
</div>


问:
set recyclerView item height wrap_content
I'm loading images into recyclerview item(imageview) from firebase.
All images are of different dimensions.

I want my imageview to scale its height according the image i'm loading.

Main layout.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/RecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>
</code>```

row.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >

        <ImageView
            android:id="@+id/ImageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

</LinearLayout>
</code>```

In java i'm doing.

```<code>RecyclerView.setHasFixedSize(true);
       RecyclerView.setLayoutManager(new LinearLayoutManager(mctx));
</code>```

Also when I scroll recyclerview it changes the image height

output

then I scrolled up and down, and see the height.
Scrolled up/down output

third time,
again scrolled and worst output

Please help me.. Thanks a lot..

答:
If you are using Constraint layout use constraint Dimens ratio as
mentioned above.

```<code><ImageView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 app:layout_constraintDimensionRatio="1:1"/>
</code>```

else if you are using linear or relative layout.

```<code><ImageView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:adjustViewBounds="true" />
</code>```

both will solve your problem but both of them are only recommend if you have small amount of data to populate, these tricks are not recommended for thousands of images, as this will calculate and set height of each item at run time which means this will run on main thread and for thousands of images this will create a laggy scrolling and may result in ANR on low end devices.

There is another work around to minimize this lag.

You can get the width of the imageView at runtime in onBindViewHolder and set the height equals to width or any multiple of width to attain your desired ratio.

```<code> CoroutineScope(Dispatchers.IO).launch {
      val width = holder.image.width

      withContext(Dispatchers.Main){
           holder.image.layoutParams.height = width
      }
  }
</code>```

Getting the width at background thread will take the load off of Main thread which ultimately results in smooth scrolling.

Body:
I'm loading images into recyclerview item(imageview) from firebase.
All images are of different dimensions.

I want my imageview to scale its height according the image i'm loading.

Main layout.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/RecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

row.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >

        <ImageView
            android:id="@+id/ImageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

</LinearLayout>

In java i'm doing.

RecyclerView.setHasFixedSize(true);
       RecyclerView.setLayoutManager(new LinearLayoutManager(mctx));

Also when I scroll recyclerview it changes the image height

output

then I scrolled up and down, and see the height.
Scrolled up/down output

third time,
again scrolled and worst output

Please help me.. Thanks a lot..

Body:
If you are using Constraint layout use constraint Dimens ratio as
mentioned above.

<ImageView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 app:layout_constraintDimensionRatio="1:1"/>

else if you are using linear or relative layout.

<ImageView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:adjustViewBounds="true" />

both will solve your problem but both of them are only recommend if you have small amount of data to populate, these tricks are not recommended for thousands of images, as this will calculate and set height of each item at run time which means this will run on main thread and for thousands of images this will create a laggy scrolling and may result in ANR on low end devices.

There is another work around to minimize this lag.

You can get the width of the imageView at runtime in onBindViewHolder and set the height equals to width or any multiple of width to attain your desired ratio.

 CoroutineScope(Dispatchers.IO).launch {
      val width = holder.image.width

      withContext(Dispatchers.Main){
           holder.image.layoutParams.height = width
      }
  }

Getting the width at background thread will take the load off of Main thread which ultimately results in smooth scrolling.


问:
How to use libsrtp or similar library to decrypt/encrypt the WebRTC data stream?
I have a server which receives OFFER, ANSWER, CANDIDATE-s from web browser for a WebRTC session and passes to its peer. Later the data is also passed from the same server.

Now to implement our own SFU-like mechanism, I was considering, if this data I can decrypt to the actual raw bytes and then pass it to the multiple peers with their own encryption. For that I thought of using open source libsrtp library. Here is its example code.

It has primarily 2 functions srtp_protect() to encrtypt and srtp_unprotect() to decrypt.

Question: How to use such library in the conjunction of above WebRTC SDP headers (viz offer, answer, candidate) to get the raw RTP bytes & encrypt them again?

[Note: The other open source solutions like "MediaSoup", "Janus" etc. are not in scope of this post.]

答:
WebRTC uses DTLS-SRTP so the SRTP keys are derived from the DTLS handshake which preceedes the SRTP packets.

The main openssl (or boringssl) APIs used for this are SSL_CTX_set_tlsext_use_srtp, SSL_set_info_callback and SSL_export_keying_material which exports the SRTP keys (that are used in the calls to libsrtps srtp_create)

Examples of using those APIs together are quite rare, both Janus and MediaSoup are good examples of how to use them if you are allowed to look at their code license-wise.


问:
Combining 3 Private Sub Worksheet_Change
I am a first time poster and a newby to VBA. So i am hoping i make sense :)
I am trying to combine 3 private subs, but not sure how to code it together.

I have a spreadsheet that has data validation and i want a input box to appear depending on what is selected.

In column "I" is the first set of data validation, with the options of Accepted, Declined and Null invoid, if "Accepted" then nothing, but if either Declined or Null in Void, I would like a pop up box to appear for the user to input $0, and past that to Column "D"

In Column "M" is the next one for data validation, with the only options is blank and Complete. if blank then nothing, but if Complete, i would like a pop up for the user to input the Quotation value, and past that to Column "D".

Thank you in advance.

This is my code

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("I:I")) Is Nothing Then
        If Target = "Declined" Then
            roww = Target.Row
            Application.EnableEvents = False
                Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value to 0", Type:=2)
            Application.EnableEvents = True
        End If
    End If
End Sub
</code>```

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("I:I")) Is Nothing Then
        If Target = "Null in Void" Then
            roww = Target.Row
            Application.EnableEvents = False
                Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value to 0", Type:=2)
            Application.EnableEvents = True
        End If
    End If
End Sub
</code>```

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("M:M")) Is Nothing Then
        If Target = "Complete" Then
            roww = Target.Row
            Application.EnableEvents = False
                Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value to the Quotation Value", Type:=2)
            Application.EnableEvents = True
        End If
    End If
End Sub
</code>```

答:
```<code>Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("M:M")) Is Nothing Then
        If Target = "Complete" Then
            roww = Target.Row
            Application.EnableEvents = FALSE
            Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value To the Quotation Value", Type:=2)
            Application.EnableEvents = TRUE
        End If
    ElseIf Not Intersect(Target, Range("I:I")) Is Nothing Then
        If Target = "Declined" Then
            roww = Target.Row
            Application.EnableEvents = FALSE
            Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value To 0", Type:=2)
            Application.EnableEvents = TRUE
        ElseIf Target = "Null in Void" Then
            roww = Target.Row
            Application.EnableEvents = FALSE
            Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value To 0", Type:=2)
            Application.EnableEvents = TRUE
        End If
    End If
End Sub
</code>```

see this official docs.

Body:
I am a first time poster and a newby to VBA. So i am hoping i make sense :)
I am trying to combine 3 private subs, but not sure how to code it together.

I have a spreadsheet that has data validation and i want a input box to appear depending on what is selected.

In column "I" is the first set of data validation, with the options of Accepted, Declined and Null invoid, if "Accepted" then nothing, but if either Declined or Null in Void, I would like a pop up box to appear for the user to input $0, and past that to Column "D"

In Column "M" is the next one for data validation, with the only options is blank and Complete. if blank then nothing, but if Complete, i would like a pop up for the user to input the Quotation value, and past that to Column "D".

Thank you in advance.

This is my code

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("I:I")) Is Nothing Then
        If Target = "Declined" Then
            roww = Target.Row
            Application.EnableEvents = False
                Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value to 0", Type:=2)
            Application.EnableEvents = True
        End If
    End If
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("I:I")) Is Nothing Then
        If Target = "Null in Void" Then
            roww = Target.Row
            Application.EnableEvents = False
                Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value to 0", Type:=2)
            Application.EnableEvents = True
        End If
    End If
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("M:M")) Is Nothing Then
        If Target = "Complete" Then
            roww = Target.Row
            Application.EnableEvents = False
                Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value to the Quotation Value", Type:=2)
            Application.EnableEvents = True
        End If
    End If
End Sub

Body:
Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("M:M")) Is Nothing Then
        If Target = "Complete" Then
            roww = Target.Row
            Application.EnableEvents = FALSE
            Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value To the Quotation Value", Type:=2)
            Application.EnableEvents = TRUE
        End If
    ElseIf Not Intersect(Target, Range("I:I")) Is Nothing Then
        If Target = "Declined" Then
            roww = Target.Row
            Application.EnableEvents = FALSE
            Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value To 0", Type:=2)
            Application.EnableEvents = TRUE
        ElseIf Target = "Null in Void" Then
            roww = Target.Row
            Application.EnableEvents = FALSE
            Cells(roww, "D").Value = Application.InputBox(Prompt:="Updated quoted value To 0", Type:=2)
            Application.EnableEvents = TRUE
        End If
    End If
End Sub

see this official docs.


问:
jsPDF Autotable API?
Just found the Autotable plugin for jsPDF and there seems to be a little bit of a learning curve for me as I try to use this.  I see the examples.js that comes with the file, but is there a full API somewhere where I can see all methods?

For example the didParseCell section there is this code:

```<code>  // Use for customizing texts or styles of specific cells after they have been formatted by this plugin.
// This hook is called just before the column width and other features are computed.
  didParseCell: function (data) {
  if (data.row.index === 5) {
    data.cell.styles.fillColor = [40, 170, 100]
  }

  if (
    (data.row.section === 'head' || data.row.section === 'foot') &&
    data.column.dataKey === 'expenses'
  ) {
    data.cell.text = '' // Use an icon in didDrawCell instead
  }

  if (data.column.dataKey === 'city') {
    data.cell.styles.font = 'mitubachi'
    if (data.row.section === 'head') {
      data.cell.text = 'シティ'
    }
    if (data.row.index === 0 && data.row.section === 'body') {
      data.cell.text = 'とうきょう'
    }
  }
},
</code>```

I'd like to know what methods/properties I can access for "data".  Is there a full API that lists these somewhere?

答:
There is readme.md available as documentation. For more details they are suggesting to read the class definitions for HookData, Table, Row, Cell etc. defined in models.ts:

To see what is included in the Table, Row, Column and Cell types, either log them to the console or take a look at src/models.ts

 For ready reference here are the definitions:

```<code>class HookData {
  table: Table
  pageNumber: number
  pageCount: number // Deprecated, use pageNumber instead
  settings: Settings
  doc: jsPDFDocument
  cursor: Pos | null
}

class CellHookData extends HookData {
  cell: Cell
  row: Row
  column: Column
  section: 'head' | 'body' | 'foot'
}

class Table {
  id?: string | number
  settings: Settings
  styles: StylesProps
  hooks: HookProps
  columns: Column[]
  head: Row[]
  body: Row[]
  foot: Row[]
  pageNumber = 1
  finalY?: number
  startPageNumber?: number
}

class Row {
  readonly raw: HTMLTableRowElement | RowInput
  readonly element?: HTMLTableRowElement
  readonly index: number
  readonly section: Section
  readonly cells: { [key: string]: Cell }
  spansMultiplePages: boolean

  height = 0
}

class Cell {
  raw: HTMLTableCellElement | CellInput
  styles: Styles
  text: string[]
  section: Section
  colSpan: number
  rowSpan: number

  contentHeight = 0
  contentWidth = 0
  wrappedWidth = 0
  minReadableWidth = 0
  minWidth = 0

  width = 0
  height = 0
  x = 0
  y = 0
}

class Column {
  raw: ColumnInput | null
  dataKey: string | number
  index: number

  wrappedWidth = 0
  minReadableWidth = 0
  minWidth = 0
  width = 0
}
</code>```

Title: jsPDF Autotable API?

Body:
Just found the Autotable plugin for jsPDF and there seems to be a little bit of a learning curve for me as I try to use this.  I see the examples.js that comes with the file, but is there a full API somewhere where I can see all methods?

For example the didParseCell section there is this code:

  // Use for customizing texts or styles of specific cells after they have been formatted by this plugin.
// This hook is called just before the column width and other features are computed.
  didParseCell: function (data) {
  if (data.row.index === 5) {
    data.cell.styles.fillColor = [40, 170, 100]
  }

  if (
    (data.row.section === 'head' || data.row.section === 'foot') &&
    data.column.dataKey === 'expenses'
  ) {
    data.cell.text = '' // Use an icon in didDrawCell instead
  }

  if (data.column.dataKey === 'city') {
    data.cell.styles.font = 'mitubachi'
    if (data.row.section === 'head') {
      data.cell.text = 'シティ'
    }
    if (data.row.index === 0 && data.row.section === 'body') {
      data.cell.text = 'とうきょう'
    }
  }
},

I'd like to know what methods/properties I can access for "data".  Is there a full API that lists these somewhere?

Body:
There is readme.md available as documentation. For more details they are suggesting to read the class definitions for HookData, Table, Row, Cell etc. defined in models.ts:

To see what is included in the Table, Row, Column and Cell types, either log them to the console or take a look at src/models.ts

 For ready reference here are the definitions:

class HookData {
  table: Table
  pageNumber: number
  pageCount: number // Deprecated, use pageNumber instead
  settings: Settings
  doc: jsPDFDocument
  cursor: Pos | null
}

class CellHookData extends HookData {
  cell: Cell
  row: Row
  column: Column
  section: 'head' | 'body' | 'foot'
}

class Table {
  id?: string | number
  settings: Settings
  styles: StylesProps
  hooks: HookProps
  columns: Column[]
  head: Row[]
  body: Row[]
  foot: Row[]
  pageNumber = 1
  finalY?: number
  startPageNumber?: number
}

class Row {
  readonly raw: HTMLTableRowElement | RowInput
  readonly element?: HTMLTableRowElement
  readonly index: number
  readonly section: Section
  readonly cells: { [key: string]: Cell }
  spansMultiplePages: boolean

  height = 0
}

class Cell {
  raw: HTMLTableCellElement | CellInput
  styles: Styles
  text: string[]
  section: Section
  colSpan: number
  rowSpan: number

  contentHeight = 0
  contentWidth = 0
  wrappedWidth = 0
  minReadableWidth = 0
  minWidth = 0

  width = 0
  height = 0
  x = 0
  y = 0
}

class Column {
  raw: ColumnInput | null
  dataKey: string | number
  index: number

  wrappedWidth = 0
  minReadableWidth = 0
  minWidth = 0
  width = 0
}


问:
NOT EXISTS is not working for multiple records which has same value
I am try to create a SQL query for the user should have revoke entry in Database for the respective grant access for that study.
For ex, if the user is having total count of 20 GRANT records then the user should have total count of REVOKE records. If not we need to enter the missing records.

I have created the following query. The query is working fine for the user who is having single Grant record for study but if the user is having Multiple grant record for particular study its not working.

For ex. User A is having two GRANT records and 1 REVOKE records for study ABC. the below query is not showing any output since the REVOKE record is already listed for that study.

But we have only one REVOKE records for that study. So I want to display that MISSING  GRANT record

```<code>SELECT Getdate() [RequestedDate],
   Getdate() [ApprovedDate],
   A.requestedfor,
   'XXX'    [ApprovedBy],
   A.projectnumber,
   'Revoke'  [AccessRequestType]

FROM   [dbo].[Table1] A
WHERE  A.requestedfor  = 1234
   AND A.accessrequesttype = 'Grant'
   AND NOT EXISTS (SELECT *
                   FROM   [dbo].[Table1] B
                   WHERE  B.requestedfor =1234
                          AND B.accessrequesttype = 'Revoke'
                          AND A.projectnumber =  B.projectnumber
                          AND A.accessgroup = B. accessgroup
                          AND A.RequestedFor = B. RequestedFor
                          )
</code>```

答:
I think you should use LEFT JOIN to link rows 1 to 1 and filter in WHERE clause by null fot that rows, where not exists linked pair by access type 'revoke'.

EXISTS clause checks only existed data. For example you want to insert new rows without duplicates.

```<code>SELECT  a.[RequestedDate],
   a.[ApprovedDate],
   A.requestedfor,
   a.ApprovedBy,
   A.projectnumber,
   'Revoke'  [AccessRequestType]

FROM   #Table1 A
LEFT JOIN #Table1 B ON        B.accessrequesttype = 'Revoke'
                          AND A.projectnumber =  B.projectnumber
                          AND A.accessgroup = B. accessgroup
                          AND A.RequestedFor = B. RequestedFor
WHERE  A.requestedfor  = 1234
   AND A.accessrequesttype = 'Grant'
   ---this shows only rows, which not have pair 'Grant'-'Revoke'
   AND B.ID IS NULL
</code>```

Exists clause

Example result set to show an idea of query:

ReqDate
RequestedBy
AccessType
projNumber
accessGroup
RequestedFor
AccessType

2019-07-31
XXXXXX
Grant
1
1
1
Revoke

2019-07-30
XXXXX1
Grant
1
1
1
NULL

2019-07-29
XXXXXX
Grant
2
2
2
Revoke

2019-07-30
XXXXX1
Grant
1
1
1
NULL

2019-07-01
XXXXX1
Grant
3
2
2
NULL

Body:
I am try to create a SQL query for the user should have revoke entry in Database for the respective grant access for that study.
For ex, if the user is having total count of 20 GRANT records then the user should have total count of REVOKE records. If not we need to enter the missing records.

I have created the following query. The query is working fine for the user who is having single Grant record for study but if the user is having Multiple grant record for particular study its not working.

For ex. User A is having two GRANT records and 1 REVOKE records for study ABC. the below query is not showing any output since the REVOKE record is already listed for that study.

But we have only one REVOKE records for that study. So I want to display that MISSING  GRANT record

SELECT Getdate() [RequestedDate],
   Getdate() [ApprovedDate],
   A.requestedfor,
   'XXX'    [ApprovedBy],
   A.projectnumber,
   'Revoke'  [AccessRequestType]

FROM   [dbo].[Table1] A
WHERE  A.requestedfor  = 1234
   AND A.accessrequesttype = 'Grant'
   AND NOT EXISTS (SELECT *
                   FROM   [dbo].[Table1] B
                   WHERE  B.requestedfor =1234
                          AND B.accessrequesttype = 'Revoke'
                          AND A.projectnumber =  B.projectnumber
                          AND A.accessgroup = B. accessgroup
                          AND A.RequestedFor = B. RequestedFor
                          )

Body:
I think you should use LEFT JOIN to link rows 1 to 1 and filter in WHERE clause by null fot that rows, where not exists linked pair by access type 'revoke'.

EXISTS clause checks only existed data. For example you want to insert new rows without duplicates.

SELECT  a.[RequestedDate],
   a.[ApprovedDate],
   A.requestedfor,
   a.ApprovedBy,
   A.projectnumber,
   'Revoke'  [AccessRequestType]

FROM   #Table1 A
LEFT JOIN #Table1 B ON        B.accessrequesttype = 'Revoke'
                          AND A.projectnumber =  B.projectnumber
                          AND A.accessgroup = B. accessgroup
                          AND A.RequestedFor = B. RequestedFor
WHERE  A.requestedfor  = 1234
   AND A.accessrequesttype = 'Grant'
   ---this shows only rows, which not have pair 'Grant'-'Revoke'
   AND B.ID IS NULL

Exists clause

Example result set to show an idea of query:

ReqDate
RequestedBy
AccessType
projNumber
accessGroup
RequestedFor
AccessType

2019-07-31
XXXXXX
Grant
1
1
1
Revoke

2019-07-30
XXXXX1
Grant
1
1
1
NULL

2019-07-29
XXXXXX
Grant
2
2
2
Revoke

2019-07-30
XXXXX1
Grant
1
1
1
NULL

2019-07-01
XXXXX1
Grant
3
2
2
NULL


问:
NGRX - dispatch action on catchError effect with different payload
I need to call an API that can return errors, warnings or success.

If it returns warnings the user must able to accept the warning and I should send the same payload + acceptWarning: true.

I need to display an ionic modal and wait for the user's response to see if he accepts or cancel the warning.

What should be the best way to achieve that?

Right now I have something like this:

```<code>  @Effect()
  public Assign$ = this.actions$.pipe(
    ofType(myActions.Assign),
    map(action => action.payload),
    exhaustMap(assignment =>
      this.assignService.assign(assignment).pipe(
        switchMap(() => {
          this.errorService.showPositiveToast(' Assigned Successfully');
          return [
            new LoadAssignments(),
            new LoadOtherData()
          ];
        }),
        catchError(error =>
          from(this.openErrorModal(error)).pipe(
            switchMap(({ data = '' }) => {
              if (data === 'Accept') {
                return of(new Assign({ ...assignment, acceptWarning: true }));
              }

              return of(new AssignShipmentFailure());
            })
          )
        )
      )
    )
  );

async openErrorModal(response: any) {
    const errorModal = await this.modalCtrl.create({
      component: ErrorValidationPopup,
      componentProps: {
        response: response,
      },
    });
    await errorModal.present();
    return errorModal.onDidDismiss();
  }
</code>```

But it is not triggering the Assign action again. Thanks for your help

答:
If any error occurred in the effect's observable (or any Observable), then its stream emitted no value and it immediately errored out. After the error, no completion occurred, and the Effect will stop working.

To keep the Effect working if any error occurred, you have to swichMap instead of exhaustMap, and handle the errors within the inner observable of the switchMap, so the main Observable won't be affected by that.

Why use switchMap?

The main difference between switchMap and other flattening operators is the cancelling effect. On each emission the previous inner observable (the result of the function you supplied) is cancelled and the new observable is subscribed. You can remember this by the phrase switch to a new observable

You can try something like the following:

@Effect()
public Assign$ = this.actions$.pipe(
  ofType(myActions.Assign),
  map(action => action.payload),
  switchMap(assignment =>
    this.assignService.assign(assignment).pipe(
      switchMap(() => {
        this.errorService.showPositiveToast('Assigned Successfully');
        return [
          new LoadAssignments(),
          new LoadOtherData()
        ];
      }),
      catchError(error =>
        from(this.openErrorModal(error)).pipe(
          map(({ data = '' }) => {
            if (data === 'Accept') {
              return new Assign({ ...assignment, acceptWarning: true });
            }

            return new AssignShipmentFailure();
          })
        )
      )
    )
  )
);
```

Body:
I need to call an API that can return errors, warnings or success.

If it returns warnings the user must able to accept the warning and I should send the same payload + acceptWarning: true.

I need to display an ionic modal and wait for the user's response to see if he accepts or cancel the warning.

What should be the best way to achieve that?

Right now I have something like this:

  @Effect()
  public Assign$ = this.actions$.pipe(
    ofType(myActions.Assign),
    map(action => action.payload),
    exhaustMap(assignment =>
      this.assignService.assign(assignment).pipe(
        switchMap(() => {
          this.errorService.showPositiveToast(' Assigned Successfully');
          return [
            new LoadAssignments(),
            new LoadOtherData()
          ];
        }),
        catchError(error =>
          from(this.openErrorModal(error)).pipe(
            switchMap(({ data = '' }) => {
              if (data === 'Accept') {
                return of(new Assign({ ...assignment, acceptWarning: true }));
              }

              return of(new AssignShipmentFailure());
            })
          )
        )
      )
    )
  );

async openErrorModal(response: any) {
    const errorModal = await this.modalCtrl.create({
      component: ErrorValidationPopup,
      componentProps: {
        response: response,
      },
    });
    await errorModal.present();
    return errorModal.onDidDismiss();
  }

But it is not triggering the Assign action again. Thanks for your help


问:
Error trying to remove a namespace from an XML in Mule 4
I see the error like "Trying to write END_DOCUMENT when document has no root" while I replace all the payload env and xmlns with "".

It throws error :

```<code>Message               : "Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document, while writing Xml.
Trace:
  at main (Unknown)" evaluating expression: "payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")".
Element               : map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload)
Element DSL           : <set-payload value="#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]" doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc"></set-payload>
Error type            : MULE:EXPRESSION
FlowStack             : at map_requestFlow(map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload))

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
</code>```

Mule flow :

```<code><flow name="map_requestFlow" doc:id="21d0d652-3766-47ed-95aa-a451f62c5776" >
        <http:listener doc:name="Listener" doc:id="7312114b-2857-40b3-98cd-f52b628b3a28" config-ref="HTTP_Listener_config" path="/map"/>
        <set-payload value='#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]' doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc" />
        <logger level="INFO" doc:name="Logger" doc:id="21051f39-bb9f-412c-af73-f65051317757" message="#[payload]"/>
</flow>
</code>```

Input payload : https://github.com/Manikandan99/Map_request/blob/main/soap_request.xml

Expected output : https://github.com/Manikandan99/Map_request/blob/main/soap_response.xml

I am trying to replace payload using

```<code>#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]
</code>```

Please assist me to resolve this issue.

答:
Here's a version that uses the namespace prefix instead of the url.</p>
```<code>%dw 2.0
output application/xml

fun removeNamespace(element,namespacePrefix) =
    element mapObject (value, key) -> {
    //key
    (
        if (key.#.prefix as String == namespacePrefix) (key as String)
        else (key)) @((key.@)
    )
    : //value
    (
        if (value is Object) removeNamespace(value, namespacePrefix)
        else value
    )}
---
payload removeNamespace  "env"
</code>```

Body:
I see the error like "Trying to write END_DOCUMENT when document has no root" while I replace all the payload env and xmlns with "".

It throws error :

Message               : "Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document, while writing Xml.
Trace:
  at main (Unknown)" evaluating expression: "payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")".
Element               : map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload)
Element DSL           : <set-payload value="#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]" doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc"></set-payload>
Error type            : MULE:EXPRESSION
FlowStack             : at map_requestFlow(map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload))

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)

Mule flow :

<flow name="map_requestFlow" doc:id="21d0d652-3766-47ed-95aa-a451f62c5776" >
        <http:listener doc:name="Listener" doc:id="7312114b-2857-40b3-98cd-f52b628b3a28" config-ref="HTTP_Listener_config" path="/map"/>
        <set-payload value='#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]' doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc" />
        <logger level="INFO" doc:name="Logger" doc:id="21051f39-bb9f-412c-af73-f65051317757" message="#[payload]"/>
</flow>

Input payload : https://github.com/Manikandan99/Map_request/blob/main/soap_request.xml

Expected output : https://github.com/Manikandan99/Map_request/blob/main/soap_response.xml

I am trying to replace payload using

#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]

Please assist me to resolve this issue.

Body:
Here's a version that uses the namespace prefix instead of the url.

%dw 2.0
output application/xml

fun removeNamespace(element,namespacePrefix) =
    element mapObject (value, key) -> {
    //key
    (
        if (key.#.prefix as String == namespacePrefix) (key as String)
        else (key)) @((key.@)
    )
    : //value
    (
        if (value is Object) removeNamespace(value, namespacePrefix)
        else value
    )}
---
payload removeNamespace  "env"


问:
Get collection of elements from JSON
I have a JSON file with the structure as below:

```<code>{"root" : {
     "parent" : {
          "childA" :
              ["element1",
               "element2"],
          "childB" :
              ["element1",
               "element2"]
     }
}
</code>```

How can I get a collection of children [childA, childB] from it?

For now what I'm doing:

Parse the JSON file to an object (I know how to do that and suggested response is about this).

Create the collection:

```<code>var collection = [JSON.root.parent.childA, JSON.root.parent.childB];
collection.forEach(function(child) {
    print(child[0])
});
</code>```

to print "element1".

I'm new to JavaScript but I believe there is a better and more generic way to achieve the point 2.

EDIT:
I forgot to add that this Java Script is used inside Nashorn jjs script.

答:
You can try using JToken also -</p>
```<code> using Newtonsoft.Json.Linq;

 JToken.Parse(response.Content)
.SelectTokens("root.parent");
</code>```

Title: Get collection of elements from JSON

Body:
I have a JSON file with the structure as below:

{"root" : {
     "parent" : {
          "childA" :
              ["element1",
               "element2"],
          "childB" :
              ["element1",
               "element2"]
     }
}

How can I get a collection of children [childA, childB] from it?

For now what I'm doing:

Parse the JSON file to an object (I know how to do that and suggested response is about this).

Create the collection:

var collection = [JSON.root.parent.childA, JSON.root.parent.childB];
collection.forEach(function(child) {
    print(child[0])
});

to print "element1".

I'm new to JavaScript but I believe there is a better and more generic way to achieve the point 2.

EDIT:
I forgot to add that this Java Script is used inside Nashorn jjs script.

Body:
You can try using JToken also -

 using Newtonsoft.Json.Linq;

 JToken.Parse(response.Content)
.SelectTokens("root.parent");


问:
Local variables not working in a gnu Makefile?
I am running make on macOS and it is not pleased with any local variables . Take this snippet intended to get the full path to the directory of the Makefile script

```<code>setup_for_run:
    mkfile_path=$(abspath $(lastword $(MAKEFILE_LIST)))
    mkfile_dir=$(dir $(mkfile_path))
    echo "scriptdir=$(SCRIPT_DIR)"
    export PATH=$($(SCRIPT_DIR)/.venv/bin:$(PATH))
</code>```

The result of make setup_for_run is:

```<code>$make setup_for_run
mkfile_path=/Users/steve/git/hercl/Makefile
mkfile_dir=
echo "scriptdir="
scriptdir=
export PATH=
</code>```

So we see that none of the local variables are operational.  What is the way to get them activated in the gnu make installed by default on macOS ?

答:
Make runs each command in a recipe in its own shell (unless declaring .ONESHELL). Any modified state such as variables is cleared for each command. And, any variables set are never communicated outside make. For this purpose you're more likely to want to source a bash script.

Make are for making files from other files.

There are several alternatives to set the variables:

```<code># Global scope
VARIABLE := myglobal

# Target specific
mytarget: VARIABLE := targetspecific

# Prefix the command
myprefix:
    VARIABLE=prefix env
</code>```

Body:
I am running make on macOS and it is not pleased with any local variables . Take this snippet intended to get the full path to the directory of the Makefile script

setup_for_run:
    mkfile_path=$(abspath $(lastword $(MAKEFILE_LIST)))
    mkfile_dir=$(dir $(mkfile_path))
    echo "scriptdir=$(SCRIPT_DIR)"
    export PATH=$($(SCRIPT_DIR)/.venv/bin:$(PATH))

The result of make setup_for_run is:

$make setup_for_run
mkfile_path=/Users/steve/git/hercl/Makefile
mkfile_dir=
echo "scriptdir="
scriptdir=
export PATH=

So we see that none of the local variables are operational.  What is the way to get them activated in the gnu make installed by default on macOS ?

Body:
Make runs each command in a recipe in its own shell (unless declaring .ONESHELL). Any modified state such as variables is cleared for each command. And, any variables set are never communicated outside make. For this purpose you're more likely to want to source a bash script.

Make are for making files from other files.

There are several alternatives to set the variables:

# Global scope
VARIABLE := myglobal

# Target specific
mytarget: VARIABLE := targetspecific

# Prefix the command
myprefix:
    VARIABLE=prefix env


问:
The list of items I scrape from a webpage differs from the source of the page
I'm trying to scrape a list of zpids from this webpage using the requests module. The zpids are available within a list right next to searchListZpids in the page source (ctrl + u). They are 40 in number.

The script below can fetch the zpids errorlessly. However, the problem is the list the script produces are different from the ones available on that webpage. Some of the zpids in the list I received have exact matchings with those available on that page.

Sometimes the list I get is accurate but most of the time they are different.

The script that I'm using:

```<code>import re
import requests

link = 'https://www.zillow.com/ct/9_p/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
}

res = requests.get(link,headers=headers)
zpids = re.findall(r"searchListZpids[\s\S]+?\[(.*?)\]",res.text)[0]
print(zpids)
</code>```

Output I get at this moment:

```<code>57912175, 177202011, 57838346, 57702376, 2083150985, 2091636205, 59028017, 2066602375, 57843835, 2066598335, 58845027, 58904562, 58118011, 58838731, 57930222, 2066611590, 59977275, 197747278, 57932219, 57893209, 58775017, 2066600444, 2066601022, 58059157, 177275234, 58819070, 59297439, 58859881, 2078457589, 58775318, 57790587, 57689409, 2066601997, 57394605, 177286302, 58133143, 59068957, 58096934, 240506947, 83121293
</code>```

How can I scrape the exact list of zpids from that webpage using requests?

EDIT:

I thought to further clarify the whereabouts of the list of pids I wish to extract from that site's page source. After navigating to this link, when you press Ctrl + U, you should see the page source in a different tab. Now, press ctrl + f and write searchListZpids in the search bar like this. This time you should see the list of pids right next to searchListZpids in that page, which is more like this. This is the very list what I wish to extract. Sometimes the list the above script produces is identical to the ones available in the page source but most of the time they are different.

Body:
I'm trying to scrape a list of zpids from this webpage using the requests module. The zpids are available within a list right next to searchListZpids in the page source (ctrl + u). They are 40 in number.

The script below can fetch the zpids errorlessly. However, the problem is the list the script produces are different from the ones available on that webpage. Some of the zpids in the list I received have exact matchings with those available on that page.

Sometimes the list I get is accurate but most of the time they are different.

The script that I'm using:

import re
import requests

link = 'https://www.zillow.com/ct/9_p/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
}

res = requests.get(link,headers=headers)
zpids = re.findall(r"searchListZpids[\s\S]+?\[(.*?)\]",res.text)[0]
print(zpids)

Output I get at this moment:

57912175, 177202011, 57838346, 57702376, 2083150985, 2091636205, 59028017, 2066602375, 57843835, 2066598335, 58845027, 58904562, 58118011, 58838731, 57930222, 2066611590, 59977275, 197747278, 57932219, 57893209, 58775017, 2066600444, 2066601022, 58059157, 177275234, 58819070, 59297439, 58859881, 2078457589, 58775318, 57790587, 57689409, 2066601997, 57394605, 177286302, 58133143, 59068957, 58096934, 240506947, 83121293

How can I scrape the exact list of zpids from that webpage using requests?

EDIT:

I thought to further clarify the whereabouts of the list of pids I wish to extract from that site's page source. After navigating to this link, when you press Ctrl + U, you should see the page source in a different tab. Now, press ctrl + f and write searchListZpids in the search bar like this. This time you should see the list of pids right next to searchListZpids in that page, which is more like this. This is the very list what I wish to extract. Sometimes the list the above script produces is identical to the ones available in the page source but most of the time they are different.

Body:
How can I scrape the exact list of zpids from that webpage using requests?

Try following pattern to get exactly the list

zpids = re.findall(r"searchListZpids[\s\S]+?(\[.*?\])", res.text)[0]
zpids = eval(zpids)

print(zpids)

Output:

[57893930, 58081832, 58860541, 58890802, 69057773, 210140012, 58913561, 58820158, 82973247, 197791135, 58838105, 2066643456, 57784503, 210141981, 57312365, 58776838, 58859881, 60103968, 58088978, 333569598, 58952600, 177281260, 2066618828, 2066555488, 57246785, 57336201, 58960631, 58042110, 58028998, 174037330, 60005139, 174072877, 210140037, 210145877, 57248627, 57278888, 57330507, 57958372, 174447170, 58875088]


问:
ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')
I can view the variables in the html-page but I got the error for only the value of the gametitle

ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')

Here is the ts-file:

```<code>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import gamejson from '../../assets/data/gametest.json';

interface GAMEDETAIL {
  id: number,
  gametitle: string,
  releasedate: number,
  description: string,
  adddate: string,
  changedate: string,
  pdffile: string,
  youtubelink: string,
  images: any,
  producer: any
}

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})

export class GameComponent implements OnInit {

  private data:any = [];
  gamedetail!: GAMEDETAIL;
  gameid: number = 0;

    constructor(private route: ActivatedRoute, private http:HttpClient) {
    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );

      this.getJSON(this.gameid).subscribe(data => {
        this.gamedetail = data;
        console.log(this.gamedetail);
        console.log("gametitle: " + this.gamedetail.gametitle);
    });
    }

    getJSON(spielid: Number): Observable<GAMEDETAIL> {
      return this.http.get<GAMEDETAIL>('https://example.org/api/gamedetail/' + spielid);
    }

}
</code>```

And here is the html-file, that I simple use for viewing the details

```<code>    <h1>{{ gamedetail.gametitle }}</h1>

    <p>{{ gamedetail.description }}</p>
</code>```

And finally the output from the console of my browser:

答:
So, this.getJSON() is asynchronous, it needs some time to get executed, in the meantime the HTML will be rendered and gamedetailis still undefined.
You can avoid this error like this:

```<code><ng-container *ngIf="gamedetail">
    <h1>{{ gamedetail.gametitle }}</h1>
    <p>{{ gamedetail.description }}</p>
</ng-container>
</code>```

or

```<code><h1>{{ gamedetail?.gametitle }}</h1>
<p>{{ gamedetail?.description }}</p>
</code>```

the first approach is cleaner because the
 and
 tag wont be rendered until the data is loaded. also you have the possibility to show some sort of loading animation or text in case it takes some time.

Loading...

Body:
I can view the variables in the html-page but I got the error for only the value of the gametitle

ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')

Here is the ts-file:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import gamejson from '../../assets/data/gametest.json';

interface GAMEDETAIL {
  id: number,
  gametitle: string,
  releasedate: number,
  description: string,
  adddate: string,
  changedate: string,
  pdffile: string,
  youtubelink: string,
  images: any,
  producer: any
}

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})

export class GameComponent implements OnInit {

  private data:any = [];
  gamedetail!: GAMEDETAIL;
  gameid: number = 0;

    constructor(private route: ActivatedRoute, private http:HttpClient) {
    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );

      this.getJSON(this.gameid).subscribe(data => {
        this.gamedetail = data;
        console.log(this.gamedetail);
        console.log("gametitle: " + this.gamedetail.gametitle);
    });
    }

    getJSON(spielid: Number): Observable<GAMEDETAIL> {
      return this.http.get<GAMEDETAIL>('https://example.org/api/gamedetail/' + spielid);
    }

}

And here is the html-file, that I simple use for viewing the details

{{ gamedetail.gametitle }}

{{ gamedetail.description }}

And finally the output from the console of my browser:

Body:
So, this.getJSON() is asynchronous, it needs some time to get executed, in the meantime the HTML will be rendered and gamedetailis still undefined.
You can avoid this error like this:

<ng-container *ngIf="gamedetail">
    <h1>{{ gamedetail.gametitle }}</h1>
    <p>{{ gamedetail.description }}</p>
</ng-container>

or

<h1>{{ gamedetail?.gametitle }}</h1>
<p>{{ gamedetail?.description }}</p>

the first approach is cleaner because the <h1> and <p> tag wont be rendered until the data is loaded. also you have the possibility to show some sort of loading animation or text in case it takes some time.
<h2 *ngIf="!gamedetail">Loading...</h2>


问:
Regular expression is not working if json response value contain special character . how to extract the 'sid' value from below mention json
Regular expression is not working if json response value contain special character . how to extract the 'sid' value from below mention json as ""sid"?\s*:?\s*"(\w+)"" is not working as json response contain special character on sid.

0{"sid":"RhANkc9V7-psbnzmJAAGS","upgrades":["websocket"],"pingTimeout":20000,"pingInterval":25000}

答:
You can also use Boundary Extractor if you don't want to mess with the complexity of Regular Expression.

Left Boundary: sid":"

Right Boundary: ",


问:
How do I convert UTC/ GMT datetime to CST in Javascript? (not local, CST always)
I have a challenge where backend data is always stored in UTC time. Our front-end data is always presented in CST. I don't have access to this 'black box.'

I would like to mirror this in our data warehouse. Which is based in Europe (CET). So "local" conversion will not work.

I'm wondering the simplest, most straightforward way to accurately convert UTC time (I can have it in epoch milliseconds or a date format '2015-01-01 00:00:00') to Central Standard Time. (which is 5 or 6 hours behind based on Daylight Savings).

I see a lot of threads about converting to 'local' time ... again I don't want this, nor do I simply want to subtract 6 hours which will be wrong half the year.

Anyone have any ideas? This seems to be a very common problem but I've been searching for a while, and have found nothing.

答:
You can use below code snippet

// Get time zone offset for CDT or CST
const getCdtCstOffset = () => {
  const getNthSunday = (date, nth) => {
      date.setDate((7*(nth-1))+(8-date.getDay()));
      return date;
  }
  const isCdtTimezoneOffset = (today) => {
    console.log('Today : ', today);
    let dt = new Date();
    var mar = new Date(dt.getFullYear(), 2, 1);
    mar = getNthSunday(mar, 2);
    console.log('CDT Start : ', mar);
    var nov = new Date(dt.getFullYear(), 10, 1, 23, 59, 59);
    nov = getNthSunday(nov, 1);
    console.log('CDT End : ', nov);
    return mar.getTime()< today.getTime() && nov.getTime()> today.getTime();
  }
  var today = new Date()// current date
  if (isCdtTimezoneOffset(today)) {
    return -5
  } else {
    return -6
  }
}
let cstOrCdt = new Date();
cstOrCdt.setHours(cstOrCdt.getHours()+getCdtCstOffset())
console.log('CstOrCdt : ', cstOrCdt);```


问:
What is the default queue size for apache tomcat in spring boot?
What is the default request queue size in apache tomcat which is embedded in spring boot ?</p>

答:
The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. In Spring Boot, we can define the maximum amount of Tomcat worker threads are 200. You may specify this property in your application.properties as follows.</p>
```<code>server.tomcat.max-threads=200
</code>```

Body:
The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. In Spring Boot, we can define the maximum amount of Tomcat worker threads are 200. You may specify this property in your application.properties as follows.

server.tomcat.max-threads=200


答: Have you considered using TableLayout? It is best suited for grid like views such as this one. You can even specify weights for different columns, etc. and have different column widths.

Title: How to make a fill parent+wrap_content (in that order) Android

Body:
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

 LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

<RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

<RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance


问:
pygame.QUIT() - TypeError: 'int' object is not callable
I'm fairly new to python. I'm writing a code for a simple alien invasion game but I'm getting this error.

```<code>import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf

def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Game")
    ship = Ship(screen)
    bg_color = (230, 230, 230)

    while True:
        gf.check_events(ship)
        ship.update()
        gf.update_screen(ai_settings, screen, ship)
        for event in pygame.event.get():
            if event.type==pygame.QUIT():
                sys.exit()
        screen.fill(ai_settings.bg_color)
        ship.blitme()
        pygame.display.flip()
run_game()
</code>```

I'm aware that I'm accidentally calling some integer value but I have no clue where I'm going wrong.

I have also checked these lines

File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 25, in
run_game()

File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 16, in run_game
gf.check_events(ship)

File "C:\Users\Areeb Irfan.PyCharmCE2018.3\config\scratches\game_functions.py", line 5, in check_events
if event.type==pygame.QUIT():

TypeError: 'int' object is not callable

答:
To fix that, remove the parentheses () at pygame.QUIT.
Get rid of them, and run the code again. It should work, as long as you don't have that same "if" somewhere else.</p>

Body:
I'm fairly new to python. I'm writing a code for a simple alien invasion game but I'm getting this error.

import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf

def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Game")
    ship = Ship(screen)
    bg_color = (230, 230, 230)

    while True:
        gf.check_events(ship)
        ship.update()
        gf.update_screen(ai_settings, screen, ship)
        for event in pygame.event.get():
            if event.type==pygame.QUIT():
                sys.exit()
        screen.fill(ai_settings.bg_color)
        ship.blitme()
        pygame.display.flip()
run_game()

I'm aware that I'm accidentally calling some integer value but I have no clue where I'm going wrong.

I have also checked these lines

File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 25, in
run_game()

File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 16, in run_game
gf.check_events(ship)

File "C:\Users\Areeb Irfan.PyCharmCE2018.3\config\scratches\game_functions.py", line 5, in check_events
if event.type==pygame.QUIT():

TypeError: 'int' object is not callable


问:
(-2:Unspecified error) Can't create layer "FeatureExtractor/MobilenetV3/Conv/hard_swish/add" of type "AddV2" in function 'getLayerInstance'
I am facing a problem in classIds, confs, bbox = net.detect(img,confThreshold=float0.5)
How to fix it?Please help.

I am trying to run a very simple OpenCV script:

```<code>import cv2

img = cv2.imread("index.jpeg")

classNames= []
classFile = 'coco.names'
with open(classFile,'rt') as f:
    classNames = f.read().rstrip('\n').split('\n')

configPath = "ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt"
weightsPath = "frozen_inference_graph.pb"

net = cv2.dnn_DetectionModel(weightsPath,configPath)
net.setInputSize(320,320)
net.setInputScale(1.0/ 127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)

classIds, confs, bbox = net.detect(img,confThreshold=0.5) #line 19
print(classIds,bbox)

cv2.imshow("Output",img)
cv2.waitKey(0)
</code>```

Picture of full error

Thanks in advance!

答: I think upgrading your opencv version up to 4.5 and above, is needed.</p>

Body:
I am facing a problem in classIds, confs, bbox = net.detect(img,confThreshold=float0.5)
How to fix it?Please help.

I am trying to run a very simple OpenCV script:

import cv2

img = cv2.imread("index.jpeg")

classNames= []
classFile = 'coco.names'
with open(classFile,'rt') as f:
    classNames = f.read().rstrip('\n').split('\n')

configPath = "ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt"
weightsPath = "frozen_inference_graph.pb"

net = cv2.dnn_DetectionModel(weightsPath,configPath)
net.setInputSize(320,320)
net.setInputScale(1.0/ 127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)

classIds, confs, bbox = net.detect(img,confThreshold=0.5) #line 19
print(classIds,bbox)

cv2.imshow("Output",img)
cv2.waitKey(0)

Picture of full error

Thanks in advance!


问:
asp.net core upload file as part of a form
Trying to upload a file as part of a form and store it in a folder in wwwroot then store the url for the file in a sql server database table along with the other details of the form? If anyone has any ideas it would be greatly appriciated. I have used this code but it does not store anything. However when i created a fresh new project i managed to get the code working on that correctly but cannot seem to get it to work in this work project. Not sure if it has something to do with the fact i have repositories and the fresh project i created that did work didnt have any repositories. That is the only difference i can think of. Any ideas?

//Model

```<code>namespace PostProjectEvaluations.Web.Models
{
    public partial class Projects
    {
        [Key]
        public int ProjectId { get; set; }
        [Required]
        [StringLength(300)]
        public string Name { get; set; }
        [Required]
        [StringLength(50)]
        public string Manager { get; set; }

        public string FilePath { get; set; }

    }
    public class ProjectsVM
    {
        public string Name { get; set; }
        public IFormFile File { get; set; }
    }
</code>```

//Controller

```<code>    namespace PostProjectEvaluations.Web.Controllers
    {
        public class projectsController : Controller
        {
            private readonly IApplicationRepository ApplicationRepository;
            private readonly PostProjectEvaluationsContext _context;
            private IHostingEnvironment mxHostingEnvironment { get; set; }
            private object objproject;

            public projectsController(IApplicationRepository applicationRepository,
                IHostingEnvironment hostingEnvironment, PostProjectEvaluationsContext context)
            {
                mxHostingEnvironment = hostingEnvironment;
                ApplicationRepository = applicationRepository;
                _context = context;
            }

            public IActionResult Index()
            {
                ViewBag.dataSource = ApplicationRepository.GetAllProjects().ToList();
                var projects = ApplicationRepository.GetAllProjects();
                return View(projects);
            }

            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Index(ProjectsVM projectsVM)
            {
                if (projectsVM.File != null)
                {
                    //upload files to wwwroot
                    var fileName = Path.GetFileName(projectsVM.File.FileName);
                    var filePath = Path.Combine(mxHostingEnvironment.WebRootPath, "Uploads", fileName);

                    using (var fileSteam = new FileStream(filePath, FileMode.Create))
                    {
                        await projectsVM.File.CopyToAsync(fileSteam);
                    }
                    //your logic to save filePath to database, for example

                    Projects projects = new Projects();
                    projects.Name = projectsVM.Name;
                    projects.FilePath = filePath;

                    _context.Projects.Add(projects);
                    _context.SaveChanges();
                }
                else
                {

                }
                return View("Index");
            }
 public IActionResult Details(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            return View(project);
        }

        [HttpGet]
        public IActionResult Create()
        {

            var project = new Projects();
            return View(project);
        }

        [HttpPost]
        public IActionResult Create(Projects projects)
        {
            ApplicationRepository.Create(projects);
            return RedirectToAction("Index");

        }

        public IActionResult Delete(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            ApplicationRepository.Delete(project);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public IActionResult Edit(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            //mxApplicationRepository.SaveChangesAsync();
            return View(project);
        }
        [HttpPost]
        public IActionResult Edit(Projects projects)
        {
            ApplicationRepository.Edit(projects);
            //mxApplicationRepository.SaveChangesAsync();
            return RedirectToAction("Index");
        }

    }

}
</code>```

//View

```<code>      <form enctype="multipart/form-data" asp-controller="Projects" asp-action="Create" method="post" class="form-horizontal">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-body">
                <h3 class="form-section">Project Info</h3>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label col-md-3">Project Name</label>
                            <div class="col-md-9">
                                <input asp-for="Name" class="form-control" placeholder="Name">
                                <span asp-validation-for="Name" class="text-danger"></span>
                            </div>
                        </div>
                    </div>
                    <!--/span-->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label col-md-3">Project Manager</label>
                            <div class="col-md-9">
                                <input asp-for="Manager" class="form-control" placeholder="Name">
                            </div>
                        </div>
                    </div>
                    <!--/span-->
                </div>

                <!--/span-->
            </div>
            <h3 class="form-section">Project Files</h3>
            <!--/row-->
            <div class="row">
                <div>
                    <div class="col-md-6">
                        <div class="col-md-10">
                            <p>Upload one or more files using this form:</p>
                            <input type="file" name="files" multiple />
                        </div>
                    </div>
                </div>
                <div>
                </div>
                </div>

                <div class="form-actions right">
                    <input type="submit" class="btn blue-assembly" name="submitButton" value="Save" />
                    <a asp-action="Index" class="btn default" onclick="cancelClick()">Cancel</a>
                </div>
</form>
</code>```

答:
Try the following code

```<code> if (ModelState.IsValid)
        {
            string folder = null;
            if (model.File != null)
            {
                if (model.File.Length > 0)
                {
                    Guid guid1 = Guid.NewGuid();
                    folder = "/attachement/docs/" + guid1 + model.File.FileName;
                    string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "attachement/docs");
                    string uniqueFileName = guid1 + model.File.FileName;

                    string filePath = Path.Combine(uploadFolder, uniqueFileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await model.FormFile.CopyToAsync(stream);
                    }
                }
            }}
</code>```

And for uploading multiple files, first you have to define this in Model

```<code>public List<IFormFile> ImageFiles { get; set; }
</code>```

and in Model constructor

```<code> ImageFiles = new List<IFormFile>();

</code>```

and then use the following code

```<code> foreach (var file in model.ImageFiles)
            {
                if (file.Length > 0)
                {
                    Guid guid = Guid.NewGuid();
                    folder = "/attachement/images/" + guid + file.FileName;
                    string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "attachement/images");
                    string uniqueFileName = guid + file.FileName;

                    string filePath = Path.Combine(uploadFolder, uniqueFileName);
                    // string filePath = Path.Combine(uploadFolder, model.FormFile.FileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    await context.GraspProgressDetails.AddAsync(new GraspProgressDetail
                    {
                        GraspProgressId = result.Entity.ProgressId,
                        ImageUrl = folder
                    });
                }
            }
</code>```

Body:
Trying to upload a file as part of a form and store it in a folder in wwwroot then store the url for the file in a sql server database table along with the other details of the form? If anyone has any ideas it would be greatly appriciated. I have used this code but it does not store anything. However when i created a fresh new project i managed to get the code working on that correctly but cannot seem to get it to work in this work project. Not sure if it has something to do with the fact i have repositories and the fresh project i created that did work didnt have any repositories. That is the only difference i can think of. Any ideas?

//Model

namespace PostProjectEvaluations.Web.Models
{
    public partial class Projects
    {
        [Key]
        public int ProjectId { get; set; }
        [Required]
        [StringLength(300)]
        public string Name { get; set; }
        [Required]
        [StringLength(50)]
        public string Manager { get; set; }

        public string FilePath { get; set; }

    }
    public class ProjectsVM
    {
        public string Name { get; set; }
        public IFormFile File { get; set; }
    }

//Controller

    namespace PostProjectEvaluations.Web.Controllers
    {
        public class projectsController : Controller
        {
            private readonly IApplicationRepository ApplicationRepository;
            private readonly PostProjectEvaluationsContext _context;
            private IHostingEnvironment mxHostingEnvironment { get; set; }
            private object objproject;

            public projectsController(IApplicationRepository applicationRepository,
                IHostingEnvironment hostingEnvironment, PostProjectEvaluationsContext context)
            {
                mxHostingEnvironment = hostingEnvironment;
                ApplicationRepository = applicationRepository;
                _context = context;
            }

            public IActionResult Index()
            {
                ViewBag.dataSource = ApplicationRepository.GetAllProjects().ToList();
                var projects = ApplicationRepository.GetAllProjects();
                return View(projects);
            }

            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Index(ProjectsVM projectsVM)
            {
                if (projectsVM.File != null)
                {
                    //upload files to wwwroot
                    var fileName = Path.GetFileName(projectsVM.File.FileName);
                    var filePath = Path.Combine(mxHostingEnvironment.WebRootPath, "Uploads", fileName);

                    using (var fileSteam = new FileStream(filePath, FileMode.Create))
                    {
                        await projectsVM.File.CopyToAsync(fileSteam);
                    }
                    //your logic to save filePath to database, for example

                    Projects projects = new Projects();
                    projects.Name = projectsVM.Name;
                    projects.FilePath = filePath;

                    _context.Projects.Add(projects);
                    _context.SaveChanges();
                }
                else
                {

                }
                return View("Index");
            }
 public IActionResult Details(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            return View(project);
        }

        [HttpGet]
        public IActionResult Create()
        {

            var project = new Projects();
            return View(project);
        }

        [HttpPost]
        public IActionResult Create(Projects projects)
        {
            ApplicationRepository.Create(projects);
            return RedirectToAction("Index");

        }

        public IActionResult Delete(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            ApplicationRepository.Delete(project);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public IActionResult Edit(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            //mxApplicationRepository.SaveChangesAsync();
            return View(project);
        }
        [HttpPost]
        public IActionResult Edit(Projects projects)
        {
            ApplicationRepository.Edit(projects);
            //mxApplicationRepository.SaveChangesAsync();
            return RedirectToAction("Index");
        }

    }

}

//View

      <form enctype="multipart/form-data" asp-controller="Projects" asp-action="Create" method="post" class="form-horizontal">

Project Info

                            Project Name

                                <input asp-for="Name" class="form-control" placeholder="Name">

                            Project Manager

                                <input asp-for="Manager" class="form-control" placeholder="Name">

Project Files

Upload one or more files using this form:

                            <input type="file" name="files" multiple />

                    <input type="submit" class="btn blue-assembly" name="submitButton" value="Save" />
                    Cancel

</form>

Body:
Try the following code

 if (ModelState.IsValid)
        {
            string folder = null;
            if (model.File != null)
            {
                if (model.File.Length > 0)
                {
                    Guid guid1 = Guid.NewGuid();
                    folder = "/attachement/docs/" + guid1 + model.File.FileName;
                    string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "attachement/docs");
                    string uniqueFileName = guid1 + model.File.FileName;

                    string filePath = Path.Combine(uploadFolder, uniqueFileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await model.FormFile.CopyToAsync(stream);
                    }
                }
            }}

And for uploading multiple files, first you have to define this in Model

public List<IFormFile> ImageFiles { get; set; }

and in Model constructor

 ImageFiles = new List<IFormFile>();

and then use the following code

 foreach (var file in model.ImageFiles)
            {
                if (file.Length > 0)
                {
                    Guid guid = Guid.NewGuid();
                    folder = "/attachement/images/" + guid + file.FileName;
                    string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "attachement/images");
                    string uniqueFileName = guid + file.FileName;

                    string filePath = Path.Combine(uploadFolder, uniqueFileName);
                    // string filePath = Path.Combine(uploadFolder, model.FormFile.FileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    await context.GraspProgressDetails.AddAsync(new GraspProgressDetail
                    {
                        GraspProgressId = result.Entity.ProgressId,
                        ImageUrl = folder
                    });
                }
            }


问:
Create Folder using storage access framework
I am knew to Android Studio. I want to create folder in external storage through android app. I tried using getExternalStorageDir() but it is not implemented for API level above 23. Please guide me to create folder and file in android app. Ignore any grammatical mistake if present. And I also want this process to be done in background without going anywhere from mainactivity.

答:
Put this in public void

```<code>Intent intent = new
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, NEW_FOLDER_REQUEST_CODE);
</code>```

This on Activity Result

```<code>if (_resultCode == Activity.RESULT_OK) { if (_requestCode ==
NEW_FOLDER_REQUEST_CODE)
{ if (_data != null) { Uri currentUri = _data.getData();
DocumentFile pickedDir =
DocumentFile.fromTreeUri(this, currentUri);
DocumentFile newDir =
pickedDir.createDirectory("MyFolder"); } } }
</code>```

This is another public void on oncreate

```<code>}
private static final int NEW_FOLDER_REQUEST_CODE = 43;
}
</code>```

Body:
Put this in public void

Intent intent = new
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, NEW_FOLDER_REQUEST_CODE);

This on Activity Result

if (_resultCode == Activity.RESULT_OK) { if (_requestCode ==
NEW_FOLDER_REQUEST_CODE)
{ if (_data != null) { Uri currentUri = _data.getData();
DocumentFile pickedDir =
DocumentFile.fromTreeUri(this, currentUri);
DocumentFile newDir =
pickedDir.createDirectory("MyFolder"); } } }

This is another public void on oncreate

}
private static final int NEW_FOLDER_REQUEST_CODE = 43;
}