问:
What is the impact of not calling the arguments while calling a function
My question is about the difference between two ways to pass the the arguments of a function

for instance

```<code>function1(obj1, obj2, obj3, obj4, obj5)
</code>```

or

```<code>function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)
</code>```

Is there a rule/convention/document for that?

I can see at least 2 situations where the first way is not great

If we want to add a new argument, we are forced to add it at the end of the list, which may not great for the common sense (as I like to group arguments that goes together)

The arguments with default have to be put at the end of the list, otherwise you have to input it even if you use the default value.

Any ideas on that?

答:
From a function implementer's point of view, you must always add new parameters to the end and name them so they don't have a prefix in common with existing arguments.

This is because people are free to use positional matching and partial names. A fact of R life...

Body:
My question is about the difference between two ways to pass the the arguments of a function

for instance

function1(obj1, obj2, obj3, obj4, obj5)

or

function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)

Is there a rule/convention/document for that?

I can see at least 2 situations where the first way is not great

If we want to add a new argument, we are forced to add it at the end of the list, which may not great for the common sense (as I like to group arguments that goes together)

The arguments with default have to be put at the end of the list, otherwise you have to input it even if you use the default value.

Any ideas on that?


来源: stackexchange

问:
How do I remove focus from a TextField in SwiftUI on MacOS?
I have a view in which the user enters data into a several textfields, but I can't allow the user to exit the textfields; one of them is always selected. How do I make the fields un-focus when I click on something else (the background, the submit button, etc.)?

Current View:

```<code>struct ContentView: View {
    var body: some View {
        Form {
            TextField("Username", text: $username)
            TextField("Password", text: $password)

            Button("Submit") {
                // Submit data
            }
        }
    }
}
</code>```

答:
You need to use an optional @FocusState and use .allowsHitTesting(true). On the form, you put a .onTapGesture that sets @FocusState to nil.

```<code>struct ContentView: View {
    @State private var username: String = ""
    @State private var password: String = ""
    @FocusState private var focusedField: String?

    var body: some View {
        Form {
            TextField("Username", text: $username)
                .focused($focusedField, equals: "user")
            TextField("Password", text: $password)
                .focused($focusedField, equals: "password")
            Button("Submit") {
                // Submit data
                focusedField = nil
            }
        }
        .onTapGesture {
            focusedField = nil
        }
    }
}
</code>```

The .allowsHitTesting(true) lets the TextFields accept tap gestures directly, otherwise they would be blocked by the Form's .onTapGesture.

On macOS, in the sidebar, the form is only the size of the Button and TextFields. If you wanted a larger tap area, you would need some kind of background to place it on.

ContentLicense: CC BY-SA 4.0

Body:
I have a view in which the user enters data into a several textfields, but I can't allow the user to exit the textfields; one of them is always selected. How do I make the fields un-focus when I click on something else (the background, the submit button, etc.)?

Current View:

struct ContentView: View {
    var body: some View {
        Form {
            TextField("Username", text: $username)
            TextField("Password", text: $password)

            Button("Submit") {
                // Submit data
            }
        }
    }
}

Body:
You need to use an optional @FocusState and use .allowsHitTesting(true). On the form, you put a .onTapGesture that sets @FocusState to nil.

struct ContentView: View {
    @State private var username: String = ""
    @State private var password: String = ""
    @FocusState private var focusedField: String?

    var body: some View {
        Form {
            TextField("Username", text: $username)
                .focused($focusedField, equals: "user")
            TextField("Password", text: $password)
                .focused($focusedField, equals: "password")
            Button("Submit") {
                // Submit data
                focusedField = nil
            }
        }
        .onTapGesture {
            focusedField = nil
        }
    }
}

The .allowsHitTesting(true) lets the TextFields accept tap gestures directly, otherwise they would be blocked by the Form's .onTapGesture.

On macOS, in the sidebar, the form is only the size of the Button and TextFields. If you wanted a larger tap area, you would need some kind of background to place it on.


问:
Compute number of word distance of 1 for every word in pandas column
For each string in a list, I need to find the number of strings in that list that are one levenshtein-distance away. The levenshtein-distance is smallest number of character substitutions, additions, or removals necessary to derive one word from another. For illustration, please see the following DataFrame:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'word':['can', 'cans', 'canse', 'canpe', 'canp', 'camp'],
'code':['k@n', 'k@n}', 'k@(z', np.nan, 'k@()', np.nan]})

  word  code
0 can    k@n
1 cans  k@n}
2 canse k@(z
3 canpe
4 canp  k@()
5 camp
</code>```

My current implementation is way too slow:

```<code>from Levenshtein import distance as lev

df = df.fillna('')

# get unique strings
wordAll = df['word'].dropna().to_list()
codeAll = list(set(df['code'].dropna().to_list()))

# prepare dataframe for storage
df['wordLev'] = np.nan
df['codeLev'] = np.nan

# find neighbors
for idx,row in df.iterrows():
    i=0
    j=0

    # get word and code
    word = row['word']
    code = row['code']

    # remove word and code from all-strings-list
    wordSubset = [w for w in wordAll if w != word]
    codeSubset = [c for c in codeAll if c != code]

    # compute number of neighbors
    for item in wordSubset:
        if lev(word, item) == 1:
            i += 1
    for item in codeSubset:
        if lev(code, item) == 1:
            j += 1

    # add number of neighbors to df
    df.loc[df['code'] == code, 'wordLev'] = i
    if code != '':
        df.loc[df['code'] == code, 'codeLev'] = j
    else:
        df.loc[df['code'] == code, 'codeLev'] = ''

df

  word  code wordLev codeLev
0 can    k@n       2       1
1 cans  k@n}       3       1
2 canse k@(z       2       1
3 canpe            2
4 canp  k@()       3       1
5 camp             1

</code>```

How can I speed it up? The DataFrame has ~500k rows...

答:
The following code seems to be ~5x faster than your code at 1.8ms vs 9.6ms (at least on the df you've provided).

```<code>df = df.fillna('')
df['wordLev'] = [sum(1 for item in df['word'] if item!=word and lev(word, item)==1) for word in df['word']]
df['codeLev'] = [sum(1 for item in df['code'] if item!=code and lev(code, item)==1) or '' for code in df['code']]
</code>```

This code is really very similar to yours. Biggest difference is that instead of creating wordSubset or codeSubset and then iterating over them again to apply the levenshtein distance function, it does it in all in a single generator expression. Since you're checking each word with every word in the column, you can't escape a double loop imo.

Body:
For each string in a list, I need to find the number of strings in that list that are one levenshtein-distance away. The levenshtein-distance is smallest number of character substitutions, additions, or removals necessary to derive one word from another. For illustration, please see the following DataFrame:

import pandas as pd
import numpy as np
df = pd.DataFrame({
'word':['can', 'cans', 'canse', 'canpe', 'canp', 'camp'],
'code':['k@n', 'k@n}', 'k@(z', np.nan, 'k@()', np.nan]})

  word  code
0 can    k@n
1 cans  k@n}
2 canse k@(z
3 canpe
4 canp  k@()
5 camp

My current implementation is way too slow:

from Levenshtein import distance as lev

df = df.fillna('')

# get unique strings
wordAll = df['word'].dropna().to_list()
codeAll = list(set(df['code'].dropna().to_list()))

# prepare dataframe for storage
df['wordLev'] = np.nan
df['codeLev'] = np.nan

# find neighbors
for idx,row in df.iterrows():
    i=0
    j=0

    # get word and code
    word = row['word']
    code = row['code']

    # remove word and code from all-strings-list
    wordSubset = [w for w in wordAll if w != word]
    codeSubset = [c for c in codeAll if c != code]

    # compute number of neighbors
    for item in wordSubset:
        if lev(word, item) == 1:
            i += 1
    for item in codeSubset:
        if lev(code, item) == 1:
            j += 1

    # add number of neighbors to df
    df.loc[df['code'] == code, 'wordLev'] = i
    if code != '':
        df.loc[df['code'] == code, 'codeLev'] = j
    else:
        df.loc[df['code'] == code, 'codeLev'] = ''

df

  word  code wordLev codeLev
0 can    k@n       2       1
1 cans  k@n}       3       1
2 canse k@(z       2       1
3 canpe            2
4 canp  k@()       3       1
5 camp             1

How can I speed it up? The DataFrame has ~500k rows...

Body:
The following code seems to be ~5x faster than your code at 1.8ms vs 9.6ms (at least on the df you've provided).

df = df.fillna('')
df['wordLev'] = [sum(1 for item in df['word'] if item!=word and lev(word, item)==1) for word in df['word']]
df['codeLev'] = [sum(1 for item in df['code'] if item!=code and lev(code, item)==1) or '' for code in df['code']]

This code is really very similar to yours. Biggest difference is that instead of creating wordSubset or codeSubset and then iterating over them again to apply the levenshtein distance function, it does it in all in a single generator expression. Since you're checking each word with every word in the column, you can't escape a double loop imo.


问:
Discordjs TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client
I'm making a bot for ddiscord and I can't solve this error:
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.

```<code>const { Client, Intents } = require('discord.js');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

const config = require('./config.json')
const dotenv = require('dotenv')
dotenv.config()

const privateMessage = require('./private-message');
const test = require('./test.js')

const mySecret = process.env['TOKEN'];

client.on('ready', () => {
  console.log(`${client.user.tag} has logged in.`);
});
</code>```

and this is the complete error:

```<code>D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:548
      throw new TypeError('CLIENT_MISSING_INTENTS');
      ^

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
    at Client._validateOptions (D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:548:13)
    at new Client (D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:76:10)
    at Object.<anonymous> (D:\user\Bots\dadobot2801\a\test.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\user\Bots\dadobot2801\a\index.js:10:14) {
  [Symbol(code)]: 'CLIENT_MISSING_INTENTS'
}
</code>```

Any ideas?

答:
Try using this. Since new updated of discord.js like version ^13.0 you have to specify client intents:

const { Client, Intents } = require('discord.js');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
```

Its how you do it

Body:
I'm making a bot for ddiscord and I can't solve this error:
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.

const { Client, Intents } = require('discord.js');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

const config = require('./config.json')
const dotenv = require('dotenv')
dotenv.config()

const privateMessage = require('./private-message');
const test = require('./test.js')

const mySecret = process.env['TOKEN'];

client.on('ready', () => {
  console.log(`${client.user.tag} has logged in.`);
});

and this is the complete error:

D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:548
      throw new TypeError('CLIENT_MISSING_INTENTS');
      ^

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
    at Client._validateOptions (D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:548:13)
    at new Client (D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:76:10)
    at Object.<anonymous> (D:\user\Bots\dadobot2801\a\test.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\user\Bots\dadobot2801\a\index.js:10:14) {
  [Symbol(code)]: 'CLIENT_MISSING_INTENTS'
}

Any ideas?

Body:
Try using this. Since new updated of discord.js like version ^13.0 you have to specify client intents:

const { Client, Intents } = require('discord.js');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

Its how you do it


问:
SwiftUI ColorPicker cause pop to root view
I have this weird issue. When I click the ColorPicker, the view dismissed and pop back to the root view. I have attach a screen record below. Anyone have idea how to fix this issue?

The code run on simulator ios 15.2

See screen record here

```<code>import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                HomePageView()
                    .tabItem {
                        Label("Home", systemImage: "circle.grid.cross.fill")
                    }

                ProfileView()
                    .tabItem {
                        Label("Profile", systemImage: "person.fill")
                    }
            }
            .background(.secondary)
        }
    }
}

struct HomePageView: View {
    var body: some View {
        Text("Home View")
    }
}

struct ProfileView: View {
    var body: some View {
        NavigationLink {
            ColorPickerView()
        } label: {
            Text("Color Picker View")
        }
    }
}

struct ColorPickerView: View {
    @State var bgColor = Color.blue
    var body: some View {
        ColorPicker("Pick color", selection: self.$bgColor)
            .padding(.horizontal, 15)
    }
}
</code>```

答: NavigationView in each tab instead of outside the TabView

Body:
I have this weird issue. When I click the ColorPicker, the view dismissed and pop back to the root view. I have attach a screen record below. Anyone have idea how to fix this issue?

The code run on simulator ios 15.2

See screen record here

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                HomePageView()
                    .tabItem {
                        Label("Home", systemImage: "circle.grid.cross.fill")
                    }

                ProfileView()
                    .tabItem {
                        Label("Profile", systemImage: "person.fill")
                    }
            }
            .background(.secondary)
        }
    }
}

