问:
Subprocess checkoutput is not returning output for help command?
Here I am trying to read output for regular help cmd on windows but I am getting error subprocess.CalledProcessError: Command 'help' `returned non-zero exit status 1
is there anything I can do to fix this here

With the same command if I try with systeminfo keyword I am getting the output , why does it returns values for systeminfo but not for cmd keyword

```<code>import subprocess

calling_output = subprocess.check_output(
        "help", shell=True, stderr=subprocess.STDOUT)

print (calling_output)
</code>```

Expected Output

```<code>For more information on a specific command, type HELP command-name
ASSOC          Displays or modifies file extension associations.
ATTRIB         Displays or changes file attributes.
BREAK          Sets or clears extended CTRL+C checking.
BCDEDIT        Sets properties in boot database to control boot loading.
CACLS          Displays or modifies access control lists (ACLs) of files.
CALL           Calls one batch program from another.
CD             Displays the name of or changes the current directory.
CHCP           Displays or sets the active code page number.
CHDIR          Displays the name of or changes the current directory.
CHKDSK         Checks a disk and displays a status report.
CHKNTFS        Displays or modifies the checking of disk at boot time.
CLS            Clears the screen.
CMD            Starts a new instance of the Windows command interpreter.
COLOR          Sets the default console foreground and background colors.
COMP           Compares the contents of two files or sets of files.
COMPACT        Displays or alters the compression of files on NTFS partitions.
CONVERT        Converts FAT volumes to NTFS.  You cannot convert the
               current drive.
COPY           Copies one or more files to another location.
DATE           Displays or sets the date.
DEL            Deletes one or more files.
DIR            Displays a list of files and subdirectories in a directory.
DISKPART       Displays or configures Disk Partition properties.
DOSKEY         Edits command lines, recalls Windows commands, and
               creates macros.
DRIVERQUERY    Displays current device driver status and properties.
ECHO           Displays messages, or turns command echoing on or off.
ENDLOCAL       Ends localization of environment changes in a batch file.
ERASE          Deletes one or more files.
EXIT           Quits the CMD.EXE program (command interpreter).
FC             Compares two files or sets of files, and displays the
               differences between them.
FIND           Searches for a text string in a file or files.
FINDSTR        Searches for strings in files.
FOR            Runs a specified command for each file in a set of files.
FORMAT         Formats a disk for use with Windows.
FSUTIL         Displays or configures the file system properties.
FTYPE          Displays or modifies file types used in file extension
               associations.
GOTO           Directs the Windows command interpreter to a labeled line in
               a batch program.
GPRESULT       Displays Group Policy information for machine or user.
GRAFTABL       Enables Windows to display an extended character set in
               graphics mode.
HELP           Provides Help information for Windows commands.
ICACLS         Display, modify, backup, or restore ACLs for files and
               directories.
IF             Performs conditional processing in batch programs.
LABEL          Creates, changes, or deletes the volume label of a disk.
MD             Creates a directory.
MKDIR          Creates a directory.
MKLINK         Creates Symbolic Links and Hard Links
MODE           Configures a system device.
MORE           Displays output one screen at a time.
MOVE           Moves one or more files from one directory to another
               directory.
OPENFILES      Displays files opened by remote users for a file share.
PATH           Displays or sets a search path for executable files.
PAUSE          Suspends processing of a batch file and displays a message.
POPD           Restores the previous value of the current directory saved by
               PUSHD.
PRINT          Prints a text file.
PROMPT         Changes the Windows command prompt.
PUSHD          Saves the current directory then changes it.
RD             Removes a directory.
RECOVER        Recovers readable information from a bad or defective disk.
REM            Records comments (remarks) in batch files or CONFIG.SYS.
REN            Renames a file or files.
RENAME         Renames a file or files.
REPLACE        Replaces files.
RMDIR          Removes a directory.
ROBOCOPY       Advanced utility to copy files and directory trees
SET            Displays, sets, or removes Windows environment variables.
SETLOCAL       Begins localization of environment changes in a batch file.
SC             Displays or configures services (background processes).
SCHTASKS       Schedules commands and programs to run on a computer.
SHIFT          Shifts the position of replaceable parameters in batch files.
SHUTDOWN       Allows proper local or remote shutdown of machine.
SORT           Sorts input.
START          Starts a separate window to run a specified program or command.
SUBST          Associates a path with a drive letter.
SYSTEMINFO     Displays machine specific properties and configuration.
TASKLIST       Displays all currently running tasks including services.
TASKKILL       Kill or stop a running process or application.
TIME           Displays or sets the system time.
TITLE          Sets the window title for a CMD.EXE session.
TREE           Graphically displays the directory structure of a drive or
               path.
TYPE           Displays the contents of a text file.
VER            Displays the Windows version.
VERIFY         Tells Windows whether to verify that your files are written
               correctly to a disk.
VOL            Displays a disk volume label and serial number.
XCOPY          Copies files and directory trees.
WMIC           Displays WMI information inside interactive command shell.
</code>```

答:
For your requirement you can use popen

```<code>data =subprocess.Popen("help", stdout=subprocess.PIPE, shell=True).stdout.read().decode("utf-8")
print(data)
</code>```

It will return the output for both help & systeminfo

Body:
Here I am trying to read output for regular help cmd on windows but I am getting error subprocess.CalledProcessError: Command 'help' `returned non-zero exit status 1
is there anything I can do to fix this here

With the same command if I try with systeminfo keyword I am getting the output , why does it returns values for systeminfo but not for cmd keyword

import subprocess

calling_output = subprocess.check_output(
        "help", shell=True, stderr=subprocess.STDOUT)

print (calling_output)

Expected Output

For more information on a specific command, type HELP command-name
ASSOC          Displays or modifies file extension associations.
ATTRIB         Displays or changes file attributes.
BREAK          Sets or clears extended CTRL+C checking.
BCDEDIT        Sets properties in boot database to control boot loading.
CACLS          Displays or modifies access control lists (ACLs) of files.
CALL           Calls one batch program from another.
CD             Displays the name of or changes the current directory.
CHCP           Displays or sets the active code page number.
CHDIR          Displays the name of or changes the current directory.
CHKDSK         Checks a disk and displays a status report.
CHKNTFS        Displays or modifies the checking of disk at boot time.
CLS            Clears the screen.
CMD            Starts a new instance of the Windows command interpreter.
COLOR          Sets the default console foreground and background colors.
COMP           Compares the contents of two files or sets of files.
COMPACT        Displays or alters the compression of files on NTFS partitions.
CONVERT        Converts FAT volumes to NTFS.  You cannot convert the
               current drive.
COPY           Copies one or more files to another location.
DATE           Displays or sets the date.
DEL            Deletes one or more files.
DIR            Displays a list of files and subdirectories in a directory.
DISKPART       Displays or configures Disk Partition properties.
DOSKEY         Edits command lines, recalls Windows commands, and
               creates macros.
DRIVERQUERY    Displays current device driver status and properties.
ECHO           Displays messages, or turns command echoing on or off.
ENDLOCAL       Ends localization of environment changes in a batch file.
ERASE          Deletes one or more files.
EXIT           Quits the CMD.EXE program (command interpreter).
FC             Compares two files or sets of files, and displays the
               differences between them.
FIND           Searches for a text string in a file or files.
FINDSTR        Searches for strings in files.
FOR            Runs a specified command for each file in a set of files.
FORMAT         Formats a disk for use with Windows.
FSUTIL         Displays or configures the file system properties.
FTYPE          Displays or modifies file types used in file extension
               associations.
GOTO           Directs the Windows command interpreter to a labeled line in
               a batch program.
GPRESULT       Displays Group Policy information for machine or user.
GRAFTABL       Enables Windows to display an extended character set in
               graphics mode.
HELP           Provides Help information for Windows commands.
ICACLS         Display, modify, backup, or restore ACLs for files and
               directories.
IF             Performs conditional processing in batch programs.
LABEL          Creates, changes, or deletes the volume label of a disk.
MD             Creates a directory.
MKDIR          Creates a directory.
MKLINK         Creates Symbolic Links and Hard Links
MODE           Configures a system device.
MORE           Displays output one screen at a time.
MOVE           Moves one or more files from one directory to another
               directory.
OPENFILES      Displays files opened by remote users for a file share.
PATH           Displays or sets a search path for executable files.
PAUSE          Suspends processing of a batch file and displays a message.
POPD           Restores the previous value of the current directory saved by
               PUSHD.
PRINT          Prints a text file.
PROMPT         Changes the Windows command prompt.
PUSHD          Saves the current directory then changes it.
RD             Removes a directory.
RECOVER        Recovers readable information from a bad or defective disk.
REM            Records comments (remarks) in batch files or CONFIG.SYS.
REN            Renames a file or files.
RENAME         Renames a file or files.
REPLACE        Replaces files.
RMDIR          Removes a directory.
ROBOCOPY       Advanced utility to copy files and directory trees
SET            Displays, sets, or removes Windows environment variables.
SETLOCAL       Begins localization of environment changes in a batch file.
SC             Displays or configures services (background processes).
SCHTASKS       Schedules commands and programs to run on a computer.
SHIFT          Shifts the position of replaceable parameters in batch files.
SHUTDOWN       Allows proper local or remote shutdown of machine.
SORT           Sorts input.
START          Starts a separate window to run a specified program or command.
SUBST          Associates a path with a drive letter.
SYSTEMINFO     Displays machine specific properties and configuration.
TASKLIST       Displays all currently running tasks including services.
TASKKILL       Kill or stop a running process or application.
TIME           Displays or sets the system time.
TITLE          Sets the window title for a CMD.EXE session.
TREE           Graphically displays the directory structure of a drive or
               path.
TYPE           Displays the contents of a text file.
VER            Displays the Windows version.
VERIFY         Tells Windows whether to verify that your files are written
               correctly to a disk.
VOL            Displays a disk volume label and serial number.
XCOPY          Copies files and directory trees.
WMIC           Displays WMI information inside interactive command shell.

Body:
For your requirement you can use popen

data =subprocess.Popen("help", stdout=subprocess.PIPE, shell=True).stdout.read().decode("utf-8")
print(data)

It will return the output for both help & systeminfo


来源: stackexchange

问:
How to gracefully shutdown Amazon ECS Fargate task?
Problem: Fargate tasks are being shut down without completing the processes within the task upon scaling in. (Auto Scaling implemented)

Is there a possibility for the Fargate task to exit gracefully (to complete all the processes within the task before shutting it down)?

There is a way in EC2 to handle this through Life cycle hooks but I'm not sure if there is anything similar in the Amazon Fargate cluster.

答:
Capture the SIGTERM signal and do your cleanup in there. You can trap it in your application, using whatever programming language that you want, or trap it in a shell entrypoint script.

For more information see this blogpost from AWS.

ContentLicense: CC BY-SA 4.0


