问:
Why is TOAD faster than my java code?
I want to execute a select query and be able to get the count of the results, without using "COUNT(*)", like TOAD does. The concept is to give the option to the user to input any 'select query' he wants and to count the number of the results for him.

```<code>try {
   selectStatement = globalConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
   ResultSet selectResultSet = selectStatement.executeQuery(selectStatementString);
   selectResultSet.last();
   int countOfResults = selectResultSet.getRow();
   writeInLabel(kllStatusLabel, "Count Finished: Found " + countOfResults + " Inserts");
} catch (SQLException ex) {
   writeInLabel(kllStatusLabel, "Error executing select query.");
}
</code>```

This code delays much in line: "selectResultSet.last();".
TOAD does it with much less delay. (Right-Click -> Record Count).
Even when I scroll the results table all the way down in TOAD it does it faster.

How does TOAD get the record count?

OK I got it, I will use count(*) and have a second ResultSet to show my results.

```<code>ResultSet selectResultSet = selectStatement.executeQuery("select count(*) from (" + selectStatementString + ")");
int countOfResults = 0;
if (selectResultSet.next()){
   countOfResults = selectResultSet.getInt(1);
}
</code>```

答:
TOAD is probably selecting the @@rowcount or some other DB specific result metadata.
If you want the size of the result, ask the DB for it explicitly (with COUNT())

If you're using mysql then you can use ROW_COUNT().

Title: Why is TOAD faster than my java code?

Body:
I want to execute a select query and be able to get the count of the results, without using "COUNT(*)", like TOAD does. The concept is to give the option to the user to input any 'select query' he wants and to count the number of the results for him.

try {
   selectStatement = globalConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
   ResultSet selectResultSet = selectStatement.executeQuery(selectStatementString);
   selectResultSet.last();
   int countOfResults = selectResultSet.getRow();
   writeInLabel(kllStatusLabel, "Count Finished: Found " + countOfResults + " Inserts");
} catch (SQLException ex) {
   writeInLabel(kllStatusLabel, "Error executing select query.");
}

This code delays much in line: "selectResultSet.last();".
TOAD does it with much less delay. (Right-Click -> Record Count).
Even when I scroll the results table all the way down in TOAD it does it faster.

How does TOAD get the record count?

OK I got it, I will use count(*) and have a second ResultSet to show my results.

ResultSet selectResultSet = selectStatement.executeQuery("select count(*) from (" + selectStatementString + ")");
int countOfResults = 0;
if (selectResultSet.next()){
   countOfResults = selectResultSet.getInt(1);
}


来源: stackexchange

问:
Checking a hash table if a key exists, otherwise default to something that exists and return that value
I have the following function which works great, but I would like to make sure that if the supplied zone does not exist, that it uses default zone key.

```<code>module.exports = (zone, key) => {

  const zones = {
    default: require('./default'),
    northeast: require('./northeast'),
    centralCoast: require('./centralCoast')
  };

  return zones[zone][key];
}
</code>```

Is there a cooler way to do this straight in the return statement?  Right now, I am just using a conditional check to check if I get anything but undefined and return that..

How can I check that the zone is one of the zones like northeast, centralCoast, etc but if someone passes western it would just return values for default

答:
You can use a simple ternary operator to achieve conditional logic in the return statement. You can also use an arrow function to omit having to specify explicit return:

```<code>module.exports = (zone, key) => zones[zone]
  ? zones[zone][key]
  : zones.default[key];
</code>```

I suggest to also move some of the static (non-changing code) outside of the function so it's not unnecessarily executed on each function call:

```<code>// move constants outside of the function because there's no need to recreate them on each function call
const zoneNames = ['default', 'northeast', 'centralCoast'];

// import the zones dynamically
// this way, adding new zones requires only adding a string to the array above
const zones = zoneNames.reduce((zones, zoneName) => {
  zones[zoneName] = require(zoneName);
  return zones;
}, {});

module.exports = (zone, key) => zones[zone]
  ? zones[zone][key]
  : zones.default[key];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following function which works great, but I would like to make sure that if the supplied zone does not exist, that it uses default zone key.

module.exports = (zone, key) => {

  const zones = {
    default: require('./default'),
    northeast: require('./northeast'),
    centralCoast: require('./centralCoast')
  };

  return zones[zone][key];
}

Is there a cooler way to do this straight in the return statement?  Right now, I am just using a conditional check to check if I get anything but undefined and return that..

How can I check that the zone is one of the zones like northeast, centralCoast, etc but if someone passes western it would just return values for default

Body:
You can use a simple ternary operator to achieve conditional logic in the return statement. You can also use an arrow function to omit having to specify explicit return:

module.exports = (zone, key) => zones[zone]
  ? zones[zone][key]
  : zones.default[key];

I suggest to also move some of the static (non-changing code) outside of the function so it's not unnecessarily executed on each function call:

// move constants outside of the function because there's no need to recreate them on each function call
const zoneNames = ['default', 'northeast', 'centralCoast'];

// import the zones dynamically
// this way, adding new zones requires only adding a string to the array above
const zones = zoneNames.reduce((zones, zoneName) => {
  zones[zoneName] = require(zoneName);
  return zones;
}, {});

module.exports = (zone, key) => zones[zone]
  ? zones[zone][key]
  : zones.default[key];


问:
Bitwise complement operator
Can you guys please explain the below program

```<code>int main()
{
 int max = ~0;
 printf("%d\n",max);
 return 0;
}
</code>```

AFAIK ~ will flip the bits. In this case i.e ~0 will set all the bits into 1. So max variable should contain MAX value but I am getting o/p as -1. So can anyone here please tell me why I am getting o/p as -1.

答:
This question was a long time ago, but for posterity's sake:

It might help you to see it better if you print ~0 as both int and hex as follows:

```<code>printf("compliment of zero %d\n", (~0));
printf("compliment of zero 0x%x\n", (~0));
</code>```

Output:

Compliment of zero -1

Compliment of zero 0xffffffff

Title: Bitwise complement operator

Body:
Can you guys please explain the below program

int main()
{
 int max = ~0;
 printf("%d\n",max);
 return 0;
}

AFAIK ~ will flip the bits. In this case i.e ~0 will set all the bits into 1. So max variable should contain MAX value but I am getting o/p as -1. So can anyone here please tell me why I am getting o/p as -1.

Body:
This question was a long time ago, but for posterity's sake:

It might help you to see it better if you print ~0 as both int and hex as follows:

printf("compliment of zero %d\n", (~0));
printf("compliment of zero 0x%x\n", (~0));

Output:

Compliment of zero -1

Compliment of zero 0xffffffff


问:
Import xlsx file into Python using xlrd
Trying to import a .xlsx file into Python. I've google and google. I had this code written and working for .csv but it needs to be for .xlsx files. So I basically pieced together and did a hail mary in hopes that it would work. Any and all help is greatly appreciated!

** Added my whole code and a snippet of the data file. I need it to import .xlsx and execute the data.

```<code>import xlrd

workbook = xlrd.open_workbook('GAT_US_PartReview_2017-06-23.xlsx')

worksheet = workbook.get_sheet(0, update_pos=True)

header = []
report_card = []

# Count Stmnts for Required Data
valid_count = 0
app_req_count = 0
intr_req_count = 0
oe_intr_req_count = 0
part_img_req_count = 0
upc_req_count = 0
unspsc_req_count = 0
msds_req_count = 0

# Count Stmts for Missing Data
missing_app_count = 0
missing_intr_count = 0
missing_oe_intr_count = 0
missing_mpcc_count = 0
missing_attr_values_count = 0
missing_part_img_count = 0
missing_upc_count = 0
missing_warr_text_count = 0
missing_warr_pdf_count = 0
missing_unspsc_count = 0
missing_msds_count = 0

for row_num, row in enumerate(worksheet):
    if row_num <= 4:
        #  print(row)  # Print out the header
        header.append([row[0], row[2]])
    else:
        hq_line, part_no, part_class, appl_req, appl_count, intr_req,
        intr_count, oe_intr_req, has_oe_intr, has_attr_editor,
        has_attr_values, part_img_req, has_part_img, has_mpcc, warr_req,
        has_warr_txt, has_warr_pdf, msds_req, has_msds, upc_req, has_upc,
        has_unspsc, attr_count, attrval_count, valid_part = row

    if valid_part == 'YES':
        valid_count += 1

        # Required Parts Count
        if appl_req == 'YES':
            app_req_count += 1
        if intr_req == 'YES':
            intr_req_count += 1
        if oe_intr_req == 'YES':
            oe_intr_req_count += 1
        if part_img_req == 'YES':
            part_img_req_count += 1
        if upc_req == 'YES':
            upc_req_count += 1
        if msds_req == 'YES':
            msds_req_count += 1

        # Missing Data Counts
        if appl_req == 'YES' and appl_count == '0':
            missing_app_count += 1
        if intr_req == 'YES' and intr_count == '0':
            missing_intr_count += 1
        if oe_intr_req == 'YES' and has_oe_intr == '0':
             missing_oe_intr_count += 1
        if has_mpcc == 'NO':
             missing_mpcc_count += 1
        if has_attr_values == 'NO':
            missing_attr_values_count += 1
        if has_part_img == 'NO':
            missing_part_img_count += 1
        if upc_req == 'YES' and has_upc == '0':
            missing_upc_count += 1
        if warr_req == 'YES' and has_warr_txt == 'NO':
            missing_warr_text_count += 1
        if warr_req == 'YES' and has_warr_pdf == 'NO':
            missing_warr_pdf_count += 1
        if has_unspsc == 'NO':
            missing_unspsc_count += 1
        if msds_req == 'YES' and has_msds == 'NO':
            missing_msds_count += 1

# Statements for Required Counts
valid_parts = ('Number of Valid Parts: ', '{:,}'.format(valid_count))
application_required = ('Application Records Required: ',
'{:,}'.format(app_req_count))
interchange_required = ('Interchange Records Required: ',
'{:,}'.format(intr_req_count))
oe_interchange_required = ('OE Interchange Records Required: ',
'{:,}'.format(oe_intr_req_count))
mpcc = ('MPCC Required: ', '{:,}'.format(valid_count))  # Every valid part
requires a MPCC
attributes = ('Attributes Required: ', '{:,}'.format(valid_count))  # Every
valid part requires attributes
image_required = ('Image Required: ', '{:,}'.format(part_img_req_count))
upc = ('UPC Requited: ', '{:,}'.format(upc_req_count))
warranties = ('Warranty Text/PDF Required: ', '{:,}'.format(valid_count))  #
Require warranty text/pdf on all parts
unspsc = ('UNSPSC Code Required: ', '{:,}'.format(valid_count))  # Require
UNSPSC Codes for all parts
msds = ('MSDS Required: ', '{:,}'.format(msds_req_count))