struct HomePageView: View {
    var body: some View {
        Text("Home View")
    }
}

struct ProfileView: View {
    var body: some View {
        NavigationLink {
            ColorPickerView()
        } label: {
            Text("Color Picker View")
        }
    }
}

struct ColorPickerView: View {
    @State var bgColor = Color.blue
    var body: some View {
        ColorPicker("Pick color", selection: self.$bgColor)
            .padding(.horizontal, 15)
    }
}


问:
UILocalNotifications playing Custom sound
I implemented local notification in my app but I am just wondering is there a way to play a sound that is not part of the main bundle of iPhone App.
Basically in my app, I want user to record a sound that gets played when the local notification is generated instead of playing a pre-recorded or default sound.
As far as i know this can be implementable because i have seen 2-3 App in  app store which is doing the same thing which i want to do</p>

```<code>- (void)alertSelector:(NSString *)AlertTitle WithFiringTime:(NSDate *)date
{

UILocalNotification *localNotification = [[[UILocalNotification alloc] init] autorelease];
   [localNotification setFireDate:date];
   [localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
   NSDictionary *data = [NSDictionary dictionaryWithObject:date forKey:@"payload"];
   [localNotification setUserInfo:data];[localNotification setAlertBody:AlertTitle];
   [localNotification setAlertAction:@"View"]; [localNotification setHasAction:YES];
   localNotification.soundName=@"voice.aif";

   if (!localNotification)
          return;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
</code>```

答:
From the description of the soundName property -

For this property, specify the filename (including extension) of a
  sound resource in the application’s main bundle or
  UILocalNotificationDefaultSoundName to request the default system
  sound.

It doesn't seem that sounds other than those present in the bundle can be used. Are you sure that the apps are using local notifications with their custom sounds? Maybe they are playing sounds with alerts or something like that.

HTH,

Akshay

ContentLicense: CC BY-SA 3.0

Body:
I implemented local notification in my app but I am just wondering is there a way to play a sound that is not part of the main bundle of iPhone App.
Basically in my app, I want user to record a sound that gets played when the local notification is generated instead of playing a pre-recorded or default sound.
As far as i know this can be implementable because i have seen 2-3 App in  app store which is doing the same thing which i want to do