问:
AWS DMS Error - Unable to use plugins to establish logical replication on source PostgreSQL instance
I'm getting this error trying to replicate a postgre database (not RDS) to another postgre database (also not RDS). I get this connection error but the endpoints (source and target) are tested successfully. Any ideas?

Error: Last Error Unable to use plugins to establish logical replication on source PostgreSQL instance. Follow all prerequisites for 'PostgreSQL as a source in DMS' from https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.html Task error notification received from subtask 0, thread 0 [reptask/replicationtask.c:2880] [1020490] Remaining 1 error messages are truncated. Check the task log to find details Stop Reason FATAL_ERROR Error Level FATAL

答:
You need at least to set logical_replication = 1 in your source database configuration.

And then set the max_replication_slots = N, N being higher or equal to the number of replication processes you plan to run.


问:
Widget is null inside initState
It's the first time a use Flutter (2.8.1) and I'having problems trying to undestrand what's going wrong.

I have a Stateful widget like this:

class SimpleWidget extends StatefulWidget {
  final Type2 aValue;
  const SimpleWidget({Key key, @required this.aValue}) : super(key: key);
  @override
  _SimpleWidgetState createState() => _SimpleWidgetState();
}

class _SimpleWidgetState extends State<SimpleWidget> {
  Type1 color;

  @override
  void initState() {
    super.initState();

    color = widget.aValue; // <-- widget is null
  }
  ...
}
```
<p>that I call in this way:</p>
<pre class="lang-dart prettyprint-override"><code>List<Type1> something = await showDialog(
  context: context,
  builder: (context) {
    print('currentElement.aValue: ${currentElement.aValue}'); // not null
    return SimpleWidget(aValue: currentElement.aValue);
  },
);
</code>```

Why is widget.aValue == null in initState()? How can I solve it?

答:
There are some error in your coding;
The first one is construction of SimpleWidget

```<code>const SimpleWidget({Key key, @required this.aValue}) : super(key: key);
</code>```

when you call like SimpleWidget(aValue: currentElement.aValue); It will should error like key can not be null. You can use ? to make it nullable. Also, @ should be remove, it is a syntax error

The correct one looks like

```<code>const SimpleWidget({Key? key, required this.aValue}) : super(key: key);
</code>```

The second one is in SimpleWidgetState

You can change Type1 color; to late Type1 color;
Or make it nullable.
For more details, you can check flutter codelabs

Title: Widget is null inside initState

Body:
It's the first time a use Flutter (2.8.1) and I'having problems trying to undestrand what's going wrong.

I have a Stateful widget like this:

class SimpleWidget extends StatefulWidget {
  final Type2 aValue;
  const SimpleWidget({Key key, @required this.aValue}) : super(key: key);
  @override
  _SimpleWidgetState createState() => _SimpleWidgetState();
}

class _SimpleWidgetState extends State<SimpleWidget> {
  Type1 color;

  @override
  void initState() {
    super.initState();

    color = widget.aValue; // <-- widget is null
  }
  ...
}

that I call in this way:

List<Type1> something = await showDialog(
  context: context,
  builder: (context) {
    print('currentElement.aValue: ${currentElement.aValue}'); // not null
    return SimpleWidget(aValue: currentElement.aValue);
  },
);

Why is widget.aValue == null in initState()? How can I solve it?

Body:
There are some error in your coding;
The first one is construction of SimpleWidget

const SimpleWidget({Key key, @required this.aValue}) : super(key: key);

when you call like SimpleWidget(aValue: currentElement.aValue); It will should error like key can not be null. You can use ? to make it nullable. Also, @ should be remove, it is a syntax error

The correct one looks like

const SimpleWidget({Key? key, required this.aValue}) : super(key: key);

The second one is in SimpleWidgetState

You can change Type1 color; to late Type1 color;
Or make it nullable.
For more details, you can check flutter codelabs


问:
How do I encode categorical values in a Pandas DataFrame using a dictionary scheme given in an Excel file?
I have a Pandas DataFrame with a key attribute and other categorical attributes. How can I encode the categorical attributes using the 'dictionary' in this excel file?

This is the dataframe

and this is the excel file

I want to encode every categorical variable, say, for example, ACGB03A from the DataFrame by looking it up in the 'VARIABLE' column of the excel file, and getting the corresponding integer value from the 'Value Scheme Detail' column.

'VARIABLE' is the key, and 'Value Scheme Detail' gives the encoding details. I need to encode it from the string in the DataFrame to the corresponding integer specified in the 'Value Scheme Detail' column for the particular 'VARIABLE'.

I have around 300 columns in the dataset, so I'd like a way to encode automatically without hardcoding the strings and integers in.

Thanks.

答:
Use:

```<code>import pandas as pd

def categorizer(val):
  if val == '0 to 10%':
    return 1
  elif val == '11 to 25%':
    return 2
  elif val == '26 to 50%':
    return 3
  else:
    return 4

df = pd.DataFrame({'11 to 25%'}, columns = ['ACBG03A'])
excel = pd.DataFrame({'variable': ['ACBG03A'], 'VSD': [11]})
temp = excel[excel['variable'].isin(df.columns)]
temp['enc'] = temp['VSD'].apply(categorizer)
</code>```

Result:

I created the excel file, but you need just to read that using read_excel.

Based on the comments:

```<code>def autodic(string):
  temp = string.replace(';', '",').replace(':', ':"')
  temp = '{'+temp+'"'+'}'
  return eval(temp)
</code>```

Body:
Use:

import pandas as pd

def categorizer(val):
  if val == '0 to 10%':
    return 1
  elif val == '11 to 25%':
    return 2
  elif val == '26 to 50%':
    return 3
  else:
    return 4

df = pd.DataFrame({'11 to 25%'}, columns = ['ACBG03A'])
excel = pd.DataFrame({'variable': ['ACBG03A'], 'VSD': [11]})
temp = excel[excel['variable'].isin(df.columns)]
temp['enc'] = temp['VSD'].apply(categorizer)

Result:

I created the excel file, but you need just to read that using read_excel.

Based on the comments:

def autodic(string):
  temp = string.replace(';', '",').replace(':', ':"')
  temp = '{'+temp+'"'+'}'
  return eval(temp)


问:
GKE Autopilot failing to create new deployment after 10-12 deployments saying "Insufficient CPU"
I am having some issue with GKE(autopilot).

I am deploying statefulsets and for each statefulset I deploy a service with public IP.
But after deploying like 10-12 statefulsets, if I try deploying any new it remains  red(Unschedulable) with message "Insufficient cpu".

When I go to cluster section is show a different message saying:

```<code>Can’t scale up because instances in managed instance groups hosting node pools ran out of IPs
</code>```

Image of error: https://i.imgur.com/t8I4Yij.png

I am new to GKE and tried doing what suggested in links of those image but it seems most of steps give error saying its not supported in autopilot mode.

Any help/suggestion is appreciated.

Thanks.

答: Unfortunately, the only option at this point is to create a new cluster and make sure that the CIDR ranges you assign to the cluster have enough available IPs for the number of nodes you believe you'll need.  The default setting for Autopilot should be enough.</p>

Body:
I am having some issue with GKE(autopilot).

I am deploying statefulsets and for each statefulset I deploy a service with public IP.
But after deploying like 10-12 statefulsets, if I try deploying any new it remains  red(Unschedulable) with message "Insufficient cpu".

When I go to cluster section is show a different message saying:

Can’t scale up because instances in managed instance groups hosting node pools ran out of IPs

Image of error: https://i.imgur.com/t8I4Yij.png

I am new to GKE and tried doing what suggested in links of those image but it seems most of steps give error saying its not supported in autopilot mode.

Any help/suggestion is appreciated.

Thanks.


问:
LOF vs k-NN in data with varying density
When the dataset is comprised of regions of varying densities, which technique is more effective for outlier detection Localised Outlier Factor(LoF) or K-Nearest neighbors (KNN)</p>

答: Localised Outlier Factor(LoF) would be better for groups with varying densities. Pls check the formula for LOF https://en.wikipedia.org/wiki/Local_outlier_factor</p>


问:
Add multiple criteria in select
I'm trying to complete my query with one additional criteria in select. This is how it looks now

SELECT
    c.hostname,
    s.executablepath,
    s.version,
    (
        SELECT TOP 1 filesize
        FROM [inventorydatabase].[inv].[softwareview]
        WHERE version = s.version
          AND PathName = s.ExecutablePath
    ) AS 'Size'
FROM tblApplications ca
INNER JOIN tblSoftware s ON s.Software = cs.Software
INNER JOIN tblComputer c ON ca.CompID  = c.CompID
```

So this query gives me out result if I have match in both version tables and both path tables.

...but I need to add additional criteria so that it give me result of 'Size' even if I have only match in both pathname = s.executablepath tables.

Because there some applications with no version available and it just gives me NULL under Size.

Hope someone help me to resolve this issue.

答:
Assuming that "there some applications with no version available" means version is null, then the sub query would be:

```<code>select top (1) filesize
from [inventorydatabase].[inv].[softwareview]
where pathName = s.ExecutablePath and (
    version = s.version or
    version is null
)
</code>```

Title: Add multiple criteria in select

Body:
I'm trying to complete my query with one additional criteria in select. This is how it looks now

SELECT
    c.hostname,
    s.executablepath,
    s.version,
    (
        SELECT TOP 1 filesize
        FROM [inventorydatabase].[inv].[softwareview]
        WHERE version = s.version
          AND PathName = s.ExecutablePath
    ) AS 'Size'
FROM tblApplications ca
INNER JOIN tblSoftware s ON s.Software = cs.Software
INNER JOIN tblComputer c ON ca.CompID  = c.CompID

So this query gives me out result if I have match in both version tables and both path tables.

...but I need to add additional criteria so that it give me result of 'Size' even if I have only match in both pathname = s.executablepath tables.

Because there some applications with no version available and it just gives me NULL under Size.

Hope someone help me to resolve this issue.

Body:
Assuming that "there some applications with no version available" means version is null, then the sub query would be:

select top (1) filesize
from [inventorydatabase].[inv].[softwareview]
where pathName = s.ExecutablePath and (
    version = s.version or
    version is null
)


问:
Need sql query to get expected output for the below,
Tried the below query, but it works only for the first and second records.

Select
  name,
  dept,
  sal,
  (
    coalesce(sal, 0) + coalesce(saltodrop)
  ) as running total (
    SELECT
      name,
      dept,
      sal,
      LAG(Sal, 1, 0) OVER(
        PARTITION BY [dept]
        ORDER BY
          [name],
          [dept] ASC
      ) AS [saltodrop]
    FROM
      dataset
  ) as data_set_extract

```
<p>Input</p>
```Name dept sal
John sales 10000
Tom sales 8000
Tim sales 5000
George finance 6000
Dane finance 4000
Mike hr 5000
Meme hr 6000
Ark it 5000
```
<p>Output</p>
```Name dept sal
John sales 1000
Tom sales 18000
Tim sales 23000
George finance 29000
Dane finance 33000
Mike hr 38000
Meme hr 44000
Ark it 49000
```

