问:
Erlang and its consumption of Heap Memory
I have been running a highly concurrent application on my HP Proliant Servers. The application is a file system indexer i coded in erlang. It spawns a process per Folder it finds on the file system and records all file paths in a fragmented Mnesia Database. (Database consists of disc_only_copies type of tables and a screen shot of its file system can be viewed here.)

The Snippet of code that does the high intensive job of going through the file system is shown below:

```

%%% -------- COPYRIGHT NOTICE --------------------------------------------------------------------
%% @author Muzaaya Joshua, <joshmuza@gmail.com> [http://joshanderlang.blogspot.com]
%% @version 1.0 free software, but modification prohibited
%% @copyright Muzaaya Joshua (file_scavenger-1.0) 2011 - 2012 . All rights reserved
%% @reference <a href="http://www.erlang.org">OpenSource Erlang WebSite</a>
%%
%%% ---------------- EDOC INTRODUCTION TO THE MODULE ----------------------------------------------
%% @doc This module provides the low level APIs for reading, writing,
%% searching, joining and moving within directories.The module implementation
%% took place on @date at @time.
%% @end

-module(file_scavenger_utilities).

%%% ------- EXPORTS -------------------------------------------------------------------------------
-compile(export_all).

%%% ------- INCLUDES -----------------------------------------------------------------------------

%%% -------- MACROS ------------------------------------------------------------------------------
-define(IS_FOLDER(X),filelib:is_dir(X)).
-define(IS_FILE(X),filelib:is_file(X)).
-define(FAILED_TO_LIST_DIR(X),error_logger:error_report(["*** File Scavenger Utilities Error ***** ",{error,"Failed to List Directory"},{directory,X}])).
-define(NOT_DIR(X),error_logger:error_report(["*** File Scavenger Utilities Error ***** ",{error,"Not a Directory"},{alleged,X}])).
-define(NOT_FILE(X),error_logger:error_report(["*** File Scavenger Utilities Error ***** ",{error,"Not a File"},{alleged,X}])).
%%%--------- TYPES -------------------------------------------------------------------------------

%% @type dir() = string().
%%  Must be containing forward slashes, not back slashes. Must not end with a slash
%%  after the exact directory.e.g this is wrong: "C:/Program Files/SomeDirectory/"
%%  but this is right: "C:/Program Files/SomeDirectory"
%% @type file_path() = string().
%%  Must be containing forward slashes, not back slashes.
%%  Should include the file extension as well e.g "C:/Program Files/SomeFile.pdf"

%% -----------------------------------------------------------------------------------------------
%% @doc Enters a directory and executes the fun ForEachFileFound/2 for each file it finds
%% If it finds a directory, it executes the fun %% ForEachDirFound/2.
%% Both funs above take the parent Dir as the first Argument. Then, it will spawn an
%% erlang process that will spread the found Directory too in the same way as the parent directory
%% was spread. The process of spreading goes on and on until every File (wether its in a nested
%% Directory) is registered by its full path.
%% @end
%%
%% @spec spread_directory(dir(),dir(),funtion(),function())-> ok.

spread_directory(Dir,Top_Directory,ForEachFileFound,ForEachDirFound) when is_function(ForEachFileFound),is_function(ForEachDirFound) ->
    case ?IS_FOLDER(Dir) of
        false -> ?NOT_DIR(Dir);
        true ->
            F = fun(X)->
                    FileOrDir = filename:absname_join(Dir,X),
                    case ?IS_FOLDER(FileOrDir) of
                        true ->
                            (catch ForEachDirFound(Top_Directory,FileOrDir)),
                            spawn(fun() -> ?MODULE:spread_directory(FileOrDir,Top_Directory,ForEachFileFound,ForEachDirFound) end);
                        false ->
                            case ?IS_FILE(FileOrDir) of
                                false -> {error,not_a_file,FileOrDir};
                                true -> (catch ForEachFileFound(Top_Directory,FileOrDir))
                            end
                    end
                end,
            case file:list_dir(Dir) of
                {error,_} -> ?FAILED_TO_LIST_DIR(Dir);
                {ok,List} -> lists:foreach(F,List)
            end
    end.

```

The function spread_directory/4 is generic in a way that it takes two funs. One fun: ForEachFileFound/2 takes along with the Top Most Directory, the found file and does anything with it and the other fun: ForEachDirFound/2 takes along with the Top Most Directory, the folder it finds and uses it in any way it wants.

The start script i use for this application makes sure that erlang will be able to spawn as many processes as possible. Once a process finishes indexing a folder it exits.

```
#!/usr/bin/env sh
echo "Starting File Scavenger System. Layer 1 on the P2P File Sharing System....."
erl \
    -name file_scavenger@127.0.0.1 \
    +P 13421779 \
    -pa ./ebin ./lib/*/ebin ./include \
    -mnesia dir '"./database"' \
    -mnesia dump_log_write_threshold 10000 \
    -eval "application:load(file_scavenger)" \
    -eval "application:start(file_scavenger)"
```

There is a gen_server which interfaces the intensive module with the database in which i record all paths. A snippet of where it starts the spread_directory work is shown here below:

```
handle_cast(index_dirs,#scavenger{directory_paths = Dirs} = State)->
    {File,Folder} = case {State#scavenger.verbose,State#scavenger.verbose_to} of
                        {true,tty} ->
                            {
                            fun(TopDir,Fl)->
                                io:format(" File: ~p~n",[Fl]),
                                file_scavenger_database:insert_file(filename:basename(Fl),file,Fl,TopDir,filename:extension(Fl))
                            end,
                            fun(TopDir,Fd) ->
                                io:format(" Folder: ~p~n",[Fd]),
                                file_scavenger_database:insert_file(Fd,folder,Fd,TopDir,undefined)
                            end
                            };
                        {true,SomeFile}->
                            {
                            fun(TopDir,Fl)->
                                os:cmd("echo File: " ++ Fl ++ " >> " ++ SomeFile),
                                file_scavenger_database:insert_file(filename:basename(Fl),file,Fl,TopDir,filename:extension(Fl))
                            end,
                            fun(TopDir,Fd)->
                                os:cmd("echo Folder: " ++ Fd ++ " >> " ++ SomeFile),
                                file_scavenger_database:insert_file(Fd,folder,Fd,TopDir,undefined)
                            end
                            }
                    end,
    Main = fun(Dir) ->
                error_logger:info_msg("*** File scavenger Server indexing directory: ~p~n",[Dir]),
                spawn(fun() -> file_scavenger_utilities:spread_directory(Dir,Dir,File,Folder) end)
            end,
    lists:foreach(Main,Dirs),
    {noreply,State};
handle_cast(stop, State) -> {stop, normal, State}.
```

More Source details can be found in the whole application.
The application entire Source and build can be found here: File_scavenger-1.0.zip.

Now, i start the application on the Server (HP Proliant G6, containing Intel processors (2 processors, each 4 cores, 2.4 GHz speed each core, 8 MB Cache size), 20 GB RAM size, 1.5 Terabytes disk space. Now, 2 of these high power machines are in our disposal. System Database should be replicated across the two. Each server runs Solaris 10, 64 bit), whose terminal now looks like this below:

```
bash-3.00# sh file_scavenger.sh
Starting File Scavenger System. Layer 1 on the P2P File Sharing System.....
Erlang R14B03 (erts-5.8.4) [source] [smp:8:8] [rq:8] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.8.4  (abort with ^G)
(file_scavenger@127.0.0.1)1>
=INFO REPORT==== 18-Aug-2011::09:36:04 ===
Starting File Scavenger Database......
=INFO REPORT==== 18-Aug-2011::09:36:04 ===
Database Successfully Started....

=INFO REPORT==== 18-Aug-2011::09:36:04 ===
Starting File Scavenger Database......
=INFO REPORT==== 18-Aug-2011::09:36:04 ===
Database Successfully Started....

=INFO REPORT==== 18-Aug-2011::09:36:04 ===
File Scavenger Server starting with default verbose settings....

(file_scavenger@127.0.0.1)1> file_scavenger_server:index_dirs().
```

The server starts to run and verboses to the terminal all files and folders it finds. The server is equipped with too much RAM (20 GB), and Swap space (Swap is 16 GB). However, it ran for about 18 hours and finally, the erlang Virtual machine reported this:

```
File: "/proc/4324/root/opt/csw/gcc4/share/locale/ja/LC_MESSAGES/gcc.mo"
 Folder: "/proc/4324/root/opt/csw/gcc4/share/locale/da"
 Folder: "/proc/4324/root/opt/csw/gcc4/share/locale/es/LC_MESSAGES"
 File: "/proc/4324/root/proc/4984/root/.thumbnails/normal/dc259e3897e8af4b379c6d956b6c1393.png"
 File: "/proc/4324/root/proc/4984/root/.thumbnails/fail/gnome-thumbnail-factory/223c19786421b7101d14075bdec46f61.png"
 File: "/proc/4324/root/opt/csw/gcc4/libexec/gcc/i386-pc-solaris2.10/4.5.1/install-tools/mkheaders"
 File: "/proc/4324/root/opt/csw/gcc4/libexec/gcc/i386-pc-solaris2.10/4.5.1/cc1plus"
 File: "/proc/4324/root/opt/csw/gcc4/lib/libsupc++.la"

Crash dump was written to: erl_crash.dump
eheap_alloc: Cannot allocate 153052320 bytes of memory (of type "heap").
Abort - core dumped
bash-3.00#

```