# Statements for Missing Counts
missing_applications = ('Missing Applications: ',
'{:,}'.format(missing_app_count))
missing_interchange = ('Missing Interchange: ',
'{:,}'.format(missing_intr_count))
missing_oe_interchange = ('Missing OE Interchange: ',
'{:,}'.format(missing_oe_intr_count))
missing_mpcc = ('Missing MPCC: ', '{:,}'.format(missing_mpcc_count))
missing_attributes = ('Missing Attributes: ',
'{:,}'.format(missing_attr_values_count))
missing_image = ('Missing Image: ', '{:,}'.format(missing_part_img_count))
missing_UPC = ('Missing UPC: ', '{:,}'.format(missing_upc_count))
missing_warranty_text = ('Missing Warranty Text: ',
'{:,}'.format(missing_warr_text_count))
missing_warranty_pdf = ('Missing Warranty PDF: ',
'{:,}'.format(missing_warr_pdf_count))
missing_unspsc = ('Missing UNSPSC Code: ',
'{:,}'.format(missing_unspsc_count))
missing_msds = ('Missing MSDS: ', '{:,}'.format(missing_msds_count))

# CSV Output
report_card.append(valid_parts)
report_card.append(application_required)
report_card.append(interchange_required)
report_card.append(oe_interchange_required)
report_card.append(mpcc)
report_card.append(attributes)
report_card.append(image_required)
report_card.append(upc)
report_card.append(warranties)
report_card.append(unspsc)
report_card.append(msds)
report_card.append(missing_applications)
report_card.append(missing_interchange)
report_card.append(missing_oe_interchange)
report_card.append(missing_mpcc)
report_card.append(missing_attributes)
report_card.append(missing_image)
report_card.append(missing_UPC)
report_card.append(missing_warranty_text)
report_card.append(missing_warranty_pdf)
report_card.append(missing_unspsc)
report_card.append(missing_msds)

for row in header:
    print(row)

for x in report_card:
    print(x)