Using the Oracle database, I need to add a consecutive row of the
first two records, later the sum of the first record and second record
with that of the third record and so on.

答:
Assuming you have already ordered the results then use the SUM analytic function and order by ROWNUM to keep the current ordering:

SELECT t.*,
       SUM(sal) OVER (ORDER BY ROWNUM) AS cumulative_sal
FROM   table_name t;
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE table_name (Name, dept, sal) AS
SELECT 'John',   'sales',   10000 FROM DUAL UNION ALL
SELECT 'Tom',    'sales',    8000 FROM DUAL UNION ALL
SELECT 'Tim',    'sales',    5000 FROM DUAL UNION ALL
SELECT 'George', 'finance',  6000 FROM DUAL UNION ALL
SELECT 'Dane',   'finance',  4000 FROM DUAL UNION ALL
SELECT 'Mike',   'hr',       5000 FROM DUAL UNION ALL
SELECT 'Meme',   'hr',       6000 FROM DUAL UNION ALL
SELECT 'Ark',    'it',       5000 FROM DUAL;
</code>```

Outputs:

NAME
DEPT
SAL
CUMULATIVE_SAL

John
sales
10000
10000

Tom
sales
8000
18000

Tim
sales
5000
23000

George
finance
6000
29000

Dane
finance
4000
33000

Mike
hr
5000
38000

Meme
hr
6000
44000

Ark
it
5000
49000

db<>fiddle here

Body:
Tried the below query, but it works only for the first and second records.

Select
  name,
  dept,
  sal,
  (
    coalesce(sal, 0) + coalesce(saltodrop)
  ) as running total (
    SELECT
      name,
      dept,
      sal,
      LAG(Sal, 1, 0) OVER(
        PARTITION BY [dept]
        ORDER BY
          [name],
          [dept] ASC
      ) AS [saltodrop]
    FROM
      dataset
  ) as data_set_extract

Input

Name dept sal
John sales 10000
Tom sales 8000
Tim sales 5000
George finance 6000
Dane finance 4000
Mike hr 5000
Meme hr 6000
Ark it 5000

Output

Name dept sal
John sales 1000
Tom sales 18000
Tim sales 23000
George finance 29000
Dane finance 33000
Mike hr 38000
Meme hr 44000
Ark it 49000

Using the Oracle database, I need to add a consecutive row of the
first two records, later the sum of the first record and second record
with that of the third record and so on.

Body:
Assuming you have already ordered the results then use the SUM analytic function and order by ROWNUM to keep the current ordering:

SELECT t.*,
       SUM(sal) OVER (ORDER BY ROWNUM) AS cumulative_sal
FROM   table_name t;

Which, for the sample data:

CREATE TABLE table_name (Name, dept, sal) AS
SELECT 'John',   'sales',   10000 FROM DUAL UNION ALL
SELECT 'Tom',    'sales',    8000 FROM DUAL UNION ALL
SELECT 'Tim',    'sales',    5000 FROM DUAL UNION ALL
SELECT 'George', 'finance',  6000 FROM DUAL UNION ALL
SELECT 'Dane',   'finance',  4000 FROM DUAL UNION ALL
SELECT 'Mike',   'hr',       5000 FROM DUAL UNION ALL
SELECT 'Meme',   'hr',       6000 FROM DUAL UNION ALL
SELECT 'Ark',    'it',       5000 FROM DUAL;

Outputs:

NAME
DEPT
SAL
CUMULATIVE_SAL

John
sales
10000
10000

Tom
sales
8000
18000

Tim
sales
5000
23000

George
finance
6000
29000

Dane
finance
4000
33000

Mike
hr
5000
38000

Meme
hr
6000
44000

Ark
it
5000
49000

db<>fiddle here


问:
how to shift grid in netcdf file from (-180, 180) to (0, 360) in python?
I'm a obvious newbie to netCDF and some libraries in python.
What i've been struggling to is, I want to change longitude grid in netCDF file. It's like (-180, 180) but I have to change it to (0, 360).

In this case, I would have used 'shiftgrid' which could have been used with 'from mpl_toolkits.basemap import shiftgrid'.

But this mpl_toolkits.basemap is a troublesome to me. It's impossible to use this one..
So I'd like to solve this problem with cartopy or other things, you guys can see the libraries that I normally use at the bottom.

How can I change the grid thing?

```<code>from netCDF4 import Dataset
import matplotlib.pylot as plt
from mpl_toolkits.basemap import shiftgrid
from sys import exit
import numpy as np
import pickle

file1= '/home/HadISST_sst.nc'
DATA1 = Dataset(file1, 'r')

hd_lat = DATA1.variables['latitude'][:] #89.5 -89.5
hd_lon0 = DATA1.variables['longitude'][:] #-179.5 179.5
hd_sst0 = DATA1.variables['sst'][1320:,:,:] #time, y, x
DATA1.close()

# shift grid from (-180,180) to (0,360)
hd_sst, hd_lon = shiftgrid(0, hd_sst0, hd_lon0, start=True)
hd_lon2, hd_lat2 = np.meshgrid(hd_lon, hd_lat) # to 2d data
</code>```

答:
Basemap and netCDF are libraries which you should not use any more.
Xarray and Cartopy are much better to handle climate data. (some examples: https://xarray.pydata.org/en/stable/examples/visualization_gallery.html)

You can change the grid like this:

```<code>import xarray as xr
your_data = xr.open_dataset('path/to/file.nc')
your_data['lon'] = your_data.lon + 180
</code>```

Body:
I'm a obvious newbie to netCDF and some libraries in python.
What i've been struggling to is, I want to change longitude grid in netCDF file. It's like (-180, 180) but I have to change it to (0, 360).

In this case, I would have used 'shiftgrid' which could have been used with 'from mpl_toolkits.basemap import shiftgrid'.

But this mpl_toolkits.basemap is a troublesome to me. It's impossible to use this one..
So I'd like to solve this problem with cartopy or other things, you guys can see the libraries that I normally use at the bottom.

How can I change the grid thing?

from netCDF4 import Dataset
import matplotlib.pylot as plt
from mpl_toolkits.basemap import shiftgrid
from sys import exit
import numpy as np
import pickle

file1= '/home/HadISST_sst.nc'
DATA1 = Dataset(file1, 'r')

hd_lat = DATA1.variables['latitude'][:] #89.5 -89.5
hd_lon0 = DATA1.variables['longitude'][:] #-179.5 179.5
hd_sst0 = DATA1.variables['sst'][1320:,:,:] #time, y, x
DATA1.close()

# shift grid from (-180,180) to (0,360)
hd_sst, hd_lon = shiftgrid(0, hd_sst0, hd_lon0, start=True)
hd_lon2, hd_lat2 = np.meshgrid(hd_lon, hd_lat) # to 2d data

Body:
Basemap and netCDF are libraries which you should not use any more.
Xarray and Cartopy are much better to handle climate data. (some examples: https://xarray.pydata.org/en/stable/examples/visualization_gallery.html)

You can change the grid like this:

import xarray as xr
your_data = xr.open_dataset('path/to/file.nc')
your_data['lon'] = your_data.lon + 180


问:
"Forbidden You don't have permission to access this resource." on phpMyAdmin in Mac Os
I tried to install phpMyadmin in MacOs. But When I go to localhost/phpmyadmin it says Forbidden You don't have permission to access this resource. My phpMyAdmin folder is in
/usr/local folder in Finder. I configured the phpmyadmin.conf file with sudo nano /etc/apache2/other/phpmyadmin.conf with the following codes:

```<code><Directory /usr/local/phpmyadmin>
        Options Indexes
        Order allow,deny
        Allow from all
        allow from 127.0.0.1
        allow from 192.168.1.0/15
</Directory>
</code>```

What should I do to get rid of this error?

答:
You need to check 2 things:

that your phpmyadmin folder (/usr/local/share/phpmyadmin by default, but judging by your question I assume it's /usr/local/phpmyadmin; be sure to check on that too) is readable by your user and that directories that needs to be writeable by you are.

that you have correct order for Allow and Deny settings for that directory (you either deny from all and then allow from certain locations, or allow from all locations and then disallow from some).

I suggest changing the config file to look like this:

<Directory /usr/local/phpMyAdmin/>
    Options Indexes
    Order Deny,Allow
    Deny from All
    Allow from 127.0.0.1
    Allow from 192.168.1.0/15
</Directory>```

Make sure that the path in <Directory /usr/local/phpMyAdmin/> is pointing to your phpmyadmin location.

Also I'm not sure there should be Options Indexes line in the config, try removing it temporarily.