Question 1. With such a powerful server, why would the operating system fail to provide such memory to the application (it was the only application running)?

Question 2. The Erlang Emulator i start is instructed to be able to spawn as many processes as it may need. the value +P 13421779. Is Erlang VM failing to access this memory or failing to allocate it to its processes ?

Question 3. To Solaris, it sees one process: epmd, perhaps containing and starting thousands of micro threads. What configurations can i make to Solaris to be able to never stop my application however much "memory hungry" it may be? Swap space available is 16 GB, RAM 20 GB, honestly, there must be something wrong.

Question 4. Which configurations can i make to the Erlang Emulator, to avoid these heap memory crash dumps especially when all the memory it may need is available on the server? How will i run more memory consuming apps on this server if Erlang still fails to allocate such memory to a simple file system indexer (well its heavily concurrent)?

finally, all other tweaks i could do to avoid heap memory problems on such capable hardware are welcome. Thanks in advance

答:
I haven't had time to look at the source, but here are some comments:

Question 1. With such a powerful server, why would the operating
  system fail to provide such memory to the application (it was the only
  application running)?

Because the Erlang VM tried to consume more than the available free memory.

Question 2. The Erlang Emulator i start is instructed to be able to
  spawn as many processes as it may need. the value +P 13421779. Is
  Erlang VM failing to access this memory or failing to allocate it to
  its processes ?

No. If you would have run out of processess, the Erlang VM would have said so (and the VM would still be up and running):

```<code>=ERROR REPORT==== 18-Aug-2011::10:04:04 ===
Error in process <0.31775.138> with exit value: {system_limit,[{erlang,spawn_link,    [erlang,apply,[#Fun<shell.3.130303173>,[]]]},{erlang,spawn_link,1},{shell,get_command,5},    {shell,server_loop,7}]}
</code>```

Question 3. To Solaris, it sees one process: epmd, perhaps containing
  and starting thousands of micro threads. What configurations can i
  make to Solaris to be able to never stop my application however much
  "memory hungry" it may be? Swap space available is 16 GB, RAM 20 GB,
  honestly, there must be something wrong.

epmd is the Erlang port mapping deamon. It's responsible for managing distributet Erlang and has nothing to with your individual Erlang application. The processes you should look for will be name beam.smp most likely. These will show the OS memory consumption of the Erlang VM etc.

Question 4. Which configurations can i make to the Erlang Emulator, to
  avoid these heap memory crash dumps especially when all the memory it
  may need is available on the server? How will i run more memory
  consuming apps on this server if Erlang still fails to allocate such
  memory to a simple file system indexer (well its heavily concurrent)?

The Erlang VM should be able to use all of the available memory in your machine. However, it depends on how your application is written. There can be many reasons for memory leaks:

Atom table filling up (you create too many unique atoms)

ETS or Mnesia tables are not garbage collected (you do not delete old unused elements)

Not enough memory for processes (you spawn too many processess)

Too many binaries are created (you might keep unused references to old binaries)

Body:
I have been running a highly concurrent application on my HP Proliant Servers. The application is a file system indexer i coded in erlang. It spawns a process per Folder it finds on the file system and records all file paths in a fragmented Mnesia Database. (Database consists of disc_only_copies type of tables and a screen shot of its file system can be viewed here.)

The Snippet of code that does the high intensive job of going through the file system is shown below:

%%% -------- COPYRIGHT NOTICE --------------------------------------------------------------------
%% @author Muzaaya Joshua, <joshmuza@gmail.com> [http://joshanderlang.blogspot.com]
%% @version 1.0 free software, but modification prohibited
%% @copyright Muzaaya Joshua (file_scavenger-1.0) 2011 - 2012 . All rights reserved
%% @reference OpenSource Erlang WebSite
%%
%%% ---------------- EDOC INTRODUCTION TO THE MODULE ----------------------------------------------
%% @doc This module provides the low level APIs for reading, writing,
%% searching, joining and moving within directories.The module implementation
%% took place on @date at @time.
%% @end

-module(file_scavenger_utilities).

%%% ------- EXPORTS -------------------------------------------------------------------------------
-compile(export_all).

%%% ------- INCLUDES -----------------------------------------------------------------------------

%%% -------- MACROS ------------------------------------------------------------------------------
-define(IS_FOLDER(X),filelib:is_dir(X)).
-define(IS_FILE(X),filelib:is_file(X)).
-define(FAILED_TO_LIST_DIR(X),error_logger:error_report(["*** File Scavenger Utilities Error ***** ",{error,"Failed to List Directory"},{directory,X}])).
-define(NOT_DIR(X),error_logger:error_report(["*** File Scavenger Utilities Error ***** ",{error,"Not a Directory"},{alleged,X}])).
-define(NOT_FILE(X),error_logger:error_report(["*** File Scavenger Utilities Error ***** ",{error,"Not a File"},{alleged,X}])).
%%%--------- TYPES -------------------------------------------------------------------------------

%% @type dir() = string().
%%  Must be containing forward slashes, not back slashes. Must not end with a slash
%%  after the exact directory.e.g this is wrong: "C:/Program Files/SomeDirectory/"
%%  but this is right: "C:/Program Files/SomeDirectory"
%% @type file_path() = string().
%%  Must be containing forward slashes, not back slashes.
%%  Should include the file extension as well e.g "C:/Program Files/SomeFile.pdf"

%% -----------------------------------------------------------------------------------------------
%% @doc Enters a directory and executes the fun ForEachFileFound/2 for each file it finds
%% If it finds a directory, it executes the fun %% ForEachDirFound/2.
%% Both funs above take the parent Dir as the first Argument. Then, it will spawn an
%% erlang process that will spread the found Directory too in the same way as the parent directory
%% was spread. The process of spreading goes on and on until every File (wether its in a nested
%% Directory) is registered by its full path.
%% @end
%%
%% @spec spread_directory(dir(),dir(),funtion(),function())-> ok.

spread_directory(Dir,Top_Directory,ForEachFileFound,ForEachDirFound) when is_function(ForEachFileFound),is_function(ForEachDirFound) ->
    case ?IS_FOLDER(Dir) of
        false -> ?NOT_DIR(Dir);
        true ->
            F = fun(X)->
                    FileOrDir = filename:absname_join(Dir,X),
                    case ?IS_FOLDER(FileOrDir) of
                        true ->
                            (catch ForEachDirFound(Top_Directory,FileOrDir)),
                            spawn(fun() -> ?MODULE:spread_directory(FileOrDir,Top_Directory,ForEachFileFound,ForEachDirFound) end);
                        false ->
                            case ?IS_FILE(FileOrDir) of
                                false -> {error,not_a_file,FileOrDir};
                                true -> (catch ForEachFileFound(Top_Directory,FileOrDir))
                            end
                    end
                end,
            case file:list_dir(Dir) of
                {error,_} -> ?FAILED_TO_LIST_DIR(Dir);
                {ok,List} -> lists:foreach(F,List)
            end
    end.

The function spread_directory/4 is generic in a way that it takes two funs. One fun: ForEachFileFound/2 takes along with the Top Most Directory, the found file and does anything with it and the other fun: ForEachDirFound/2 takes along with the Top Most Directory, the folder it finds and uses it in any way it wants.

The start script i use for this application makes sure that erlang will be able to spawn as many processes as possible. Once a process finishes indexing a folder it exits.

#!/usr/bin/env sh
echo "Starting File Scavenger System. Layer 1 on the P2P File Sharing System....."
erl \
    -name file_scavenger@127.0.0.1 \
    +P 13421779 \
    -pa ./ebin ./lib/*/ebin ./include \
    -mnesia dir '"./database"' \
    -mnesia dump_log_write_threshold 10000 \
    -eval "application:load(file_scavenger)" \
    -eval "application:start(file_scavenger)"

There is a gen_server which interfaces the intensive module with the database in which i record all paths. A snippet of where it starts the spread_directory work is shown here below:

handle_cast(index_dirs,#scavenger{directory_paths = Dirs} = State)->
    {File,Folder} = case {State#scavenger.verbose,State#scavenger.verbose_to} of
                        {true,tty} ->
                            {
                            fun(TopDir,Fl)->
                                io:format(" File: ~p~n",[Fl]),
                                file_scavenger_database:insert_file(filename:basename(Fl),file,Fl,TopDir,filename:extension(Fl))
                            end,
                            fun(TopDir,Fd) ->
                                io:format(" Folder: ~p~n",[Fd]),
                                file_scavenger_database:insert_file(Fd,folder,Fd,TopDir,undefined)
                            end
                            };
                        {true,SomeFile}->
                            {
                            fun(TopDir,Fl)->
                                os:cmd("echo File: " ++ Fl ++ " >> " ++ SomeFile),
                                file_scavenger_database:insert_file(filename:basename(Fl),file,Fl,TopDir,filename:extension(Fl))
                            end,
                            fun(TopDir,Fd)->
                                os:cmd("echo Folder: " ++ Fd ++ " >> " ++ SomeFile),
                                file_scavenger_database:insert_file(Fd,folder,Fd,TopDir,undefined)
                            end
                            }
                    end,
    Main = fun(Dir) ->
                error_logger:info_msg("*** File scavenger Server indexing directory: ~p~n",[Dir]),
                spawn(fun() -> file_scavenger_utilities:spread_directory(Dir,Dir,File,Folder) end)
            end,
    lists:foreach(Main,Dirs),
    {noreply,State};
handle_cast(stop, State) -> {stop, normal, State}.

More Source details can be found in the whole application.
The application entire Source and build can be found here: File_scavenger-1.0.zip.

Now, i start the application on the Server (HP Proliant G6, containing Intel processors (2 processors, each 4 cores, 2.4 GHz speed each core, 8 MB Cache size), 20 GB RAM size, 1.5 Terabytes disk space. Now, 2 of these high power machines are in our disposal. System Database should be replicated across the two. Each server runs Solaris 10, 64 bit), whose terminal now looks like this below:

bash-3.00# sh file_scavenger.sh
Starting File Scavenger System. Layer 1 on the P2P File Sharing System.....
Erlang R14B03 (erts-5.8.4) [source] [smp:8:8] [rq:8] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.8.4  (abort with ^G)
(file_scavenger@127.0.0.1)1>
=INFO REPORT==== 18-Aug-2011::09:36:04 ===
Starting File Scavenger Database......
=INFO REPORT==== 18-Aug-2011::09:36:04 ===
Database Successfully Started....

=INFO REPORT==== 18-Aug-2011::09:36:04 ===
Starting File Scavenger Database......
=INFO REPORT==== 18-Aug-2011::09:36:04 ===
Database Successfully Started....

=INFO REPORT==== 18-Aug-2011::09:36:04 ===
File Scavenger Server starting with default verbose settings....

(file_scavenger@127.0.0.1)1> file_scavenger_server:index_dirs().

The server starts to run and verboses to the terminal all files and folders it finds. The server is equipped with too much RAM (20 GB), and Swap space (Swap is 16 GB). However, it ran for about 18 hours and finally, the erlang Virtual machine reported this:

File: "/proc/4324/root/opt/csw/gcc4/share/locale/ja/LC_MESSAGES/gcc.mo"
 Folder: "/proc/4324/root/opt/csw/gcc4/share/locale/da"
 Folder: "/proc/4324/root/opt/csw/gcc4/share/locale/es/LC_MESSAGES"
 File: "/proc/4324/root/proc/4984/root/.thumbnails/normal/dc259e3897e8af4b379c6d956b6c1393.png"
 File: "/proc/4324/root/proc/4984/root/.thumbnails/fail/gnome-thumbnail-factory/223c19786421b7101d14075bdec46f61.png"
 File: "/proc/4324/root/opt/csw/gcc4/libexec/gcc/i386-pc-solaris2.10/4.5.1/install-tools/mkheaders"
 File: "/proc/4324/root/opt/csw/gcc4/libexec/gcc/i386-pc-solaris2.10/4.5.1/cc1plus"
 File: "/proc/4324/root/opt/csw/gcc4/lib/libsupc++.la"

Crash dump was written to: erl_crash.dump
eheap_alloc: Cannot allocate 153052320 bytes of memory (of type "heap").
Abort - core dumped
bash-3.00#

Question 1. With such a powerful server, why would the operating system fail to provide such memory to the application (it was the only application running)?

Question 2. The Erlang Emulator i start is instructed to be able to spawn as many processes as it may need. the value +P 13421779. Is Erlang VM failing to access this memory or failing to allocate it to its processes ?

Question 3. To Solaris, it sees one process: epmd, perhaps containing and starting thousands of micro threads. What configurations can i make to Solaris to be able to never stop my application however much "memory hungry" it may be? Swap space available is 16 GB, RAM 20 GB, honestly, there must be something wrong.

Question 4. Which configurations can i make to the Erlang Emulator, to avoid these heap memory crash dumps especially when all the memory it may need is available on the server? How will i run more memory consuming apps on this server if Erlang still fails to allocate such memory to a simple file system indexer (well its heavily concurrent)?

finally, all other tweaks i could do to avoid heap memory problems on such capable hardware are welcome. Thanks in advance

Body:
I haven't had time to look at the source, but here are some comments:

Question 1. With such a powerful server, why would the operating
  system fail to provide such memory to the application (it was the only
  application running)?

Because the Erlang VM tried to consume more than the available free memory.

Question 2. The Erlang Emulator i start is instructed to be able to
  spawn as many processes as it may need. the value +P 13421779. Is
  Erlang VM failing to access this memory or failing to allocate it to
  its processes ?

No. If you would have run out of processess, the Erlang VM would have said so (and the VM would still be up and running):

=ERROR REPORT==== 18-Aug-2011::10:04:04 ===
Error in process <0.31775.138> with exit value: {system_limit,[{erlang,spawn_link,    [erlang,apply,[#Fun<shell.3.130303173>,[]]]},{erlang,spawn_link,1},{shell,get_command,5},    {shell,server_loop,7}]}

Question 3. To Solaris, it sees one process: epmd, perhaps containing
  and starting thousands of micro threads. What configurations can i
  make to Solaris to be able to never stop my application however much
  "memory hungry" it may be? Swap space available is 16 GB, RAM 20 GB,
  honestly, there must be something wrong.

epmd is the Erlang port mapping deamon. It's responsible for managing distributet Erlang and has nothing to with your individual Erlang application. The processes you should look for will be name beam.smp most likely. These will show the OS memory consumption of the Erlang VM etc.

Question 4. Which configurations can i make to the Erlang Emulator, to
  avoid these heap memory crash dumps especially when all the memory it
  may need is available on the server? How will i run more memory
  consuming apps on this server if Erlang still fails to allocate such
  memory to a simple file system indexer (well its heavily concurrent)?

The Erlang VM should be able to use all of the available memory in your machine. However, it depends on how your application is written. There can be many reasons for memory leaks:

Atom table filling up (you create too many unique atoms)

ETS or Mnesia tables are not garbage collected (you do not delete old unused elements)

Not enough memory for processes (you spawn too many processess)

Too many binaries are created (you might keep unused references to old binaries)


来源: stackexchange

问:
React Parent To Child Component Props Update Issue
Let say i have two components one parent and another child
now i have a prop in child component called active which basically assign {active} class to child if its true now i wanted to change this prop from its parent component while rendering. take a look at some codes below

main code

```<code>import React from 'react';
import { List , Item } from "../Buttons";

export function Sample2() {
    return (
        <List>
            <Item>items</Item>
            <Item>items</Item>
            <Item>items</Item>
        </List>
    )
}
</code>```

component codes

commented line is what i am trying to achieve but its not allowed

```<code>export function List({ children }){
    const [index,setIndex] = useState(0)

    function getOptions(){
        return children.map((each,i)=>{
            //each.props.active = index == i
            return each
        })
    }

    return (
        <div className="list">
            {getOptions()}
        </div>
    )
}

export function Item({ active , children }){
    const classes ="item p-4 border-b" + (active?` active`:"")
    return (
        <div className={classes}>{children}</div>
    )
}
</code>```

now i wanted to know what is the way to achive this or i am not following react flow ? i am old in javascript but very much new to react so please explain what would be the best way to achive this

here's a screenshot of my codes

答:
React is a declarative paradigm. It would be better if you don't mutate the each. Instead:

```<code>function getOptions(){
 return React.Children.map(children,
   (child, i) => (
     React.cloneElement(child, {active: index === i}})
   ))
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Let say i have two components one parent and another child
now i have a prop in child component called active which basically assign {active} class to child if its true now i wanted to change this prop from its parent component while rendering. take a look at some codes below

main code

import React from 'react';
import { List , Item } from "../Buttons";

export function Sample2() {
    return (
        <List>
            <Item>items</Item>
            <Item>items</Item>
            <Item>items</Item>
        </List>
    )
}

component codes

commented line is what i am trying to achieve but its not allowed

export function List({ children }){
    const [index,setIndex] = useState(0)

    function getOptions(){
        return children.map((each,i)=>{
            //each.props.active = index == i
            return each
        })
    }

    return (

            {getOptions()}

    )
}

export function Item({ active , children }){
    const classes ="item p-4 border-b" + (active?` active`:"")
    return (

{children}

    )
}

now i wanted to know what is the way to achive this or i am not following react flow ? i am old in javascript but very much new to react so please explain what would be the best way to achive this

here's a screenshot of my codes

Body:
React is a declarative paradigm. It would be better if you don't mutate the each. Instead:

function getOptions(){
 return React.Children.map(children,
   (child, i) => (
     React.cloneElement(child, {active: index === i}})
   ))
}


问:
Avoid creating named variables when pointer is required
I have been creating named variables in order to be able to pass their adress to a constructor that expects a pointer, but I want to be able to create them in a constructor or other function and then pass their address to the constructor that expects a pointer.

I am using C++ 20 and I have the following classes:

```<code>#include <iostream>
#include <string>
#include <vector>
#include <random>

using std::string, std::cout, std::cin, std::endl, std::vector;

class symbol {
public:
    enum symbolKind {
        null,
        terminal,
        sequence,
        weighted,
        random
    };
protected:
    symbolKind kind;
public:
    virtual string evaluate() const = 0;
    symbolKind getKind() {
        return kind;
    }
};

class nullSymbol : public symbol {
public:
    nullSymbol() {
        kind = symbol::null;
    }
    string evaluate() const override {
        return "";
    }
};

class terminalSymbol : public symbol {
private:
    string termString;
public:
    terminalSymbol(string pString) {
        kind = symbol::terminal;
        termString = pPhoneme;
    }
    string evaluate() const override {
        return termString;
    }
};

class sequenceSymbol : public symbol {
private:
    vector<symbol*> symArray;
public:
    sequenceSymbol(vector<symbol*> pArr) {
        kind = symbol::sequence;
        symArray = pArr;
    }
    string evaluate() const override {
        string retStr = "";
        for (symbol* current : symArray) {
            retStr += current->evaluate();
        }
        return retStr;
    }
};

class weightedSymbol : public symbol {
private:
    float weight;
    symbol* subSym;
public:
    weightedSymbol(symbol* pSym, float pWeight) {
        kind = symbol::weighted;
        subSym = pSym;
        weight = pWeight;
    }
    string evaluate() const override {
        return subSym->evaluate();
    }
    float getWeight() {
        return weight;
    }
};

class randomSymbol : public symbol {
private:
    vector<weightedSymbol*> symArray;
public:
    randomSymbol(vector<weightedSymbol*> pArr) {
        kind = symbol::random;
        symArray = pArr;
    }
    string evaluate() const override {
        float sum = 0.0;
        for (weightedSymbol* current : symArray) {
            sum += current->getWeight();
        }

        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_real_distribution<> dis(0.0, sum);
        float randomResult = dis(gen);

        float prev = 0;
        for (weightedSymbol* current : symArray) {
            if (randomResult < (prev += current->getWeight())) return current->evaluate();
        }
    }
};
</code>```

I have been creating symbols like this:

```<code>terminalSymbol term_a("a");
terminalSymbol term_b("b");
sequenceSymbol seq_ab({ &term_a, &term_b});

cout << "ab test: " << seq_ab.evaluate() << endl;
</code>```

But I would want to be able to do it like this or similar:

```<code>sequenceSymbol seq_ab_2({&terminalSymbol("a"), &terminalSymbol("b")});

cout << "ab test 2: " << seq_ab_2.evaluate() << endl;
</code>```

This creates an error '&' requires l-value in Visual Studio.

This is a pretty simple example, often there are a lot more variables being created than this. In this case, the addresses are being passed to the std::vector<weightedSymbol*>() constructor; it's the same with the weightedSymbol() constructor which also expects a pointer. This should work not only for the constructor (it doesn't even need to work with the constructor itself if there is another way to achieve the same functionality), but I want a way to create heap objects in a function and then return a pointer to them that works in this situation. It might be that I need to change the classes themselves for this to work, they should just provide the same functionality.

In the end, I want to create these symbol objects dynamically based on user input.

I have searched online and tried using a bunch of different things but didn't manage to get the functionality I want working. What would be a good way to implement this? There is probably a common technique/idiom that I can use, if so, please explain it to me in detail so that I can use it in other projects too.

答:
The objects you pass by pointers need to be destroyed somehow. In this snippet they will be destroyed automatically whenever you exit the block:

terminalSymbol term_a("a");
terminalSymbol term_b("b");
sequenceSymbol seq_ab({ &term_a, &term_b});
```
<p>What should happen if you create objects without a named variable? Your classes never delete the objects that you pass by pointers, so that should be the caller responsibility to manage the lifespan of each object.</p>
<p>One solution for your problem is to wrap the objects into any sort of smart pointers. For example:</p>
<pre class="lang-cpp prettyprint-override"><code>class sequenceSymbol : public symbol {
public:
    sequenceSymbol(vector<shared_ptr<symbol>> pArr);
};

sequenceSymbol seq_ab_2({
    std::make_shared<terminalSymbol>("a"),
    std::make_shared<terminalSymbol>("b")
});
</code>```

Body:
I have been creating named variables in order to be able to pass their adress to a constructor that expects a pointer, but I want to be able to create them in a constructor or other function and then pass their address to the constructor that expects a pointer.

I am using C++ 20 and I have the following classes:

#include <iostream>
#include <string>
#include <vector>
#include <random>

using std::string, std::cout, std::cin, std::endl, std::vector;

class symbol {
public:
    enum symbolKind {
        null,
        terminal,
        sequence,
        weighted,
        random
    };
protected:
    symbolKind kind;
public:
    virtual string evaluate() const = 0;
    symbolKind getKind() {
        return kind;
    }
};

class nullSymbol : public symbol {
public:
    nullSymbol() {
        kind = symbol::null;
    }
    string evaluate() const override {
        return "";
    }
};

class terminalSymbol : public symbol {
private:
    string termString;
public:
    terminalSymbol(string pString) {
        kind = symbol::terminal;
        termString = pPhoneme;
    }
    string evaluate() const override {
        return termString;
    }
};

class sequenceSymbol : public symbol {
private:
    vector<symbol*> symArray;
public:
    sequenceSymbol(vector<symbol*> pArr) {
        kind = symbol::sequence;
        symArray = pArr;
    }
    string evaluate() const override {
        string retStr = "";
        for (symbol* current : symArray) {
            retStr += current->evaluate();
        }
        return retStr;
    }
};

class weightedSymbol : public symbol {
private:
    float weight;
    symbol* subSym;
public:
    weightedSymbol(symbol* pSym, float pWeight) {
        kind = symbol::weighted;
        subSym = pSym;
        weight = pWeight;
    }
    string evaluate() const override {
        return subSym->evaluate();
    }
    float getWeight() {
        return weight;
    }
};

class randomSymbol : public symbol {
private:
    vector<weightedSymbol*> symArray;
public:
    randomSymbol(vector<weightedSymbol*> pArr) {
        kind = symbol::random;
        symArray = pArr;
    }
    string evaluate() const override {
        float sum = 0.0;
        for (weightedSymbol* current : symArray) {
            sum += current->getWeight();
        }

        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_real_distribution<> dis(0.0, sum);
        float randomResult = dis(gen);

        float prev = 0;
        for (weightedSymbol* current : symArray) {
            if (randomResult < (prev += current->getWeight())) return current->evaluate();
        }
    }
};

I have been creating symbols like this:

terminalSymbol term_a("a");
terminalSymbol term_b("b");
sequenceSymbol seq_ab({ &term_a, &term_b});

cout << "ab test: " << seq_ab.evaluate() << endl;

But I would want to be able to do it like this or similar:

sequenceSymbol seq_ab_2({&terminalSymbol("a"), &terminalSymbol("b")});

cout << "ab test 2: " << seq_ab_2.evaluate() << endl;

This creates an error '&' requires l-value in Visual Studio.

This is a pretty simple example, often there are a lot more variables being created than this. In this case, the addresses are being passed to the std::vector<weightedSymbol*>() constructor; it's the same with the weightedSymbol() constructor which also expects a pointer. This should work not only for the constructor (it doesn't even need to work with the constructor itself if there is another way to achieve the same functionality), but I want a way to create heap objects in a function and then return a pointer to them that works in this situation. It might be that I need to change the classes themselves for this to work, they should just provide the same functionality.

In the end, I want to create these symbol objects dynamically based on user input.

I have searched online and tried using a bunch of different things but didn't manage to get the functionality I want working. What would be a good way to implement this? There is probably a common technique/idiom that I can use, if so, please explain it to me in detail so that I can use it in other projects too.

Body:
The objects you pass by pointers need to be destroyed somehow. In this snippet they will be destroyed automatically whenever you exit the block:

terminalSymbol term_a("a");
terminalSymbol term_b("b");
sequenceSymbol seq_ab({ &term_a, &term_b});

What should happen if you create objects without a named variable? Your classes never delete the objects that you pass by pointers, so that should be the caller responsibility to manage the lifespan of each object.

One solution for your problem is to wrap the objects into any sort of smart pointers. For example:

class sequenceSymbol : public symbol {
public:
    sequenceSymbol(vector<shared_ptr<symbol>> pArr);
};

sequenceSymbol seq_ab_2({
    std::make_shared<terminalSymbol>("a"),
    std::make_shared<terminalSymbol>("b")
});


问:
Removing duplicates from an vector is giving unexpected results

Given a vector of integers, iterate through the vector and check whether there are more than one of the same number. In that case, remove them so that only a single index of the vector contains that number. Here are a few examples:

```<code>vector<int> arr {1,1,1,1}
When arr is printed out the result should be 1.

vector<int> arr {1,2,1,2}
When arr is printed out the result should be 1,2.

vector<int> arr {1,3,2}
When arr is printed out the result should be 1,3,2.
</code>```

I know there are many solutions regarding this, but I want to solve it using my method. The solutions I've looked at use a lot of built-in functions, which I don't want to get too comfortable with as a beginner. I want to practice my problem-solving skills.

This is my code:

```<code>#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> arr {1,1,1,1,2,1,1,1,1,1};

    for (int i {}; i < arr.size(); ++i)
    {
        int counter {};

        for (int j {}; j < arr.size(); ++j)
        {
            if (arr.at(i) == arr.at(j))
            {
                counter++;

                if (counter > 1)
                    arr.erase(arr.begin()+j);
            }
        }
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        cout << value << endl;
    }

    return 0;
}
</code>```

The thing is that it works for the most part, except a few cases which have me confused.

For instance:

```<code>vector<int> arr {1,1,1,1,2,1,1,1,1,1}
When arr is printed out the result is 1,2,1 instead of 1,2.
</code>```

However, in this case:

```<code>vector<int> arr {1,1,1,1,2,1,1,1}
When arr is printed out the result is 1,2.
</code>```

It seems to work in the vast majority of cases, but when a number repeats itself a lot of times in the vector, it seems to not work, and I can't seem to find a reason for this.

I am now asking you to firstly tell me the cause of the problem, and then to give me guidance on how I should tackle this problem using my solution.

答:
This inner for loop is incorrect

```<code>    int counter {};

    for (int j {}; j < arr.size(); ++j)
    {
        if (arr.at(i) == arr.at(j))
        {
            counter++;

            if (counter > 1)
                arr.erase(arr.begin()+j);
        }
    }
</code>```

If an element was removed the index j shall not be increased. Otherwise  the next element after deleted will be bypassed because all elements after the deleted element in the vector are moved one position left.

Using the variable counter is redundant. Just start the inner loop with j = i + 1.

Using your approach the program can look the following way

```<code>#include <iostream>
#include <vector>

int main()
{
    std::vector<int> arr{ 1,1,1,1,2,1,1,1,1,1 };

    for ( decltype( arr )::size_type i = 0; i < arr.size(); ++i)
    {
        for ( decltype( arr )::size_type j = i + 1; j < arr.size(); )
        {
            if (arr.at( i ) == arr.at( j ))
            {
                arr.erase( arr.begin() + j );
            }
            else
            {
                j++;
            }
        }
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        std::cout << value << std::endl;
    }
}
</code>```

The program output is

```<code>1
2
</code>```

This approach when each duplicated element is deleted separately is inefficient. It is better to use the so called erase-remove idiom.

Here is a demonstration program.

```<code>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::vector<int> arr{ 1,1,1,1,2,1,1,1,1,1 };

    for (auto first = std::begin( arr ); first != std::end( arr ); ++first)
    {
        arr.erase( std::remove( std::next( first ), std::end( arr ), *first ), std::end( arr ) );
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        std::cout << value << std::endl;
    }

}
</code>```

Body:
Given a vector of integers, iterate through the vector and check whether there are more than one of the same number. In that case, remove them so that only a single index of the vector contains that number. Here are a few examples:

vector<int> arr {1,1,1,1}
When arr is printed out the result should be 1.

vector<int> arr {1,2,1,2}
When arr is printed out the result should be 1,2.

vector<int> arr {1,3,2}
When arr is printed out the result should be 1,3,2.

I know there are many solutions regarding this, but I want to solve it using my method. The solutions I've looked at use a lot of built-in functions, which I don't want to get too comfortable with as a beginner. I want to practice my problem-solving skills.

This is my code:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> arr {1,1,1,1,2,1,1,1,1,1};

    for (int i {}; i < arr.size(); ++i)
    {
        int counter {};

        for (int j {}; j < arr.size(); ++j)
        {
            if (arr.at(i) == arr.at(j))
            {
                counter++;

                if (counter > 1)
                    arr.erase(arr.begin()+j);
            }
        }
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        cout << value << endl;
    }

    return 0;
}

The thing is that it works for the most part, except a few cases which have me confused.

For instance:

vector<int> arr {1,1,1,1,2,1,1,1,1,1}
When arr is printed out the result is 1,2,1 instead of 1,2.

However, in this case:

vector<int> arr {1,1,1,1,2,1,1,1}
When arr is printed out the result is 1,2.

It seems to work in the vast majority of cases, but when a number repeats itself a lot of times in the vector, it seems to not work, and I can't seem to find a reason for this.

I am now asking you to firstly tell me the cause of the problem, and then to give me guidance on how I should tackle this problem using my solution.

Body:
This inner for loop is incorrect

    int counter {};

    for (int j {}; j < arr.size(); ++j)
    {
        if (arr.at(i) == arr.at(j))
        {
            counter++;

            if (counter > 1)
                arr.erase(arr.begin()+j);
        }
    }

If an element was removed the index j shall not be increased. Otherwise  the next element after deleted will be bypassed because all elements after the deleted element in the vector are moved one position left.

Using the variable counter is redundant. Just start the inner loop with j = i + 1.

Using your approach the program can look the following way

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> arr{ 1,1,1,1,2,1,1,1,1,1 };

    for ( decltype( arr )::size_type i = 0; i < arr.size(); ++i)
    {
        for ( decltype( arr )::size_type j = i + 1; j < arr.size(); )
        {
            if (arr.at( i ) == arr.at( j ))
            {
                arr.erase( arr.begin() + j );
            }
            else
            {
                j++;
            }
        }
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        std::cout << value << std::endl;
    }
}

The program output is

1
2

This approach when each duplicated element is deleted separately is inefficient. It is better to use the so called erase-remove idiom.

Here is a demonstration program.

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::vector<int> arr{ 1,1,1,1,2,1,1,1,1,1 };

    for (auto first = std::begin( arr ); first != std::end( arr ); ++first)
    {
        arr.erase( std::remove( std::next( first ), std::end( arr ), *first ), std::end( arr ) );
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        std::cout << value << std::endl;
    }

}


问:
How to redirect to the same current page with different passed values
I have a page which contains a textbox and a button, let's say its URL is:

default.aspx

When user enters a value (new) in the textbox and click on the button (which causes the redirection to the same page + passing the value) the URL should change to:

default.aspx?keyword=new

The problem is when the URL is:

default.aspx?keyword=new

and when I try to enter another value in the textbox the URL after redirection wont contain the new word !

Code in Page_load

```<code>   if (Request.QueryString["keyword"] != null)
            {
                TextBox1.Text = Request.QueryString["keyword"]; //For redirection from another page
                search();
            }
</code>```

Code in onClick button

```<code> Response.Redirect("~/Default.aspx?keyword=" + TextBox1.Text);
</code>```

I've tried to debug and figured out that, on the second value entry in textbox the button post back which causes the Page_Load to be called and the URL here will be default.aspx?keyword=new so the condition result will be true and the value in the text box will get back to how it was, how should I solve that?

答:
```<code>if ( Request.QueryString["keyword"] != null )
{
    if(String.IsNullOrEmpty(TextBox1.Text))
    TextBox1.Text = Request.QueryString["keyword"];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a page which contains a textbox and a button, let's say its URL is:

default.aspx

When user enters a value (new) in the textbox and click on the button (which causes the redirection to the same page + passing the value) the URL should change to:

default.aspx?keyword=new

The problem is when the URL is:

default.aspx?keyword=new

and when I try to enter another value in the textbox the URL after redirection wont contain the new word !

Code in Page_load

   if (Request.QueryString["keyword"] != null)
            {
                TextBox1.Text = Request.QueryString["keyword"]; //For redirection from another page
                search();
            }

Code in onClick button

 Response.Redirect("~/Default.aspx?keyword=" + TextBox1.Text);

I've tried to debug and figured out that, on the second value entry in textbox the button post back which causes the Page_Load to be called and the URL here will be default.aspx?keyword=new so the condition result will be true and the value in the text box will get back to how it was, how should I solve that?


问:
Javascript alert function not displaying message after clicking button
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.</p>
```<code>    <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <style type="text/css">

      body {
        margin: 40px;
        font-family: 'Open Sans';
      }
      #fieldSize, #fieldCrust {
        width: 150px;
        float: left;
        border: none;
      }
       #fieldToppings {
         width: 350px;
         border: none;

       }
       fieldset {
         margin-top: 20px;
       }
      #toppings1 {
        float: left;
      }
      label {
        display: inline-block;
        width: 150px;
        margin: 7px;
        text-align: left;
      }
      input[type="text"] {
        width: 250px;
      }
      div {
        padding: 10px;
      }
      #btnOrder {
        width: auto;
        border-radius: 10px;
      }

    </style>
    <script type="text/javascript">

      function orderSubmit() {
        var name = document.getElementById("txtName").value;
        var phone = document.getElementById("txtPhone").value;
        phone = '(' + phone.substring(0,3) + ')' + phone.substring(3,6) + '-' + phone.substring(6);
        var address = document.getElementById("txtAddress").value;

        var msg = name + ", your order is being prepared. \n";
        msg+= "Your order will be delivered at " + address;
        msg+= "Your contact infromation is: " + phone "\n";
        msg+= "Order details: \n \n";

        for(var i = 0; i < document.frm1.rdoSize.length; i++) {
           if(document.frm1.rdoSize[i].checked) {
             var radioStateSize = document.frm1.rdoSize[i].value;
           }
        }
        for(var j = 0; j < document.frm1.rdoCrust.length; j++) {
           if(document.frm1.rdoCrust[j].checked) {
             var radioStateCrust = document.frm1.rdoCrust[j].value;
           }
        }
        msg+= radioStateSize + ' ' + radioStateCrust + " pizza with the following toppings: \n";

        var chkToppings = document.frm1.chkToppings;

        for(k=0; k < document.frm1.chkToppings; k++) {
           if(document.frm1.chkToppings[k].checked) {
           msg += document.frm1.chkToppings[k].value + ' ';
           }
        }
        alert(msg);
      }

    </script>

  </head>

  <body>
    <fieldset id="main">
      <legend><h2>Pizza Order!</h2></legend>

      <form name="frm1">
        <div>
          <label for="lblName">Name:</label>
          <input type="text" id="txtName">
        </div>

        <div>
          <label for="lblPhone">Phone Number:</label>
          <input type="text" id="txtPhone">
        </div>

        <div>
          <label for="lblAddress">Address:</label>
          <input type="text" id="txtAddress">
        </div>

      <fieldset id="fieldSize">
        <legend><strong>Size</strong></legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small <br>
          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium <br>
          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large <br>
      </fieldset>

      <fieldset id="fieldCrust">
        <legend><strong>Crust</strong></legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small <br>
          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed <br>
          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free <br>
      </fieldset>

      <fieldset id="fieldToppings">
        <legend><strong>Toppings</strong></legend>
          <div id="toppings1">
            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage <br>
            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken <br>
            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies <br>
          </div>
          <div id="toppings2">
            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms <br>
            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers <br>
            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta <br>
            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives <br>
            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions <br>
          </div>
      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>
  </body>
</html>
</code>```

答: in the example you posted, there are some typos and syntax errors, you may want to check for that first. You can check for those using the console (in some browsers: Ctrl-i), which is always useful for debugging BTW. As pointed in other answers, when using brackets, you don't need to use the dot ( rdoCrust.[j] )</p>

Body:
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.

    <!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <fieldset id="main">
      <legend>
Pizza Order!
</legend>

      <form name="frm1">

          Name:
          <input type="text" id="txtName">

          Phone Number:
          <input type="text" id="txtPhone">

          Address:
          <input type="text" id="txtAddress">

      <fieldset id="fieldSize">
        <legend>Size</legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small

          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium

          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large

      </fieldset>

      <fieldset id="fieldCrust">
        <legend>Crust</legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small

          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed

          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free

      </fieldset>

      <fieldset id="fieldToppings">
        <legend>Toppings</legend>

            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage

            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken

            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies

            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms

            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers

            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta

            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives

            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions

      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>


问:
Not able to find the reference tab to add Json.NET for C#
I created my first project and I am trying to work with JSON files. I am not able to see the tab of references in my Visual Studio. How can I retrieve the tab? I tried to Google and I cannot see the issue here.

This is my current Project Solution looks

[]

[]

答:
Double click the project node in Solution Explorer, add the following, press ctrl + S. After a few seconds the package is downloaded and installed.

```<code><ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
</code>```

You should also read up on using NuGet package manager in Visual Studio.

Body:
Double click the project node in Solution Explorer, add the following, press ctrl + S. After a few seconds the package is downloaded and installed.

<ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>

You should also read up on using NuGet package manager in Visual Studio.


问:
How to replace the text with the previous text in the label?
I am trying to write a code to have a label, and a button, and whenever we click on the button the defined text just replaces with the previous text in the Label. Right now it adds it the previous text.

```<code>from tkinter import *

root = Tk()
root.geometry("400x400")

my_label = Label(text="Hello").pack()

def test():
    my_label = Label(text="Bye").pack()

my_button = Button(root, text="Open a file", command=test).pack()

root.mainloop()
</code>```

I saw that people using config to do that. But I don't understand what is the problem with my code.

```<code>from tkinter import *

root = Tk()
root.geometry("400x400")

global my_label
my_label = Label(text="Hello").pack()

def test():
    my_label.config(text="Bye")

my_button = Button(root, text="Open a file", command=test).pack()

root.mainloop()
</code>```

It gives me this error:

```<code>AttributeError: 'NoneType' object has no attribute 'config'
</code>```

答:
The problem with your tkinter code is covered in the accepted answer to the question Tkinter: AttributeError: NoneType object has no attribute .

As for what you want to know how to do:

While, generally speaking, you can change the options of an existing widget by using the universal widget config() method, as you're doing.
There's an even better way to do things when you want to change a value that one (or more) of them is displaying. In those cases you can refer one or more widgets to a tkinter Variable and then just update the variable's value and all the widgets referring to it change.

Here's how to do things that way.

```<code>import tkinter as tk  # PEP 8 recommends against `import *`.

root = tk.Tk()
root.geometry("400x400")

label_text = tk.StringVar(value="Hello")

my_label = tk.Label(textvariable=label_text)
my_label.pack()

def test():
    label_text.set("Bye")

my_button = tk.Button(root, text="Open a file", command=test)
my_button.pack()

root.mainloop()
</code>```

Body:
I am trying to write a code to have a label, and a button, and whenever we click on the button the defined text just replaces with the previous text in the Label. Right now it adds it the previous text.

from tkinter import *

root = Tk()
root.geometry("400x400")

my_label = Label(text="Hello").pack()

def test():
    my_label = Label(text="Bye").pack()

my_button = Button(root, text="Open a file", command=test).pack()

root.mainloop()

I saw that people using config to do that. But I don't understand what is the problem with my code.

from tkinter import *

root = Tk()
root.geometry("400x400")

global my_label
my_label = Label(text="Hello").pack()

def test():
    my_label.config(text="Bye")

my_button = Button(root, text="Open a file", command=test).pack()

root.mainloop()

It gives me this error:

AttributeError: 'NoneType' object has no attribute 'config'

Body:
The problem with your tkinter code is covered in the accepted answer to the question Tkinter: AttributeError: NoneType object has no attribute .

As for what you want to know how to do:

While, generally speaking, you can change the options of an existing widget by using the universal widget config() method, as you're doing.
There's an even better way to do things when you want to change a value that one (or more) of them is displaying. In those cases you can refer one or more widgets to a tkinter Variable and then just update the variable's value and all the widgets referring to it change.

Here's how to do things that way.

import tkinter as tk  # PEP 8 recommends against `import *`.

root = tk.Tk()
root.geometry("400x400")

label_text = tk.StringVar(value="Hello")

my_label = tk.Label(textvariable=label_text)
my_label.pack()

def test():
    label_text.set("Bye")

my_button = tk.Button(root, text="Open a file", command=test)
my_button.pack()

root.mainloop()


问:
Get Top and Left position of an FMX Control, based on screen bounds
I'm trying to place an outside program right into an FMX TPanel using SetWindowPOS from WinAPI.
In order to do that I need the exact Top and Left values of the TPanel to pass it to SetWindowPOS. However, this value is always according to its parent, so i.e. if the Tpanel's parent is a TLayout and no margins are set, then the value of Top will be 0.

I need the Top value according to the screen.
I tried searching for that quite a bit but I can't figure it out.
Any help with that would be greatly appreciated.

答:
After just posting the question I got the simple solution

```<code>var
    pnt: TPointF;
begin
  pnt := myRctngl.LocalRect.TopLeft;
  pnt := myRctngl.LocalToAbsolute(pnt);
  pnt := ClientToScreen(pnt);
End;
</code>```

pnt should now have the value of the Point according to the screen.

You can now use pnt.x and pnt.y to get the top/left values.

Body:
After just posting the question I got the simple solution

var
    pnt: TPointF;
begin
  pnt := myRctngl.LocalRect.TopLeft;
  pnt := myRctngl.LocalToAbsolute(pnt);
  pnt := ClientToScreen(pnt);
End;

pnt should now have the value of the Point according to the screen.

You can now use pnt.x and pnt.y to get the top/left values.


问:
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

```<code>void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}
</code>```

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

答:
If evaluating A is fast, B is slow, and when the short circuit happens (A returns true), then if (A || B) will avoid the slow path where if (A | B) will not.

If evaluating A almost always gives the same result, the processor's branch prediction may give if (A || B) performance better than if (A | B) even if B is fast.

As others have mentioned, there are cases where the short circuit is mandatory:  you only want to execute B if A is known to evaluate false:

```<code>if (p == NULL || test(*p)) { ... }  // null pointer would crash on *p

if (should_skip() || try_update()) { ... }  // active use of side effects
</code>```

Body:
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

Body:
If evaluating A is fast, B is slow, and when the short circuit happens (A returns true), then if (A || B) will avoid the slow path where if (A | B) will not.

If evaluating A almost always gives the same result, the processor's branch prediction may give if (A || B) performance better than if (A | B) even if B is fast.

As others have mentioned, there are cases where the short circuit is mandatory:  you only want to execute B if A is known to evaluate false:

if (p == NULL || test(*p)) { ... }  // null pointer would crash on *p

if (should_skip() || try_update()) { ... }  // active use of side effects


问:
Use a dictionary to find/replace exact terms in a tokenized pandas series
Using a dictionary, I need to find and replace terms in a pandas series according to the following criteria:

dictionary values are replacing dictionary keys wherever they are found in the pandas series (e.g., for example, in 'mastersphd': 'masters phd', the replacement outcome would be 'masters phd' wherever 'mastersphd' occurs)

maintain record integrity (i.e., can't use a bag of words approach because I need the unique records to remain intact.)

Only exact matches should be replaced (for example, if key:value is 'rf': 'random forest', the replacement should not turn 'performance' into 'perandom forestormance'); so regex=True is causing this, obviously)

The Data: term_fixes is the dictionary, and df['job_description'] is the tokenized series of interest

```<code>term_fixes = {'rf': 'random forest',
              'mastersphd': 'masters phd',
              'curiosity': 'curious',
              'trustworthy': 'ethical',
              'realise': 'realize'}

df = pd.DataFrame(data={'job_description': [['knowledge', 'of', 'algorithm', 'like', 'rf'],
                                            ['must', 'have', 'a', 'mastersphd'],
                                            ['trustworthy', 'and', 'possess', 'curiosity'],
                                            ['we', 'realise', 'performance', 'is', 'key']]})
</code>```

**Note: I have also (unsuccessfully) tried an untokenized data structure, but prefer tokenized since I have more NLP to do

```<code>df = pd.DataFrame(data={'job_description': ['knowledge of algorithm like rf',
                                            'must have a mastersphd',
                                            'must be trustworthy and possess curiosity',
                                            'we realise performance is critical']})
</code>```

**Desired Outcome (note that the 'rf' in performance is not replaced by 'random forest'):
df['job_description']

```<code>0    ['knowledge' 'of' 'algorithm' 'like' 'random' 'forest']
1                        ['must' 'have' 'a' 'masters' 'phd']
2          ['must' 'be' 'ethical' 'and' 'possess' 'curious']
3             ['we' 'realize' 'performance' 'is' 'critical']
</code>```

I have tried a number of approaches.
Fail: df['job_description'].replace(list(term_fixes.keys()), list(term_fixes.values()), regex=False, inplace=True)

Fail: df['job_description'].replace(dict(zip(list(term_fixes.keys()), list(term_fixes.values()))), regex=False, inplace=True)

Fail: df['job_description'] = df['job_description'].str.replace(term_fixes, regex=False)

Fail: df['job_description'] = df['job_description'].str.replace(str(term_fixes.keys()), str(term_fixes.values()), regex=True)

The closest I have come is:

```<code>df['job_description'] = df_jobs['job_description'].replace(term_fixes, regex=True)
</code>```

However, the regex=True flags on any match (like the 'rf' and 'performance' example above). Changing the flag to regex=False fails to replace anything, unfortunately. I looked in the documentation for another argument I could use, but no luck. Note that this uses the untokenized structure.

Any help would be much appreciated. Thanks!

答:
Using the "tokenized" version of your df.

```<code>df['job_description'] = df['job_description'].explode().replace(term_fixes).groupby(level=-1).agg(list)

# explode to get single terms per "cell"
# replace to replace the terms in "term_fixes"
# groupby to reverse the previous explode and return to a column of lists

                                   job_description
0  [knowledge, of, algorithm, like, random forest]
1                     [must, have, a, masters phd]
2                 [ethical, and, possess, curious]
3              [we, realize, performance, is, key]
</code>```

If you need the new terms also split on white space, then you can add another intermediate step .str.split().explode() before the final groupby

```<code>df['job_description'] = df['job_description'].explode().replace(term_fixes).str.split().explode().groupby(level=-1).agg(list)

                                    job_description
0  [knowledge, of, algorithm, like, random, forest] # random forest is now split
1                     [must, have, a, masters, phd] # masters phd is now split
2                  [ethical, and, possess, curious]
3               [we, realize, performance, is, key]
</code>```

Body:
Using a dictionary, I need to find and replace terms in a pandas series according to the following criteria:

dictionary values are replacing dictionary keys wherever they are found in the pandas series (e.g., for example, in 'mastersphd': 'masters phd', the replacement outcome would be 'masters phd' wherever 'mastersphd' occurs)

maintain record integrity (i.e., can't use a bag of words approach because I need the unique records to remain intact.)

Only exact matches should be replaced (for example, if key:value is 'rf': 'random forest', the replacement should not turn 'performance' into 'perandom forestormance'); so regex=True is causing this, obviously)

The Data: term_fixes is the dictionary, and df['job_description'] is the tokenized series of interest

term_fixes = {'rf': 'random forest',
              'mastersphd': 'masters phd',
              'curiosity': 'curious',
              'trustworthy': 'ethical',
              'realise': 'realize'}

df = pd.DataFrame(data={'job_description': [['knowledge', 'of', 'algorithm', 'like', 'rf'],
                                            ['must', 'have', 'a', 'mastersphd'],
                                            ['trustworthy', 'and', 'possess', 'curiosity'],
                                            ['we', 'realise', 'performance', 'is', 'key']]})

**Note: I have also (unsuccessfully) tried an untokenized data structure, but prefer tokenized since I have more NLP to do

df = pd.DataFrame(data={'job_description': ['knowledge of algorithm like rf',
                                            'must have a mastersphd',
                                            'must be trustworthy and possess curiosity',
                                            'we realise performance is critical']})

**Desired Outcome (note that the 'rf' in performance is not replaced by 'random forest'):
df['job_description']

0    ['knowledge' 'of' 'algorithm' 'like' 'random' 'forest']
1                        ['must' 'have' 'a' 'masters' 'phd']
2          ['must' 'be' 'ethical' 'and' 'possess' 'curious']
3             ['we' 'realize' 'performance' 'is' 'critical']

I have tried a number of approaches.
Fail: df['job_description'].replace(list(term_fixes.keys()), list(term_fixes.values()), regex=False, inplace=True)

Fail: df['job_description'].replace(dict(zip(list(term_fixes.keys()), list(term_fixes.values()))), regex=False, inplace=True)

Fail: df['job_description'] = df['job_description'].str.replace(term_fixes, regex=False)

Fail: df['job_description'] = df['job_description'].str.replace(str(term_fixes.keys()), str(term_fixes.values()), regex=True)

The closest I have come is:

df['job_description'] = df_jobs['job_description'].replace(term_fixes, regex=True)

However, the regex=True flags on any match (like the 'rf' and 'performance' example above). Changing the flag to regex=False fails to replace anything, unfortunately. I looked in the documentation for another argument I could use, but no luck. Note that this uses the untokenized structure.

Any help would be much appreciated. Thanks!

Body:
Using the "tokenized" version of your df.

df['job_description'] = df['job_description'].explode().replace(term_fixes).groupby(level=-1).agg(list)

# explode to get single terms per "cell"
# replace to replace the terms in "term_fixes"
# groupby to reverse the previous explode and return to a column of lists

                                   job_description
0  [knowledge, of, algorithm, like, random forest]
1                     [must, have, a, masters phd]
2                 [ethical, and, possess, curious]
3              [we, realize, performance, is, key]

If you need the new terms also split on white space, then you can add another intermediate step .str.split().explode() before the final groupby

df['job_description'] = df['job_description'].explode().replace(term_fixes).str.split().explode().groupby(level=-1).agg(list)

                                    job_description
0  [knowledge, of, algorithm, like, random, forest] # random forest is now split
1                     [must, have, a, masters, phd] # masters phd is now split
2                  [ethical, and, possess, curious]
3               [we, realize, performance, is, key]


问:
Data Types at Azure Data Lake
I am bringing data from SAP HANA based OLTP source to Microsoft azure based data lake using azure adf and data bricks. What should data type be at Microsoft azure based data lake for below data types at SAP HANA source:

NVARCHAR(4)

DECIMAL (9,5)

Float

int

datetime

nvarchar(64)

decimal(10,2)

答:
If you are using Copy activity for your copy process, in ADLS Gen2 you can store data in many different file formats like delimited, avro. paraquet, XML, etc . Depending upon which format you want the data types will change. For example, if you select delimited format, everything will be stored as string.

For Parquet, Avro, Delta, Orc formats there are few limitations in ADF while using copy activity.

For example:
Parquet limitations:

ORC format limiation:

You can go through the ADF documentation for each file format to look for respective limitation with respect to datatypes.

You can also check for this documentation to explore more about the copy activity interim data types supported in ADF : ADF Copy activity Data type mapping

Title: Data Types at Azure Data Lake


问:
Using a function to print an input one letter at a time
I am making a game/quiz in Python, but ran into a small issue. I made a function to print one letter at a time, but when I use that function for an input, it does not work and prints all at once. I've tried making a string for the input and multiple other things. To fix this temporarily, I have just been printing my question, and then using an input function to make an input, but I'm wondering if there is a better way. Here is my code:</p>
```<code>import time
import sys

def input1():
    input("")

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()
</code>```

答:
I think you may want to add the same for loop that requires c inside of your script in your input1 function, here is an example of how you could do such a thing:

```<code>import time
import sys

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

def input1():
    inp = input("")
    oneprint(inp)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()
</code>```

if you try this it will print the desired color that was answered by the player by getting the input and getting each letter and writing it and flushing it through the oneprint function.

Body:
I am making a game/quiz in Python, but ran into a small issue. I made a function to print one letter at a time, but when I use that function for an input, it does not work and prints all at once. I've tried making a string for the input and multiple other things. To fix this temporarily, I have just been printing my question, and then using an input function to make an input, but I'm wondering if there is a better way. Here is my code:

import time
import sys

def input1():
    input("")

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()

Body:
I think you may want to add the same for loop that requires c inside of your script in your input1 function, here is an example of how you could do such a thing:

import time
import sys

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

def input1():
    inp = input("")
    oneprint(inp)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()

if you try this it will print the desired color that was answered by the player by getting the input and getting each letter and writing it and flushing it through the oneprint function.


问:
Airflow how to run parallel tasks
I'm trying to run multiple tasks in parallel on a single EC2 instance.  I've set up a psql backend and switched to using local executor in addition to changing the configs in the config file.  However, my tasks seem to be executing sequentially rather than in parallel.  Are you theoretically able to run multiple tasks in parallel with the PythonOperator?  Ideally, I would expect to see alternating Hi and Hello's when I run this task but instead I get 10 Hello's and then 10 Hi's.  If I can get this toy example working, it will really help with a workflow I'm trying to design.</p>
```<code>    "test-airflow",
    default_args=default_args,
    description="airflow pipeline features",
    start_date=days_ago(2),
    tags=["example"],
    schedule_interval="@daily",
    catchup=False,
) as dag:
    # [END instantiate_dag]

    # t1, t2 and t3 are examples of tasks created by instantiating operators
    # [START basic_task]
    def test():
        for i in range(0,10):
            print('Hello')
            time.sleep(1)
        return 3

    def test1():
        for i in range(0,10):
            print('Hi')
            time.sleep(1)
        return 3

    t = PythonOperator(task_id='test', python_callable=test)

    t1 = PythonOperator(task_id='test1', python_callable=test1)

    [t, t1]
</code>```

答: I ended up needing to restart the EC2 after I installed the psql backend and changed the config file.  Airflow wasn't updating until I restarted it but that fixed the issue.</p>

Title: Airflow how to run parallel tasks

Body:
I'm trying to run multiple tasks in parallel on a single EC2 instance.  I've set up a psql backend and switched to using local executor in addition to changing the configs in the config file.  However, my tasks seem to be executing sequentially rather than in parallel.  Are you theoretically able to run multiple tasks in parallel with the PythonOperator?  Ideally, I would expect to see alternating Hi and Hello's when I run this task but instead I get 10 Hello's and then 10 Hi's.  If I can get this toy example working, it will really help with a workflow I'm trying to design.

    "test-airflow",
    default_args=default_args,
    description="airflow pipeline features",
    start_date=days_ago(2),
    tags=["example"],
    schedule_interval="@daily",
    catchup=False,
) as dag:
    # [END instantiate_dag]

    # t1, t2 and t3 are examples of tasks created by instantiating operators
    # [START basic_task]
    def test():
        for i in range(0,10):
            print('Hello')
            time.sleep(1)
        return 3

    def test1():
        for i in range(0,10):
            print('Hi')
            time.sleep(1)
        return 3

    t = PythonOperator(task_id='test', python_callable=test)

    t1 = PythonOperator(task_id='test1', python_callable=test1)

    [t, t1]


问:
Binary Tree Upside Down
The output from my code return an empty array while trying to put a binary tree upside down using dfs recursion. How do I fix this ?

```<code>public class TreeNode {
    var val :Int
    var left: TreeNode?
    var right: TreeNode?

        public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
         self.val = val
         self.left = left
         self.right = right
      }

      func upsideDownBinaryTree(_ root: TreeNode?) -> TreeNode? {
        return dfs(current: root)
    }

    func dfs( current: TreeNode?) -> TreeNode? {
        if current == nil {
            return nil
        }
        let newRoot = dfs(current: current?.left)
        current?.left?.left = current?.right
        current?.left?.right = current
        current?.left = nil
        current?.right = nil
        return newRoot
    }
  }
</code>```

enter image description here

答:
The problem is at the base case of recursion: it will always return nil. Since any other returned value is exactly the same as what was retrieved from the recursive call (newRoot), it can never be anything else than nil. There is no way the function can return anything else than nil.

Realise that the case current == nil is only there to deal with an empty tree. In all other cases the recursion should stop one step earlier: when it is a node without left child. In that case that node should be returned.

So change:

```<code>if current == nil {
    return nil
}
</code>```

To:

```<code>if current?.left == nil {
    return current
}
</code>```

Now the base case is focussed on the non-presence of the left child, and in that case the node itself will be returned. The case where current itself is nil is only relevant when the tree is empty, but it is also covered here.

Title: Binary Tree Upside Down

Body:
The output from my code return an empty array while trying to put a binary tree upside down using dfs recursion. How do I fix this ?

public class TreeNode {
    var val :Int
    var left: TreeNode?
    var right: TreeNode?

        public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
         self.val = val
         self.left = left
         self.right = right
      }

      func upsideDownBinaryTree(_ root: TreeNode?) -> TreeNode? {
        return dfs(current: root)
    }

    func dfs( current: TreeNode?) -> TreeNode? {
        if current == nil {
            return nil
        }
        let newRoot = dfs(current: current?.left)
        current?.left?.left = current?.right
        current?.left?.right = current
        current?.left = nil
        current?.right = nil
        return newRoot
    }
  }

enter image description here

Body:
The problem is at the base case of recursion: it will always return nil. Since any other returned value is exactly the same as what was retrieved from the recursive call (newRoot), it can never be anything else than nil. There is no way the function can return anything else than nil.

Realise that the case current == nil is only there to deal with an empty tree. In all other cases the recursion should stop one step earlier: when it is a node without left child. In that case that node should be returned.

So change:

if current == nil {
    return nil
}

To:

if current?.left == nil {
    return current
}

Now the base case is focussed on the non-presence of the left child, and in that case the node itself will be returned. The case where current itself is nil is only relevant when the tree is empty, but it is also covered here.


问:
upload multiple csv files into one dataframe while defining variable types (using tidyverse)
I have a list of csv files in a specific path. I am hoping to upload all of them into one dataframe. This is the code I use:

```<code>d <-
    list.files(path,pattern="*.csv", full.names = T) %>%
    map_dfr(read_csv)
</code>```

Trouble is that some of these columns (for example the column array_values) are strings that are then converted into numbers. I tried all sorts of ways to convert the variables  but can't get it to work unless I have a much more complicated code in which I upload the files one by one, convert and then add to the larger dataframe. Would love to learn if there is a simple way to add it to the code here.

Thanks!

答:
Camille's point is valid. Complete code at least includes the packages that you used with the code snippet you provided.

Having said that, if your CSVs all have the same columns (thus assuming all the columns are the same types) and the columns are in the same order and your problem is that a character column is read as a factor column in some cases or something similar, you can add an argument to read_csv(), col_types to make sure each column is read the same. It's difficult to tell from your question what exactly is wrong.

```<code>library(tidyverse)

> list.files(pattern="t.*csv")
[1] "test1.csv" "test2.csv"
> d <- list.files(pattern="t.*csv") %>% map_dfr(read_csv, col_types="dc")
                                                                                > d
# A tibble: 6 × 2
   col1 col2
  <dbl> <chr>
1   3   a
2   4   b
3   4.5 a
4  13   a
5   4   goat
6   4.5 a
</code>```

You can find the column types in the "Column Specification with readr" section here.

Body:
I have a list of csv files in a specific path. I am hoping to upload all of them into one dataframe. This is the code I use:

d <-
    list.files(path,pattern="*.csv", full.names = T) %>%
    map_dfr(read_csv)

Trouble is that some of these columns (for example the column array_values) are strings that are then converted into numbers. I tried all sorts of ways to convert the variables  but can't get it to work unless I have a much more complicated code in which I upload the files one by one, convert and then add to the larger dataframe. Would love to learn if there is a simple way to add it to the code here.

Thanks!

Body:
Camille's point is valid. Complete code at least includes the packages that you used with the code snippet you provided.

Having said that, if your CSVs all have the same columns (thus assuming all the columns are the same types) and the columns are in the same order and your problem is that a character column is read as a factor column in some cases or something similar, you can add an argument to read_csv(), col_types to make sure each column is read the same. It's difficult to tell from your question what exactly is wrong.

library(tidyverse)

> list.files(pattern="t.*csv")
[1] "test1.csv" "test2.csv"
> d <- list.files(pattern="t.*csv") %>% map_dfr(read_csv, col_types="dc")
                                                                                > d
# A tibble: 6 × 2
   col1 col2
  <dbl> <chr>
1   3   a
2   4   b
3   4.5 a
4  13   a
5   4   goat
6   4.5 a

You can find the column types in the "Column Specification with readr" section here.


问:
How can I tell if a date is before a certain time in Java?
For example given a java.util.Date how could I test if the time was before 12.30 PM that day?</p>

答:
This works. It does the check using only the hour and minute portions of your date:</p>

```<code>Date yourDate;
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourDate);
boolean before = calendar.get(Calendar.HOUR) * 60 + calendar.get(Calendar.MINUTE) < 12 * 60 + 30;
</code>```

Body:
This works. It does the check using only the hour and minute portions of your date:

Date yourDate;
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourDate);
boolean before = calendar.get(Calendar.HOUR) * 60 + calendar.get(Calendar.MINUTE) < 12 * 60 + 30;