with open('Report_Card.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(header)
    writer.writerows(report_card)
</code>```

CSV file:

```<code>Supplier Line:,,Gates Rubber - Denver (GAT),,,,,,,,,,,,,,,,,,,,,,
Summary:,,Parts HQ Abbr,,,,,,,,,,,,,,,,,,,,,,
ACCT No:,,40013586,,,,,,,,,,,,,,,,,,,,,,
RecCount:,,10221,,,,,,,,,,,,,,,,,,,,,,
Applicable Date:,,"June 14, 2017 (Wednesday)",,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,
HQ Line,Part No,Part Class,Appl Req,Appl Count ,Intr Req,Intr Count ,OE Intr Req,Has OE Intr,Has Attr Editor, Has Attr Values,Part IMG Req,Has Part IMG,Has MPCC,Warr Req,Has Warr TXT,Has Warr PDF,MSDS Req,Has MSDS,UPC Req,Has UPC,Has UNSPSC,Attr Count ,AttrVal Count ,Valid Part
GAT,'27210',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27211',O,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,14,YES
GAT,'27212',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27213',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27220',S,NO,0,YES,2,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,35,20,YES
GAT,'27221',S,NO,0,YES,2,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,35,20,YES
</code>```

答:
Since it's an Excel Workbook object and not just a .CSV file, your book object is made up of sheets. So first you have to grab a sheet you want to work with, then you need to get the rows by calling sheet.get_rows()

The code below should work, I tested it locally.

```<code>import xlrd

book = xlrd.open_workbook('GAT_US_PartReview_2017-06-23.xlsx')

header = []
report_card = []

# Count Stmnts for Required Data
valid_count = 0
app_req_count = 0
intr_req_count = 0

# Count Stmts for Missing Data
missing_app_count = 0
missing_intr_count = 0
missing_oe_intr_count = 0

sheet = book.sheets()[0]
for row_num, row in enumerate(sheet.get_rows()):
    if row_num <= 4:
        #  print(row)  # Print out the header
        header.append([row[0], row[2]])

print(header)
</code>```

Title: Import xlsx file into Python using xlrd

Body:
Trying to import a .xlsx file into Python. I've google and google. I had this code written and working for .csv but it needs to be for .xlsx files. So I basically pieced together and did a hail mary in hopes that it would work. Any and all help is greatly appreciated!

** Added my whole code and a snippet of the data file. I need it to import .xlsx and execute the data.

import xlrd

workbook = xlrd.open_workbook('GAT_US_PartReview_2017-06-23.xlsx')

worksheet = workbook.get_sheet(0, update_pos=True)

header = []
report_card = []

# Count Stmnts for Required Data
valid_count = 0
app_req_count = 0
intr_req_count = 0
oe_intr_req_count = 0
part_img_req_count = 0
upc_req_count = 0
unspsc_req_count = 0
msds_req_count = 0

# Count Stmts for Missing Data
missing_app_count = 0
missing_intr_count = 0
missing_oe_intr_count = 0
missing_mpcc_count = 0
missing_attr_values_count = 0
missing_part_img_count = 0
missing_upc_count = 0
missing_warr_text_count = 0
missing_warr_pdf_count = 0
missing_unspsc_count = 0
missing_msds_count = 0

for row_num, row in enumerate(worksheet):
    if row_num <= 4:
        #  print(row)  # Print out the header
        header.append([row[0], row[2]])
    else:
        hq_line, part_no, part_class, appl_req, appl_count, intr_req,
        intr_count, oe_intr_req, has_oe_intr, has_attr_editor,
        has_attr_values, part_img_req, has_part_img, has_mpcc, warr_req,
        has_warr_txt, has_warr_pdf, msds_req, has_msds, upc_req, has_upc,
        has_unspsc, attr_count, attrval_count, valid_part = row

    if valid_part == 'YES':
        valid_count += 1

        # Required Parts Count
        if appl_req == 'YES':
            app_req_count += 1
        if intr_req == 'YES':
            intr_req_count += 1
        if oe_intr_req == 'YES':
            oe_intr_req_count += 1
        if part_img_req == 'YES':
            part_img_req_count += 1
        if upc_req == 'YES':
            upc_req_count += 1
        if msds_req == 'YES':
            msds_req_count += 1

        # Missing Data Counts
        if appl_req == 'YES' and appl_count == '0':
            missing_app_count += 1
        if intr_req == 'YES' and intr_count == '0':
            missing_intr_count += 1
        if oe_intr_req == 'YES' and has_oe_intr == '0':
             missing_oe_intr_count += 1
        if has_mpcc == 'NO':
             missing_mpcc_count += 1
        if has_attr_values == 'NO':
            missing_attr_values_count += 1
        if has_part_img == 'NO':
            missing_part_img_count += 1
        if upc_req == 'YES' and has_upc == '0':
            missing_upc_count += 1
        if warr_req == 'YES' and has_warr_txt == 'NO':
            missing_warr_text_count += 1
        if warr_req == 'YES' and has_warr_pdf == 'NO':
            missing_warr_pdf_count += 1
        if has_unspsc == 'NO':
            missing_unspsc_count += 1
        if msds_req == 'YES' and has_msds == 'NO':
            missing_msds_count += 1

# Statements for Required Counts
valid_parts = ('Number of Valid Parts: ', '{:,}'.format(valid_count))
application_required = ('Application Records Required: ',
'{:,}'.format(app_req_count))
interchange_required = ('Interchange Records Required: ',
'{:,}'.format(intr_req_count))
oe_interchange_required = ('OE Interchange Records Required: ',
'{:,}'.format(oe_intr_req_count))
mpcc = ('MPCC Required: ', '{:,}'.format(valid_count))  # Every valid part
requires a MPCC
attributes = ('Attributes Required: ', '{:,}'.format(valid_count))  # Every
valid part requires attributes
image_required = ('Image Required: ', '{:,}'.format(part_img_req_count))
upc = ('UPC Requited: ', '{:,}'.format(upc_req_count))
warranties = ('Warranty Text/PDF Required: ', '{:,}'.format(valid_count))  #
Require warranty text/pdf on all parts
unspsc = ('UNSPSC Code Required: ', '{:,}'.format(valid_count))  # Require
UNSPSC Codes for all parts
msds = ('MSDS Required: ', '{:,}'.format(msds_req_count))

# Statements for Missing Counts
missing_applications = ('Missing Applications: ',
'{:,}'.format(missing_app_count))
missing_interchange = ('Missing Interchange: ',
'{:,}'.format(missing_intr_count))
missing_oe_interchange = ('Missing OE Interchange: ',
'{:,}'.format(missing_oe_intr_count))
missing_mpcc = ('Missing MPCC: ', '{:,}'.format(missing_mpcc_count))
missing_attributes = ('Missing Attributes: ',
'{:,}'.format(missing_attr_values_count))
missing_image = ('Missing Image: ', '{:,}'.format(missing_part_img_count))
missing_UPC = ('Missing UPC: ', '{:,}'.format(missing_upc_count))
missing_warranty_text = ('Missing Warranty Text: ',
'{:,}'.format(missing_warr_text_count))
missing_warranty_pdf = ('Missing Warranty PDF: ',
'{:,}'.format(missing_warr_pdf_count))
missing_unspsc = ('Missing UNSPSC Code: ',
'{:,}'.format(missing_unspsc_count))
missing_msds = ('Missing MSDS: ', '{:,}'.format(missing_msds_count))

# CSV Output
report_card.append(valid_parts)
report_card.append(application_required)
report_card.append(interchange_required)
report_card.append(oe_interchange_required)
report_card.append(mpcc)
report_card.append(attributes)
report_card.append(image_required)
report_card.append(upc)
report_card.append(warranties)
report_card.append(unspsc)
report_card.append(msds)
report_card.append(missing_applications)
report_card.append(missing_interchange)
report_card.append(missing_oe_interchange)
report_card.append(missing_mpcc)
report_card.append(missing_attributes)
report_card.append(missing_image)
report_card.append(missing_UPC)
report_card.append(missing_warranty_text)
report_card.append(missing_warranty_pdf)
report_card.append(missing_unspsc)
report_card.append(missing_msds)

for row in header:
    print(row)

for x in report_card:
    print(x)

with open('Report_Card.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(header)
    writer.writerows(report_card)

CSV file:

Supplier Line:,,Gates Rubber - Denver (GAT),,,,,,,,,,,,,,,,,,,,,,
Summary:,,Parts HQ Abbr,,,,,,,,,,,,,,,,,,,,,,
ACCT No:,,40013586,,,,,,,,,,,,,,,,,,,,,,
RecCount:,,10221,,,,,,,,,,,,,,,,,,,,,,
Applicable Date:,,"June 14, 2017 (Wednesday)",,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,
HQ Line,Part No,Part Class,Appl Req,Appl Count ,Intr Req,Intr Count ,OE Intr Req,Has OE Intr,Has Attr Editor, Has Attr Values,Part IMG Req,Has Part IMG,Has MPCC,Warr Req,Has Warr TXT,Has Warr PDF,MSDS Req,Has MSDS,UPC Req,Has UPC,Has UNSPSC,Attr Count ,AttrVal Count ,Valid Part
GAT,'27210',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27211',O,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,14,YES
GAT,'27212',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27213',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27220',S,NO,0,YES,2,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,35,20,YES
GAT,'27221',S,NO,0,YES,2,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,35,20,YES

Body:
Since it's an Excel Workbook object and not just a .CSV file, your book object is made up of sheets. So first you have to grab a sheet you want to work with, then you need to get the rows by calling sheet.get_rows()

The code below should work, I tested it locally.

import xlrd

book = xlrd.open_workbook('GAT_US_PartReview_2017-06-23.xlsx')

header = []
report_card = []

# Count Stmnts for Required Data
valid_count = 0
app_req_count = 0
intr_req_count = 0

# Count Stmts for Missing Data
missing_app_count = 0
missing_intr_count = 0
missing_oe_intr_count = 0

sheet = book.sheets()[0]
for row_num, row in enumerate(sheet.get_rows()):
    if row_num <= 4:
        #  print(row)  # Print out the header
        header.append([row[0], row[2]])

print(header)


问:
Return only the item with 10th total Sale
I need to write a query that ONLY returns the item which has the 10th totalSale value. I know that I can use TOP to get the first 10items, but I want it to only show the 10th item. Here is the query that I have written:

```<code>SELECT TOP 10 D_I.ID, SUM(F_S.Sale) AS TOTALSALE
FROM Dim_ItemsD_I JOIN FCT_Sales F_S ON D_I.ID = F_S.ID
GROUP BY D_I.ID
</code>```

Please help! thank you

答:
You need to use a subquery. Order the first 10 items in descending order then select the first item:

```<code> select top 1 ITEM, TOTALSALE
 from
    (select top 10 D_I.ITEM, SUM(F_S.Sale) as TOTALSALE
     from Dim_Items D_I
     join FCT_Sales F_S on D_I.ID = F_S.Item_ID
     group by D_I.Item
     order by TOTALSALE DESC) T
</code>```

Check here for a simplified example: http://rextester.com/live/SAOQ22288

Body:
I need to write a query that ONLY returns the item which has the 10th totalSale value. I know that I can use TOP to get the first 10items, but I want it to only show the 10th item. Here is the query that I have written:

SELECT TOP 10 D_I.ID, SUM(F_S.Sale) AS TOTALSALE
FROM Dim_ItemsD_I JOIN FCT_Sales F_S ON D_I.ID = F_S.ID
GROUP BY D_I.ID

Please help! thank you

Body:
You need to use a subquery. Order the first 10 items in descending order then select the first item:

 select top 1 ITEM, TOTALSALE
 from
    (select top 10 D_I.ITEM, SUM(F_S.Sale) as TOTALSALE
     from Dim_Items D_I
     join FCT_Sales F_S on D_I.ID = F_S.Item_ID
     group by D_I.Item
     order by TOTALSALE DESC) T

Check here for a simplified example: http://rextester.com/live/SAOQ22288


问:
How to convert delimited string into multi-dimensional array with associative keys?
Can anyone help with this regular expression please?

Here's an example string I'm trying to convert into php array.

$str="hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported"

And I need the final aray to be:

```<code>$filters = array (
    "hopOptions"  => array("hops", "salmonSafe"),
    "region"      => array("domestic", "specialty", "imported")
);
</code>```

Any help or direction will be greatly appreciated!

答:
Faster is to avoid regex and use two explode calls:

Demo

Code:

```<code>$str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported";
foreach(explode(' ',$str) as $pair){
    $x=explode(':',$pair);
    $result[$x[0]][]=$x[1];
}
var_export($result);
</code>```

Or with regex...

PHP Demo

Code:

```<code>$str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported";
if(preg_match_all('/([^ ]+):([^ ]+)/',$str,$out)){
    foreach($out[1] as $i=>$v){
        $result[$v][]=$out[2][$i];
    }
    var_export($result);
}else{
    echo "no matches";
}
</code>```

Body:
Can anyone help with this regular expression please?

Here's an example string I'm trying to convert into php array.

$str="hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported"

And I need the final aray to be:

$filters = array (
    "hopOptions"  => array("hops", "salmonSafe"),
    "region"      => array("domestic", "specialty", "imported")
);

Any help or direction will be greatly appreciated!

Body:
Faster is to avoid regex and use two explode calls:

Demo

Code:

$str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported";
foreach(explode(' ',$str) as $pair){
    $x=explode(':',$pair);
    $result[$x[0]][]=$x[1];
}
var_export($result);

Or with regex...

PHP Demo

Code:

$str = "hopOptions:hops hopOptions:salmonSafe region:domestic region:specialty region:imported";
if(preg_match_all('/([^ ]+):([^ ]+)/',$str,$out)){
    foreach($out[1] as $i=>$v){
        $result[$v][]=$out[2][$i];
    }
    var_export($result);
}else{
    echo "no matches";
}


问:
Constants Table Design MySQL Best Practice
I need to store a set of 'weight' constants, that will change periodically, which are to be used within some calculations. Which of the following is the better table design, or neither!

This is what I need to store:

```<code>Month Weight (%)
Jan 5
Feb 5
Mar 10
Apr 10
May 10
Jun 10
Jul 10
Aug 10
Sep 10
Oct 10
Nov 5
Dec 5
</code>```

A table with 1 row and 12 columns:

```<code>CREATE TABLE IF NOT EXISTS `constant_month` (
  `month_01` DECIMAL(5,2) NOT NULL,
  `month_02` DECIMAL(5,2) NOT NULL,
  `month_03` DECIMAL(5,2) NOT NULL,
  `month_04` DECIMAL(5,2) NOT NULL,
  `month_05` DECIMAL(5,2) NOT NULL,
  `month_06` DECIMAL(5,2) NOT NULL,
  `month_07` DECIMAL(5,2) NOT NULL,
  `month_08` DECIMAL(5,2) NOT NULL,
  `month_09` DECIMAL(5,2) NOT NULL,
  `month_10` DECIMAL(5,2) NOT NULL,
  `month_11` DECIMAL(5,2) NOT NULL,
  `month_12` DECIMAL(5,2) NOT NULL)
ENGINE = InnoDB
</code>```

A table with 12 rows and 6 columns:

```<code>CREATE TABLE `constant_month` (
  `constant_month_id` int(11) NOT NULL,
  `create_date` datetime NOT NULL,
  `modified_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `number` int(11) NOT NULL,
  `name` varchar(25) NOT NULL,
  `weight` decimal(5,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

The second option allows for more info but it isn't necessarily required.

Expanding this question what happens if the constants I need to store are different data types? In this case they are all percentages but I have another constants table which requires mixed data types. Is option 1 better where I can set the data type specifically for each constant (a mix of INT, DECIMAL and FLOAT) or use option 2 with a generic TEXT data type?

Thanks

答:
"generic TEXT data type" -- bad, especially if you need to compare numeric values.

Splaying an array across columns -- bad.  (The 1-row 12-col approach).

Do you need all 6 columns in your 12x6 approach?

Body:
I need to store a set of 'weight' constants, that will change periodically, which are to be used within some calculations. Which of the following is the better table design, or neither!

This is what I need to store:

Month Weight (%)
Jan 5
Feb 5
Mar 10
Apr 10
May 10
Jun 10
Jul 10
Aug 10
Sep 10
Oct 10
Nov 5
Dec 5

A table with 1 row and 12 columns:

CREATE TABLE IF NOT EXISTS `constant_month` (
  `month_01` DECIMAL(5,2) NOT NULL,
  `month_02` DECIMAL(5,2) NOT NULL,
  `month_03` DECIMAL(5,2) NOT NULL,
  `month_04` DECIMAL(5,2) NOT NULL,
  `month_05` DECIMAL(5,2) NOT NULL,
  `month_06` DECIMAL(5,2) NOT NULL,
  `month_07` DECIMAL(5,2) NOT NULL,
  `month_08` DECIMAL(5,2) NOT NULL,
  `month_09` DECIMAL(5,2) NOT NULL,
  `month_10` DECIMAL(5,2) NOT NULL,
  `month_11` DECIMAL(5,2) NOT NULL,
  `month_12` DECIMAL(5,2) NOT NULL)
ENGINE = InnoDB

A table with 12 rows and 6 columns:

CREATE TABLE `constant_month` (
  `constant_month_id` int(11) NOT NULL,
  `create_date` datetime NOT NULL,
  `modified_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `number` int(11) NOT NULL,
  `name` varchar(25) NOT NULL,
  `weight` decimal(5,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The second option allows for more info but it isn't necessarily required.

Expanding this question what happens if the constants I need to store are different data types? In this case they are all percentages but I have another constants table which requires mixed data types. Is option 1 better where I can set the data type specifically for each constant (a mix of INT, DECIMAL and FLOAT) or use option 2 with a generic TEXT data type?

Thanks


问:
How to do case insensitive search in Vim
I'd like to search for an upper case word, for example COPYRIGHT in a file. I tried performing a search like:

```<code>/copyright/i    # Doesn't work
</code>```

but it doesn't work.  I know that in Perl, if I give the i flag into a regex it will turn the regex into a case-insensitive regex. It seems that Vim  has its own way to indicate a case-insensitive regex.

答:
You can set ignorecase by default, run this in shell

```<code>echo "set ic" >> ~/.vimrc
</code>```

Body:
I'd like to search for an upper case word, for example COPYRIGHT in a file. I tried performing a search like:

/copyright/i    # Doesn't work

but it doesn't work.  I know that in Perl, if I give the i flag into a regex it will turn the regex into a case-insensitive regex. It seems that Vim  has its own way to indicate a case-insensitive regex.

Body:
You can set ignorecase by default, run this in shell

echo "set ic" >> ~/.vimrc


问:
How to use Android RXJava to chain linked Retrofit calls and return new Object model
So the scenario is one where we need to make 2 retrofit calls,

```<code> @GET("/")
Observable<Search> searchMovies(@Query("apikey") String apiKey, @Query("s") String searchKey);

@GET("/")
Observable<Details> getMovie(@Query("apikey") String apiKey, @Query("t") String searchKey);
</code>```

the first one is to get a list and then for each item in that list we will make a new call in order to get further information about that movie.

So the first question I have is how can I chain these 2 calls together inside ond rxjava method ?

The second question that i have follows up from this one in that I want to chain these 2 calls together inside and Rxjava method but then return a new observable pojo object based upon a few fields from each of the response. So for example say that request 1 contains "Name" and then request 2 contains "plot". I want to compose what would be a list of MovieInformation pojo objects based on these 2 fields and wrap that into an observable.

答:
You should use flatMap operator to chain these two calls.

Normally getMovie() should take in parameteres the result of searchMovies(). I suppose that apiKey,searchKey are the result of getMovies(apikey,searchKey) :

```<code>yourretrofitservice.searchMovies(apikey,searchKey)

                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                //waiting for response of yourretrofitservice.searchMovies()

                .flatMap(new Func1<Search, Observable<Details>>() {

                    @Override
                    public Observable<Details> call(Search search_result) {

                        return yourretrofitservice.searchMovies(apiKey, searchKey); //maybe searchKey = search_result (you should define how to set the result of the First Retrofit call in the second call

                    }

                })

                //waiting for the response  of yourretrofitservice.getMovie()

                .flatMap(new Func1<Search, Observable<YourPojoClass>>() {

                    @Override
                    public Observable<YourPojoClass> call(Search search_result) {
                        //do something with pojo_object
                        return pojo_object; second call

                    }

                })

                .subscribe(new Action1<YourPojoClass>() {

                    @Override
                    public void call(YourPojoClass  pojo_object) {
                        //Your final action
                    }

                });
</code>```

FlatMap operator : http://reactivex.io/documentation/operators/flatmap.html

Body:
So the scenario is one where we need to make 2 retrofit calls,

 @GET("/")
Observable<Search> searchMovies(@Query("apikey") String apiKey, @Query("s") String searchKey);

@GET("/")
Observable getMovie(@Query("apikey") String apiKey, @Query("t") String searchKey);

the first one is to get a list and then for each item in that list we will make a new call in order to get further information about that movie.

So the first question I have is how can I chain these 2 calls together inside ond rxjava method ?

The second question that i have follows up from this one in that I want to chain these 2 calls together inside and Rxjava method but then return a new observable pojo object based upon a few fields from each of the response. So for example say that request 1 contains "Name" and then request 2 contains "plot". I want to compose what would be a list of MovieInformation pojo objects based on these 2 fields and wrap that into an observable.

Body:
You should use flatMap operator to chain these two calls.

Normally getMovie() should take in parameteres the result of searchMovies(). I suppose that apiKey,searchKey are the result of getMovies(apikey,searchKey) :

yourretrofitservice.searchMovies(apikey,searchKey)

                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                //waiting for response of yourretrofitservice.searchMovies()

                .flatMap(new Func1<Search, Observable<Details>>() {

                    @Override
                    public Observable<Details> call(Search search_result) {

                        return yourretrofitservice.searchMovies(apiKey, searchKey); //maybe searchKey = search_result (you should define how to set the result of the First Retrofit call in the second call

                    }

                })

                //waiting for the response  of yourretrofitservice.getMovie()

                .flatMap(new Func1<Search, Observable<YourPojoClass>>() {

                    @Override
                    public Observable<YourPojoClass> call(Search search_result) {
                        //do something with pojo_object
                        return pojo_object; second call

                    }

                })

                .subscribe(new Action1<YourPojoClass>() {

                    @Override
                    public void call(YourPojoClass  pojo_object) {
                        //Your final action
                    }

                });

FlatMap operator : http://reactivex.io/documentation/operators/flatmap.html


问:
align button text and other ion-col text to bottom in ionic 2
my code looks like:

```<code><ion-row><ion-col ><button ion-button outline no-padding  large (click)="setUserName()">D</button>ay in the life </ion-col></ion-row>
</code>```

this looks ugly as the letter D goes in the middle and overall col text a bit above.

all i want is everything bottom aligned.

答:
What's happen?

.row {
  display: flex;
  flex-wrap: wrap;
}

.col {
  position: relative;
  width: 100%;
  margin: 0;
  min-height: 1px;
  -webkit-flex-basis: 0;
  -ms-flex-preferred-size: 0;
  flex-basis: 0;
  -webkit-flex-grow: 1;
  -ms-flex-positive: 1;
  flex-grow: 1;
  max-width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-row class='row'>
  <ion-col class='col'><button ion-button outline no-padding large (click)="setUserName()">D</button>ay in the life </ion-col>
</ion-row></code>```

Body:
my code looks like:

<ion-row><ion-col ><button ion-button outline no-padding  large (click)="setUserName()">D</button>ay in the life </ion-col></ion-row>

this looks ugly as the letter D goes in the middle and overall col text a bit above.

all i want is everything bottom aligned.

Body:
What's happen?

.row {
  display: flex;
  flex-wrap: wrap;
}

.col {
  position: relative;
  width: 100%;
  margin: 0;
  min-height: 1px;
  -webkit-flex-basis: 0;
  -ms-flex-preferred-size: 0;
  flex-basis: 0;
  -webkit-flex-grow: 1;
  -ms-flex-positive: 1;
  flex-grow: 1;
  max-width: 100%;
}

<ion-row class='row'>
  <ion-col class='col'><button ion-button outline no-padding large (click)="setUserName()">D</button>ay in the life </ion-col>
</ion-row>


问:
how to access remote computer windows service using asp.net
how to access remote computer windows service using asp.net </p>

答:
One easy way is to open a dos command from inside asp.net and call the net command,
for example starting the service by call "net start ServiceName"

Code

How to run interactive command shell or bath files from asp.net

ContentLicense: CC BY-SA 2.5


问:
State management in ext js?
I am trying to use this following code in my application to retain the current state of my application even after it is refreshed.

```<code>Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
</code>```

But after executing above code, It's not working for me.

Kindly suggest any way to do this as, I am new to ExtJs

Thanks.

答:
You need to define this in the Launch function of your application or init of controller. Its critical to use expires when using state provider.

```<code>init : function() {
        Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
            expires : new Date(Ext.Date.now() + (1000*60*60*24*90)) // 90 days
        }));
    }
</code>```

Then based on what components state you are trying to save set its stateful property to true, alternatively giving it a stateId.

Below is example to save state of grid:

```<code>Ext.define('MyApp.view.Users', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.users_grid',
    title: 'Users',
    stateful:true,
    stateId:'users_grid_stid',
    store:{
        data:[
            {
                first_name:'Joe',
                last_name:'Blogs'
            }
        ]
    },
    columns: {
        items: [
            {
                xtype: 'gridcolumn',
                dataIndex: 'first_name',
                text: 'First Name',
                width: 200
            },
            {
                xtype: 'gridcolumn',
                dataIndex: 'last_name',
                text: 'Last Name',
                width: 200
            }
        ]
    }
});
</code>```

You can test this by modifying the width of one of the columns on this grid and then that column will be hold the modified width when you next load the page, even after browser restart.
 Check F12 Console -> Application Cookies for saved component states.

Title: State management in ext js?

Body:
I am trying to use this following code in my application to retain the current state of my application even after it is refreshed.

Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

But after executing above code, It's not working for me.

Kindly suggest any way to do this as, I am new to ExtJs

Thanks.

Body:
You need to define this in the Launch function of your application or init of controller. Its critical to use expires when using state provider.

init : function() {
        Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
            expires : new Date(Ext.Date.now() + (1000*60*60*24*90)) // 90 days
        }));
    }

Then based on what components state you are trying to save set its stateful property to true, alternatively giving it a stateId.

Below is example to save state of grid:

Ext.define('MyApp.view.Users', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.users_grid',
    title: 'Users',
    stateful:true,
    stateId:'users_grid_stid',
    store:{
        data:[
            {
                first_name:'Joe',
                last_name:'Blogs'
            }
        ]
    },
    columns: {
        items: [
            {
                xtype: 'gridcolumn',
                dataIndex: 'first_name',
                text: 'First Name',
                width: 200
            },
            {
                xtype: 'gridcolumn',
                dataIndex: 'last_name',
                text: 'Last Name',
                width: 200
            }
        ]
    }
});

You can test this by modifying the width of one of the columns on this grid and then that column will be hold the modified width when you next load the page, even after browser restart.
 Check F12 Console -> Application Cookies for saved component states.


答:
You could use ROW_NUMBER here:

```<code>SELECT t.ID, t.TOTALSALE
FROM
(
    SELECT
        D_I.ID,
        SUM(F_S.Sale) AS TOTALSALE,
        ROW_NUMBER() OVER (ORDER BY SUM(F_S.Sale) DESC) rn
    FROM Dim_Items D_I
    JOIN FCT_Sales F_S
        ON D_I.ID = F_S.ID
    GROUP BY D_I.ID
) t
WHERE t.rn = 10;
</code>```

Title: Return only the item with 10th total Sale

Body:
You could use ROW_NUMBER here:

SELECT t.ID, t.TOTALSALE
FROM
(
    SELECT
        D_I.ID,
        SUM(F_S.Sale) AS TOTALSALE,
        ROW_NUMBER() OVER (ORDER BY SUM(F_S.Sale) DESC) rn
    FROM Dim_Items D_I
    JOIN FCT_Sales F_S
        ON D_I.ID = F_S.ID
    GROUP BY D_I.ID
) t
WHERE t.rn = 10;


问:
Force ask authorization onOpen() (force popup)
SUMMARY: Is it possible to ask for authorization onOpen()?

DETAILED VERSION:
I have a spreadsheet with buttons that gets distributed to a lot of people.
When any button is pressed, some functions that require permissions are called, so Google Apps Script shows this popup:

AFTER this is accepted, everything runs well, since it has authorization now. However, I want to run things that require permissions BEFORE a button is pushed, when the Workbook is opened. However, if you place authorization-requiring code into an onEdit or onOpen function, it runs with no privileges by default and crashes halfway, rather than showing the popup and asking for permissions.

Here is some code that exemplifies this - crashing instead of asking for permissions to create a trigger (also works for CalendarApp, etc.):

```<code>function onOpen(e) {
  Browser.msgBox("This is shown to the user");
  try {
    ScriptApp.newTrigger('someFunction').forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onEdit().create();
  }
  catch (e) {
    Browser.msgBox(e);
  }
  Browser.msgBox("This message is never shown to the user if there is no try catch because it crashes");
}
</code>```

答:
Note:  A simple trigger cannot access services that require authorization. For example, a simple trigger cannot send an email because the Gmail service requires authorization

onOpen() is a reserved function name for a function that is a simple trigger.

There is a way to check the authorization status, and then get the authorization URL if the code needs to be authorized.  However, if the ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL) method needs authorization by the user, then it won't work when run from onOpen()

The onOpen method can not open a sidebar, so the authorization status can't be checked from the onOpen trigger.  The user would need to click a menu item that opened the sidebar or a dialog box first.

I'm not sure that the code 'ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL)` works that well.  To force a re-authorization prompt, you may need to run code that would cause the scopes to be evaluated.