- (void)alertSelector:(NSString *)AlertTitle WithFiringTime:(NSDate *)date
{

UILocalNotification *localNotification = [[[UILocalNotification alloc] init] autorelease];
   [localNotification setFireDate:date];
   [localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
   NSDictionary *data = [NSDictionary dictionaryWithObject:date forKey:@"payload"];
   [localNotification setUserInfo:data];[localNotification setAlertBody:AlertTitle];
   [localNotification setAlertAction:@"View"]; [localNotification setHasAction:YES];
   localNotification.soundName=@"voice.aif";

   if (!localNotification)
          return;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}


问:
Use sed to Replace Multiple Lines
I'm trying to use sed to replace multiple lines which are found via regex with one substitution.  For example, given the following simplified text file

```<code>first
second
third
fourth
fifth
sixth
seventh
eighth
</code>```

How would I go about using regex to find the second to fourth lines and replace the whole range with one instance of the word "found" so that the end result is

```<code>first
found
fifth
sixth
seventh
eighth
</code>```

I'm basically looking to combine the substitution syntax (sed 's/second/found/') with the range syntax (sed '/second/,/fourth/') into something like sed 's/second/,/fourth/found/' that actually works.

答:
This might work for you (GNU sed):

```<code>sed '/second/,/fourth/cfound' file
</code>```

or for those line numbers:

```<code>sed '2,4cfound' file
</code>```

Title: Use sed to Replace Multiple Lines

Body:
I'm trying to use sed to replace multiple lines which are found via regex with one substitution.  For example, given the following simplified text file

first
second
third
fourth
fifth
sixth
seventh
eighth

How would I go about using regex to find the second to fourth lines and replace the whole range with one instance of the word "found" so that the end result is

first
found
fifth
sixth
seventh
eighth

I'm basically looking to combine the substitution syntax (sed 's/second/found/') with the range syntax (sed '/second/,/fourth/') into something like sed 's/second/,/fourth/found/' that actually works.

Body:
This might work for you (GNU sed):

sed '/second/,/fourth/cfound' file

or for those line numbers:

sed '2,4cfound' file


问:
PL SQL FUNCTION BODY RETURN SQL QUERY GETS ERROR: ORA-20001: Query must begin with SELECT or WITH
I get an ORA-20001: Query must begin with SELECT or WITH when I verify the code below. Does that mean I can't use FOR record (sql query) and a loop? Is it ok to load APEX card info the way I did in the loop?  Any help is appreciated.

My goal is to display all media for a project and make the icon turn green for MEDIA that is referenced in a specific STEP_MEDIA row. I have tried outer joins, but I get duplicates. If there is a better way please let me know.

Oracle Cloud
Application Express 21.1.7
Database Version: 19c

```<code>return q'~

DECLARE
n_count number;
BEGIN
FOR record in (SELECT *
FROM MEDIA
where KHN_PROJECT_ID = :P300_PROJECT_ID
 ORDER BY FILE_NAME)

LOOP
 CARD_TITLE := record.FILE_NAME;
 CARD_SUBTITLE := record.FILE_MIMETYPE;
CARD_LINK := apex_util.prepare_url( '#' );
       CASE WHEN record.FILE_MIMETYPE LIKE 'video%'
        THEN
      CARD_TEXT :=  '<video> ...</video>';
       ELSE
      CARD_TEXT := '<img> ...</img>';
      END CASE;

      CARD_ICON := 'fa-check';
      SELECT COUNT(STEP_MEDIA_ID) INTO n_count
      FROM STEP_MEDIA
      WHERE MEDIA_ID = record.MEDIA_ID AND STEP_ID = :P300_STEP_ID_LOADED;
       IF ncount = 0
       THEN
      CARD_COLOR := 'u-success';
       ELSE
       CARD_COLOR := 'u-normal';
       END IF;

CARD_SUBTEXT := '<button class="t-Button t-Button--noLabel t-Button--icon add-favorite" id="fav_'||record.MEDIA_ID||'" type="button">Select</span></button>';
END LOOP;
END;

~';
</code>```

Here is the code I wrote using an outer join. It produces duplicate rows.

```<code>select m.FILE_NAME AS CARD_TITLE,
       m.FILE_MIMETYPE AS CARD_SUBTITLE,

       m.MEDIA_ID,
apex_util.prepare_url( '#' ) CARD_LINK,
       CASE WHEN m.FILE_MIMETYPE LIKE 'video%'
        THEN
        '<video >...</video>'
       ELSE
       '<img >...</img>'
      END
       CARD_TEXT,
       'fa-check' CARD_ICON,
       CASE WHEN sm.step_media_id is NULL
       THEN
       'u-success'
       ELSE
       'u-normal'
       END
        CARD_COLOR,

  from MEDIA m
  LEFT OUTER JOIN STEP_MEDIA sm
  ON m.MEDIA_ID = sm.MEDIA_ID
 where m.KHN_PROJECT_ID = :P300_PROJECT_ID OR sm.STEP_ID = :P300_STEP_ID_LOADED
 ORDER BY m.FILE_NAME
</code>```

答:
This query uses sql which is compatible with Oracle Apex and displays all media and shows which media is used in a step. The subquery was the solution.</p>
```<code>select DISTINCT m.FILE_NAME AS CARD_TITLE,
       m.FILE_MIMETYPE AS CARD_SUBTITLE,
       m.TAGS AS TAGS,
       m.MEDIA_ID,
apex_util.prepare_url( '#' ) CARD_LINK,
       CASE WHEN m.FILE_MIMETYPE LIKE 'video%'
        THEN
        '<video controls width = "100%" height= "100%" class="object-fit">... </video>'
       ELSE
       '<img >...</img>'
      END
       CARD_TEXT,
       'fa-check' CARD_ICON,
       CASE WHEN sm.step_media_id is NULL
       THEN
        'u-normal'
    ELSE
      'u-success'
       END
        CARD_COLOR,
 '<button class="t-Button t-Button--noLabel t-Button--icon add-favorite" id="fav_'||m.MEDIA_ID||'" type="button">Select</span></button>' CARD_SUBTEXT
  from MEDIA m
  LEFT OUTER JOIN (select * FROM STEP_MEDIA WHERE STEP_ID = :P300_STEP_ID_LOADED) sm
  ON m.MEDIA_ID = sm.MEDIA_ID
 where m.KHN_PROJECT_ID = :P300_PROJECT_ID
 ORDER BY m.FILE_NAME
</code>```

Body:
I get an ORA-20001: Query must begin with SELECT or WITH when I verify the code below. Does that mean I can't use FOR record (sql query) and a loop? Is it ok to load APEX card info the way I did in the loop?  Any help is appreciated.

My goal is to display all media for a project and make the icon turn green for MEDIA that is referenced in a specific STEP_MEDIA row. I have tried outer joins, but I get duplicates. If there is a better way please let me know.

Oracle Cloud
Application Express 21.1.7
Database Version: 19c

return q'~

DECLARE
n_count number;
BEGIN
FOR record in (SELECT *
FROM MEDIA
where KHN_PROJECT_ID = :P300_PROJECT_ID
 ORDER BY FILE_NAME)

LOOP
 CARD_TITLE := record.FILE_NAME;
 CARD_SUBTITLE := record.FILE_MIMETYPE;
CARD_LINK := apex_util.prepare_url( '#' );
       CASE WHEN record.FILE_MIMETYPE LIKE 'video%'
        THEN
      CARD_TEXT :=  '<video> ...</video>';
       ELSE
      CARD_TEXT := ' ...';
      END CASE;

      CARD_ICON := 'fa-check';
      SELECT COUNT(STEP_MEDIA_ID) INTO n_count
      FROM STEP_MEDIA
      WHERE MEDIA_ID = record.MEDIA_ID AND STEP_ID = :P300_STEP_ID_LOADED;
       IF ncount = 0
       THEN
      CARD_COLOR := 'u-success';
       ELSE
       CARD_COLOR := 'u-normal';
       END IF;

CARD_SUBTEXT := '<button class="t-Button t-Button--noLabel t-Button--icon add-favorite" id="fav_'||record.MEDIA_ID||'" type="button">Select</button>';
END LOOP;
END;

~';

Here is the code I wrote using an outer join. It produces duplicate rows.

select m.FILE_NAME AS CARD_TITLE,
       m.FILE_MIMETYPE AS CARD_SUBTITLE,

       m.MEDIA_ID,
apex_util.prepare_url( '#' ) CARD_LINK,
       CASE WHEN m.FILE_MIMETYPE LIKE 'video%'
        THEN
        '<video >...</video>'
       ELSE
       '...'
      END
       CARD_TEXT,
       'fa-check' CARD_ICON,
       CASE WHEN sm.step_media_id is NULL
       THEN
       'u-success'
       ELSE
       'u-normal'
       END
        CARD_COLOR,

  from MEDIA m
  LEFT OUTER JOIN STEP_MEDIA sm
  ON m.MEDIA_ID = sm.MEDIA_ID
 where m.KHN_PROJECT_ID = :P300_PROJECT_ID OR sm.STEP_ID = :P300_STEP_ID_LOADED
 ORDER BY m.FILE_NAME

Body:
This query uses sql which is compatible with Oracle Apex and displays all media and shows which media is used in a step. The subquery was the solution.

select DISTINCT m.FILE_NAME AS CARD_TITLE,
       m.FILE_MIMETYPE AS CARD_SUBTITLE,
       m.TAGS AS TAGS,
       m.MEDIA_ID,
apex_util.prepare_url( '#' ) CARD_LINK,
       CASE WHEN m.FILE_MIMETYPE LIKE 'video%'
        THEN
        '<video controls width = "100%" height= "100%" class="object-fit">... </video>'
       ELSE
       '<img >...</img>'
      END
       CARD_TEXT,
       'fa-check' CARD_ICON,
       CASE WHEN sm.step_media_id is NULL
       THEN
        'u-normal'
    ELSE
      'u-success'
       END
        CARD_COLOR,
 '<button class="t-Button t-Button--noLabel t-Button--icon add-favorite" id="fav_'||m.MEDIA_ID||'" type="button">Select</span></button>' CARD_SUBTEXT
  from MEDIA m
  LEFT OUTER JOIN (select * FROM STEP_MEDIA WHERE STEP_ID = :P300_STEP_ID_LOADED) sm
  ON m.MEDIA_ID = sm.MEDIA_ID
 where m.KHN_PROJECT_ID = :P300_PROJECT_ID
 ORDER BY m.FILE_NAME


问:
How to write generic extension method which with one type argument for generic class with another type argument
I have the following interface

public interface ITypedValueProvider<TValue>
{
    TValue GetValue(Type type);
}

```
<p>I want to create extension method which would allow me to get type from generic type argument. I have written an extension method like following.</p>
<pre class="lang-cs prettyprint-override"><code>public static class Extensions
{
    public static TValue GetValue<TType, TValue>(this ITypedValueProvider<TValue> valueProvider)
    {
        return valueProvider.GetValue(typeof(TType));
    }
}
</code>```

However, this extension method requires 2 type arguments, where I need to use only one, and hopefully other be inferred from the input generic class.

static class Program
{
    void Main()
    {
        ITypedValueProvider<int> valueProvider = new ValueProvider<int>(typeof(TargetValueConsumer));
        var value = valueProvider.GetValue<TargetValueConsumer, int>() //This line will work
        var value = valueProvider.GetValue<TargetValueConsumer>(); //This one, obviously, won't compile
    }
}

public class ValueProvider<TValue> : ITypedValueProvider<TValue>
{
   private readonly (Type ConsumerType, TValue Value) _record;

   public ValueProvider(TValue value, Type type)
   {
      _record = (type, value);
   }

   TValue GetValue(Type type)
   {
       if (_record.ConsumerType == type)
           return _record.Value;
       return default;
   }
}

public class TargetValueConsumer {}
```

How can I write the extension method which won't require second type argument for the described interface or how to use existing method which will infer second type argument from the usage?

答:
I had a similar use case and this is what worked for me. There might be something you can use. What you would do is make a extension for ITypedValueProvider and  infer the generic type of the caller from this inside the extension method.

The interface doesn't need to be generic:

```<code>public interface ITypedValueProvider
{
    TValue GetValue<TValue>();
}
</code>```

You say you want a generic class of a different T. Here you go:

```<code>class TargetValueBase<TClass> : TargetValueBase, ITypedValueProvider { }
</code>```

Make an instance of it:

```<code>var consumer = new TargetValueConsumer<AppDomain>();
</code>```

So that you can call (for example):

```<code>consumer.LogValueForClass<XElement>()
</code>```

Where a sample extension method (something you can't call on the class directly) might be something like:

```<code>public static class Extensions
{
    public static string LogValueForClass<TValue>(this ITypedValueProvider @this)
    {
        var type = @this.GetType();
        var builder = new List<string>();
        builder.Add($"INFERRED CLASS: { type.GetGenericTypeDefinition().Name.Split('`')[0]}" );
        foreach (var arg in type.GetGenericArguments())
        {
            builder.Add(arg.Name);
        }
        // Call a generic method on the provider
        var getValueResult = @this.GetValue<TValue>();

        builder.Add($"The GetValue method returned: {getValueResult}");
        return string.Join(Environment.NewLine, builder);
    }
}
</code>```

The TargetValueBase doesn't need to be generic, either.

```<code>class TargetValueBase
{
    public TValue GetValue<TValue>()
    {
        var tValueName = typeof(TValue).Name;

        // Figure out what to return.
        switch (tValueName)
        {
            case nameof(XElement):
                Console.WriteLine($"Case 1: {tValueName}");
                var instance = new XElement("xelement", new XAttribute("hello", "world"));
                return (TValue)(object)instance;
            case nameof(UInt16):
                Console.WriteLine($"Case 2: {tValueName}");
                break;
            case nameof(UInt32):
                Console.WriteLine($"Case 3: {tValueName}");
                break;
            case nameof(UInt64):
                Console.WriteLine($"Case 4: {tValueName}");
                break;
        }
        return default(TValue);
    }
    public override string ToString() => GetType().Name;
}
</code>```

Put it all in a little Unit Test...

```<code>[TestMethod]
public void GenericGetterTest()
{
    string result;
    TargetValueBase nonGeneric = new TargetValueBase();

    // Calling Generic GetValue doesn't require an extension
    // or even a generic class. But that's not what you asked.
    Console.WriteLine($"{Environment.NewLine}Calling Generic Method on Non-Generic Value Provider{Environment.NewLine}");
    nonGeneric.GetValue<XElement>();
    nonGeneric.GetValue<UInt16>();
    nonGeneric.GetValue<UInt32>();
    nonGeneric.GetValue<UInt64>();

    var retail = new TargetValueRetailer<CrossAppDomainDelegate>();
    var consumer = new TargetValueConsumer<AppDomain>();

    // We make extensions for methods we CAN'T call on the class. Maybe
    // the original class is from an external dll, or the class is
    // sealed for inheritance, or change all the references is prohibitive.

    // What you asked:
    // "Generic extension method with one generic type for class and another for value."
    // Here's a made-up one:
    Console.WriteLine($"{Environment.NewLine}Calling Extension...{Environment.NewLine}");
    result = consumer.LogValueForClass<UInt16>();
    Console.WriteLine($"{result}{Environment.NewLine}");

    Console.WriteLine($"{Environment.NewLine}Calling Extension...{Environment.NewLine}");
    result = retail.LogValueForClass<XElement>();
    Console.WriteLine($"{retail.LogValueForClass<XElement>()}{Environment.NewLine}");
}
</code>```

... and run it!

Fun.

Body:
I have the following interface

public interface ITypedValueProvider<TValue>
{
    TValue GetValue(Type type);
}

I want to create extension method which would allow me to get type from generic type argument. I have written an extension method like following.

public static class Extensions
{
    public static TValue GetValue<TType, TValue>(this ITypedValueProvider<TValue> valueProvider)
    {
        return valueProvider.GetValue(typeof(TType));
    }
}

However, this extension method requires 2 type arguments, where I need to use only one, and hopefully other be inferred from the input generic class.

static class Program
{
    void Main()
    {
        ITypedValueProvider<int> valueProvider = new ValueProvider<int>(typeof(TargetValueConsumer));
        var value = valueProvider.GetValue<TargetValueConsumer, int>() //This line will work
        var value = valueProvider.GetValue<TargetValueConsumer>(); //This one, obviously, won't compile
    }
}

public class ValueProvider<TValue> : ITypedValueProvider<TValue>
{
   private readonly (Type ConsumerType, TValue Value) _record;

   public ValueProvider(TValue value, Type type)
   {
      _record = (type, value);
   }

   TValue GetValue(Type type)
   {
       if (_record.ConsumerType == type)
           return _record.Value;
       return default;
   }
}

public class TargetValueConsumer {}

How can I write the extension method which won't require second type argument for the described interface or how to use existing method which will infer second type argument from the usage?

Body:
I had a similar use case and this is what worked for me. There might be something you can use. What you would do is make a extension for ITypedValueProvider and  infer the generic type of the caller from this inside the extension method.

The interface doesn't need to be generic:

public interface ITypedValueProvider
{
    TValue GetValue<TValue>();
}

You say you want a generic class of a different T. Here you go:

class TargetValueBase<TClass> : TargetValueBase, ITypedValueProvider { }

Make an instance of it:

var consumer = new TargetValueConsumer<AppDomain>();

So that you can call (for example):

consumer.LogValueForClass<XElement>()

Where a sample extension method (something you can't call on the class directly) might be something like:

public static class Extensions
{
    public static string LogValueForClass<TValue>(this ITypedValueProvider @this)
    {
        var type = @this.GetType();
        var builder = new List<string>();
        builder.Add($"INFERRED CLASS: { type.GetGenericTypeDefinition().Name.Split('`')[0]}" );
        foreach (var arg in type.GetGenericArguments())
        {
            builder.Add(arg.Name);
        }
        // Call a generic method on the provider
        var getValueResult = @this.GetValue<TValue>();

        builder.Add($"The GetValue method returned: {getValueResult}");
        return string.Join(Environment.NewLine, builder);
    }
}