Upd: You need to restart apache after making changes to config files (usually it's sudo service apache2 restart)

Body:
I tried to install phpMyadmin in MacOs. But When I go to localhost/phpmyadmin it says Forbidden You don't have permission to access this resource. My phpMyAdmin folder is in
/usr/local folder in Finder. I configured the phpmyadmin.conf file with sudo nano /etc/apache2/other/phpmyadmin.conf with the following codes:

<Directory /usr/local/phpmyadmin>
        Options Indexes
        Order allow,deny
        Allow from all
        allow from 127.0.0.1
        allow from 192.168.1.0/15
</Directory>

What should I do to get rid of this error?

Body:
You need to check 2 things:

that your phpmyadmin folder (/usr/local/share/phpmyadmin by default, but judging by your question I assume it's /usr/local/phpmyadmin; be sure to check on that too) is readable by your user and that directories that needs to be writeable by you are.

that you have correct order for Allow and Deny settings for that directory (you either deny from all and then allow from certain locations, or allow from all locations and then disallow from some).

I suggest changing the config file to look like this:

<Directory /usr/local/phpMyAdmin/>
    Options Indexes
    Order Deny,Allow
    Deny from All
    Allow from 127.0.0.1
    Allow from 192.168.1.0/15
</Directory>

Make sure that the path in <Directory /usr/local/phpMyAdmin/> is pointing to your phpmyadmin location.

Also I'm not sure there should be Options Indexes line in the config, try removing it temporarily.

Upd: You need to restart apache after making changes to config files (usually it's sudo service apache2 restart)


问:
Why do I get a segmentation fault when calling a virtual method in this code?
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

```<code>#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}
</code>```

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

答:
Whoa there.

There's a few problems, but your segfault is probably because you're passing a char* -- which is just a pointer, and then trying to cout it in disp(). Problem is, that pointer does not live in disp(), it lives in main(). You probably want to either deep-copy the char*, or use std::string. Doing it this way will not work.

EDIT:

See EDIT 2

You can not just assign name to the class's name variable. If you do that, you'll get unpredictable results - and you'll probably STILL segfault. Remember: in C/C++, objects are locally scoped unless allocated on the heap. In this case, in your ctor, you'd want to do something like:

```<code>this->name = new char[ strlen( name ) + 1 ];
strcpy( this->name, name );
</code>```

And in the destructor, you'll want to do something like:

```<code>delete [] this->name;
</code>```

Note: my syntax may be completely wrong, and I realize the above code is inherently unsafe as you're not checking the char* to make sure it's not NULL, and you're not checking the return value of new. Nevertheless, this should get you started.

EDIT 2:
I stand corrected. String literals are treated as constant storage and thus live on for the duration of the program. Nevertheless, the lesson, I believe, is important: in general, when not dealing with string literals, passing a pointer (or array, etc.), you need to allocate storage for it and deep-copy. You also need to de-allocate appropriately when destroying said object.

OwnerDisplayName: Srikanth

ContentLicense: CC BY-SA 2.5

Body:
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

Body:
Whoa there.

There's a few problems, but your segfault is probably because you're passing a char* -- which is just a pointer, and then trying to cout it in disp(). Problem is, that pointer does not live in disp(), it lives in main(). You probably want to either deep-copy the char*, or use std::string. Doing it this way will not work.

EDIT:

See EDIT 2

You can not just assign name to the class's name variable. If you do that, you'll get unpredictable results - and you'll probably STILL segfault. Remember: in C/C++, objects are locally scoped unless allocated on the heap. In this case, in your ctor, you'd want to do something like:

this->name = new char[ strlen( name ) + 1 ];
strcpy( this->name, name );

And in the destructor, you'll want to do something like:

delete [] this->name;

Note: my syntax may be completely wrong, and I realize the above code is inherently unsafe as you're not checking the char* to make sure it's not NULL, and you're not checking the return value of new. Nevertheless, this should get you started.

EDIT 2:
I stand corrected. String literals are treated as constant storage and thus live on for the duration of the program. Nevertheless, the lesson, I believe, is important: in general, when not dealing with string literals, passing a pointer (or array, etc.), you need to allocate storage for it and deep-copy. You also need to de-allocate appropriately when destroying said object.

OwnerDisplayName: FreeMemory

LastEditorDisplayName: FreeMemory


问:
argumentException was unhandled error when converting byte of array to image
I have  done this one for converting the byte of array in one of the columns in gridview  to system.drawing.image  got an error        at this line             </p>

```<code>Image returnImage = Image.FromStream(ms);

              argumentexception was unhandled
              Parameter is not valid.
</code>```

<p>and the code is like this </p>

```<code>private byte[] objtoarray(object obj)
{
    if (obj == null)
        return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray();

}

public Image bytearraytoimage(byte[] bytearray)
{
    MemoryStream ms = new MemoryStream(bytearray,0,bytearray.Length);

    Image returnImage = Image.FromStream(ms);
    return returnImage;

}

private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
{
    byte[] bits = null;
    Image img = null;

    if (e.ColumnIndex != productgridview.Columns["productimage"].Index) return;

    if (productgridview.SelectedCells.Count == 0) return;

    object selectedValue = productgridview.SelectedCells[0].Value;
    bits= objtoarray(selectedValue);
    img = bytearraytoimage(bits);

    if (img is Image)
    {
        // Forms are IDisposable, so use them embedded in a using statement.
        using (ProductDescriptionForm pf = new ProductDescriptionForm())
        {
            pf.picture = (Image)selectedValue;
            pf.ShowDialog(this);
        }
    }
}
</code>```

答:
The docs state that ArgumentException can be raise for :

```<code>The stream does not have a valid image format
-or-
stream is null.
</code>```

So since objtoarray can return null, is productgridview.SelectedCells[0].Value null, or of an invalid value?

```<code>    object selectedValue = productgridview.SelectedCells[0].Value;
    bits= objtoarray(selectedValue);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have  done this one for converting the byte of array in one of the columns in gridview  to system.drawing.image  got an error        at this line

Image returnImage = Image.FromStream(ms);

              argumentexception was unhandled
              Parameter is not valid.

and the code is like this

private byte[] objtoarray(object obj)
{
    if (obj == null)
        return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray();

}

public Image bytearraytoimage(byte[] bytearray)
{
    MemoryStream ms = new MemoryStream(bytearray,0,bytearray.Length);

    Image returnImage = Image.FromStream(ms);
    return returnImage;

}

private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
{
    byte[] bits = null;
    Image img = null;

    if (e.ColumnIndex != productgridview.Columns["productimage"].Index) return;

    if (productgridview.SelectedCells.Count == 0) return;

    object selectedValue = productgridview.SelectedCells[0].Value;
    bits= objtoarray(selectedValue);
    img = bytearraytoimage(bits);

    if (img is Image)
    {
        // Forms are IDisposable, so use them embedded in a using statement.
        using (ProductDescriptionForm pf = new ProductDescriptionForm())
        {
            pf.picture = (Image)selectedValue;
            pf.ShowDialog(this);
        }
    }
}

Body:
The docs state that ArgumentException can be raise for :

The stream does not have a valid image format
-or-
stream is null.

So since objtoarray can return null, is productgridview.SelectedCells[0].Value null, or of an invalid value?

    object selectedValue = productgridview.SelectedCells[0].Value;
    bits= objtoarray(selectedValue);


问:
Execution failed for task ':app:packageDebug' - Failed to read zip file
Without any changes in my code, suddenly i get this error when I try to run my app:

What went wrong:
  Execution failed for task ':app:packageDebug'.
  com.android.builder.packaging.PackagerException: java.io.IOException: Failed to read zip file 'C:\Users\Eliran\AndroidStudioProjects\Forum\app\build\outputs\apk\app-debug.apk'.

I have no idea why its trying to read the apk as zip file.

If I restart Android Studio, I can run the app once and then It happens again.

答:
1.delete debug.keystore file

```<code>C:\Users\xxx\.android\debug.keystore
</code>```

flutter clean

restart ide

Body:
1.delete debug.keystore file

C:\Users\xxx\.android\debug.keystore

flutter clean

restart ide


问:
AudioManager auto switching own mode + not respecting setSpeakerphoneOn()
I want to play some audio with volume lvl adjusted to ear aka. "phone call mode". For this purpose, I'm using well-known and commonly advised

```<code>audioManager.setMode(audioNormalState ?
            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
</code>```

The problem is that I'm not always playing audio just after mode switching, I have to wait and can't be sure how long, it may be even minutes. I've made some looped logging and MODE_IN_COMMUNICATION mode is kept as long as the user is in "phone call mode" in my app on some Motorola with Android 9, but on Pixel 3 with Android 12 after 6 seconds mode is auto-switching back to MODE_NORMAL when nothing is played. No additional code executed (like some listener), no additional (system) logs. When I start playing audio 1 sec after switching to MODE_IN_COMMUNICATION mode it won't auto-switch as long as the audio is played (even more than 6 secs), but right after finishing mode gets also auto-switched to MODE_NORMAL.

My app makes sort-of real-time voice calls (commands), but can also "beep" a few signals-patterns, and there is also a history feature providing all chronological sound-making actions to be played again in order. If this would be only voice then switching to MODE_IN_COMMUNICATION and back only during a call might be sufficient, but what to do with highly-important SoundPool jingles, do I have to switch mode also for them? (or for history play, which is a mix) AFAIK mode switching isn't fast (even a few secs on some devices), so I may apply some significant delay for short hundreds-of-ms signals (no way, every ms is crucial!) or I'm risking playing out loud signal/voice even in "phone call mode", when mode doesn't change "fast enough" (user won't be happy). I was relying on setting fixed (but configured according to app state and settings) MODE_IN_COMMUNICATION, which was working till Android 12... (can confirm new/wrong behavior on Pixels and Samsungs)

currently used method for switching audio mode + configuration below, worth noting that setSpeakerphoneOn method also doesn't work always on Android 12. At least not when on MODE_NORMAL, which is default auto-switch-back-to mode now, also isSpeakerphoneOn is false on the very first start, but all my audio sources are in fact played loud...

```<code>// forceAudioNormalState = true only when app exit!
public static void resolveLoudState(AudioManager audioManager, boolean forceAudioNormalState) {
    boolean silentPhoneCallMode = isPhoneCallModeEnabled(); // phone call GUI, only ear-friendly volume!!
    boolean silentHeadset = HeadsetPlugReceiver.isHeadsetPlugged &&
            !HeadsetPlugReceiver.forceSpeakerWhenHeadsetOn; // headset plugged, but "muted", force speaker
    boolean silentBluetooth = BluetoothController.isAudioDeviceConnected() &&
            !audioManager.isBluetoothScoOn(); // bt headset plugged, but "muted", force speaker

    boolean loud = true; // by default
    if (silentPhoneCallMode || silentHeadset || silentBluetooth) loud = false;

    String log = String.format("resolveLoudState play loud: %s," +
                    " silentPhoneCallMode: %s, silentHeadset: %s, silentBluetooth: %s",
            loud, silentPhoneCallMode, silentHeadset, silentBluetooth);
    Timber.i(log);

    audioManager.setMode(forceAudioNormalState ?
            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
    audioManager.setSpeakerphoneOn(loud);
    // even if deprecated this still works! fake wired headset on even for bt
    audioManager.setWiredHeadsetOn(!loud && (silentHeadset || silentBluetooth));
    // not loud and any headset connected and "muted"
}
</code>```

note that in the above snippet there is no flag/information about the current playing state, only apps state/config

I want to manage these modes by myself and decide which audio output will be used or maybe there is any other way for forcing playing all audio (AudioTrack, SoundPool, MediaPlayer, ExoPlayer etc.) with ear-friendly adjusted volume?

edit: Just noticed when the mode auto-switches to MODE_NORMAL and I will start playing STREAM_VOICE_CALL it will auto switch to MODE_IN_COMMUNICATION (with some small but significant delay) and reset back again just after finishing audio... This is some new undocumented behavior of system overall, become very unfriendly, bugged and unclear API...

edit2: this looks like related issue

PS. I've noticed that MediaSession apps (e.g. music players) on Android 12 device got a new option straight on Notification for picking speaker/headphones when wired/bt headset/earphones connected, but I'm not using session API at all. bonus question: is there an API for that?

答:
found some answers to my own question, sharing with community

6-sec auto-switch mode is a new feature in Android 12, which works only if (mode == AudioSystem.MODE_IN_COMMUNICATION) (check out  flow related to MSG_CHECK_MODE_FOR_UID flag). This should help for MODE_IN_COMMUNICATION set to AudioManager and left after app exit, this was messing with global/system-level audio routing. There is also a brand new AudioManager.OnModeChangedListener called when mode is (auto-)changing

and setSpeakerphoneOn turns out to be deprecated, even if this isn't marked in doc... we have new method setCommunicationDevice(AudioDeviceInfo) and in its description we have info about startBluetoothSco(), stopBluetoothSco() and setSpeakerphoneOn(boolean) deprecation. I'm using all three methods and now on Android 12 I'm iterating through getAvailableCommunicationDevices(), comparing type of every item and if desired type found I'm calling setCommunicationDevice(targetAudioDeviceInfo). I'm NOT switching audio mode at all now, staying on MODE_NORMAL. All my streams are AudioManager.STREAM_VOICE_CALL type (where applicable)

for built-in earpiece audio playback aka. "ear-friendly mode" we were using

```<code>if (earpieceMode) {
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    audioManager.setSpeakerphoneOn(false); // call AFTER setMode
}
</code>```

that won't work reliable on Android 12 (after multiple speakerphone state switches). Now I'm using below code (comprehensive snippet)

```<code>ArrayList<Integer> targetTypes = new ArrayList<>();
//add types according to needs, may be few in order of importance
if (bluetoothScoConnected) {
    targetTypes.add(AudioDeviceInfo.TYPE_BLUETOOTH_SCO);
} else if (wiredHeadsetConnected) {
    if (isUsbHeadset) {
        targetTypes.add(AudioDeviceInfo.TYPE_USB_HEADSET);
        targetTypes.add(AudioDeviceInfo.TYPE_USB_DEVICE);
        targetTypes.add(AudioDeviceInfo.TYPE_USB_ACCESSORY);
    } else {
        targetTypes.add(AudioDeviceInfo.TYPE_WIRED_HEADSET);
        targetTypes.add(AudioDeviceInfo.TYPE_WIRED_HEADPHONES);
    }
} else if (earpieceMode) {
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
} else { // play out loud
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
}

Boolean result = null;
List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();

outer:
for (Integer targetType : targetTypes) {
    for (AudioDeviceInfo device : devices) {
        if (device.getType() == targetType) {
            result = audioManager.setCommunicationDevice(device);
            Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
            break outer;
        }
    }
}

if (result == null) {
    Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType NOT FOUND!!");
}
</code>```

worth mentioning Bluetooth SCO headset case - when freshly connected/paired with device all my accessories are recognized as AudioDeviceInfo.TYPE_BLUETOOTH_A2DP type (getCommunicationDevice()). I do want SCO, which isn't listed in getAvailableCommunicationDevices() for few seconds after A2DP connection, so I'm leaving some countdown timer, which checks (interval 2s) and waits for AudioDeviceInfo.TYPE_BLUETOOTH_SCO for few secs (I've set 16), then I'm switching to this type when appear on list or just dismissing timer

Body:
I want to play some audio with volume lvl adjusted to ear aka. "phone call mode". For this purpose, I'm using well-known and commonly advised

audioManager.setMode(audioNormalState ?
            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);

The problem is that I'm not always playing audio just after mode switching, I have to wait and can't be sure how long, it may be even minutes. I've made some looped logging and MODE_IN_COMMUNICATION mode is kept as long as the user is in "phone call mode" in my app on some Motorola with Android 9, but on Pixel 3 with Android 12 after 6 seconds mode is auto-switching back to MODE_NORMAL when nothing is played. No additional code executed (like some listener), no additional (system) logs. When I start playing audio 1 sec after switching to MODE_IN_COMMUNICATION mode it won't auto-switch as long as the audio is played (even more than 6 secs), but right after finishing mode gets also auto-switched to MODE_NORMAL.

My app makes sort-of real-time voice calls (commands), but can also "beep" a few signals-patterns, and there is also a history feature providing all chronological sound-making actions to be played again in order. If this would be only voice then switching to MODE_IN_COMMUNICATION and back only during a call might be sufficient, but what to do with highly-important SoundPool jingles, do I have to switch mode also for them? (or for history play, which is a mix) AFAIK mode switching isn't fast (even a few secs on some devices), so I may apply some significant delay for short hundreds-of-ms signals (no way, every ms is crucial!) or I'm risking playing out loud signal/voice even in "phone call mode", when mode doesn't change "fast enough" (user won't be happy). I was relying on setting fixed (but configured according to app state and settings) MODE_IN_COMMUNICATION, which was working till Android 12... (can confirm new/wrong behavior on Pixels and Samsungs)

currently used method for switching audio mode + configuration below, worth noting that setSpeakerphoneOn method also doesn't work always on Android 12. At least not when on MODE_NORMAL, which is default auto-switch-back-to mode now, also isSpeakerphoneOn is false on the very first start, but all my audio sources are in fact played loud...

// forceAudioNormalState = true only when app exit!
public static void resolveLoudState(AudioManager audioManager, boolean forceAudioNormalState) {
    boolean silentPhoneCallMode = isPhoneCallModeEnabled(); // phone call GUI, only ear-friendly volume!!
    boolean silentHeadset = HeadsetPlugReceiver.isHeadsetPlugged &&
            !HeadsetPlugReceiver.forceSpeakerWhenHeadsetOn; // headset plugged, but "muted", force speaker
    boolean silentBluetooth = BluetoothController.isAudioDeviceConnected() &&
            !audioManager.isBluetoothScoOn(); // bt headset plugged, but "muted", force speaker

    boolean loud = true; // by default
    if (silentPhoneCallMode || silentHeadset || silentBluetooth) loud = false;

    String log = String.format("resolveLoudState play loud: %s," +
                    " silentPhoneCallMode: %s, silentHeadset: %s, silentBluetooth: %s",
            loud, silentPhoneCallMode, silentHeadset, silentBluetooth);
    Timber.i(log);

    audioManager.setMode(forceAudioNormalState ?
            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
    audioManager.setSpeakerphoneOn(loud);
    // even if deprecated this still works! fake wired headset on even for bt
    audioManager.setWiredHeadsetOn(!loud && (silentHeadset || silentBluetooth));
    // not loud and any headset connected and "muted"
}

note that in the above snippet there is no flag/information about the current playing state, only apps state/config

I want to manage these modes by myself and decide which audio output will be used or maybe there is any other way for forcing playing all audio (AudioTrack, SoundPool, MediaPlayer, ExoPlayer etc.) with ear-friendly adjusted volume?

edit: Just noticed when the mode auto-switches to MODE_NORMAL and I will start playing STREAM_VOICE_CALL it will auto switch to MODE_IN_COMMUNICATION (with some small but significant delay) and reset back again just after finishing audio... This is some new undocumented behavior of system overall, become very unfriendly, bugged and unclear API...

edit2: this looks like related issue

PS. I've noticed that MediaSession apps (e.g. music players) on Android 12 device got a new option straight on Notification for picking speaker/headphones when wired/bt headset/earphones connected, but I'm not using session API at all. bonus question: is there an API for that?

Body:
found some answers to my own question, sharing with community

6-sec auto-switch mode is a new feature in Android 12, which works only if (mode == AudioSystem.MODE_IN_COMMUNICATION) (check out  flow related to MSG_CHECK_MODE_FOR_UID flag). This should help for MODE_IN_COMMUNICATION set to AudioManager and left after app exit, this was messing with global/system-level audio routing. There is also a brand new AudioManager.OnModeChangedListener called when mode is (auto-)changing

and setSpeakerphoneOn turns out to be deprecated, even if this isn't marked in doc... we have new method setCommunicationDevice(AudioDeviceInfo) and in its description we have info about startBluetoothSco(), stopBluetoothSco() and setSpeakerphoneOn(boolean) deprecation. I'm using all three methods and now on Android 12 I'm iterating through getAvailableCommunicationDevices(), comparing type of every item and if desired type found I'm calling setCommunicationDevice(targetAudioDeviceInfo). I'm NOT switching audio mode at all now, staying on MODE_NORMAL. All my streams are AudioManager.STREAM_VOICE_CALL type (where applicable)

for built-in earpiece audio playback aka. "ear-friendly mode" we were using

if (earpieceMode) {
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    audioManager.setSpeakerphoneOn(false); // call AFTER setMode
}

that won't work reliable on Android 12 (after multiple speakerphone state switches). Now I'm using below code (comprehensive snippet)

ArrayList<Integer> targetTypes = new ArrayList<>();
//add types according to needs, may be few in order of importance
if (bluetoothScoConnected) {
    targetTypes.add(AudioDeviceInfo.TYPE_BLUETOOTH_SCO);
} else if (wiredHeadsetConnected) {
    if (isUsbHeadset) {
        targetTypes.add(AudioDeviceInfo.TYPE_USB_HEADSET);
        targetTypes.add(AudioDeviceInfo.TYPE_USB_DEVICE);
        targetTypes.add(AudioDeviceInfo.TYPE_USB_ACCESSORY);
    } else {
        targetTypes.add(AudioDeviceInfo.TYPE_WIRED_HEADSET);
        targetTypes.add(AudioDeviceInfo.TYPE_WIRED_HEADPHONES);
    }
} else if (earpieceMode) {
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
} else { // play out loud
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
}

Boolean result = null;
List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();

outer:
for (Integer targetType : targetTypes) {
    for (AudioDeviceInfo device : devices) {
        if (device.getType() == targetType) {
            result = audioManager.setCommunicationDevice(device);
            Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
            break outer;
        }
    }
}

if (result == null) {
    Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType NOT FOUND!!");
}

worth mentioning Bluetooth SCO headset case - when freshly connected/paired with device all my accessories are recognized as AudioDeviceInfo.TYPE_BLUETOOTH_A2DP type (getCommunicationDevice()). I do want SCO, which isn't listed in getAvailableCommunicationDevices() for few seconds after A2DP connection, so I'm leaving some countdown timer, which checks (interval 2s) and waits for AudioDeviceInfo.TYPE_BLUETOOTH_SCO for few secs (I've set 16), then I'm switching to this type when appear on list or just dismissing timer


问:
MongoDB: how to pass current value to operator?
Here is sample db structure where I'm trying to modify value of every work_starts_at.

```<code>{
    "_id": 1,
    "work_week": [
        {'name': 'ponedeljak', 'work_hours': []},
        {'name': 'utorak', 'work_hours': []},
    ]
},
{
    "_id": 2,
    "work_week": [
        {'name': 'monday', 'work_hours': [
            {'work_starts_at': 1, 'work_ends_at': 2}
        ]},
    ]
},
{
    "_id": 3,
    "work_week": [
        {'name': 'понедельник', 'work_hours': [
            {'work_starts_at': 2, 'work_ends_at': 3},
            {'work_starts_at': 6, 'work_ends_at': 7},
        ]},
        {'name': 'вторник', 'work_hours': []},
    ]
}
</code>```

The best solution I came to is the following (in python), but instead of subtracting 5 from current value of work_week.work_hours.work_starts_at it's traversing I got null. I suppose it's because construction $$CURRENT.work_hours.work_starts_at doesn't point to work_starts_at, so I'm actually subtracting 5 from null.

How can I properly address value of currently traversed element?

collection.update_many(
{},
[
    {
        '$set': {
            'work_week.work_hours.work_starts_at': {
                '$subtract': ['$$CURRENT.work_hours.work_starts_at', 5]
            }
        }
    }
]
```

答:
You can do this way from the mongo shell (it must be very similar in python):

```<code>db.collection.update({
 "work_week.work_hours.work_starts_at": {
  $exists: true
}
},
{
 $inc: {
   "work_week.$[].work_hours.$[].work_starts_at": -5
}
},
{
 multi: true
})
</code>```

playground

Body:
Here is sample db structure where I'm trying to modify value of every work_starts_at.

{
    "_id": 1,
    "work_week": [
        {'name': 'ponedeljak', 'work_hours': []},
        {'name': 'utorak', 'work_hours': []},
    ]
},
{
    "_id": 2,
    "work_week": [
        {'name': 'monday', 'work_hours': [
            {'work_starts_at': 1, 'work_ends_at': 2}
        ]},
    ]
},
{
    "_id": 3,
    "work_week": [
        {'name': 'понедельник', 'work_hours': [
            {'work_starts_at': 2, 'work_ends_at': 3},
            {'work_starts_at': 6, 'work_ends_at': 7},
        ]},
        {'name': 'вторник', 'work_hours': []},
    ]
}

The best solution I came to is the following (in python), but instead of subtracting 5 from current value of work_week.work_hours.work_starts_at it's traversing I got null. I suppose it's because construction $$CURRENT.work_hours.work_starts_at doesn't point to work_starts_at, so I'm actually subtracting 5 from null.

How can I properly address value of currently traversed element?

collection.update_many(
{},
[
    {
        '$set': {
            'work_week.work_hours.work_starts_at': {
                '$subtract': ['$$CURRENT.work_hours.work_starts_at', 5]
            }
        }
    }
]

Body:
You can do this way from the mongo shell (it must be very similar in python):

db.collection.update({
 "work_week.work_hours.work_starts_at": {
  $exists: true
}
},
{
 $inc: {
   "work_week.$[].work_hours.$[].work_starts_at": -5
}
},
{
 multi: true
})

playground


问:
getDefaultAdapter() in BluetoothAdapter has been deprecated
I am unable to fix this error on my flutter app.

```<code>    > Task :permission_handler:compileDebugJavaWithJavac FAILED
/Users/sumeetpujari/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-6.1.3/android/src/main/java/com/baseflow/permissionhandler/ServiceManager.java:154: warning: [deprecation] getDefaultAdapter() in BluetoothAdapter has been deprecated
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                                                                  ^
error: warnings found and -Werror specified
1 error
1 warning
warnings found and -Werror specified
</code>```

The code :

```<code>    @SuppressLint("MissingPermission")
private boolean isBluetoothServiceEnabled() {
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    return bluetoothAdapter.isEnabled();
</code>```

答:
To get the default BluetoothAdapter you have to get it from the BluetoothManager system service. The sample below is from SomeActivity. In this case this refers to an instance of an activity.

```<code>BluetoothManager bluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager == null) {
  /* Error handling */
}

BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null) {
  /* Error handling */
}
</code>```

I have tested it with Android API 26 to API31.

Body:
I am unable to fix this error on my flutter app.

    > Task :permission_handler:compileDebugJavaWithJavac FAILED
/Users/sumeetpujari/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-6.1.3/android/src/main/java/com/baseflow/permissionhandler/ServiceManager.java:154: warning: [deprecation] getDefaultAdapter() in BluetoothAdapter has been deprecated
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                                                                  ^
error: warnings found and -Werror specified
1 error
1 warning
warnings found and -Werror specified

The code :

    @SuppressLint("MissingPermission")
private boolean isBluetoothServiceEnabled() {
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    return bluetoothAdapter.isEnabled();

Body:
To get the default BluetoothAdapter you have to get it from the BluetoothManager system service. The sample below is from SomeActivity. In this case this refers to an instance of an activity.

BluetoothManager bluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager == null) {
  /* Error handling */
}

BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null) {
  /* Error handling */
}

I have tested it with Android API 26 to API31.


问:
Why does vs code show so many untracked files whenever I try to see the code for a built-in flutter widget?
While working in Flutter, sometimes I wish to see how a certain built-in or third-party widget works internally. And when I do ctrl+click on my vs code on that widget and hope to see its code, vs code then suddenly shows me like 140-150 untracked files. It only happens when I try to view the code for built-in or third-party widgets.
Help me!!!!
Thanks...

答: Your SDK is actually something cloned from Github or something that has been connected with Github. Any change in that file may reflect in our files too. Source Control feature of VS Code actually follows that repo. Simply close that source control by minimizing it. Usually, Flutter with Source Control enabled to have these problems.</p>


问:
How to perform operation on specific elements of a list?
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want

```<code>i=['0','7','2','3','4']
o=['0','14','2,'6','4']
</code>```

here's the code I tried:

```<code>list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)
</code>```

here's the error I get:

```<code>PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting
</code>```

答:
The below approach uses a list comprehension to achieve the desired list. Here, if we consider in_list as input list then no. inside list is stored as a string so while iterating over the list to check whether no. is odd or even first no. needs to be converted to int and then it is checked with % operator if it is even then it's multiplied with 2 and then result is converted back to string as the output requirement is a list of numbers stored as a string</p>
```<code>in_list=['0','7','2','3','4']
output = [i if (int(i)%2)==0 else str(int(i)*2) for i in in_list ]
print(output)
</code>```

Body:
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want

i=['0','7','2','3','4']
o=['0','14','2,'6','4']

here's the code I tried:

list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)

here's the error I get:

PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting

Body:
The below approach uses a list comprehension to achieve the desired list. Here, if we consider in_list as input list then no. inside list is stored as a string so while iterating over the list to check whether no. is odd or even first no. needs to be converted to int and then it is checked with % operator if it is even then it's multiplied with 2 and then result is converted back to string as the output requirement is a list of numbers stored as a string

in_list=['0','7','2','3','4']
output = [i if (int(i)%2)==0 else str(int(i)*2) for i in in_list ]
print(output)


问:
CORS issue with Keycloak using it in React and Web Origins set
Keycloak is running on localhost:8080 (realm - demo, client - demo)

React app is running on localhost:3000

Want to fetch data from Keycloak into React for which first, I need to get an access token. The config used here works in Postman.

```<code>useEffect(() => {
  const fetchKeycloakUser = async () => {
    setIsKeycloakUserError(false)

    try {
      const URL =
        'http://localhost:8080/auth/realms/demo/protocol/openid-connect/token'

      const result = await axios({
        method: 'POST',
        url: URL,
        data: {
          username: 'admin',
          password: 'admin',
          client_id: 'admin-cli',
          grant_type: 'password',
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        withCredentials: false, //even 'true' doesn't work
      })
      console.log(result)
    } catch (error) {
      console.log(error)
      setIsKeycloakUserError(true)
    }
  }

  fetchKeycloakUser()
}, [])
</code>```

The Web Origins for the client 'demo' is this (I've tried '*' and '+' also):

And this is the error that I'm getting:

P.S. - This is not using Keycloak inside React. They both are separate apps and I'm only trying to fetch Keycloak data into my React app.

答: You can try to use a + in "Web origins" for the "security-admin-console" Client in the "master" realm.</p>

Body:
Keycloak is running on localhost:8080 (realm - demo, client - demo)

React app is running on localhost:3000

Want to fetch data from Keycloak into React for which first, I need to get an access token. The config used here works in Postman.

useEffect(() => {
  const fetchKeycloakUser = async () => {
    setIsKeycloakUserError(false)

    try {
      const URL =
        'http://localhost:8080/auth/realms/demo/protocol/openid-connect/token'

      const result = await axios({
        method: 'POST',
        url: URL,
        data: {
          username: 'admin',
          password: 'admin',
          client_id: 'admin-cli',
          grant_type: 'password',
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        withCredentials: false, //even 'true' doesn't work
      })
      console.log(result)
    } catch (error) {
      console.log(error)
      setIsKeycloakUserError(true)
    }
  }

  fetchKeycloakUser()
}, [])

The Web Origins for the client 'demo' is this (I've tried '*' and '+' also):

And this is the error that I'm getting:

P.S. - This is not using Keycloak inside React. They both are separate apps and I'm only trying to fetch Keycloak data into my React app.


问:
Java generics: Does "T2 extends T1" imply "T1 super T2"?
If I have a generic <T2 extends T1>, does the compiler infer T1 super T2?

I have a more complex collection, which I reduced to the MWE below. The collection shall be mergeable with any such collection with elements of any subtype.

Now I'm wondering, why the call to forEach in merge is not accepted. It fails with

java.util.function.Consumer<java.util.Optional> cannot be converted to java.util.function.Consumer<java.util.Optional<? super T2>>

I've depicted the type relationships in the diagram below. In merge, T2 extends T1. The call to forEach is applied on the other object, hence the T1 of this becomes the ? of other.forEach and the T2 of this.merge is the T1 of other. Hence, this' T1 should be accepted as super of other's T1.

I also tried public void merge(Group<? extends T> other) with the same result. And public void merge(Group<T> other) does not accept such collections with elements of any subtype of T1.

MWE:

```<code>class Group<T1> {
    public <T2 extends T1> void merge(Group<T2> other) {
        Consumer<Optional<T1>> task = t -> t.ifPresentOrElse(this::foo, this::bar);
        other.forEach(task);
    }

    public Collection<Optional<T1>> values() {
        return List.of();
    }

    public void forEach(Consumer<Optional<? super T1>> consumer) {
        values().forEach(consumer);
    }

    private void foo(T1 t) {}

    private void bar() {}
}
</code>```

Relationships:

```<code>   this.T1      -becomes->  other.forEach.?
      ^                            |
      |                          super
   extends                         |
      |                            v
this.merge.T2     -is->        other.T1
</code>```

答:
You can solve your problem using

class Group<T1> {
    public <T2 extends T1> void merge(Group<T2> other) {
        Consumer<Optional<? extends T1>> task=t->t.ifPresentOrElse(this::foo, this::bar);
        other.forEach(task);
    }

    public Collection<Optional<T1>> values() {
        return List.of();
    }

    public void forEach(Consumer<? super Optional<T1>> consumer) {
        values().forEach(consumer);
    }

    private void foo(T1 t) {}

    private void bar() {}
}
```
<p>This is an application of the PECS rule.</p>
<p>Your <code>task</code> will treat the <code>Optional</code> as a <em>producer</em>, hence, has to declare <code>Optional<? extends T1></code> to allow the optional to produce subtypes of <code>T1</code>. We know that optional will always act as a producer, but Java’s generic type system does not have the concept of classes always acting like a producer or consumer and needs an explicit <code>? extends T1</code> here.</p>
<p>The <code>forEach</code> receives a consumer, even literally in the interface name, so <code>? super …</code> is the right way to declare that this consumer may be a consumer of supertypes of <code>Optional<T1></code>. This does not only include <code>Object</code>, the superclass of <code>Optional</code>, but also <code>Optional<? extends T1></code> when <code>T1 := T2</code>, as in the invocation within <code>merge</code>, as <code>Optional<? extends T1></code> is a supertype of <code>Optional<T2></code>.</p>
<hr />
<p>Of course, you could also solve the issue by simply using</p>
<pre class="lang-java prettyprint-override"><code>Consumer<Optional<T2>> task = t -> t.ifPresentOrElse(this::foo, this::bar);
</code>```

as this only requires foo to accept a T2 argument, which it always does, as T2 is a subtype of T1. But changing the signature of forEach to raise the flexibility is always a good move. Since it’s a public method, there might be other callers benefitting from it.

Body:
If I have a generic <T2 extends T1>, does the compiler infer T1 super T2?

I have a more complex collection, which I reduced to the MWE below. The collection shall be mergeable with any such collection with elements of any subtype.

Now I'm wondering, why the call to forEach in merge is not accepted. It fails with

java.util.function.Consumer<java.util.Optional> cannot be converted to java.util.function.Consumer<java.util.Optional<? super T2>>

I've depicted the type relationships in the diagram below. In merge, T2 extends T1. The call to forEach is applied on the other object, hence the T1 of this becomes the ? of other.forEach and the T2 of this.merge is the T1 of other. Hence, this' T1 should be accepted as super of other's T1.

I also tried public void merge(Group<? extends T> other) with the same result. And public void merge(Group<T> other) does not accept such collections with elements of any subtype of T1.

MWE:

class Group<T1> {
    public <T2 extends T1> void merge(Group<T2> other) {
        Consumer<Optional<T1>> task = t -> t.ifPresentOrElse(this::foo, this::bar);
        other.forEach(task);
    }

    public Collection<Optional<T1>> values() {
        return List.of();
    }

    public void forEach(Consumer<Optional<? super T1>> consumer) {
        values().forEach(consumer);
    }

    private void foo(T1 t) {}

    private void bar() {}
}

Relationships:

   this.T1      -becomes->  other.forEach.?
      ^                            |
      |                          super
   extends                         |
      |                            v
this.merge.T2     -is->        other.T1

Body:
You can solve your problem using

class Group<T1> {
    public <T2 extends T1> void merge(Group<T2> other) {
        Consumer<Optional<? extends T1>> task=t->t.ifPresentOrElse(this::foo, this::bar);
        other.forEach(task);
    }

    public Collection<Optional<T1>> values() {
        return List.of();
    }

    public void forEach(Consumer<? super Optional<T1>> consumer) {
        values().forEach(consumer);
    }

    private void foo(T1 t) {}

    private void bar() {}
}

This is an application of the PECS rule.

Your task will treat the Optional as a producer, hence, has to declare Optional<? extends T1> to allow the optional to produce subtypes of T1. We know that optional will always act as a producer, but Java’s generic type system does not have the concept of classes always acting like a producer or consumer and needs an explicit ? extends T1 here.

The forEach receives a consumer, even literally in the interface name, so ? super … is the right way to declare that this consumer may be a consumer of supertypes of Optional<T1>. This does not only include Object, the superclass of Optional, but also Optional<? extends T1> when T1 := T2, as in the invocation within merge, as Optional<? extends T1> is a supertype of Optional<T2>.

Of course, you could also solve the issue by simply using

Consumer<Optional<T2>> task = t -> t.ifPresentOrElse(this::foo, this::bar);

as this only requires foo to accept a T2 argument, which it always does, as T2 is a subtype of T1. But changing the signature of forEach to raise the flexibility is always a good move. Since it’s a public method, there might be other callers benefitting from it.


问:
Why can't I use a dictionary named `dict` before assigning to it?
I have multiple files that I need to load so I'm using a dict to shorten things. When I run I get a

```<code>TypeError: 'type' object is not subscriptable
</code>```

Error. How can I get this to work?

```<code>m1 = pygame.image.load(dict[1])
m2 = pygame.image.load(dict[2])
m3 = pygame.image.load(dict[3])
dict = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
playerxy = (375,130)
window.blit(m1, (playerxy))
</code>```

答:
you should update to python >= 3.9
and everything will work well

Body:
I have multiple files that I need to load so I'm using a dict to shorten things. When I run I get a

TypeError: 'type' object is not subscriptable

Error. How can I get this to work?

m1 = pygame.image.load(dict[1])
m2 = pygame.image.load(dict[2])
m3 = pygame.image.load(dict[3])
dict = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
playerxy = (375,130)
window.blit(m1, (playerxy))


问:
Using Amadeus flight search API, how does my users search for flight when they don't have location code
I am using amadeus flight search API, built the endpoint with PHP and tested on postman, working perfectly now i am worried about how my users will use the frontend to search for flight, do they have to know the city codes to be able to search for flights? I want a situation whereby they just entered the names of the cities in the form from my frontend and they get to search for flights not entering city codes</p>

答: Thanks everyone for the contribution, i am really grateful, though i discovered getting list of JSON data of IATA codes, cities, and countries in my frontend application and then using javascript filter to search through responding to the onChange event handler from the user's form will solve the problem, once again i appreciate everyone contributions, i am really grateful</p>


问:
How to read Kubent output?
I am using Kubent to diagnose API deprecation before upgrading my Kubernetes cluster. I am having hard time finding information on how to properly read the programs' output.

```<code>-----------
>>> Deprecated APIs removed in 1.22 <<<
-----------
KIND                             NAMESPACE         NAME                                       API_VERSION                            REPLACE_WITH (SINCE)
ClusterRoleBinding               <undefined>       kubernetes-dashboard                       rbac.authorization.k8s.io/v1beta1      rbac.authorization.k8s.io/v1 (1.8.0)
CustomResourceDefinition         <undefined>       authorizationpolicies.security.istio.io    apiextensions.k8s.io/v1beta1           apiextensions.k8s.io/v1 (1.16.0)

</code>```

Notice the Column REPLACE_WITH (SINCE), which created my confusion because k8 is far from 1.8.0 version. Also, the Deprecated APIs... message suggest that those Endpoints enclosed in <<>> will be deprecated in the last release.

So, may you please explain how should this output be interpreted?

答:
Kube No Trouble (kubent) has a defined set of rules which are used to determine deprecated APIs.

For example, below we can see the rule for ClusterRoleBinding:

```<code>    "ClusterRoleBinding": {
        "old": ["rbac.authorization.k8s.io/v1beta1"],
        "new": "rbac.authorization.k8s.io/v1",
        "since": "1.8",
    },
</code>```

The rbac.authorization.k8s.io/v1beta1 API has been promoted to rbac.authorization.k8s.io/v1 in the v1.8 and this is the reason this specific Kubernetes version is mentioned in the rule above (see: Deprecated API Migration Guide).

Additionally, please note that the rbac.authorization.k8s.io/v1beta1 API version of ClusterRole, ClusterRoleBinding, Role, and RoleBinding is no longer served as of v1.22.

Title: How to read Kubent output?

Body:
I am using Kubent to diagnose API deprecation before upgrading my Kubernetes cluster. I am having hard time finding information on how to properly read the programs' output.

-----------
>>> Deprecated APIs removed in 1.22 <<<
-----------
KIND                             NAMESPACE         NAME                                       API_VERSION                            REPLACE_WITH (SINCE)
ClusterRoleBinding               <undefined>       kubernetes-dashboard                       rbac.authorization.k8s.io/v1beta1      rbac.authorization.k8s.io/v1 (1.8.0)
CustomResourceDefinition         <undefined>       authorizationpolicies.security.istio.io    apiextensions.k8s.io/v1beta1           apiextensions.k8s.io/v1 (1.16.0)

Notice the Column REPLACE_WITH (SINCE), which created my confusion because k8 is far from 1.8.0 version. Also, the Deprecated APIs... message suggest that those Endpoints enclosed in <<>> will be deprecated in the last release.

So, may you please explain how should this output be interpreted?

Body:
Kube No Trouble (kubent) has a defined set of rules which are used to determine deprecated APIs.

For example, below we can see the rule for ClusterRoleBinding:

    "ClusterRoleBinding": {
        "old": ["rbac.authorization.k8s.io/v1beta1"],
        "new": "rbac.authorization.k8s.io/v1",
        "since": "1.8",
    },

The rbac.authorization.k8s.io/v1beta1 API has been promoted to rbac.authorization.k8s.io/v1 in the v1.8 and this is the reason this specific Kubernetes version is mentioned in the rule above (see: Deprecated API Migration Guide).

Additionally, please note that the rbac.authorization.k8s.io/v1beta1 API version of ClusterRole, ClusterRoleBinding, Role, and RoleBinding is no longer served as of v1.22.


问:
How to point to project index page by default in XAMPP
i am pretty new this kind of work. I had developed a web app using PHP. i am using XAMPP Server. Now when i am hitting http://www.mywebsite.com/myproject i got my project index page. Now what i looking is if i enter http://www.mywebsite.com it should display myproject's index page.

I am not sure what is this term called. I didn't know how to search for this solution.

Your help will be much appreciated if you can provide the term i should look for or the solution for this.

thanks

答:
Open the file index.php  from the htdocs in xammp ( ..\xampp\htdocs\index.php)

Change the line

header('Location: '.$uri.'/dashboard/');

to

header('Location: '.$uri.'/yoursitefolder/');

this will resolve the issue.


问:
How to tell gwt-maven-plugin not to use certain parameters when calling the GWT-compiler
I am trying to migrate a GWT-2.0.2 project to the net.ltgt.gwt.maven:gwt-maven-plugin, but it seems to be calling the GWT-compiler with parameters that weren't recognized back in times of GWT 2.0.2, like -deploy, -sourceLevel etc.

I know it is possible to add extra parameters, but is it possible to exclude some?

答:
Not possible: https://github.com/tbroyer/gwt-maven-plugin/blob/main/src/main/java/net/ltgt/gwt/maven/GwtOptions.java

  class CommandlineBuilder {
    public static List<String> buildArgs(Log log, GwtOptions options) {
      List<String> args = new ArrayList<>();
      if (options.getLogLevel() != null) {
        args.add("-logLevel");
        args.add(options.getLogLevel());
      }
      args.add("-war");
      args.add(options.getWarDir().getAbsolutePath());
      args.add("-workDir");
      args.add(options.getWorkDir().getAbsolutePath());
      args.add("-deploy");
      args.add(options.getDeployDir().getAbsolutePath());```
</code>```


问:
Angular : parent function not called when child emits
I have seen a lot of topics related to this problem but have not found an answer. So here is my topic :

I want to pass data from my child component to my parent component with EventEmitter.emit(value).

The problem is that my emitter does not emit any data (undefined) when I console.log it.
Also, the Parent function is not called when the data is emitted.

I have tried :

Changing the type of the data to string : not working

Changing the imports to '@angular/core' : but was already from '@angular/core'

Changing $event to $event.value in the Parent HTML : the event should be a "Movies"|"TV Shows" so not working

I did everything according to the Angular doc and precedent topics but I do not see what I did wrong.

Thanks to repond and for your time.

Child component HTML

```<code><div class="switch-menu">
        <button class="switch-btn" (click)="toggleMovies($event)" [ngClass]="this.showingMovies == 'Movies' ? 'active-button':''" value="Movies">Movies</button>
        <button class="switch-btn" (click)="toggleMovies($event)" [ngClass]="this.showingMovies == 'TV Shows' ? 'active-button':''" value="TV Shows">TV Shows</button>
    </div>
</code>```

Child component TS

```<code>@Output() eshowingMovies: EventEmitter<string> = new EventEmitter();
showingMovies: "Movies"|"TV Shows" = "Movies";

toggleMovies(_ev: Event): void{
    if (this.showingMovies !== (_ev.target as HTMLInputElement).value){
      this.showingMovies = this.showingMovies == "Movies" ? "TV Shows" : "Movies";
      this.eshowingMovies.emit(this.showingMovies);
    }
  }
</code>```

Parent component HTML

```<code><app-movie-list-find (eshowingMovies)="toggleMovies($event)" ></app-movie-list-find>
<app-show-list-find (eshowingMovies)="toggleMovies($event)" ></app-show-list-find>
</code>```

I have this error message in the Parent html file

The event should be a "Movies"|"TV Shows" type but is an Event.

```<code>(parameter) $event: Event
Argument of type 'Event' is not assignable to parameter of type '"Movies" | "TV Shows"'.
  Type 'Event' is not assignable to type '"TV Shows"'.ngtsc(2345)
find.component.ts(4, 20): Error occurs in the template of component FindComponent.
</code>```

Parent component TS

```<code>showingMovies: "Movies"|"TV Shows" = "Movies";

toggleMovies(event: "Movies"|"TV Shows"): void{
    if (this.showingMovies !== event){
      this.showingMovies = event;
    }
  }
</code>```

答:
it's unclear to me what exactly you tried to achieve with your current implementation but I don't see a reason to pass the event itself in your child when a button is clicked. you can instead do the following:

```<code><div class="switch-menu">
        <button class="switch-btn" (click)="toggleMovies('Movies')" [ngClass]="this.showingMovies == 'Movies' ? 'active-button':''" value="Movies">Movies</button>
        <button class="switch-btn" (click)="toggleMovies('TV Shows')" [ngClass]="this.showingMovies == 'TV Shows' ? 'active-button':''" value="TV Shows">TV Shows</button>
    </div>
</code>```

then in your child function which emits the value -

```<code>toggleMovies(category: "Movies" | "TV Shows"): void {
      this.eshowingMovies.emit(category);
    }
  }
</code>```

that should solve your issue

Body:
I have seen a lot of topics related to this problem but have not found an answer. So here is my topic :

I want to pass data from my child component to my parent component with EventEmitter.emit(value).

The problem is that my emitter does not emit any data (undefined) when I console.log it.
Also, the Parent function is not called when the data is emitted.

I have tried :

Changing the type of the data to string : not working

Changing the imports to '@angular/core' : but was already from '@angular/core'

Changing $event to $event.value in the Parent HTML : the event should be a "Movies"|"TV Shows" so not working

I did everything according to the Angular doc and precedent topics but I do not see what I did wrong.

Thanks to repond and for your time.

Child component HTML

        <button class="switch-btn" (click)="toggleMovies($event)" [ngClass]="this.showingMovies == 'Movies' ? 'active-button':''" value="Movies">Movies</button>
        <button class="switch-btn" (click)="toggleMovies($event)" [ngClass]="this.showingMovies == 'TV Shows' ? 'active-button':''" value="TV Shows">TV Shows</button>

Child component TS

@Output() eshowingMovies: EventEmitter<string> = new EventEmitter();
showingMovies: "Movies"|"TV Shows" = "Movies";

toggleMovies(_ev: Event): void{
    if (this.showingMovies !== (_ev.target as HTMLInputElement).value){
      this.showingMovies = this.showingMovies == "Movies" ? "TV Shows" : "Movies";
      this.eshowingMovies.emit(this.showingMovies);
    }
  }

Parent component HTML

<app-movie-list-find (eshowingMovies)="toggleMovies($event)" ></app-movie-list-find>
<app-show-list-find (eshowingMovies)="toggleMovies($event)" ></app-show-list-find>

I have this error message in the Parent html file

The event should be a "Movies"|"TV Shows" type but is an Event.

(parameter) $event: Event
Argument of type 'Event' is not assignable to parameter of type '"Movies" | "TV Shows"'.
  Type 'Event' is not assignable to type '"TV Shows"'.ngtsc(2345)
find.component.ts(4, 20): Error occurs in the template of component FindComponent.

Parent component TS

showingMovies: "Movies"|"TV Shows" = "Movies";

toggleMovies(event: "Movies"|"TV Shows"): void{
    if (this.showingMovies !== event){
      this.showingMovies = event;
    }
  }

Body:
it's unclear to me what exactly you tried to achieve with your current implementation but I don't see a reason to pass the event itself in your child when a button is clicked. you can instead do the following:

<div class="switch-menu">
        <button class="switch-btn" (click)="toggleMovies('Movies')" [ngClass]="this.showingMovies == 'Movies' ? 'active-button':''" value="Movies">Movies</button>
        <button class="switch-btn" (click)="toggleMovies('TV Shows')" [ngClass]="this.showingMovies == 'TV Shows' ? 'active-button':''" value="TV Shows">TV Shows</button>
    </div>

then in your child function which emits the value -

toggleMovies(category: "Movies" | "TV Shows"): void {
      this.eshowingMovies.emit(category);
    }
  }

that should solve your issue


问:
ServletUriComponentsBuilder.fromCurrentContextPath() inside ElasticBeanstalk return http instead of https
I deployed a Spring Boot Application on EB using a docker container.
It works well but in some parts of my code I've something like this:

```<code>ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
</code>```

to get the current url of the application. In the local machine it works fine but on EB (using classing load balancer) - that uses https protocol - that line of code return http instead of https.

I've already added this configuration in my project:

```<code>    @Bean
    FilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter() {
        FilterRegistrationBean<ForwardedHeaderFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new ForwardedHeaderFilter());
        return bean;
    }
</code>```

Do you have any hint to follow to fix the problem?

答:
I solved using this Spring Boot property:</p>
```<code>server.forward-headers-strategy = framework
</code>```

Body:
I deployed a Spring Boot Application on EB using a docker container.
It works well but in some parts of my code I've something like this:

ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();

to get the current url of the application. In the local machine it works fine but on EB (using classing load balancer) - that uses https protocol - that line of code return http instead of https.

I've already added this configuration in my project:

    @Bean
    FilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter() {
        FilterRegistrationBean<ForwardedHeaderFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new ForwardedHeaderFilter());
        return bean;
    }

Do you have any hint to follow to fix the problem?

Body:
I solved using this Spring Boot property:

server.forward-headers-strategy = framework


问:
VBScript: Addition producing a negative number
I am updating an old VBScript. I was trying to add two variables together in a VBScript function I'm working on, one is a negative while the other is a positive but when the number gets sent back to the SQL table it doesn't calculate correctly. I have code that is similar to this that function correctly when you subtract

EX:-76+4 ends up being -80 instead of -72.

here is code maybe something is wrong with variable.

```<code>    strSQL = "UPDATE Parts SET On_Hand = '"
    strSQL = strSQL & (CInt(objRS("On_Hand")) + CInt(Request.Form("QtyIssued"))) & "'"
    strSQL = strSQL & "WHERE Part_ID = '" & Request.Form("PartNum" & x) & "';"
</code>```

Note: I have change Cint from Ccur and still didn't work.

On_Hand is also a float in the table.

EDIT: Added full code for clarity

```<code>  strSQL = "UPDATE Parts SET On_Hand = '"
  strSQL = strSQL & (CInt(objRS("On_Hand")) + CInt(Request.Form("QtyIssued"))) & "'"
  strSQL = strSQL & "WHERE Part_ID = '" & Request.Form("PartNum" & x) & "';"
  Response.Write strSQL & "<br>"
  objRS.close
  objRS.Open strSQL, objConn
</code>```

Here is Response Write:

UPDATE Parts SET On_Hand = '-80'WHERE Part_ID = '15-0219';

答:
You need to check your input values coming from the form, as a simple test can debunk your theory that the calculation is wrong.

<%
Dim sum
Dim x, y

x = -76
y = 4

sum = x + y

Call Response.Write(sum)
Call Response.Write("
")

x = "-76"
y = "4"

sum = CInt(x) + CInt(y)

Call Response.Write(sum)
%>
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>-72
-72
</code>```

Body:
I am updating an old VBScript. I was trying to add two variables together in a VBScript function I'm working on, one is a negative while the other is a positive but when the number gets sent back to the SQL table it doesn't calculate correctly. I have code that is similar to this that function correctly when you subtract

EX:-76+4 ends up being -80 instead of -72.

here is code maybe something is wrong with variable.

    strSQL = "UPDATE Parts SET On_Hand = '"
    strSQL = strSQL & (CInt(objRS("On_Hand")) + CInt(Request.Form("QtyIssued"))) & "'"
    strSQL = strSQL & "WHERE Part_ID = '" & Request.Form("PartNum" & x) & "';"

Note: I have change Cint from Ccur and still didn't work.

On_Hand is also a float in the table.

EDIT: Added full code for clarity

  strSQL = "UPDATE Parts SET On_Hand = '"
  strSQL = strSQL & (CInt(objRS("On_Hand")) + CInt(Request.Form("QtyIssued"))) & "'"
  strSQL = strSQL & "WHERE Part_ID = '" & Request.Form("PartNum" & x) & "';"
  Response.Write strSQL & "
"
  objRS.close
  objRS.Open strSQL, objConn

Here is Response Write:

UPDATE Parts SET On_Hand = '-80'WHERE Part_ID = '15-0219';

Body:
You need to check your input values coming from the form, as a simple test can debunk your theory that the calculation is wrong.

<%
Dim sum
Dim x, y

x = -76
y = 4

sum = x + y

Call Response.Write(sum)
Call Response.Write("<br />")

x = "-76"
y = "4"

sum = CInt(x) + CInt(y)

Call Response.Write(sum)
%>

Output:

-72
-72