Code.gs

```<code>function onOpen() {
  //Create custom menu or add-on menu
}

function showSidebar() {
  var html = HtmlService.createTemplateFromFile('HTML_Sidebar').evaluate()
      .setTitle('Log Tools')
      .setWidth(300);
  SpreadsheetApp.getUi()
      .showSidebar(html);
}
</code>```

HTML_Sidebar

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_blank">
  </head>
  <body>

    <div><?!= getAuthUrl(); ?></div>
  </body>

</html>
</code>```

GS_Sidebar

```<code>function getAuthUrl() {
  var authInfo,msg;

  authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);

  msg = 'This spreadsheet needs permission to use Apps Script Services.  Click ' +
    'this url to authorize: <br><br>' +
      '<a href="' + authInfo.getAuthorizationUrl() +
      '">Link to Authorization Dialog</a>' +
      '<br><br> This spreadsheet needs to either ' +
      'be authorized or re-authorized.';

  //return msg;//Use this for testing

  //ScriptApp.AuthMode.FULL is the auth mode to check for since no other authorization mode requires
  //that users grant authorization
  if (authInfo.getAuthorizationStatus() === ScriptApp.AuthorizationStatus.REQUIRED) {
    return msg;
  } else {
    return "No Authorization needed";
  }
}
</code>```

Body:
SUMMARY: Is it possible to ask for authorization onOpen()?

DETAILED VERSION:
I have a spreadsheet with buttons that gets distributed to a lot of people.
When any button is pressed, some functions that require permissions are called, so Google Apps Script shows this popup:

AFTER this is accepted, everything runs well, since it has authorization now. However, I want to run things that require permissions BEFORE a button is pushed, when the Workbook is opened. However, if you place authorization-requiring code into an onEdit or onOpen function, it runs with no privileges by default and crashes halfway, rather than showing the popup and asking for permissions.

Here is some code that exemplifies this - crashing instead of asking for permissions to create a trigger (also works for CalendarApp, etc.):

function onOpen(e) {
  Browser.msgBox("This is shown to the user");
  try {
    ScriptApp.newTrigger('someFunction').forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onEdit().create();
  }
  catch (e) {
    Browser.msgBox(e);
  }
  Browser.msgBox("This message is never shown to the user if there is no try catch because it crashes");
}

Body:
Note:  A simple trigger cannot access services that require authorization. For example, a simple trigger cannot send an email because the Gmail service requires authorization

onOpen() is a reserved function name for a function that is a simple trigger.

There is a way to check the authorization status, and then get the authorization URL if the code needs to be authorized.  However, if the ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL) method needs authorization by the user, then it won't work when run from onOpen()

The onOpen method can not open a sidebar, so the authorization status can't be checked from the onOpen trigger.  The user would need to click a menu item that opened the sidebar or a dialog box first.

I'm not sure that the code 'ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL)` works that well.  To force a re-authorization prompt, you may need to run code that would cause the scopes to be evaluated.