The TargetValueBase doesn't need to be generic, either.

class TargetValueBase
{
    public TValue GetValue<TValue>()
    {
        var tValueName = typeof(TValue).Name;

        // Figure out what to return.
        switch (tValueName)
        {
            case nameof(XElement):
                Console.WriteLine($"Case 1: {tValueName}");
                var instance = new XElement("xelement", new XAttribute("hello", "world"));
                return (TValue)(object)instance;
            case nameof(UInt16):
                Console.WriteLine($"Case 2: {tValueName}");
                break;
            case nameof(UInt32):
                Console.WriteLine($"Case 3: {tValueName}");
                break;
            case nameof(UInt64):
                Console.WriteLine($"Case 4: {tValueName}");
                break;
        }
        return default(TValue);
    }
    public override string ToString() => GetType().Name;
}

Put it all in a little Unit Test...

[TestMethod]
public void GenericGetterTest()
{
    string result;
    TargetValueBase nonGeneric = new TargetValueBase();

    // Calling Generic GetValue doesn't require an extension
    // or even a generic class. But that's not what you asked.
    Console.WriteLine($"{Environment.NewLine}Calling Generic Method on Non-Generic Value Provider{Environment.NewLine}");
    nonGeneric.GetValue<XElement>();
    nonGeneric.GetValue<UInt16>();
    nonGeneric.GetValue<UInt32>();
    nonGeneric.GetValue<UInt64>();

    var retail = new TargetValueRetailer<CrossAppDomainDelegate>();
    var consumer = new TargetValueConsumer<AppDomain>();

    // We make extensions for methods we CAN'T call on the class. Maybe
    // the original class is from an external dll, or the class is
    // sealed for inheritance, or change all the references is prohibitive.

    // What you asked:
    // "Generic extension method with one generic type for class and another for value."
    // Here's a made-up one:
    Console.WriteLine($"{Environment.NewLine}Calling Extension...{Environment.NewLine}");
    result = consumer.LogValueForClass<UInt16>();
    Console.WriteLine($"{result}{Environment.NewLine}");

    Console.WriteLine($"{Environment.NewLine}Calling Extension...{Environment.NewLine}");
    result = retail.LogValueForClass<XElement>();
    Console.WriteLine($"{retail.LogValueForClass<XElement>()}{Environment.NewLine}");
}

... and run it!

Fun.


问:
how to move button inline with horizontal checklist?
I have the following code for creating a horizontal checklist and a submit button: jsfiddle

I would like for the submit button to show up inline with the checklist, right after "Visual Title". How can I achieve this? I've tried display: inline-block, display: inline, display: flex, but none of it works.

.widget-container {
    display: flex;
    flex-wrap: wrap;
    /*justify-content: center;*/
}

.checkbox-wrapper-htmlview {
    padding: 0.5em;
    margin: 0.5em 1em 0.5em 0;
    background-color: #f6f6f6;
    border-color: #ddd;
    border-width: 1px;
    border-style: solid;
    border-radius: 0.3125em;
}