Code.gs

function onOpen() {
  //Create custom menu or add-on menu
}

function showSidebar() {
  var html = HtmlService.createTemplateFromFile('HTML_Sidebar').evaluate()
      .setTitle('Log Tools')
      .setWidth(300);
  SpreadsheetApp.getUi()
      .showSidebar(html);
}

HTML_Sidebar

<!DOCTYPE html>
<html>
  <head>
    <base target="_blank">
  </head>
  <body>

    <div><?!= getAuthUrl(); ?></div>
  </body>

</html>

GS_Sidebar

function getAuthUrl() {
  var authInfo,msg;

  authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);

  msg = 'This spreadsheet needs permission to use Apps Script Services.  Click ' +
    'this url to authorize: <br><br>' +
      '<a href="' + authInfo.getAuthorizationUrl() +
      '">Link to Authorization Dialog</a>' +
      '<br><br> This spreadsheet needs to either ' +
      'be authorized or re-authorized.';

  //return msg;//Use this for testing

  //ScriptApp.AuthMode.FULL is the auth mode to check for since no other authorization mode requires
  //that users grant authorization
  if (authInfo.getAuthorizationStatus() === ScriptApp.AuthorizationStatus.REQUIRED) {
    return msg;
  } else {
    return "No Authorization needed";
  }
}

ContentLicense: CC BY-SA 4.0


问:
Why is my prepareForSegue method not being called?
When I press the back button in this navigation controller, I want to send the state of the switches to variables in a different View Controller. However, the prepareForSegue method is not being called. How do I fix this?

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("here")
    let secondViewController:ViewController2 = segue.destination as! ViewController2

    if undoSwitch.isOn {
        secondViewController.undoControls[0] = true
    }
    else {
     secondViewController.undoControls[0] = false
    }
}
</code>```

答:
The back button is different from segue. If you want to reload the undoSwitch when going back from the current view controller. One of the ways is to use a static global variable. Something like

```<code>class AppVar {
    static var controlState = true
}
</code>```

Update your AppVar.controlState where you need and add this

```<code>if AppVar.controlState {
    secondViewController.undoControls[0] = true
}
else {
     secondViewController.undoControls[0] = false
}
</code>```

to viewWillAppear of the ViewController2 as the ViewController2 was retained and stored in stack. When you navigate back to it, the viewWillAppear will be called.

Body:
When I press the back button in this navigation controller, I want to send the state of the switches to variables in a different View Controller. However, the prepareForSegue method is not being called. How do I fix this?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("here")
    let secondViewController:ViewController2 = segue.destination as! ViewController2

    if undoSwitch.isOn {
        secondViewController.undoControls[0] = true
    }
    else {
     secondViewController.undoControls[0] = false
    }
}

Body:
The back button is different from segue. If you want to reload the undoSwitch when going back from the current view controller. One of the ways is to use a static global variable. Something like

class AppVar {
    static var controlState = true
}

Update your AppVar.controlState where you need and add this

if AppVar.controlState {
    secondViewController.undoControls[0] = true
}
else {
     secondViewController.undoControls[0] = false
}

to viewWillAppear of the ViewController2 as the ViewController2 was retained and stored in stack. When you navigate back to it, the viewWillAppear will be called.


问:
Laravel how to get the average of two result values
So I have a query that return all the stats of a player from their last season and current season. What I want to do is get the average of a player from last season and current season and make in to a one object only. Below is my query and sample result.

Query

```<code>public static function getAllTimeLeaders($request) {
        $competitionIds = self::getLasTwoSeason();
        $data = DB::table('leader_board_stats as lbs')
            ->select([
                'sGamesStarted',
                'sMinutesAverage',
                'sPointsAverage',
                'sFieldGoalsMadeAverage',
                'sFieldGoalsAttemptedAverage',
                'sFieldGoalsPercentage',
                'sTwoPointersMadeAverage',
                'sTwoPointersAttemptedAverage',
                'sThreePointersMadeAverage',
                'sThreePointersAttemptedAverage',
                'sThreePointersPercentage',
                'sFreeThrowsMadeAverage',
                'sFreeThrowsAttemptedAverage',
                'sReboundsTotalAverage',
                'sAssistsAverage',
                'sStealsAverage',
                'sBlocksAverage',
                'sTurnoversAverage',
                'sFoulsPersonalAverage',
                'firstName',
                'familyName',
                'personId',
                'teamId',
                'competitionId'
            ])
            ->where('lbs.periodNumber', '0')
            ->whereIn('lbs.competitionId', [$competitionIds[0]->competitionId, $competitionIds[1]->competitionId])
            ->get();
        echo '```';
        var_dump($data);
    }
```

<p><strong>Sample of returned value</strong></p>

```[
    [0]=> object(stdClass)#262 (24) {
      ["sGamesStarted"]=>
      int(6)
      ["sMinutesAverage"]=>
      float(17.66)
      ["sPointsAverage"]=>
      float(7.71)
      ["sFieldGoalsMadeAverage"]=>
      float(2.59)
      ["sFieldGoalsAttemptedAverage"]=>
      float(5.62)
      ["sFieldGoalsPercentage"]=>
      float(0.46)
      ["sTwoPointersMadeAverage"]=>
      float(1.47)
      ["sTwoPointersAttemptedAverage"]=>
      float(2.53)
      ["sThreePointersMadeAverage"]=>
      float(1.12)
      ["sThreePointersAttemptedAverage"]=>
      float(3.09)
      ["sThreePointersPercentage"]=>
      float(0.36)
      ["sFreeThrowsMadeAverage"]=>
      float(1.41)
      ["sFreeThrowsAttemptedAverage"]=>
      float(1.76)
      ["sReboundsTotalAverage"]=>
      float(2.85)
      ["sAssistsAverage"]=>
      float(1.71)
      ["sStealsAverage"]=>
      float(0.68)
      ["sBlocksAverage"]=>
      float(0.21)
      ["sTurnoversAverage"]=>
      float(0.91)
      ["sFoulsPersonalAverage"]=>
      float(2.35)
      ["firstName"]=>
      string(3) "Person1"
      ["familyName"]=>
      string(8) "Familyname"
      ["personId"]=>
      int(28831)
      ["teamId"]=>
      int(3749)
      ["competitionId"]=>
      int(9224)
    },
    [88]=> object(stdClass)#527 (24) {
      ["sGamesStarted"]=>
      int(11)
      ["sMinutesAverage"]=>
      float(23.28)
      ["sPointsAverage"]=>
      float(9.5)
      ["sFieldGoalsMadeAverage"]=>
      float(3.07)
      ["sFieldGoalsAttemptedAverage"]=>
      float(7.97)
      ["sFieldGoalsPercentage"]=>
      float(0.38)
      ["sTwoPointersMadeAverage"]=>
      float(1.4)
      ["sTwoPointersAttemptedAverage"]=>
      float(3.47)
      ["sThreePointersMadeAverage"]=>
      float(1.67)
      ["sThreePointersAttemptedAverage"]=>
      float(4.5)
      ["sThreePointersPercentage"]=>
      float(0.37)
      ["sFreeThrowsMadeAverage"]=>
      float(1.7)
      ["sFreeThrowsAttemptedAverage"]=>
      float(2.2)
      ["sReboundsTotalAverage"]=>
      float(3.57)
      ["sAssistsAverage"]=>
      float(1.43)
      ["sStealsAverage"]=>
      float(0.93)
      ["sBlocksAverage"]=>
      float(0.23)
      ["sTurnoversAverage"]=>
      float(0.97)
      ["sFoulsPersonalAverage"]=>
      float(2.77)
      ["firstName"]=>
      string(3) "Person1"
      ["familyName"]=>
      string(8) "Familyname"
      ["personId"]=>
      int(28831)
      ["teamId"]=>
      int(3749)
      ["competitionId"]=>
      int(2254)
    }
]
```

答:
Finally I figured it out I just need to use DB::raw and AVG of each stats fields then group it by personId.</p>

```<code>public static function getAllTimeLeaders($request) {
        $competitionIds = self::getLasTwoSeason();
        $data = DB::table('leader_board_stats as lbs')
            ->select([
                DB::raw('AVG(sGamesStarted)'),
                DB::raw('AVG(sMinutesAverage)'),
                DB::raw('AVG(sPointsAverage)'),
                DB::raw('AVG(sFieldGoalsMadeAverage)'),
                DB::raw('AVG(sFieldGoalsAttemptedAverage)'),
                DB::raw('AVG(sFieldGoalsPercentage)'),
                DB::raw('AVG(sTwoPointersMadeAverage)'),
                DB::raw('AVG(sTwoPointersAttemptedAverage)'),
                DB::raw('AVG(sThreePointersMadeAverage)'),
                DB::raw('AVG(sThreePointersAttemptedAverage)'),
                DB::raw('AVG(sThreePointersPercentage)'),
                DB::raw('AVG(sFreeThrowsMadeAverage)'),
                DB::raw('AVG(sFreeThrowsAttemptedAverage)'),
                DB::raw('AVG(sReboundsTotalAverage)'),
                DB::raw('AVG(sAssistsAverage)'),
                DB::raw('AVG(sStealsAverage)'),
                DB::raw('AVG(sBlocksAverage)'),
                DB::raw('AVG(sTurnoversAverage)'),
                DB::raw('AVG(sFoulsPersonalAverage)'),
                'firstName',
                'familyName',
                'personId',
                'teamId',
                'competitionId'
            ])
            ->where('lbs.periodNumber', '0')
            ->whereIn('lbs.competitionId', [$competitionIds[0]->competitionId, $competitionIds[1]->competitionId])
            ->groupBy('lbs.personId')
            ->get();

       dd($data);
    }
</code>```

Body:
So I have a query that return all the stats of a player from their last season and current season. What I want to do is get the average of a player from last season and current season and make in to a one object only. Below is my query and sample result.

Query

public static function getAllTimeLeaders($request) {
        $competitionIds = self::getLasTwoSeason();
        $data = DB::table('leader_board_stats as lbs')
            ->select([
                'sGamesStarted',
                'sMinutesAverage',
                'sPointsAverage',
                'sFieldGoalsMadeAverage',
                'sFieldGoalsAttemptedAverage',
                'sFieldGoalsPercentage',
                'sTwoPointersMadeAverage',
                'sTwoPointersAttemptedAverage',
                'sThreePointersMadeAverage',
                'sThreePointersAttemptedAverage',
                'sThreePointersPercentage',
                'sFreeThrowsMadeAverage',
                'sFreeThrowsAttemptedAverage',
                'sReboundsTotalAverage',
                'sAssistsAverage',
                'sStealsAverage',
                'sBlocksAverage',
                'sTurnoversAverage',
                'sFoulsPersonalAverage',
                'firstName',
                'familyName',
                'personId',
                'teamId',
                'competitionId'
            ])
            ->where('lbs.periodNumber', '0')
            ->whereIn('lbs.competitionId', [$competitionIds[0]->competitionId, $competitionIds[1]->competitionId])
            ->get();
        echo '
';
        var_dump($data);
    }

Sample of returned value

[
    [0]=> object(stdClass)#262 (24) {
      ["sGamesStarted"]=>
      int(6)
      ["sMinutesAverage"]=>
      float(17.66)
      ["sPointsAverage"]=>
      float(7.71)
      ["sFieldGoalsMadeAverage"]=>
      float(2.59)
      ["sFieldGoalsAttemptedAverage"]=>
      float(5.62)
      ["sFieldGoalsPercentage"]=>
      float(0.46)
      ["sTwoPointersMadeAverage"]=>
      float(1.47)
      ["sTwoPointersAttemptedAverage"]=>
      float(2.53)
      ["sThreePointersMadeAverage"]=>
      float(1.12)
      ["sThreePointersAttemptedAverage"]=>
      float(3.09)
      ["sThreePointersPercentage"]=>
      float(0.36)
      ["sFreeThrowsMadeAverage"]=>
      float(1.41)
      ["sFreeThrowsAttemptedAverage"]=>
      float(1.76)
      ["sReboundsTotalAverage"]=>
      float(2.85)
      ["sAssistsAverage"]=>
      float(1.71)
      ["sStealsAverage"]=>
      float(0.68)
      ["sBlocksAverage"]=>
      float(0.21)
      ["sTurnoversAverage"]=>
      float(0.91)
      ["sFoulsPersonalAverage"]=>
      float(2.35)
      ["firstName"]=>
      string(3) "Person1"
      ["familyName"]=>
      string(8) "Familyname"
      ["personId"]=>
      int(28831)
      ["teamId"]=>
      int(3749)
      ["competitionId"]=>
      int(9224)
    },
    [88]=> object(stdClass)#527 (24) {
      ["sGamesStarted"]=>
      int(11)
      ["sMinutesAverage"]=>
      float(23.28)
      ["sPointsAverage"]=>
      float(9.5)
      ["sFieldGoalsMadeAverage"]=>
      float(3.07)
      ["sFieldGoalsAttemptedAverage"]=>
      float(7.97)
      ["sFieldGoalsPercentage"]=>
      float(0.38)
      ["sTwoPointersMadeAverage"]=>
      float(1.4)
      ["sTwoPointersAttemptedAverage"]=>
      float(3.47)
      ["sThreePointersMadeAverage"]=>
      float(1.67)
      ["sThreePointersAttemptedAverage"]=>
      float(4.5)
      ["sThreePointersPercentage"]=>
      float(0.37)
      ["sFreeThrowsMadeAverage"]=>
      float(1.7)
      ["sFreeThrowsAttemptedAverage"]=>
      float(2.2)
      ["sReboundsTotalAverage"]=>
      float(3.57)
      ["sAssistsAverage"]=>
      float(1.43)
      ["sStealsAverage"]=>
      float(0.93)
      ["sBlocksAverage"]=>
      float(0.23)
      ["sTurnoversAverage"]=>
      float(0.97)
      ["sFoulsPersonalAverage"]=>
      float(2.77)
      ["firstName"]=>
      string(3) "Person1"
      ["familyName"]=>
      string(8) "Familyname"
      ["personId"]=>
      int(28831)
      ["teamId"]=>
      int(3749)
      ["competitionId"]=>
      int(2254)
    }
]

Body:
Finally I figured it out I just need to use DB::raw and AVG of each stats fields then group it by personId.

public static function getAllTimeLeaders($request) {
        $competitionIds = self::getLasTwoSeason();
        $data = DB::table('leader_board_stats as lbs')
            ->select([
                DB::raw('AVG(sGamesStarted)'),
                DB::raw('AVG(sMinutesAverage)'),
                DB::raw('AVG(sPointsAverage)'),
                DB::raw('AVG(sFieldGoalsMadeAverage)'),
                DB::raw('AVG(sFieldGoalsAttemptedAverage)'),
                DB::raw('AVG(sFieldGoalsPercentage)'),
                DB::raw('AVG(sTwoPointersMadeAverage)'),
                DB::raw('AVG(sTwoPointersAttemptedAverage)'),
                DB::raw('AVG(sThreePointersMadeAverage)'),
                DB::raw('AVG(sThreePointersAttemptedAverage)'),
                DB::raw('AVG(sThreePointersPercentage)'),
                DB::raw('AVG(sFreeThrowsMadeAverage)'),
                DB::raw('AVG(sFreeThrowsAttemptedAverage)'),
                DB::raw('AVG(sReboundsTotalAverage)'),
                DB::raw('AVG(sAssistsAverage)'),
                DB::raw('AVG(sStealsAverage)'),
                DB::raw('AVG(sBlocksAverage)'),
                DB::raw('AVG(sTurnoversAverage)'),
                DB::raw('AVG(sFoulsPersonalAverage)'),
                'firstName',
                'familyName',
                'personId',
                'teamId',
                'competitionId'
            ])
            ->where('lbs.periodNumber', '0')
            ->whereIn('lbs.competitionId', [$competitionIds[0]->competitionId, $competitionIds[1]->competitionId])
            ->groupBy('lbs.personId')
            ->get();

       dd($data);
    }


问:
How to check for palindrome using Python logic
I'm trying to check for a palindrome with Python. The code I have is very for-loop intensive.

And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language.

I see on this website. Search for "C-style for", that Python doesn't have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this.

I've tried looking around, I can't find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop?

I've done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site By the way,.

```<code>def isPalindrome(n):
    lst = [int(n) for n in str(n)]
    l=len(lst)
    if l==0 || l==1:
        return True
    elif len(lst)%2==0:
        for k in range (l)
        #####
    else:
        while (k<=((l-1)/2)):
            if (list[]):
                #####

for i in range (999, 100, -1):
    for j in range (999,100, -1):
        if isPalindrome(i*j):
            print(i*j)
            break
</code>```

I'm missing a lot of code here. The five hashes are just reminders for myself.

Concrete questions:

In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python?

My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?

Does anybody have any good advice, or good websites, or resources for people in my position? I'm not a programmer, I don't aspire to be one, I just want to learn enough so that when I write my bachelor's degree thesis (electrical engineering), I don't have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. "How to go from basic C to great application of Python", that sort of thing.

Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops...

PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.

答:
the "algorithmic" way:</p>

```<code>import math

def isPalindrome(inputString):
    if inputString == None:
        return False

    strLength = len(inputString)
    for i in range(math.floor(strLength)):
        if inputString[i] != inputString[strLength - 1 - i]:
            return False
    return True