div button{
    display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="form" (ngSubmit)="submit()">
    <div class="widget-container">
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('heading', $event.target.checked)" />Heading</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('paragraph', $event.target.checked)" />Paragraph</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('unorderedlist', $event.target.checked)" />Unordered List</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('orderedlist', $event.target.checked)" />Ordered List</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('table', $event.target.checked)" />Table</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('visualtitle', $event.target.checked)" />Visual Title</label>
    </div>
    <div>
      <button>submit</button>
    </div>
</form></code>```

答:
You should put the button in the same container, where the checkboxes are located. Otherwise you can't achieve this.

.widget-container {
    display: flex;
    flex-wrap: wrap;
    /*justify-content: center;*/
}

.checkbox-wrapper-htmlview {
    padding: 0.5em;
    margin: 0.5em 1em 0.5em 0;
    background-color: #f6f6f6;
    border-color: #ddd;
    border-width: 1px;
    border-style: solid;
    border-radius: 0.3125em;
}

button{
    display: inline-block;
    margin: 0.5em 1em 0.5em 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="form" (ngSubmit)="submit()">
    <div class="widget-container">
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('heading', $event.target.checked)" />Heading</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('paragraph', $event.target.checked)" />Paragraph</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('unorderedlist', $event.target.checked)" />Unordered List</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('orderedlist', $event.target.checked)" />Ordered List</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('table', $event.target.checked)" />Table</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('visualtitle', $event.target.checked)" />Visual Title</label>
      <button>submit</button>
    </div>

</form></code>```

Body:
I have the following code for creating a horizontal checklist and a submit button: jsfiddle

I would like for the submit button to show up inline with the checklist, right after "Visual Title". How can I achieve this? I've tried display: inline-block, display: inline, display: flex, but none of it works.

.widget-container {
    display: flex;
    flex-wrap: wrap;
    /*justify-content: center;*/
}

.checkbox-wrapper-htmlview {
    padding: 0.5em;
    margin: 0.5em 1em 0.5em 0;
    background-color: #f6f6f6;
    border-color: #ddd;
    border-width: 1px;
    border-style: solid;
    border-radius: 0.3125em;
}

div button{
    display: inline-block;
}

<form [formGroup]="form" (ngSubmit)="submit()">

      <input type="checkbox" name="annotationtype" (change)="onChange('heading', $event.target.checked)" />Heading
      <input type="checkbox" name="annotationtype" (change)="onChange('paragraph', $event.target.checked)" />Paragraph
      <input type="checkbox" name="annotationtype" (change)="onChange('unorderedlist', $event.target.checked)" />Unordered List
      <input type="checkbox" name="annotationtype" (change)="onChange('orderedlist', $event.target.checked)" />Ordered List
      <input type="checkbox" name="annotationtype" (change)="onChange('table', $event.target.checked)" />Table
      <input type="checkbox" name="annotationtype" (change)="onChange('visualtitle', $event.target.checked)" />Visual Title

      <button>submit</button>

</form>

Body:
You should put the button in the same container, where the checkboxes are located. Otherwise you can't achieve this.

.widget-container {
    display: flex;
    flex-wrap: wrap;
    /*justify-content: center;*/
}

.checkbox-wrapper-htmlview {
    padding: 0.5em;
    margin: 0.5em 1em 0.5em 0;
    background-color: #f6f6f6;
    border-color: #ddd;
    border-width: 1px;
    border-style: solid;
    border-radius: 0.3125em;
}

button{
    display: inline-block;
    margin: 0.5em 1em 0.5em 0;
}

<form [formGroup]="form" (ngSubmit)="submit()">
    <div class="widget-container">
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('heading', $event.target.checked)" />Heading</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('paragraph', $event.target.checked)" />Paragraph</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('unorderedlist', $event.target.checked)" />Unordered List</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('orderedlist', $event.target.checked)" />Ordered List</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('table', $event.target.checked)" />Table</label>
      <label class="checkbox-wrapper-htmlview"><input type="checkbox" name="annotationtype" (change)="onChange('visualtitle', $event.target.checked)" />Visual Title</label>
      <button>submit</button>
    </div>

</form>


问:
Filter React children by type with Typescript
I need to build a Wrapper for some other component and for that I try to filter React children by type:

```<code>// Component
const SubComponent = (props: SubComponentProps) => <NestedComponent {...props} />;

const MyComponent = (props: MyComponentProps) => {
    const { children } = props;
    const arrayChildren = React.Children.toArray(children);

    // doesn't work, but the type is right (child.type === SubComponent)
    const content = React.Children.count(arrayChildren) && arrayChildren.find((child) => React.isValidElement(child) && child.type === SubComponent);

    // works, but the type complains (child.type.name === "SubComponent")
    const content2 = React.Children.count(arrayChildren) && arrayChildren.find((child) => React.isValidElement(child) && child.type.name === "SubComponent");

    return (
        <Something {...props}>
            {/* Type complains, but works */}
            {content && <SomethingElse>{content.props.children}</SomethingElse>}
        </Something>
    );
};

MyComponent.SubComponent = SubComponent;

export default MyComponent;

// Usage
<MyComponent>
    <MyComponent.SubComponent>
        Some Stuff
    </MyComponent.SubComponent>
</MyComponent>
</code>```

Why doesn't child.type match?

And why doesn't child.type.name exist on the type, even though it works? (The type of the child is given as React.ReactChild | React.ReactFragment | React.ReactPortal)

Thanks!

答:
And why doesn't child.type.name exist on the type, even though it works? (The type of the child is given as React.ReactChild | React.ReactFragment | React.ReactPortal)

After you check for React.isValidElement(..) you basically narrow the type of child to React.ReactElement. And the issue with React.ReactElement is that it could have either a string or a function-contructor as the value to its type field. As you probably know, a string does not have a name property on it, thus you get an error. Actually, the expected constructor definition type provided by React typings is not considered as ordinary function as well (I guess it's something the lib authors could improve upon).

So I'd say, the simplest solution is just to cast the type to a function, like this:

```<code>(child.type as unknown as () => void).name === "SubComponent"
</code>```

This will compile.

Body:
I need to build a Wrapper for some other component and for that I try to filter React children by type:

// Component
const SubComponent = (props: SubComponentProps) => <NestedComponent {...props} />;

const MyComponent = (props: MyComponentProps) => {
    const { children } = props;
    const arrayChildren = React.Children.toArray(children);

    // doesn't work, but the type is right (child.type === SubComponent)
    const content = React.Children.count(arrayChildren) && arrayChildren.find((child) => React.isValidElement(child) && child.type === SubComponent);

    // works, but the type complains (child.type.name === "SubComponent")
    const content2 = React.Children.count(arrayChildren) && arrayChildren.find((child) => React.isValidElement(child) && child.type.name === "SubComponent");

    return (
        <Something {...props}>
            {/* Type complains, but works */}
            {content && <SomethingElse>{content.props.children}</SomethingElse>}
        </Something>
    );
};

MyComponent.SubComponent = SubComponent;

export default MyComponent;

// Usage
<MyComponent>
    <MyComponent.SubComponent>
        Some Stuff
    </MyComponent.SubComponent>
</MyComponent>

Why doesn't child.type match?

And why doesn't child.type.name exist on the type, even though it works? (The type of the child is given as React.ReactChild | React.ReactFragment | React.ReactPortal)

Thanks!

Body:
And why doesn't child.type.name exist on the type, even though it works? (The type of the child is given as React.ReactChild | React.ReactFragment | React.ReactPortal)

After you check for React.isValidElement(..) you basically narrow the type of child to React.ReactElement. And the issue with React.ReactElement is that it could have either a string or a function-contructor as the value to its type field. As you probably know, a string does not have a name property on it, thus you get an error. Actually, the expected constructor definition type provided by React typings is not considered as ordinary function as well (I guess it's something the lib authors could improve upon).

So I'd say, the simplest solution is just to cast the type to a function, like this:

(child.type as unknown as () => void).name === "SubComponent"

This will compile.


问:
Adding a Nested Statement
The problem,

Write an application that reads three nonzero values entered by the user and determines and prints whether they could represent the sides of a triangle.

I currently have

```<code>import java.util.Scanner;
public class FourDecimalThirtySix {
    public static void main (String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if ( (a + b) > c) {
            if ( (a + c) > b) {
                if ( (b + c) > a)
                    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.", a,
                        b, c);
                return;
            }
        }
    }
}
</code>```

I am trying to add an else statement to this for it to say "these values cannot make a triangle" if the original conditions are not meet.  Currently the program does not do anything if the 3 conditions are not met

答:
Use a single compound if with logical and (&&) and add an else like

```<code>if ((a+b) > c && (a+c) > b && (b+c) > a) {
    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.%n", a, b, c);
} else {
    System.out.printf("A triangle can't be made of %.2f, %.2f, by %.2f.%n", a, b, c);
}
</code>```

Title: Adding a Nested Statement

Body:
The problem,

Write an application that reads three nonzero values entered by the user and determines and prints whether they could represent the sides of a triangle.

I currently have

import java.util.Scanner;
public class FourDecimalThirtySix {
    public static void main (String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if ( (a + b) > c) {
            if ( (a + c) > b) {
                if ( (b + c) > a)
                    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.", a,
                        b, c);
                return;
            }
        }
    }
}

I am trying to add an else statement to this for it to say "these values cannot make a triangle" if the original conditions are not meet.  Currently the program does not do anything if the 3 conditions are not met

Body:
Use a single compound if with logical and (&&) and add an else like

if ((a+b) > c && (a+c) > b && (b+c) > a) {
    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.%n", a, b, c);
} else {
    System.out.printf("A triangle can't be made of %.2f, %.2f, by %.2f.%n", a, b, c);
}


问:
How to pass a value from reactjs app to another reactjs app?
I have to 2 Reactjs App, I need to pass a value from my App1 to App2 using link, but I dont know how, please help me thanks.

const location = useLocation();

const tab = getUrlParameter(location.search, 'tab');

with this I am now successfully getting the data in my App1 , lets says that data is (2), the problem is when i tried to click the other tab, it doesnt work now, why?

App1

```<code><u><a href="/student/?tab=2">View Student</a></u> // I need to pass a value to App2, the value i need to pass is
</code>```

App2 / receive value from App1

```<code>export default function BasicTabs() {
  const location = useLocation();
  const tab = getUrlParameter(location.search, 'tab'); // with this I am now successfully getting the data in my App1 , lets says that data is (2)
  const [value, setValue] = React.useState(0);

  useEffect(() => {
    if(tab !== 2 ? tab : value){
      console.log(tab)
      setValue(2)
    }else{
      setValue(0)
    }
  })

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <Box sx={{ width: '100%' }}>
      <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
          <Tab label="Item One" {...a11yProps(0)} />
          <Tab label="Item Two" {...a11yProps(1)} />
          <Tab label="Item Three" {...a11yProps(2)} />
        </Tabs>
      </Box>
      <TabPanel value={value} index={0}>
        Item One
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
    </Box>
  );
}

</code>```

答:
One option is to use query string parameters. So you would do something like

https://App2Url/student/4?App1Key=App1Value

Body:
I have to 2 Reactjs App, I need to pass a value from my App1 to App2 using link, but I dont know how, please help me thanks.

const location = useLocation();

const tab = getUrlParameter(location.search, 'tab');

with this I am now successfully getting the data in my App1 , lets says that data is (2), the problem is when i tried to click the other tab, it doesnt work now, why?

App1

View Student // I need to pass a value to App2, the value i need to pass is

App2 / receive value from App1

export default function BasicTabs() {
  const location = useLocation();
  const tab = getUrlParameter(location.search, 'tab'); // with this I am now successfully getting the data in my App1 , lets says that data is (2)
  const [value, setValue] = React.useState(0);

  useEffect(() => {
    if(tab !== 2 ? tab : value){
      console.log(tab)
      setValue(2)
    }else{
      setValue(0)
    }
  })

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <Box sx={{ width: '100%' }}>
      <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
          <Tab label="Item One" {...a11yProps(0)} />
          <Tab label="Item Two" {...a11yProps(1)} />
          <Tab label="Item Three" {...a11yProps(2)} />
        </Tabs>
      </Box>
      <TabPanel value={value} index={0}>
        Item One
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
    </Box>
  );
}


问:
Checking this awk print is not vulnerable to code injection
There are awk (BusyBox v1.26.2 awk) statements to parse /proc/cmdline before passing an IP address to a program.  And I can't change them.

/bin/t `awk 'BEGIN{FS="ip="}{print  $2}' /proc/cmdline | awk 'BEGIN{FS=":"}{print  $2}'`

So that the ip=192.168.0.1:192.168.0.2:xxx:xxx:xxxx in /proc/cmdline will print 192.168.0.2 as the argument to /bin/t

I'm not too familiar with awk, but I think this is safe and attempt to inject something that will be a security problem (e.g. $(reboot), 0.0.0.0`reboot` etc) will fail.  (/bin/t has it's own checks on command line arguments passed to it).

In this case an attacker has control of uboot bootargs variable and hence can control the ip= line in /proc/cmdline.

I'd like the reassurance of awk experts this isn't injectable if possible.

Many thanks.

Note for clarification:  Is there anything I can put in /proc/cmdline that results in shell execution?

答:
Nothing to do with awk but your command isn't safe because you aren't quoting the argument to t so the shell will evaluate it. Try echo `echo '*'`  vs echo "`echo '*'`" . Your awk commands pipleine could be reduced too and you should be using $(...) instead of backticks. This should be safe as well as concise, efficient, and robust:

```<code>/bin/t "$(awk 'BEGIN{FS="ip=|:"}{print $2}' /proc/cmdline)"
</code>```

Body:
Nothing to do with awk but your command isn't safe because you aren't quoting the argument to t so the shell will evaluate it. Try echo `echo '*'`  vs echo "`echo '*'`" . Your awk commands pipleine could be reduced too and you should be using $(...) instead of backticks. This should be safe as well as concise, efficient, and robust:

/bin/t "$(awk 'BEGIN{FS="ip=|:"}{print $2}' /proc/cmdline)"


问:
User.Identity.IsAuthenticated is false in a non-auth methods after successful login in asp.net core
I am new in asp.net core. I try to login with discord as 3rd party login service (like sign-in with facebook, google).

I can login successfully and have my user object, claims and I can enter a class which has an authorize attribute. Below you can see that UserIdentity is fine.

But let assume that user wants to go back to the login page. In this case, I have to redirect him to the index but I want to check whether the user is authenticated or not by using Identity and unfortunately, it is false and no claims etc. As I understand, it may be related with cookies or something similar. I also use different attribute for class (not authorize but AllowAnonymous) You can see below my Identity object

I am sharing my authentication code

```<code>services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

})
  .AddCookie(options =>
   {
      options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
      options.Cookie.MaxAge = options.ExpireTimeSpan;
      options.SlidingExpiration = true;
      options.EventsType = typeof(CustomCookieAuthenticationEvents);
      options.AccessDeniedPath = "/auth/DiscordAuthFailed";

    })
     .AddJwtBearer(options =>
      {
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters()
        {
           ValidateIssuer = false,
           ValidateAudience = false,
           ValidateIssuerSigningKey = true,
           ValidIssuer = Configuration.GetValue<string>("Jwt:Issuer"),
           ValidAudience = Configuration.GetValue<string>("Jwt:Audience"),
           IssuerSigningKey = new SymmetricSecurityKey(
               Encoding.UTF8.GetBytes(Configuration.GetValue<string>("Jwt:EncryptionKey")))
        };
    })
     .AddOAuth("Discord",
         options =>
         {
           options.AuthorizationEndpoint = "https://discord.com/api/oauth2/authorize";
           options.TokenEndpoint = "https://discord.com/api/oauth2/token";
           options.Scope.Add("identify");
           options.Scope.Add("email");
           options.Scope.Add("guilds.join");
           options.Scope.Add("guilds.members.read");

          options.CallbackPath = "/auth/oauthCallback";
          options.ClientId = Configuration.GetValue<string>("Discord:ClientId");
          options.ClientSecret = Configuration.GetValue<string>("Discord:ClientSecret");
          options.UserInformationEndpoint = "https://discord.com/api/users/@me";

          options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
          options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
          options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
          options.ClaimActions.MapJsonKey(ClaimTypes.IsPersistent, "verified");

          options.AccessDeniedPath = "/auth/DiscordAuthFailed";
          options.Events = new OAuthEvents()
           {
             OnCreatingTicket = async context =>
              {
               var request = new HttpRequestMessage(HttpMethod.Get,
               context.Options.UserInformationEndpoint);
               request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
               request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                var response = await context.Backchannel.SendAsync(request,
                HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);

                response.EnsureSuccessStatusCode();

                var user=(await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync())).RootElement;

                context.RunClaimActions(user);

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

services.AddTransient();

So my question is that, what is the best approach to access userIdentify object in any class/method after successfully login?

答:
After very long analyses, I found the problem.

I just changed  the DefaultAuthenticateScheme as CookieAuthenticationDefaults

```<code>services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

})
</code>```

and called sign method in my login method.

```<code>var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, result.Principal);
</code>```

after successfully sign-in, I cna get HttpContext.User object in any action.

Body:
I am new in asp.net core. I try to login with discord as 3rd party login service (like sign-in with facebook, google).

I can login successfully and have my user object, claims and I can enter a class which has an authorize attribute. Below you can see that UserIdentity is fine.

But let assume that user wants to go back to the login page. In this case, I have to redirect him to the index but I want to check whether the user is authenticated or not by using Identity and unfortunately, it is false and no claims etc. As I understand, it may be related with cookies or something similar. I also use different attribute for class (not authorize but AllowAnonymous) You can see below my Identity object

I am sharing my authentication code

services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

})
  .AddCookie(options =>
   {
      options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
      options.Cookie.MaxAge = options.ExpireTimeSpan;
      options.SlidingExpiration = true;
      options.EventsType = typeof(CustomCookieAuthenticationEvents);
      options.AccessDeniedPath = "/auth/DiscordAuthFailed";

    })
     .AddJwtBearer(options =>
      {
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters()
        {
           ValidateIssuer = false,
           ValidateAudience = false,
           ValidateIssuerSigningKey = true,
           ValidIssuer = Configuration.GetValue<string>("Jwt:Issuer"),
           ValidAudience = Configuration.GetValue<string>("Jwt:Audience"),
           IssuerSigningKey = new SymmetricSecurityKey(
               Encoding.UTF8.GetBytes(Configuration.GetValue<string>("Jwt:EncryptionKey")))
        };
    })
     .AddOAuth("Discord",
         options =>
         {
           options.AuthorizationEndpoint = "https://discord.com/api/oauth2/authorize";
           options.TokenEndpoint = "https://discord.com/api/oauth2/token";
           options.Scope.Add("identify");
           options.Scope.Add("email");
           options.Scope.Add("guilds.join");
           options.Scope.Add("guilds.members.read");

          options.CallbackPath = "/auth/oauthCallback";
          options.ClientId = Configuration.GetValue<string>("Discord:ClientId");
          options.ClientSecret = Configuration.GetValue<string>("Discord:ClientSecret");
          options.UserInformationEndpoint = "https://discord.com/api/users/@me";

          options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
          options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
          options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
          options.ClaimActions.MapJsonKey(ClaimTypes.IsPersistent, "verified");

          options.AccessDeniedPath = "/auth/DiscordAuthFailed";
          options.Events = new OAuthEvents()
           {
             OnCreatingTicket = async context =>
              {
               var request = new HttpRequestMessage(HttpMethod.Get,
               context.Options.UserInformationEndpoint);
               request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
               request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                var response = await context.Backchannel.SendAsync(request,
                HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);

                response.EnsureSuccessStatusCode();

                var user=(await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync())).RootElement;

                context.RunClaimActions(user);

                }
          };
    });

services.AddTransient();

So my question is that, what is the best approach to access userIdentify object in any class/method after successfully login?

Body:
After very long analyses, I found the problem.

I just changed  the DefaultAuthenticateScheme as CookieAuthenticationDefaults

services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

})

and called sign method in my login method.

var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, result.Principal);

after successfully sign-in, I cna get HttpContext.User object in any action.


问:
How to use raw socket send and receive arp package in python
I need to "send and receive ARP packet in one program". I'm aware that the scapy packet is already do it quiet well, and you just need to pass some argument. However, I want to know much further than just pass argument. So, if you recommend scapy as answer, it might not help.

Code

```<code>python
import struct
import socket
import binascii

rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,
                          socket.htons(0x0003))
rawSocket.bind(("wlp5s0", socket.htons(0x0003)))

source_mac = binascii.unhexlify('00:A0:C9:14:C8:29'.replace(':', ''))
#b'\x00\x00\x00\x00\x00\x00' sender mac address
dest_mac = binascii.unhexlify('ff:ff:ff:ff:ff:ff'.replace(':', ''))
#  b'\xff\xff\xff\xff\xff\xff'  target mac address

source_ip = "192.168.100.3"  # sender ip address
dest_ip = "192.168.100.1"  # target ip address

# Ethernet Header
protocol = 0x0806  # 0x0806 for ARP
eth_hdr = struct.pack("!6s6sH", dest_mac, source_mac, protocol)

# ARP header
htype = 1  # Hardware_type ethernet
ptype = 0x0800  # Protocol type TCP
hlen = 6  # Hardware address Len
plen = 4  # Protocol addr. len
operation = 1  # 1=request/2=reply
src_ip = socket.inet_aton(source_ip)
dst_ip = socket.inet_aton(dest_ip)
arp_hdr = struct.pack("!HHBBH6s4s6s4s", htype, ptype, hlen, plen, operation,
                      source_mac, src_ip, dest_mac, dst_ip)

packet = eth_hdr + arp_hdr
rawSocket.send(packet)
rawSocket.recvfrom(65535)
```
By the way I can clear see the packet already send and reply but `Wireshark`
```

Platform:

OS: Linux Ubuntn 16.04

Interpreter: Python 3.5.2

答:
When you do the bind you should set it to 0 for the second parameter:
rawSocket.bind(("wlp5s0", 0))

I was able to receive ARP packets no problem

Body:
I need to "send and receive ARP packet in one program". I'm aware that the scapy packet is already do it quiet well, and you just need to pass some argument. However, I want to know much further than just pass argument. So, if you recommend scapy as answer, it might not help.

Code

python
import struct
import socket
import binascii

rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,
                          socket.htons(0x0003))
rawSocket.bind(("wlp5s0", socket.htons(0x0003)))

source_mac = binascii.unhexlify('00:A0:C9:14:C8:29'.replace(':', ''))
#b'\x00\x00\x00\x00\x00\x00' sender mac address
dest_mac = binascii.unhexlify('ff:ff:ff:ff:ff:ff'.replace(':', ''))
#  b'\xff\xff\xff\xff\xff\xff'  target mac address

source_ip = "192.168.100.3"  # sender ip address
dest_ip = "192.168.100.1"  # target ip address

# Ethernet Header
protocol = 0x0806  # 0x0806 for ARP
eth_hdr = struct.pack("!6s6sH", dest_mac, source_mac, protocol)