</code>```

Body:
I'm trying to check for a palindrome with Python. The code I have is very for-loop intensive.

And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language.

I see on this website. Search for "C-style for", that Python doesn't have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this.

I've tried looking around, I can't find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop?

I've done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site By the way,.

def isPalindrome(n):
    lst = [int(n) for n in str(n)]
    l=len(lst)
    if l==0 || l==1:
        return True
    elif len(lst)%2==0:
        for k in range (l)
        #####
    else:
        while (k<=((l-1)/2)):
            if (list[]):
                #####

for i in range (999, 100, -1):
    for j in range (999,100, -1):
        if isPalindrome(i*j):
            print(i*j)
            break

I'm missing a lot of code here. The five hashes are just reminders for myself.

Concrete questions:

In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python?

My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?

Does anybody have any good advice, or good websites, or resources for people in my position? I'm not a programmer, I don't aspire to be one, I just want to learn enough so that when I write my bachelor's degree thesis (electrical engineering), I don't have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. "How to go from basic C to great application of Python", that sort of thing.

Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops...

PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.

Body:
the "algorithmic" way:

import math

def isPalindrome(inputString):
    if inputString == None:
        return False

    strLength = len(inputString)
    for i in range(math.floor(strLength)):
        if inputString[i] != inputString[strLength - 1 - i]:
            return False
    return True


问:
How can I get XML-structured data in each line with Log4j XMLLayout?
Using the Log4J XMLLayout, I want to put a sequence of fields, wrapped in tags, inside each log-event (log-line). <x>some info</x> <y>more info</y>.

This seems a natural way, in the context of an XML logger, to achieve a more structured log. Is there a standard way of doing this, or do I have to build the string with these tags myself?

I could also use a PatternLayout with XML tags wrapping certain fields. I'd have to escape the XML myself, and it seems that XMLLayout should be the one to use for XML.

Another problem is that XMLLayout puts the log-line into a CDATA block, which of course means that any XML in the line is not parseable as XML.

答:
There doesn't seem to be built in functionality for this.

I'd suggest doing this: since you already have log4j, you have it's source code.

Find the file org.apache.log4j.xml.XMLLayout. Copy it, rename it's package name to something that will fit into your application, simply strip \r\n where appropriate (this file isn't large, so it shouldn't be a problem) and make a reference in log4j's configuration file to use your new layout.


问:
HTML Agility Pack Parsing div
I'm trying to parse HTML, I need to get "text" from this part:

```<code><div class="_gdf kno-fb-ctx">
    <span data-ved="0ahUKEwjIr9brjO7UAhUnYZoKHda-ALgQ2koIogEoAjAT"> text</span>
</div>
</code>```

Here's my C# code:

```<code>var message = doc.DocumentNode.SelectSingleNode("//div[@class='_gdf kno-fb-ctx']").InnerText;
Console.WriteLine(message);
</code>```

What I'm doing wrong ?

答:
I see that you are not selecting the actual 'Span' node to read the InnertTex. You have selected div and trying to read InnertTex, which won't give you desired result "Text". Instead you can do like below:</p>

```<code>        HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml("<div class='_gdf kno-fb-ctx'><span data-ved = '0ahUKEwjIr9brjO7UAhUnYZoKHda-ALgQ2koIogEoAjAT'> text </span ></div >");
        var text = doc.DocumentNode.SelectSingleNode("//div[@class=\"_gdf kno-fb-ctx\"]//span").InnerText;
</code>```

Title: HTML Agility Pack Parsing div

Body:
I'm trying to parse HTML, I need to get "text" from this part:

     text

Here's my C# code:

var message = doc.DocumentNode.SelectSingleNode("//div[@class='_gdf kno-fb-ctx']").InnerText;
Console.WriteLine(message);

What I'm doing wrong ?

Body:
I see that you are not selecting the actual 'Span' node to read the InnertTex. You have selected div and trying to read InnertTex, which won't give you desired result "Text". Instead you can do like below:

        HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml("<div class='_gdf kno-fb-ctx'><span data-ved = '0ahUKEwjIr9brjO7UAhUnYZoKHda-ALgQ2koIogEoAjAT'> text </span ></div >");
        var text = doc.DocumentNode.SelectSingleNode("//div[@class=\"_gdf kno-fb-ctx\"]//span").InnerText;


问:
How to change NotifyIcon.Text in a running WinForm via command-line-arguments?
This is a tray-icon-only Windows Forms application. I'm trying to use argument to control something and change the text on the form for showing the status information.

But I found when I use argument to call it during it's running, the things I want to change are null (NotifyIcon() and MenuItem()), seems it ran a different application when I using arguments. I also tried Invoke() but there is no this definition in NotifyIcon().

Here is the code I wrote:

```<code>static void Main(string[] args)
{
    if (args.Length > 0)
    {
        Arg_Call(args[0]);
    }
    if (new Mutex(true, "{XXX}").WaitOne(TimeSpan.Zero, true))
    {
        Init_Tray();
        Application.Run();
    }
}
private static NotifyIcon trayicon;