# ARP header
htype = 1  # Hardware_type ethernet
ptype = 0x0800  # Protocol type TCP
hlen = 6  # Hardware address Len
plen = 4  # Protocol addr. len
operation = 1  # 1=request/2=reply
src_ip = socket.inet_aton(source_ip)
dst_ip = socket.inet_aton(dest_ip)
arp_hdr = struct.pack("!HHBBH6s4s6s4s", htype, ptype, hlen, plen, operation,
                      source_mac, src_ip, dest_mac, dst_ip)

packet = eth_hdr + arp_hdr
rawSocket.send(packet)
rawSocket.recvfrom(65535)
```
By the way I can clear see the packet already send and reply but `Wireshark`

Platform:

OS: Linux Ubuntn 16.04

Interpreter: Python 3.5.2


问:
How I can change child elements order in JS?
I have this html:

```<code><table>
    <tr>
        <td>
            Set right order
        </td>
        <td>
            <span style = "display: block;">asd | <a href = '#' onclick = "moveChoiceTo(this, -1);">↑</a><a href = '#' onclick = "moveChoiceTo(this, 1);">↓</a></span>
            <span style = "display: block;">dsa | <a href = '#' onclick = "moveChoiceTo(this, -1);">↑</a><a href = '#' onclick = "moveChoiceTo(this, 1);">↓</a></span>
            <span style = "display: block;">qwe | <a href = '#' onclick = "moveChoiceTo(this, -1);">↑</a><a href = '#' onclick = "moveChoiceTo(this, 1);">↓</a></span>
            <span style = "display: block;">ewq | <a href = '#' onclick = "moveChoiceTo(this, -1);">↑</a><a href = '#' onclick = "moveChoiceTo(this, 1);">↓</a></span>
        </td>
    </tr>
</table>
</code>```

And this JS:

```<code>function moveChoiceTo(elem_choice, direction)
{
    var curr_index = -1; //index of elem that we should move
    var td = elem_choice.parentElement.parentElement; //link to TD

    for (var i = 0; i < td.children.length; i++) //determine index of elem that called this function
        if (td.children[i].children[0] == elem_choice)
        {
            curr_index = i;
            break;
        }

    if (curr_index == -1)
        return;

    if (curr_index == 0 && direction < 0) //if nowhere to move
        return;

    if (curr_index == td.children.length - 1 && direction > 0) //if nowhere to move
        return;

    var curr_child = td.children[curr_index]; //save current elem into temp var
    td.children.splice(curr_index, 1); //here I getting exception that splice isn't supported by object, but arent this is array?
    td.children.splice(curr_index + direction, 0, curr_child); //attempt to insert it
}
</code>```

I getting exception that splice isn't supported, but this supposed to be an array and support this method?
What other ways I have to change children order?

答:
Same as dfsq's answer but with some modifications.

var selected_element;

function moveElementTo(selected_element, direction) {

    var element_to_move = selected_element,
        td = element_to_move.parentNode;

    if (direction === -1 && element_to_move.previousElementSibling) {
        td.insertBefore(element_to_move, element_to_move.previousElementSibling);
    } else if (direction === 1 && element_to_move.nextElementSibling) {
        td.insertBefore(element_to_move, element_to_move.nextElementSibling.nextElementSibling)
    }
}

function move(dir){
    if (selected_element != undefined){
        moveElementTo(selected_element,dir);
    }else{
        console.error("No element Selected to move!");
    }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div >

    <div onclick='selected_element = this;'><button onclick='selected_element = this.parentNode;'> Select element </button>Element One <button onclick='move(-1);'>Move_up</button></div>
    <div onclick='selected_element = this;'><button onclick='selected_element = this.parentNode;'> Select element </button>Element Two <button onclick='move(-1);'>Move_up</button></div>
    <div onclick='selected_element = this;'><button onclick='selected_element = this.parentNode;'> Select element </button>Element Three <button onclick='move(-1);'>Move_up</button></div>

</div></code>```

My scenario for this was An element needs to be selected first, because I use it for a popup dialogue for which the operations show up upon long click, the Select Element button is just for demo.

Body:
I have this html:

            Set right order

            asd | ↑↓
            dsa | ↑↓
            qwe | ↑↓
            ewq | ↑↓

And this JS:

function moveChoiceTo(elem_choice, direction)
{
    var curr_index = -1; //index of elem that we should move
    var td = elem_choice.parentElement.parentElement; //link to TD

    for (var i = 0; i < td.children.length; i++) //determine index of elem that called this function
        if (td.children[i].children[0] == elem_choice)
        {
            curr_index = i;
            break;
        }

    if (curr_index == -1)
        return;

    if (curr_index == 0 && direction < 0) //if nowhere to move
        return;

    if (curr_index == td.children.length - 1 && direction > 0) //if nowhere to move
        return;

    var curr_child = td.children[curr_index]; //save current elem into temp var
    td.children.splice(curr_index, 1); //here I getting exception that splice isn't supported by object, but arent this is array?
    td.children.splice(curr_index + direction, 0, curr_child); //attempt to insert it
}

I getting exception that splice isn't supported, but this supposed to be an array and support this method?
What other ways I have to change children order?

Body:
Same as dfsq's answer but with some modifications.

var selected_element;

function moveElementTo(selected_element, direction) {

    var element_to_move = selected_element,
        td = element_to_move.parentNode;

    if (direction === -1 && element_to_move.previousElementSibling) {
        td.insertBefore(element_to_move, element_to_move.previousElementSibling);
    } else if (direction === 1 && element_to_move.nextElementSibling) {
        td.insertBefore(element_to_move, element_to_move.nextElementSibling.nextElementSibling)
    }
}

function move(dir){
    if (selected_element != undefined){
        moveElementTo(selected_element,dir);
    }else{
        console.error("No element Selected to move!");
    }

}

<div >

    <div onclick='selected_element = this;'><button onclick='selected_element = this.parentNode;'> Select element </button>Element One <button onclick='move(-1);'>Move_up</button></div>
    <div onclick='selected_element = this;'><button onclick='selected_element = this.parentNode;'> Select element </button>Element Two <button onclick='move(-1);'>Move_up</button></div>
    <div onclick='selected_element = this;'><button onclick='selected_element = this.parentNode;'> Select element </button>Element Three <button onclick='move(-1);'>Move_up</button></div>

</div>

My scenario for this was An element needs to be selected first, because I use it for a popup dialogue for which the operations show up upon long click, the Select Element button is just for demo.


问:
How can we insert multiple texts and paragraphs in google docs using google docs api with php?
I want to insert more the one texts in google docs with multiple paragraph contents and also want to style them. I also followed this link https://developers.google.com/docs/api/reference/rest/v1/documents/request but I am unable to achieve this.

```<code>$requests [] = new Google_Service_Docs_Request(
[
    'insertText' => [
        'text' => 'Sample1\n',
        'location' => [
            'index' => 1
        ]
    ]
],
  [
    'insertText' => [
      'text' => 'sample2\n',
      'location' => [
        'index' => 9
      ]
    ]
  ],
  [
    'updateParagraphStyle' => [
      'range' => [
        'startIndex' => 1,
        'endIndex' => 8
      ],
      'paragraphStyle' => [
        'namedStyleType' => 'HEADING_1'
      ],
      'fields' => 'namedStyleType'
    ]
  ],
  [
    'updateParagraphStyle' => [
      'range' => [
        'startIndex' => 9,
        'endIndex' => 17
      ],
      'paragraphStyle' => [
        'namedStyleType' => 'NORMAL_TEXT'
      ],
      'fields' => 'namedStyleType'
  ]
  ],
  [
    'updateTextStyle' => [
      'range' => [
        'startIndex' => 9,
        'endIndex' => 16
      ],
      'textStyle' => [
        'link' => [
          'url' => 'https://www.google.com'
        ]
      ],
      'fields' => 'link'
    ]
  ]
);
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

</code>```

I am doing in this way and getting this error

```<code>PHP Fatal error:  Uncaught Google\Service\Exception: {
  "error": {
    "code": 400,
    "message": "Invalid requests[0]: No request set.",
    "errors": [
      {
        "message": "Invalid requests[0]: No request set.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

</code>```

Can anyone help me out with this. It would be a great help and i need it in PHP code.

答:
Sample1\n of 'text' => 'Sample1\n', is converted to Sample1\\n. I thought that this might be the reason of your issue. In this case, how about the following modification using PHP_EOL?

PHP_EOL: The correct 'End Of Line' symbol for this platform.

Modified script:

$requests = [
    new Google_Service_Docs_Request([
        'insertText' => [
            'text' => 'Sample1' . PHP_EOL, // Modified
            'location' => [
                'index' => 1
            ]
        ]
    ]),
    new Google_Service_Docs_Request([
        'insertText' => [
            'text' => 'Sample2' . PHP_EOL, // Modified
            'location' => [
                'index' => 9 // Modified
            ]
        ]
    ])
];
```
<p>or, please enclose the text by the double quotes as follows.</p>
<pre class="lang-php prettyprint-override"><code>$requests = [
    new Google_Service_Docs_Request([
        'insertText' => [
            'text' => "Sample1\n", // Modified
            'location' => [
                'index' => 1
            ]
        ]
    ]),
    new Google_Service_Docs_Request([
        'insertText' => [
            'text' => "Sample2\n", // Modified
            'location' => [
                'index' => 9 // Modified
            ]
        ]
    ])
];
</code>```

By this modification, 'Sample1' . PHP_EOL and "Sample1\n" are used as Sample\n. By this, I thought that your goal can be achieved.

In this case, index of the 2nd request is 9 that you have used in the first script.

References:

Predefined Constants for PHP

Single quoted

To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret the following escape sequences for special characters:

Body:
I want to insert more the one texts in google docs with multiple paragraph contents and also want to style them. I also followed this link https://developers.google.com/docs/api/reference/rest/v1/documents/request but I am unable to achieve this.