private static void Init_Tray()
{
    trayicon = new NotifyIcon() { Icon = new Icon(@"D:\projects\Icon.ico"), Text = "Waiting", Visible = true };
    trayicon.Visible = true;
    Application.Run();
}
private static void Arg_Call(string args)
{
    trayicon.Invoke((MethodInvoker)delegate {
        trayicon.Text = "OK";
    }); //from: https://stackoverflow.com/a/661662/8199423
}
</code>```

Where am I wrong? How to and what is the best way to change the NotifyIcon.Text property in the running form via command-line-arguments?

答:
I am sorry I was unable to adequately explain why your question is a duplicate of the existing "single-instance-application" questions. I will try to reiterate the train of thought here:

You wrote "How to and what is the best way to change the texts in the running form via command-line-arguments?"

Your requirement involves a currently-running process, which is presenting the NotifyIcon in the task tray, and the desire to use the command-line to modify that currently-running process's state.

It is a simple fact that when you type anything on the command line, it starts a whole new process. That process is necessarily different from the process that is already running, and which is presenting the NotifyIcon in the task tray.

Putting all of the above together, we have the conclusion that you want a new process that you start on the command line to interact with an existing process. And the simplest way to achieve that goal is to use the built-in single-instance-application support found in .NET. This is because the support for single-instance-applications includes automatic passing of the new command line arguments to the previous running program. Hence, the duplicate.

As I mentioned earlier, you should try to develop the skill to generalize and see how seemingly new problems are really just old problems in disguise and which you or someone else already knows how to solve.

In the same way that all problem solving can be summarized as "break the large problem down into smaller problems, repeat as necessary until all of the smaller problems are problems you already know how to solve", programming is very often not a matter of solving new problems, but rather of recognizing how your current problem is really a problem you already know how to solve.

All that said, I have the impression that you're still having difficulty figuring out how to apply that information to your specific scenario. So, perhaps this is an opportunity to illustrate the validity of the philosophy I espouse, by showing you how your seemingly different problem really is the problem I claim it is. :)

So, let's start with your original scenario. I am not using the code you posted, because it's mostly code that isn't needed. It seemed simpler to me to start from scratch. To do that, I wrote a little TrayManager class that encapsulates the actual NotifyIcon part of the functionality:

```<code>class TrayManager : IDisposable
{
    private readonly NotifyIcon _notifyIcon;

    public TrayManager()
    {
        _notifyIcon = new NotifyIcon
        {
            ContextMenu = new ContextMenu(new[]
            {
                new MenuItem("Exit", ContextMenu_Exit)
            }),
            Icon = Resources.TrayIcon,
            Text = "Initial value",
            Visible = true
        };
    }

    public void Dispose()
    {
        Dispose(true);
    }

    public void SetToolTipText(string text)
    {
        _notifyIcon.Text = text;
    }

    protected virtual void Dispose(bool disposing)
    {
        _notifyIcon.Visible = false;
    }

    private void ContextMenu_Exit(object sender, EventArgs e)
    {
        Application.ExitThread();
    }

    ~TrayManager()
    {
        Dispose(false);
    }
}
</code>```

The above hard-codes the context menu for the icon. Of course, it a real-world program, you'd probably want to decouple the menu from the above class, for greater flexibility.

The simplest way to use the above would look something like this:

```<code>static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        using (TrayManager trayManager = new TrayManager())
        {
            Application.Run();
        }
    }
}
</code>```

So, how do we modify the above so that when you run the program again, you can change the Text property of the NotifyIcon with the command-line arguments you type? That's where the single-instance application comes in. As seen in the duplicate I marked earlier, What is the correct way to create a single-instance application?, one of the simplest ways to accomplish this is to use the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class, which has built right in support for single-instance applications and a mechanism for delivering new command line arguments to the existing process.

The one little draw-back is that this class was designed for Winforms programs, with the assumption that there will be a main form. To use it will require creating a Form instance. For a program without the need for an actual form, this means creating a Form instance that is never shown, and making sure that it's never shown does require a little bit of finagling. Specifically:

```<code>class TrayOnlyApplication : WindowsFormsApplicationBase
{
    public TrayOnlyApplication()
    {
        IsSingleInstance = true;
        MainForm = new Form { ShowInTaskbar = false, WindowState = FormWindowState.Minimized };

        // Default behavior for single-instance is to activate main form
        // of original instance when second instance is run, which will show
        // the window (i.e. reset Visible to true) and restore the window
        // (i.e. reset WindowState to Normal). For a tray-only program,
        // we need to force the dummy window to stay invisible.
        MainForm.VisibleChanged += (s, e) => MainForm.Visible = false;
        MainForm.Resize += (s, e) => MainForm.WindowState = FormWindowState.Minimized;
    }
}
</code>```

The only thing in the above that gives us the single-instance application behavior we want is the setting of IsSingleInstance = true;. Everything else is there just to satisfy the requirement that some Form object is present as the MainForm, without actually showing that object on the screen.

Having added the above class to the project, we can now "connect the dots". The new Program class looks like this:

```<code>static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        using (TrayManager trayManager = new TrayManager())
        {
            TrayOnlyApplication app = new TrayOnlyApplication();

            app.StartupNextInstance += (s, e) => trayManager
                .SetToolTipText(e.CommandLine.Count > 0 ? e.CommandLine[0] : "<no value given>");
            app.Run(args);
        }
    }
}
</code>```

You'll note two changes:

In addition to the TrayManager, which handles the NotifyIcon, we now also create the TrayOnlyApplication object, subscribing to its StartupNextInstance event so that we can receive the command line arguments given to any new instance, and use that to set the Text property of the NotifyIcon object (by passing that to the method created specifically for that purpose).

Instead of using Application.Run() to run the require message-pump loop to handle window messages, we use the Run() method our TrayOnlyApplication class inherited from the WindowsFormsApplicationBase class. Either of these methods handle message pumping while the program is running, and return control to the caller when the Application.ExitThread() method is called, so both approaches to message pumping work with the code in the TrayManager.

Now, the above example is simply a slight modification of the original version that didn't enforce single-instance operation. You might notice that it has the arguable deficiency that it always creates the tray icon, whether or not it's the first instance to run. Subsequent instances will run, create the tray icon, then immediately dismiss the icon and exit.

The WindowsFormsApplicationBase provides a mechanism to avoid this, the Startup event. While the StartupNextInstance event is raised in any instance of the application that is run when an instance already is running, the Startup event is raised only when no other instance is already running. I.e. in the instance where you actually want to do things, like show the tray icon.

We can take advantage of that event to defer creation of the NotifyIcon until we know whether we actually need it or not:

```<code>static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        TrayManager trayManager = null;
        TrayOnlyApplication app = new TrayOnlyApplication();

        // Startup is raised only when no other instance of the
        // program is already running.
        app.Startup += (s, e) => trayManager = new TrayManager();

        // StartNextInstance is run when the program if a
        // previously -run instance is still running.
        app.StartupNextInstance += (s, e) => trayManager
            .SetToolTipText(e.CommandLine.Count > 0 ? e.CommandLine[0] : "<no value given>");

        try
        {
            app.Run(args);
        }
        finally
        {
            trayManager?.Dispose();
        }
    }
}
</code>```

Note that here, we need to write the try/finally explicitly instead of using the using statement, because the using statement requires initialization of the variable when it's declared, and we want to defer initialization until later, or never, depending on which instance is being run.

(Unfortunately, there's no way to defer creation of the dummy window in the TrayOnlyApplication class, since it's required just to call the Run() method, which requires a valid Form object be already set, and the determination as to which instance is being run happens in that call, not before.)

And that's all there is to it. The above shows, clearly I hope, exactly how the single-instance application techniques available to you directly solve the problem you are asking for help with. By providing a mechanism for a newly-run instance of your program to communicate the command line arguments passed to it, to the already-running instance of the same program, that newly-run instance can cause the already-running instance to perform whatever work it needs to (such as changing the tool-tip text for the tray icon, for example).

Naturally, any similar mechanism will achieve the same result. The only important thing is to have the newly-run instance detect an existing instance, and communicate with it. It just happens that the WindowsFormsApplicationBase class provides that functionality pre-made. There are lots of other ways to do the same thing, each with their own pros and cons.

Body:
This is a tray-icon-only Windows Forms application. I'm trying to use argument to control something and change the text on the form for showing the status information.

But I found when I use argument to call it during it's running, the things I want to change are null (NotifyIcon() and MenuItem()), seems it ran a different application when I using arguments. I also tried Invoke() but there is no this definition in NotifyIcon().

Here is the code I wrote:

static void Main(string[] args)
{
    if (args.Length > 0)
    {
        Arg_Call(args[0]);
    }
    if (new Mutex(true, "{XXX}").WaitOne(TimeSpan.Zero, true))
    {
        Init_Tray();
        Application.Run();
    }
}
private static NotifyIcon trayicon;

private static void Init_Tray()
{
    trayicon = new NotifyIcon() { Icon = new Icon(@"D:\projects\Icon.ico"), Text = "Waiting", Visible = true };
    trayicon.Visible = true;
    Application.Run();
}
private static void Arg_Call(string args)
{
    trayicon.Invoke((MethodInvoker)delegate {
        trayicon.Text = "OK";
    }); //from: https://stackoverflow.com/a/661662/8199423
}

Where am I wrong? How to and what is the best way to change the NotifyIcon.Text property in the running form via command-line-arguments?

Body:
I am sorry I was unable to adequately explain why your question is a duplicate of the existing "single-instance-application" questions. I will try to reiterate the train of thought here:

You wrote "How to and what is the best way to change the texts in the running form via command-line-arguments?"

Your requirement involves a currently-running process, which is presenting the NotifyIcon in the task tray, and the desire to use the command-line to modify that currently-running process's state.

It is a simple fact that when you type anything on the command line, it starts a whole new process. That process is necessarily different from the process that is already running, and which is presenting the NotifyIcon in the task tray.

Putting all of the above together, we have the conclusion that you want a new process that you start on the command line to interact with an existing process. And the simplest way to achieve that goal is to use the built-in single-instance-application support found in .NET. This is because the support for single-instance-applications includes automatic passing of the new command line arguments to the previous running program. Hence, the duplicate.

As I mentioned earlier, you should try to develop the skill to generalize and see how seemingly new problems are really just old problems in disguise and which you or someone else already knows how to solve.

In the same way that all problem solving can be summarized as "break the large problem down into smaller problems, repeat as necessary until all of the smaller problems are problems you already know how to solve", programming is very often not a matter of solving new problems, but rather of recognizing how your current problem is really a problem you already know how to solve.

All that said, I have the impression that you're still having difficulty figuring out how to apply that information to your specific scenario. So, perhaps this is an opportunity to illustrate the validity of the philosophy I espouse, by showing you how your seemingly different problem really is the problem I claim it is. :)

So, let's start with your original scenario. I am not using the code you posted, because it's mostly code that isn't needed. It seemed simpler to me to start from scratch. To do that, I wrote a little TrayManager class that encapsulates the actual NotifyIcon part of the functionality:

class TrayManager : IDisposable
{
    private readonly NotifyIcon _notifyIcon;

    public TrayManager()
    {
        _notifyIcon = new NotifyIcon
        {
            ContextMenu = new ContextMenu(new[]
            {
                new MenuItem("Exit", ContextMenu_Exit)
            }),
            Icon = Resources.TrayIcon,
            Text = "Initial value",
            Visible = true
        };
    }

    public void Dispose()
    {
        Dispose(true);
    }

    public void SetToolTipText(string text)
    {
        _notifyIcon.Text = text;
    }

    protected virtual void Dispose(bool disposing)
    {
        _notifyIcon.Visible = false;
    }

    private void ContextMenu_Exit(object sender, EventArgs e)
    {
        Application.ExitThread();
    }

    ~TrayManager()
    {
        Dispose(false);
    }
}

The above hard-codes the context menu for the icon. Of course, it a real-world program, you'd probably want to decouple the menu from the above class, for greater flexibility.

The simplest way to use the above would look something like this:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        using (TrayManager trayManager = new TrayManager())
        {
            Application.Run();
        }
    }
}

So, how do we modify the above so that when you run the program again, you can change the Text property of the NotifyIcon with the command-line arguments you type? That's where the single-instance application comes in. As seen in the duplicate I marked earlier, What is the correct way to create a single-instance application?, one of the simplest ways to accomplish this is to use the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class, which has built right in support for single-instance applications and a mechanism for delivering new command line arguments to the existing process.

The one little draw-back is that this class was designed for Winforms programs, with the assumption that there will be a main form. To use it will require creating a Form instance. For a program without the need for an actual form, this means creating a Form instance that is never shown, and making sure that it's never shown does require a little bit of finagling. Specifically:

class TrayOnlyApplication : WindowsFormsApplicationBase
{
    public TrayOnlyApplication()
    {
        IsSingleInstance = true;
        MainForm = new Form { ShowInTaskbar = false, WindowState = FormWindowState.Minimized };

        // Default behavior for single-instance is to activate main form
        // of original instance when second instance is run, which will show
        // the window (i.e. reset Visible to true) and restore the window
        // (i.e. reset WindowState to Normal). For a tray-only program,
        // we need to force the dummy window to stay invisible.
        MainForm.VisibleChanged += (s, e) => MainForm.Visible = false;
        MainForm.Resize += (s, e) => MainForm.WindowState = FormWindowState.Minimized;
    }
}

The only thing in the above that gives us the single-instance application behavior we want is the setting of IsSingleInstance = true;. Everything else is there just to satisfy the requirement that some Form object is present as the MainForm, without actually showing that object on the screen.

Having added the above class to the project, we can now "connect the dots". The new Program class looks like this:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        using (TrayManager trayManager = new TrayManager())
        {
            TrayOnlyApplication app = new TrayOnlyApplication();

            app.StartupNextInstance += (s, e) => trayManager
                .SetToolTipText(e.CommandLine.Count > 0 ? e.CommandLine[0] : "<no value given>");
            app.Run(args);
        }
    }
}

You'll note two changes:

In addition to the TrayManager, which handles the NotifyIcon, we now also create the TrayOnlyApplication object, subscribing to its StartupNextInstance event so that we can receive the command line arguments given to any new instance, and use that to set the Text property of the NotifyIcon object (by passing that to the method created specifically for that purpose).

Instead of using Application.Run() to run the require message-pump loop to handle window messages, we use the Run() method our TrayOnlyApplication class inherited from the WindowsFormsApplicationBase class. Either of these methods handle message pumping while the program is running, and return control to the caller when the Application.ExitThread() method is called, so both approaches to message pumping work with the code in the TrayManager.

Now, the above example is simply a slight modification of the original version that didn't enforce single-instance operation. You might notice that it has the arguable deficiency that it always creates the tray icon, whether or not it's the first instance to run. Subsequent instances will run, create the tray icon, then immediately dismiss the icon and exit.

The WindowsFormsApplicationBase provides a mechanism to avoid this, the Startup event. While the StartupNextInstance event is raised in any instance of the application that is run when an instance already is running, the Startup event is raised only when no other instance is already running. I.e. in the instance where you actually want to do things, like show the tray icon.

We can take advantage of that event to defer creation of the NotifyIcon until we know whether we actually need it or not:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        TrayManager trayManager = null;
        TrayOnlyApplication app = new TrayOnlyApplication();

        // Startup is raised only when no other instance of the
        // program is already running.
        app.Startup += (s, e) => trayManager = new TrayManager();

        // StartNextInstance is run when the program if a
        // previously -run instance is still running.
        app.StartupNextInstance += (s, e) => trayManager
            .SetToolTipText(e.CommandLine.Count > 0 ? e.CommandLine[0] : "<no value given>");

        try
        {
            app.Run(args);
        }
        finally
        {
            trayManager?.Dispose();
        }
    }
}

Note that here, we need to write the try/finally explicitly instead of using the using statement, because the using statement requires initialization of the variable when it's declared, and we want to defer initialization until later, or never, depending on which instance is being run.

(Unfortunately, there's no way to defer creation of the dummy window in the TrayOnlyApplication class, since it's required just to call the Run() method, which requires a valid Form object be already set, and the determination as to which instance is being run happens in that call, not before.)

And that's all there is to it. The above shows, clearly I hope, exactly how the single-instance application techniques available to you directly solve the problem you are asking for help with. By providing a mechanism for a newly-run instance of your program to communicate the command line arguments passed to it, to the already-running instance of the same program, that newly-run instance can cause the already-running instance to perform whatever work it needs to (such as changing the tool-tip text for the tray icon, for example).

Naturally, any similar mechanism will achieve the same result. The only important thing is to have the newly-run instance detect an existing instance, and communicate with it. It just happens that the WindowsFormsApplicationBase class provides that functionality pre-made. There are lots of other ways to do the same thing, each with their own pros and cons.