$requests [] = new Google_Service_Docs_Request(
[
    'insertText' => [
        'text' => 'Sample1\n',
        'location' => [
            'index' => 1
        ]
    ]
],
  [
    'insertText' => [
      'text' => 'sample2\n',
      'location' => [
        'index' => 9
      ]
    ]
  ],
  [
    'updateParagraphStyle' => [
      'range' => [
        'startIndex' => 1,
        'endIndex' => 8
      ],
      'paragraphStyle' => [
        'namedStyleType' => 'HEADING_1'
      ],
      'fields' => 'namedStyleType'
    ]
  ],
  [
    'updateParagraphStyle' => [
      'range' => [
        'startIndex' => 9,
        'endIndex' => 17
      ],
      'paragraphStyle' => [
        'namedStyleType' => 'NORMAL_TEXT'
      ],
      'fields' => 'namedStyleType'
  ]
  ],
  [
    'updateTextStyle' => [
      'range' => [
        'startIndex' => 9,
        'endIndex' => 16
      ],
      'textStyle' => [
        'link' => [
          'url' => 'https://www.google.com'
        ]
      ],
      'fields' => 'link'
    ]
  ]
);
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

I am doing in this way and getting this error

PHP Fatal error:  Uncaught Google\Service\Exception: {
  "error": {
    "code": 400,
    "message": "Invalid requests[0]: No request set.",
    "errors": [
      {
        "message": "Invalid requests[0]: No request set.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

Can anyone help me out with this. It would be a great help and i need it in PHP code.

Body:
Sample1\n of 'text' => 'Sample1\n', is converted to Sample1\\n. I thought that this might be the reason of your issue. In this case, how about the following modification using PHP_EOL?

PHP_EOL: The correct 'End Of Line' symbol for this platform.

Modified script:

$requests = [
    new Google_Service_Docs_Request([
        'insertText' => [
            'text' => 'Sample1' . PHP_EOL, // Modified
            'location' => [
                'index' => 1
            ]
        ]
    ]),
    new Google_Service_Docs_Request([
        'insertText' => [
            'text' => 'Sample2' . PHP_EOL, // Modified
            'location' => [
                'index' => 9 // Modified
            ]
        ]
    ])
];

or, please enclose the text by the double quotes as follows.

$requests = [
    new Google_Service_Docs_Request([
        'insertText' => [
            'text' => "Sample1\n", // Modified
            'location' => [
                'index' => 1
            ]
        ]
    ]),
    new Google_Service_Docs_Request([
        'insertText' => [
            'text' => "Sample2\n", // Modified
            'location' => [
                'index' => 9 // Modified
            ]
        ]
    ])
];

By this modification, 'Sample1' . PHP_EOL and "Sample1\n" are used as Sample\n. By this, I thought that your goal can be achieved.

In this case, index of the 2nd request is 9 that you have used in the first script.

References:

Predefined Constants for PHP

Single quoted

To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret the following escape sequences for special characters:


问:
How to manage CORS policy properly in express?
I am trying to allow access from everywhere.

I have tried using app middleware:

```<code>app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  next();
});
</code>```

I have tried using it in the route:

```<code>app.post('/login',function(req,res){
var login   = req.body;
var sess    = req.session;

if (!login.email && !login.pwd){
    return res.status(401);
}
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Headers", '*');
.... more code here
</code>```

Both do not work. I keep getting an error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Further down the server, we use similar code for another route, which works:

```<code>app.post('/questar',function(req,res){
//allow xhr post from retireup domains
var cors = {
    origin: "https://www.website.com";
};
res.header("Access-Control-Allow-Origin", cors.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.type('application/json');
</code>```

I cannot tell the difference between the code, but only one set works. Any ideas why? This seems like an issue that shouldn't be so complicated. Thanks

答:
All you have to whitelist the domains name to avoid getting cors error messages.

There is a plugin called cors, installed it into your project using this command

```<code>npm i cors
</code>```

after installing use this code to remove the cors related errors form your project.

```<code>const cors = require('cors');

const corsOption = {
    credentials: true,
    origin: ['http://localhost:3000', 'http://localhost:80']
}

app.use(cors(corsOption));
</code>```

In the origin section you can pass any domain to whitelist it. If you want to whitelist all the domain names, instead of passing the the urls array. you can pass '*' over there.

Example : origin: '*'

credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header, otherwise it is omitted.

Body:
I am trying to allow access from everywhere.

I have tried using app middleware:

app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  next();
});

I have tried using it in the route:

app.post('/login',function(req,res){
var login   = req.body;
var sess    = req.session;

if (!login.email && !login.pwd){
    return res.status(401);
}
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Headers", '*');
.... more code here

Both do not work. I keep getting an error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Further down the server, we use similar code for another route, which works:

app.post('/questar',function(req,res){
//allow xhr post from retireup domains
var cors = {
    origin: "https://www.website.com";
};
res.header("Access-Control-Allow-Origin", cors.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.type('application/json');

I cannot tell the difference between the code, but only one set works. Any ideas why? This seems like an issue that shouldn't be so complicated. Thanks

Body:
All you have to whitelist the domains name to avoid getting cors error messages.

There is a plugin called cors, installed it into your project using this command

npm i cors

after installing use this code to remove the cors related errors form your project.

const cors = require('cors');

const corsOption = {
    credentials: true,
    origin: ['http://localhost:3000', 'http://localhost:80']
}

app.use(cors(corsOption));

In the origin section you can pass any domain to whitelist it. If you want to whitelist all the domain names, instead of passing the the urls array. you can pass '*' over there.

Example : origin: '*'

credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header, otherwise it is omitted.


问:
Override element.style in CSS
I have a react component using React-qr-scanner but I cannot seem to override the element.style. I want to remove the border because it's too big.

```<code>.qrScanner {
  border: 1px solid rgba(0, 0, 0, 0.3) !important;
  box-shadow: rgba(244, 248, 0, 0.5) 0px 0px 0px 5px inset;
}
</code>```

I'm calling it by

```<code><QrReader
            delay={3000}
            onError={handleError}
            onScan={handleScan}
            // chooseDeviceId={()=>selected}
            style={{width: '250px', heigth: '200px'}}
            className={'qrScanner'}
          />
</code>```

I want to override it using CSS.

答: Try appending your custom style inline to existing one</p>

Title: Override element.style in CSS

Body:
I have a react component using React-qr-scanner but I cannot seem to override the element.style. I want to remove the border because it's too big.

.qrScanner {
  border: 1px solid rgba(0, 0, 0, 0.3) !important;
  box-shadow: rgba(244, 248, 0, 0.5) 0px 0px 0px 5px inset;
}

I'm calling it by

<QrReader
            delay={3000}
            onError={handleError}
            onScan={handleScan}
            // chooseDeviceId={()=>selected}
            style={{width: '250px', heigth: '200px'}}
            className={'qrScanner'}
          />

I want to override it using CSS.


问:
Swagger not loading - Failed to load API definition: Fetch error undefined
Trying to setup swagger in conjunction with a web application hosted on IIS express. API is built using ASP Net Core. I have followed the instructions prescribed on the relevant microsoft help page regarding Swashbuckle and ASP.NET Core.

Thus far I have got the swagger page to load up and can see that the SwaggerDoc that I have defined is loading, however no API's are present. Currently am getting the following error:

"Fetch error undefined ./swagger/v1/swagger.json"

```<code>public class Startup
{

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // services.AddDbContext<TodoContext>(opt =>
        // opt.UseInMemoryDatabase("TodoList"));
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "API WSVAP (WebSmartView)", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
            c.RoutePrefix = string.Empty;
        });

        app.UseMvc();
    }
}
</code>```

答:
I have experienced the same error when I was using Swagger and also Microsoft.AspNetCore.OData. I usually try to use the latest version - but bringing it down to v 7.5.12 - did solve my issue.

Also adding following to every Action method in the Controller, makes it work with OData v8.x too: [HttpGet], [HttpPost], or [ApiExplorerSettings(IgnoreApi = true)]

Body:
Trying to setup swagger in conjunction with a web application hosted on IIS express. API is built using ASP Net Core. I have followed the instructions prescribed on the relevant microsoft help page regarding Swashbuckle and ASP.NET Core.

Thus far I have got the swagger page to load up and can see that the SwaggerDoc that I have defined is loading, however no API's are present. Currently am getting the following error:

"Fetch error undefined ./swagger/v1/swagger.json"

public class Startup
{

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // services.AddDbContext<TodoContext>(opt =>
        // opt.UseInMemoryDatabase("TodoList"));
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "API WSVAP (WebSmartView)", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
            c.RoutePrefix = string.Empty;
        });

        app.UseMvc();
    }
}


问:
How to share the same ViewModel with ViewPager, Navigation and Hilt?
I'm trying to use the same ViewHolder between this fragments.

FragmentA, FragmentB and Fragment E are in a navGraph, Fragment C and D are not.

I tried using by viewModels() but it initialized the ViewModel 3 times (on A, C, E)

Using by activityViewModels() it initilized the ViewModel 2 times (on A and C)

I also tried by viewModels(ownerProducer = {requireParentFragment().requireParentFragment()}) in Fragment C and D but it keeps initializing the ViewModel.

And the last thing i tried is inserting Fragment A, B and E into a navGraph and using
by navGraphViewModels(R.id.customNavGraph) { defaultViewModelProviderFactory } but got the same result as above.

In conclusion, Fragment C and D keep initializing the ViewModel

How can i fix this?

答:
Have you tried accessing the viewModels extension function on requireParentFragment(). And to ensure that the viewModel is called after the child fragment is attached to the parent/host, you can initialize it lazily or just initialize it after the fragment is attached to the parent

```<code>private val viewModel by lazy { requireParentFragment().viewModels<YourViewModel>() }
</code>```

Body:
Have you tried accessing the viewModels extension function on requireParentFragment(). And to ensure that the viewModel is called after the child fragment is attached to the parent/host, you can initialize it lazily or just initialize it after the fragment is attached to the parent

private val viewModel by lazy { requireParentFragment().viewModels<YourViewModel>() }