问:
Can't connect to Bigtable to scan HTable data due to hardcoded managed=true in hbase client jars
I'm working on a custom load function to load data from Bigtable using Pig on Dataproc. I compile my java code using the following list of jar files I grabbed from Dataproc. When I run the following Pig script, it fails when it tries to establish a connection with Bigtable.

Error message is:

```<code>Bigtable does not support managed connections.
</code>```

Questions:

Is there a work around for this problem?

Is this a known issue and is there a plan to fix or adjust?

Is there a different way of implementing multi scans as a load function for Pig that will work with Bigtable?

Details:

Jar files:

```<code>hadoop-common-2.7.3.jar
hbase-client-1.2.2.jar
hbase-common-1.2.2.jar
hbase-protocol-1.2.2.jar
hbase-server-1.2.2.jar
pig-0.16.0-core-h2.jar
</code>```

Here's a simple Pig script using my custom load function:

```<code>%default gte         '2017-03-23T18:00Z'
%default lt          '2017-03-23T18:05Z'
%default SHARD_FIRST '00'
%default SHARD_LAST  '25'
%default GTE_SHARD   '$gte\_$SHARD_FIRST'
%default LT_SHARD    '$lt\_$SHARD_LAST'
raw = LOAD 'hbase://events_sessions'
      USING com.eduboom.pig.load.HBaseMultiScanLoader('$GTE_SHARD', '$LT_SHARD', 'event:*')
      AS (es_key:chararray, event_array);
DUMP raw;
</code>```

My custom load function HBaseMultiScanLoader creates a list of Scan objects to perform multiple scans on different ranges of data in the table events_sessions determined by the time range between gte and lt and sharded by SHARD_FIRST through SHARD_LAST.

HBaseMultiScanLoader extends org.apache.pig.LoadFunc so it can be used in the Pig script as load function.
When Pig runs my script, it calls LoadFunc.getInputFormat().
My implementation of getInputFormat() returns an instance of my custom class MultiScanTableInputFormat which extends org.apache.hadoop.mapreduce.InputFormat.
MultiScanTableInputFormat initializes org.apache.hadoop.hbase.client.HTable object to initialize the connection to the table.

Digging into the hbase-client source code, I see that org.apache.hadoop.hbase.client.ConnectionManager.getConnectionInternal() calls org.apache.hadoop.hbase.client.ConnectionManager.createConnection() with the attribute “managed” hardcoded to “true”.
You can see from the stack track below that my code (MultiScanTableInputFormat) tries to initialize an HTable object which invokes getConnectionInternal() which does not provide an option to set managed to false.
Going down the stack trace, you will get to AbstractBigtableConnection that will not accept managed=true and therefore cause the connection to Bigtable to fail.

Here’s the stack trace showing the error:

```<code>2017-03-24 23:06:44,890 [JobControl] ERROR com.turner.hbase.mapreduce.MultiScanTableInputFormat - java.io.IOException: java.lang.reflect.InvocationTargetException
    at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:240)
    at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:431)
    at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:424)
    at org.apache.hadoop.hbase.client.ConnectionManager.getConnectionInternal(ConnectionManager.java:302)
    at org.apache.hadoop.hbase.client.HTable.<init>(HTable.java:185)
    at org.apache.hadoop.hbase.client.HTable.<init>(HTable.java:151)
    at com.eduboom.hbase.mapreduce.MultiScanTableInputFormat.setConf(Unknown Source)
    at com.eduboom.pig.load.HBaseMultiScanLoader.getInputFormat(Unknown Source)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:264)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:301)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:318)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:196)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1290)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1287)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1698)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
    at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:335)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.pig.backend.hadoop23.PigJobControl.submit(PigJobControl.java:128)
    at org.apache.pig.backend.hadoop23.PigJobControl.run(PigJobControl.java:194)
    at java.lang.Thread.run(Thread.java:745)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:276)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:238)
    ... 26 more
Caused by: java.lang.IllegalArgumentException: Bigtable does not support managed connections.
    at org.apache.hadoop.hbase.client.AbstractBigtableConnection.<init>(AbstractBigtableConnection.java:123)
    at com.google.cloud.bigtable.hbase1_2.BigtableConnection.<init>(BigtableConnection.java:55)
    ... 31 more
</code>```

答:
The original problem was caused by the use of outdated and deprecated hbase client jars and classes.

I updated my code to use the newest hbase client jars provided by Google and the original problem was fixed.

I still get stuck with some ZK issue that I still did not figure out, but that's a conversation for a different question.

This one is answered!

Body:
I'm working on a custom load function to load data from Bigtable using Pig on Dataproc. I compile my java code using the following list of jar files I grabbed from Dataproc. When I run the following Pig script, it fails when it tries to establish a connection with Bigtable.

Error message is:

Bigtable does not support managed connections.

Questions:

Is there a work around for this problem?

Is this a known issue and is there a plan to fix or adjust?

Is there a different way of implementing multi scans as a load function for Pig that will work with Bigtable?

Details:

Jar files:

hadoop-common-2.7.3.jar
hbase-client-1.2.2.jar
hbase-common-1.2.2.jar
hbase-protocol-1.2.2.jar
hbase-server-1.2.2.jar
pig-0.16.0-core-h2.jar

Here's a simple Pig script using my custom load function:

%default gte         '2017-03-23T18:00Z'
%default lt          '2017-03-23T18:05Z'
%default SHARD_FIRST '00'
%default SHARD_LAST  '25'
%default GTE_SHARD   '$gte\_$SHARD_FIRST'
%default LT_SHARD    '$lt\_$SHARD_LAST'
raw = LOAD 'hbase://events_sessions'
      USING com.eduboom.pig.load.HBaseMultiScanLoader('$GTE_SHARD', '$LT_SHARD', 'event:*')
      AS (es_key:chararray, event_array);
DUMP raw;

My custom load function HBaseMultiScanLoader creates a list of Scan objects to perform multiple scans on different ranges of data in the table events_sessions determined by the time range between gte and lt and sharded by SHARD_FIRST through SHARD_LAST.

HBaseMultiScanLoader extends org.apache.pig.LoadFunc so it can be used in the Pig script as load function.
When Pig runs my script, it calls LoadFunc.getInputFormat().
My implementation of getInputFormat() returns an instance of my custom class MultiScanTableInputFormat which extends org.apache.hadoop.mapreduce.InputFormat.
MultiScanTableInputFormat initializes org.apache.hadoop.hbase.client.HTable object to initialize the connection to the table.

Digging into the hbase-client source code, I see that org.apache.hadoop.hbase.client.ConnectionManager.getConnectionInternal() calls org.apache.hadoop.hbase.client.ConnectionManager.createConnection() with the attribute “managed” hardcoded to “true”.
You can see from the stack track below that my code (MultiScanTableInputFormat) tries to initialize an HTable object which invokes getConnectionInternal() which does not provide an option to set managed to false.
Going down the stack trace, you will get to AbstractBigtableConnection that will not accept managed=true and therefore cause the connection to Bigtable to fail.

Here’s the stack trace showing the error:

2017-03-24 23:06:44,890 [JobControl] ERROR com.turner.hbase.mapreduce.MultiScanTableInputFormat - java.io.IOException: java.lang.reflect.InvocationTargetException
    at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:240)
    at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:431)
    at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:424)
    at org.apache.hadoop.hbase.client.ConnectionManager.getConnectionInternal(ConnectionManager.java:302)
    at org.apache.hadoop.hbase.client.HTable.<init>(HTable.java:185)
    at org.apache.hadoop.hbase.client.HTable.<init>(HTable.java:151)
    at com.eduboom.hbase.mapreduce.MultiScanTableInputFormat.setConf(Unknown Source)
    at com.eduboom.pig.load.HBaseMultiScanLoader.getInputFormat(Unknown Source)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:264)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:301)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:318)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:196)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1290)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1287)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1698)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
    at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:335)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.pig.backend.hadoop23.PigJobControl.submit(PigJobControl.java:128)
    at org.apache.pig.backend.hadoop23.PigJobControl.run(PigJobControl.java:194)
    at java.lang.Thread.run(Thread.java:745)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:276)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:238)
    ... 26 more
Caused by: java.lang.IllegalArgumentException: Bigtable does not support managed connections.
    at org.apache.hadoop.hbase.client.AbstractBigtableConnection.<init>(AbstractBigtableConnection.java:123)
    at com.google.cloud.bigtable.hbase1_2.BigtableConnection.<init>(BigtableConnection.java:55)
    ... 31 more


来源: stackexchange

问:
Most efficient way to create an array of length n filled with unique symbols
I need to create an array of variable length where each element is a unique symbol. Is there a built-in (ES6) or lodash method to easily do this? What I have currently is _.map(range(n), () => Symbol()) which is fairly efficient text and timewise, but I would prefer to replace map with a different function that allows me to replace range(n) with just n.

答:
```<code>Array.from({length: n}, () => Symbol())
</code>```

would be one option.

ContentLicense: CC BY-SA 3.0

Body:
Array.from({length: n}, () => Symbol())

would be one option.


问:
Exit PS1 script if server remoting not-enabled (Test-WsMan [Computer IP])
This cmdlet from client allows me to check to see if remoting with Powershell is enabled on server. In example below, results say it is:

```<code>PS C:\WINDOWS\system32> Test-WsMan xxx.104.50.xxx

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 0.0.0 SP: 0.0 Stack: 3.0
</code>```

However, I don't know how to get a true/false back from running Test-WsMan.
In my automation script I want to check if remoting is enabled, and if not, stop the script and exit.

I hope my question makes sense and I hope someone is a lot smarter than me.

答:
From MSDN

If the tested computer is running the service, the cmdlet displays the WS-Management identity schema, the protocol version, the product vendor, and the product version of the tested service.

MSDN does not explicitly state what it does when it is not running the service  but I am sure you could just treat this as a truthy falsy. If nothing is returned it is not working. PowerShell is very good at evaluating expressions as booleans.

```<code>if(test-wsman $computer -ErrorAction SilentlyContinue){
    # Remoting is enabled
} else {
    # Something is wrong.
}
</code>```

-ErrorAction SilentlyContinue would cover any reason for failure like if the name was wrong or otherwise not contactable. It would be up to you to determine what to do if remoting is "not working".

Body:
This cmdlet from client allows me to check to see if remoting with Powershell is enabled on server. In example below, results say it is:

PS C:\WINDOWS\system32> Test-WsMan xxx.104.50.xxx

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 0.0.0 SP: 0.0 Stack: 3.0

However, I don't know how to get a true/false back from running Test-WsMan.
In my automation script I want to check if remoting is enabled, and if not, stop the script and exit.

I hope my question makes sense and I hope someone is a lot smarter than me.

Body:
From MSDN

If the tested computer is running the service, the cmdlet displays the WS-Management identity schema, the protocol version, the product vendor, and the product version of the tested service.

MSDN does not explicitly state what it does when it is not running the service  but I am sure you could just treat this as a truthy falsy. If nothing is returned it is not working. PowerShell is very good at evaluating expressions as booleans.

if(test-wsman $computer -ErrorAction SilentlyContinue){
    # Remoting is enabled
} else {
    # Something is wrong.
}

-ErrorAction SilentlyContinue would cover any reason for failure like if the name was wrong or otherwise not contactable. It would be up to you to determine what to do if remoting is "not working".


问:
Use query result as parameter for another query
I have two tables:

table1: item (itemId,itemName)

table2: invoices (InvoiceId,InvoiceNum,InvoiceDate,ItemId..etc) (other columns are not relevant).

I need to find for a distinct item, the latest (and only the latest) invoice date.
So far I create a first query distinct on the first table and then, for each result I run a new query on the second table (top 1 ordered by date desc)

It works, but it takes forever (I have more than 10000 items).
I am using asp classic and access but I am pretty sure that the problem is related to the SQL.

I tried with the clause WHERE ... IN  but the query output all the invoice dates and not only the latest one.

Any help?
Thx in advance!

I understand that I've been very generic.
here is the SQL instruction that I am trying to use:

SELECT table1.id, table3.name, table1.name, table2.trans_num, Max(table2.transaction_date_h) AS MaxDitransaction_date_h, table2.amount_amt
FROM table3 INNER JOIN (table1 INNER JOIN table2 ON table1.id = table2.item_id) ON table3.id = table1.preferred_vendor_id
GROUP BY table1.id,table3.name, table1.name, table2.trans_num, table2.amount_amt
ORDER BY table3.name, table1.name, table2.trans_num, Max(table2.transaction_date_h) DESC;

If I run this query, the result is the entire recordset.
As said, I would like to retrieve only the top 1 latest transaction_date_h for each distinct table1.id

答:
If you just want item Id and latest invoice date, then use simple aggregation:

```<code>select itemId,
    max(InvoiceDate) as InvoiceDate
from invoices
group by itemId
</code>```

If you need item details too, join the above with item table:

```<code>select i.*, i2.InvoiceDate
from item i
join (
    select itemId,
        max(InvoiceDate) as InvoiceDate
    from invoices
    group by itemId
    ) i2 on i.itemId = i2.itemId;
</code>```

or:

```<code>select i.itemId,
    i.itemName,
    max(i2.InvoiceDate) as InvoiceDate
from item i
join invoices i2 on i.itemId = i2.itemId
group by i.itemId,
    i.itemName;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you just want item Id and latest invoice date, then use simple aggregation:

select itemId,
    max(InvoiceDate) as InvoiceDate
from invoices
group by itemId

If you need item details too, join the above with item table:

select i.*, i2.InvoiceDate
from item i
join (
    select itemId,
        max(InvoiceDate) as InvoiceDate
    from invoices
    group by itemId
    ) i2 on i.itemId = i2.itemId;

or:

select i.itemId,
    i.itemName,
    max(i2.InvoiceDate) as InvoiceDate
from item i
join invoices i2 on i.itemId = i2.itemId
group by i.itemId,
    i.itemName;


问:
Mac + Selenium + Chrome = cannot find Chrome binary
Hi i m trying to setup selenium with eclipse on a Mac pc.
When I download the ChromeDriver and place it on the below folder :

```<code>System.setProperty("webdriver.chrome.driver","/Users/george/Downloads/chromedriver");
WebDriver driver = new ChromeDriver();
</code>```

I run the code.
Then I get the following exception :

Starting ChromeDriver 2.21.371459
  (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4) on port 33424 Only local
  connections are allowed. Exception in thread "main"
  org.openqa.selenium.WebDriverException: unknown error: cannot find
  Chrome binary   (Driver info: chromedriver=2.21.371459
  (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),platform=Mac OS X 10.10.5
  x86_64) (WARNING: The server did not provide any stacktrace
  information) Command duration or timeout: 312 milliseconds Build info:
  version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
  System info: host: 'Georges-Mac-mini.local', ip: '192.168.1.2',
  os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.10.5',
  java.version: '1.7.0_25' Driver info:
  org.openqa.selenium.chrome.ChromeDriver

So I m assuming that some binary is missing? Note that I use regularly Chrome as my browser.. I dont know if this is related or not.
My pc is mac. I have read the ChromeDriver site but I dont understand what exactly to do. I have problems navigating to paths that are a bit strange like : "Google Drive" instead of "Google/Drive" or paths like
"cd Chrome\ Apps.localized/"  or "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome". I mean , wt?? are those back and forth slashes ??? I just now a few things on linux but here.. i m stuck and confused
On Windows things where much easier.. you just downloaded an .exe file locally point the driver with options to that file and everything was smoothly. I cant find information on mac specific.

Can anyone help ?

Thanks

答:
The stack trace indicates that it cannot find the binary for the chrome webdrive.  You'll need to download it if you haven't already.  Once you have downloaded the chrome webdriver, point your application at the binary.

if you have a path with spaces, such as

/Applications/Google Chrome.app/Contents/MacOS/Google Chrome

you'll need to escape the spaces with backslashes like so

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome

a backslash followed by a space, \, tells the argument parser not to use that space as a delimiter but rather to include it as part of the path.

Body:
Hi i m trying to setup selenium with eclipse on a Mac pc.
When I download the ChromeDriver and place it on the below folder :

System.setProperty("webdriver.chrome.driver","/Users/george/Downloads/chromedriver");
WebDriver driver = new ChromeDriver();

I run the code.
Then I get the following exception :

Starting ChromeDriver 2.21.371459
  (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4) on port 33424 Only local
  connections are allowed. Exception in thread "main"
  org.openqa.selenium.WebDriverException: unknown error: cannot find
  Chrome binary   (Driver info: chromedriver=2.21.371459
  (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),platform=Mac OS X 10.10.5
  x86_64) (WARNING: The server did not provide any stacktrace
  information) Command duration or timeout: 312 milliseconds Build info:
  version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
  System info: host: 'Georges-Mac-mini.local', ip: '192.168.1.2',
  os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.10.5',
  java.version: '1.7.0_25' Driver info:
  org.openqa.selenium.chrome.ChromeDriver

So I m assuming that some binary is missing? Note that I use regularly Chrome as my browser.. I dont know if this is related or not.
My pc is mac. I have read the ChromeDriver site but I dont understand what exactly to do. I have problems navigating to paths that are a bit strange like : "Google Drive" instead of "Google/Drive" or paths like
"cd Chrome\ Apps.localized/"  or "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome". I mean , wt?? are those back and forth slashes ??? I just now a few things on linux but here.. i m stuck and confused
On Windows things where much easier.. you just downloaded an .exe file locally point the driver with options to that file and everything was smoothly. I cant find information on mac specific.

Can anyone help ?

Thanks


问:
ArrayList contains case sensitivity
I am currently using the contains method belonging to the ArrayList class for making a search. Is there a way to make this search case insensitive in java? I found that in C# it is possible to use OrdinalIgnoreCase. Is there a java equivalent, or another way to do this?
Thanks.</p>

答:
In my case, as all my strings in the ArrayList are in downcase, I just execute the String.toLowerCase() method on the contains() parameter. Like this:

```<code>If (yourArrayList.contains (parameterInput.toLowerCase()) {
    // your code here
}
</code>```

As you can see, you can do the oposite, if yout arrayList has upperCase strings:

```<code>If (yourArrayList.contains (parameterInput.toUpperCase ()) {
    // your code here
}
</code>```

Using this approach, you do not need to override anything. The exception is in the case when your arrayList have a mix of upper and lower cases.

Title: ArrayList contains case sensitivity

Body:
In my case, as all my strings in the ArrayList are in downcase, I just execute the String.toLowerCase() method on the contains() parameter. Like this:

If (yourArrayList.contains (parameterInput.toLowerCase()) {
    // your code here
}

As you can see, you can do the oposite, if yout arrayList has upperCase strings:

If (yourArrayList.contains (parameterInput.toUpperCase ()) {
    // your code here
}

Using this approach, you do not need to override anything. The exception is in the case when your arrayList have a mix of upper and lower cases.


问:
Unable to capture changes to log file via nagios check_logwarn plugin command invoked via PHP exec() triggered via Jenkins
I am using nagios check_logwarn to capture changes to log files.

In order to test my setup, I have been manually adding the following log line to the concerned log file -

```<code>[Mon Mar 20 14:24:31 2017] [hphp] [12082:7f238d3ff700:32:000001] []
\nFatal error: entire web request took longer than 10 seconds and timed out in /var/cake_1.2.0.6311-beta
app/webroot/openx/www/delivery/postGetAd.php on line 483
</code>```

The above should get caught by the following nagios command, because it contains the keyword "Fatal"

```<code>/usr/local/nagios/libexec/check_logwarn -d /tmp/logwarn_hiphop_error -p /mnt/log/hiphop/error_`(date +'%Y%m%d')`.log "^.*Fatal*"
</code>```

Output (as expected) -

```<code>Log errors: \nFatal error: entire web request took longer than 10 seconds and timed out in /var/cake_1.2.
0.6311-beta
\nFatal error: entire web request took longer than 10 seconds and timed out in /var/cake_1.2.0.6311-beta
</code>```

Running this command directly works (case 1), but it seems invoking the same via a PHP exec which is triggered via a Jenkins project is not catching the same (case 2).

Following is the PHP code of case 2 -

```<code>$errorLogCommand = '/usr/local/nagios/libexec/check_logwarn -d /tmp/logwarn_hiphop_error -p /mnt/log/hiphop/error_'.$date.'.log "^.*Fatal*"';
$output = exec($errorLogCommand);
file_put_contents('/var/cake_1.2.0.6311-beta/deployment/deployment.log', "\n ".date("Y-m-d H:i:s")." Checked error key words in error_".$date.".log. command -> ".$errorLogCommand, FILE_APPEND);
if($output!="OK: No log errors found")
{
    file_put_contents('/var/cake_1.2.0.6311-beta/deployment/deployment.log', "\n ".date("Y-m-d H:i:s")." - Hiphop errors -> ".$output, FILE_APPEND);

    $failure=true;
    break;
}
else
{
    file_put_contents('/var/cake_1.2.0.6311-beta/deployment/deployment.log', "\n ".date("Y-m-d H:i:s")." - No Error found -> ".$output, FILE_APPEND);
}
</code>```

Following is the output -

```<code> 2017-03-20 14:16:45 Checked error key words in error_20170320.log. command -> /usr/local/nagios/libexec/
check_logwarn -d /tmp/logwarn_hiphop_error -p /mnt/log/hiphop/error_20170320.log "Fatal"
 2017-03-20 14:16:45 - No Error found -> OK: No log errors found
</code>```

Note that with the same nagios command (/usr/local/nagios/libexec/check_logwarn) as in case 1, log error is not detected in this case, unexpectedly.

Following are my observations of the contents of the internal tracker file which nagios generates - /tmp/logwarn_hiphop_error/mnt_log_hiphop_error_20170320.log -

When error is detected in case 1, following are the changes in the file -

Before running command

```<code># logwarn 1.0.10 state for "/mnt/log/hiphop/error_20170320.log"
INODENUM="1208110246"
LINENUM="110"
POSITION="111627"
MATCHING="true"
</code>```

After running command

```<code># logwarn 1.0.10 state for "/mnt/log/hiphop/error_20170320.log"
INODENUM="1208110246"
LINENUM="116"
POSITION="112087"
MATCHING="false"
</code>```

Also, following are the changes to the same file in case 2 -

Before running php file

```<code># logwarn 1.0.10 state for "/mnt/log/hiphop/error_20170320.log"
INODENUM="1208110246"
LINENUM="102"
POSITION="109329"
MATCHING="true"
</code>```

After

```<code># logwarn 1.0.10 state for "/mnt/log/hiphop/error_20170320.log"
INODENUM="1208110246"
LINENUM="110"
POSITION="111627"
MATCHING="true"
</code>```

I am not sure why the MATCHING parameter is true in the case 2, whereas in case 1 it is false. In fact, the error matching happened in case 1.

Update

I tried wrapping the command in an escapeshellcmd, to ensure that the regex is not being stripped out -

```<code>$output = exec(escapeshellcmd($errorLogCommand));
</code>```

but still no change in output.

Update 2

Found that I had line breaks in the log line I was manually adding. Removing those fixed it consistently for the case of running the PHP file from command line. However, the problem is still reproducible consistently for the case 2, where I am triggering the project via Jenkins and this file gets called in one of the hooks of AWS code deploy.

Well, it seems this is not going to get solved so easily. The problem got fixed for manual invocation of the PHP file, but on invocation via Jenkins, I am still getting the same problem consistently.

答:
The logwarn documentation mentions support for a negative checking expression.

Please try pre-pending an exclamation mark (!) before the pattern string to exclude rather than include these matches

Body:
I am using nagios check_logwarn to capture changes to log files.

In order to test my setup, I have been manually adding the following log line to the concerned log file -

[Mon Mar 20 14:24:31 2017] [hphp] [12082:7f238d3ff700:32:000001] []
\nFatal error: entire web request took longer than 10 seconds and timed out in /var/cake_1.2.0.6311-beta
app/webroot/openx/www/delivery/postGetAd.php on line 483

The above should get caught by the following nagios command, because it contains the keyword "Fatal"

/usr/local/nagios/libexec/check_logwarn -d /tmp/logwarn_hiphop_error -p /mnt/log/hiphop/error_`(date +'%Y%m%d')`.log "^.*Fatal*"

Output (as expected) -

Log errors: \nFatal error: entire web request took longer than 10 seconds and timed out in /var/cake_1.2.
0.6311-beta
\nFatal error: entire web request took longer than 10 seconds and timed out in /var/cake_1.2.0.6311-beta

Running this command directly works (case 1), but it seems invoking the same via a PHP exec which is triggered via a Jenkins project is not catching the same (case 2).

Following is the PHP code of case 2 -

$errorLogCommand = '/usr/local/nagios/libexec/check_logwarn -d /tmp/logwarn_hiphop_error -p /mnt/log/hiphop/error_'.$date.'.log "^.*Fatal*"';
$output = exec($errorLogCommand);
file_put_contents('/var/cake_1.2.0.6311-beta/deployment/deployment.log', "\n ".date("Y-m-d H:i:s")." Checked error key words in error_".$date.".log. command -> ".$errorLogCommand, FILE_APPEND);
if($output!="OK: No log errors found")
{
    file_put_contents('/var/cake_1.2.0.6311-beta/deployment/deployment.log', "\n ".date("Y-m-d H:i:s")." - Hiphop errors -> ".$output, FILE_APPEND);

    $failure=true;
    break;
}
else
{
    file_put_contents('/var/cake_1.2.0.6311-beta/deployment/deployment.log', "\n ".date("Y-m-d H:i:s")." - No Error found -> ".$output, FILE_APPEND);
}

Following is the output -

 2017-03-20 14:16:45 Checked error key words in error_20170320.log. command -> /usr/local/nagios/libexec/
check_logwarn -d /tmp/logwarn_hiphop_error -p /mnt/log/hiphop/error_20170320.log "Fatal"
 2017-03-20 14:16:45 - No Error found -> OK: No log errors found

Note that with the same nagios command (/usr/local/nagios/libexec/check_logwarn) as in case 1, log error is not detected in this case, unexpectedly.

Following are my observations of the contents of the internal tracker file which nagios generates - /tmp/logwarn_hiphop_error/mnt_log_hiphop_error_20170320.log -

When error is detected in case 1, following are the changes in the file -

Before running command

# logwarn 1.0.10 state for "/mnt/log/hiphop/error_20170320.log"
INODENUM="1208110246"
LINENUM="110"
POSITION="111627"
MATCHING="true"

After running command

# logwarn 1.0.10 state for "/mnt/log/hiphop/error_20170320.log"
INODENUM="1208110246"
LINENUM="116"
POSITION="112087"
MATCHING="false"

Also, following are the changes to the same file in case 2 -

Before running php file

# logwarn 1.0.10 state for "/mnt/log/hiphop/error_20170320.log"
INODENUM="1208110246"
LINENUM="102"
POSITION="109329"
MATCHING="true"

After

# logwarn 1.0.10 state for "/mnt/log/hiphop/error_20170320.log"
INODENUM="1208110246"
LINENUM="110"
POSITION="111627"
MATCHING="true"

I am not sure why the MATCHING parameter is true in the case 2, whereas in case 1 it is false. In fact, the error matching happened in case 1.

Update

I tried wrapping the command in an escapeshellcmd, to ensure that the regex is not being stripped out -

$output = exec(escapeshellcmd($errorLogCommand));

but still no change in output.

Update 2

Found that I had line breaks in the log line I was manually adding. Removing those fixed it consistently for the case of running the PHP file from command line. However, the problem is still reproducible consistently for the case 2, where I am triggering the project via Jenkins and this file gets called in one of the hooks of AWS code deploy.

Well, it seems this is not going to get solved so easily. The problem got fixed for manual invocation of the PHP file, but on invocation via Jenkins, I am still getting the same problem consistently.


问:
iPhone Passcode Integration
I want to integrate a passcode into my existing application. Does anyone know of any good tutorials, or such that would lend to my search? Is there a standard Apple tutorial to integrate one? I've not been able to find one, but I imagine it'd be as simple as putting a keypad view in the didFinishLaunching & resignActive methods right? Would keychain be a good place to store it? Again, I'd hate to reinvent the wheel on this, especially if there is a proven secure method out there. Here is the one good tutorial I've been able to find, but it doesn't incorporate a view, or multiple invoke points. http://gorgando.com/blog/topics/technology/iphone_development/simple-iphone-tutorial-password-management-using-the-keychain-by-using-sfhfkeychainutils

Thanks!

答:
I've been through this, but I don't have any link with an Api or something you can use, but some advices:

-with multitasking you should call the passcode view in the becomeActive method in the app delegate too, the way that your app could prompt for a passcode when in returns from background.

basically you have to call de passcode in two methods:

```<code>- (void)applicationDidEnterBackground:(UIApplication *)application

- (void)applicationDidBecomeActive:(UIApplication *)application
</code>```

the first one is called before going background, and it is better to call to present the code lock view before going to background than after, because if you call this after, you should probably see the application as you left it before going to background, before the code lock view is presented.

the second one, is kinda obvious =D, but you have to control not to present the code lock  twice, because the second method is also called when you return from background.

-Related to the password, it can be stored in some custom configuration file, such us a plist with a little encryption.

-Related to the view, you can create your own viewController with some protocols that handles this kind of behavior. Not big deal.

Hope this helps, bye

ContentLicense: CC BY-SA 2.5

Title: iPhone Passcode Integration

Body:
I've been through this, but I don't have any link with an Api or something you can use, but some advices:

-with multitasking you should call the passcode view in the becomeActive method in the app delegate too, the way that your app could prompt for a passcode when in returns from background.

basically you have to call de passcode in two methods:

- (void)applicationDidEnterBackground:(UIApplication *)application

- (void)applicationDidBecomeActive:(UIApplication *)application

the first one is called before going background, and it is better to call to present the code lock view before going to background than after, because if you call this after, you should probably see the application as you left it before going to background, before the code lock view is presented.

the second one, is kinda obvious =D, but you have to control not to present the code lock  twice, because the second method is also called when you return from background.

-Related to the password, it can be stored in some custom configuration file, such us a plist with a little encryption.

-Related to the view, you can create your own viewController with some protocols that handles this kind of behavior. Not big deal.

Hope this helps, bye


问:
Spring Integration IBM MQ JMS client
I have written code to send/read message from IBM MQ using Spring Integration JMS-message-driven-channel-adapter but not able to parse the JMS text response message...below is my integration xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:int="http://www.springframework.org/schema/integration"
        xmlns:int-jms="http://www.springframework.org/schema/integration/jms"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/integration
            http://www.springframework.org/schema/integration/spring-integration.xsd
            http://www.springframework.org/schema/integration/jms
            http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd">

        <context:annotation-config />
        <context:component-scan base-package="com.*****" />

        <!-- Factory Defintions -->
        <bean id="connectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
            <property name="transportType" value="1" />
            <property name="queueManager" value="****" />
            <property name="hostName" value="******" />
            <property name="port" value="****" />
            <property name="channel" value="******" />
        </bean>

        <!-- Queue Definition -->
        <bean id="inQueue" class="com.ibm.mq.jms.MQQueue" depends-on="connectionFactory">
            <constructor-arg index="0" value="****" />
            <constructor-arg index="1" value="*****" />
        </bean>

        <bean id="outQueue" class="com.ibm.mq.jms.MQQueue" depends-on="connectionFactory">
            <constructor-arg index="0" value="*****" />
            <constructor-arg index="1" value="******" />
        </bean>

        <bean id="messageListener" class="com.***.MessageListener"/>
        <bean id="messagePublisher" class="com.*****.MessagePublisher"/>

        <!-- OUTBOUND settings -->

        <int:channel id="senderChannel" />

        <int-jms:outbound-channel-adapter id="jmsOut" destination="outQueue" channel="senderChannel"/>

       <!--  <int:service-activator output-channel="senderChannel" ref="messagePublisher" method="processMessage" /> -->

        <!-- INBOUND settings -->

        <int:channel id="recieverChannel" />

        <int-jms:message-driven-channel-adapter id="jmsIn" destination="inQueue" channel="recieverChannel" extract-payload="false" />

        <int:service-activator input-channel="recieverChannel" ref="messageListener" method="processMessage" />

    </beans>
</code>```

The process intends to send a message over MQ to external server and they may(or may not respond) with an ack.

Publisher code:

```<code>import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.integration.support.MessageBuilder;
    import org.springframework.messaging.MessageChannel;

    public class MessagePublisher {

        @Autowired
        private MessageChannel senderChannel;

        public void processMessage(String message) {
            System.out.println("MessagePublisher::::::Sent message: " + message);

            senderChannel.send(MessageBuilder.withPayload(message).build());
        }
    }
</code>```

Currently in my listener I try to print the ack as :

```<code>    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.TextMessage;

    public class MessageListener {

        public void processMessage(Message message) {

            if (message instanceof TextMessage) {
                TextMessage txtmsg = (TextMessage) message;

                try {

                    System.out.println("MessageListener::::::Received message: "
                            + txtmsg.getText());
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
</code>```

The problem is when I get the message back the body contains encoded string as:

MessageListener::::::Received message: [prints encoded special chars here]

How can I parse the complete response text in a proper format? I checked the instance of response object seems to be JMS text message only, but when printed on console I only see encoded string message.

答:
OK. I think your problem is really with character encoding, which is different on sender and receiver:

Try this:

```<code>byte[] by = ((TextMessage) msg).getText().getBytes("ISO-8859-1");
String text = new String(by,"UTF-8");
</code>```

More info is here: Encoding a JMS TextMessage and here.

Title: Spring Integration IBM MQ JMS client

Body:
I have written code to send/read message from IBM MQ using Spring Integration JMS-message-driven-channel-adapter but not able to parse the JMS text response message...below is my integration xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:int="http://www.springframework.org/schema/integration"
        xmlns:int-jms="http://www.springframework.org/schema/integration/jms"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/integration
            http://www.springframework.org/schema/integration/spring-integration.xsd
            http://www.springframework.org/schema/integration/jms
            http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd">

        <context:annotation-config />
        <context:component-scan base-package="com.*****" />

        <bean id="connectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
            <property name="transportType" value="1" />
            <property name="queueManager" value="****" />
            <property name="hostName" value="******" />
            <property name="port" value="****" />
            <property name="channel" value="******" />
        </bean>

        <bean id="inQueue" class="com.ibm.mq.jms.MQQueue" depends-on="connectionFactory">
            <constructor-arg index="0" value="****" />
            <constructor-arg index="1" value="*****" />
        </bean>

        <bean id="outQueue" class="com.ibm.mq.jms.MQQueue" depends-on="connectionFactory">
            <constructor-arg index="0" value="*****" />
            <constructor-arg index="1" value="******" />
        </bean>

        <bean id="messageListener" class="com.***.MessageListener"/>
        <bean id="messagePublisher" class="com.*****.MessagePublisher"/>

        <int:channel id="senderChannel" />

        <int-jms:outbound-channel-adapter id="jmsOut" destination="outQueue" channel="senderChannel"/>

        <int:channel id="recieverChannel" />

        <int-jms:message-driven-channel-adapter id="jmsIn" destination="inQueue" channel="recieverChannel" extract-payload="false" />

        <int:service-activator input-channel="recieverChannel" ref="messageListener" method="processMessage" />

    </beans>

The process intends to send a message over MQ to external server and they may(or may not respond) with an ack.

Publisher code:

import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.integration.support.MessageBuilder;
    import org.springframework.messaging.MessageChannel;

    public class MessagePublisher {

        @Autowired
        private MessageChannel senderChannel;

        public void processMessage(String message) {
            System.out.println("MessagePublisher::::::Sent message: " + message);

            senderChannel.send(MessageBuilder.withPayload(message).build());
        }
    }

Currently in my listener I try to print the ack as :

    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.TextMessage;

    public class MessageListener {

        public void processMessage(Message message) {

            if (message instanceof TextMessage) {
                TextMessage txtmsg = (TextMessage) message;

                try {

                    System.out.println("MessageListener::::::Received message: "
                            + txtmsg.getText());
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

The problem is when I get the message back the body contains encoded string as:

MessageListener::::::Received message: [prints encoded special chars here]

How can I parse the complete response text in a proper format? I checked the instance of response object seems to be JMS text message only, but when printed on console I only see encoded string message.

Body:
OK. I think your problem is really with character encoding, which is different on sender and receiver:

Try this:

byte[] by = ((TextMessage) msg).getText().getBytes("ISO-8859-1");
String text = new String(by,"UTF-8");

More info is here: Encoding a JMS TextMessage and here.


问:
Append a Symbol on textbox on key space pressed
Append a Symbol on textbox on key space pressed

Hi hello, I try to make a search engine program and I need to insert % when they press the space key.

I have succeeded in inserting the symbol % but it puts an empty space after it. I would like to append the symbol without the empty space.

Thank you in advance

This is my code

```<code>Public Class Form2
Public Sub New()
    Me.InitializeComponent()
    Me.KeyPreview = True
End Sub

Private Sub Button1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Button1.KeyDown
    tbSearch.AppendText("%")
    'If e.KeyCode = Keys.Space Then
    'e.SuppressKeyPress = True
    'End If
End Sub

Private Sub Form2_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Space Then
        tbSearch.AppendText("%")
        tbSearch.Text.Trim()
    End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim pict = "https://i.ytimg.com/vi/" + TextBox1.Text + "/hqdefault.jpg?custom=true&w=168&h=94&stc=true&jpg444=true&jpgq=90&sp=68&sigh=6rUlsKOOsNW2_I8q7wgQJZ-z3Mw"
    PictureBox1.ImageLocation = pict
    Dim Link = "http://www.youtube.com/results?search_type=&search_query=" + TextBox1.Text + "&aq=f"

    ProgressBar1.Value = 0

    ProgressBar1.Value = 100
    Form1.TextBox1.Text = Me.TextBox1.Text
    MsgBox("Video Have Been Load And Are Ready To Play...")
    ProgressBar1.Value = 0
    Me.Close()

End Sub

Private Sub BackMainPageToolStripMenuItem_Click(sender As Object, e As EventArgs)

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

End Sub

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click

End Sub

Public Function SwapClipboardHtmlText( _
ByVal replacementHtmlText As String) As String

    Dim returnHtmlText As String = Nothing

    If (Clipboard.ContainsText(TextDataFormat.Html)) Then
        returnHtmlText = Clipboard.GetText(TextDataFormat.Html)
        Clipboard.SetText(replacementHtmlText, TextDataFormat.Html)
    End If

    Return returnHtmlText
    TextBox1.Text = returnHtmlText
End Function

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
    Dim pict = "https://i.ytimg.com/vi/" + TextBox1.Text + "/hqdefault.jpg?custom=true&w=168&h=94&stc=true&jpg444=true&jpgq=90&sp=68&sigh=6rUlsKOOsNW2_I8q7wgQJZ-z3Mw"
    Me.WebBrowser2.ScriptErrorsSuppressed() = True
    Me.WebBrowser1.ScriptErrorsSuppressed() = True
    Dim info = "http://gdata.youtube.com/feeds/api/videos/" + tbSearch.Text

    Me.WebBrowser2.Navigate("https://www.google.pt/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=" + tbSearch.Text + "&*")
    Process.Start("chrome", "https://www.youtube.com/results?search_query=" + tbSearch.Text)

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Process.Start("chrome", "http://www.google.com/search?hl=en&q=" + tbSearch.Text + "&aq=f&oq=")
End Sub

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    tbSearch.Select()
    MsgBox("Type Your Search Keyword And Press Search Youtube")
End Sub
End Class
</code>```

答:
You can set the KeyEventArgs.SuppressKeyPress property to True to make it ignore the currently pressed key, but for that to work you must handle the text box's KeyDown event rather than the form's.

```<code>Private Sub tbSearch_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbSearch.KeyDown
    If e.KeyCode = Keys.Space Then
        tbSearch.AppendText("%")
        e.SuppressKeyPress = True
    End If
End Sub
</code>```

Body:
Append a Symbol on textbox on key space pressed

Hi hello, I try to make a search engine program and I need to insert % when they press the space key.

I have succeeded in inserting the symbol % but it puts an empty space after it. I would like to append the symbol without the empty space.

Thank you in advance

This is my code

Public Class Form2
Public Sub New()
    Me.InitializeComponent()
    Me.KeyPreview = True
End Sub

Private Sub Button1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Button1.KeyDown
    tbSearch.AppendText("%")
    'If e.KeyCode = Keys.Space Then
    'e.SuppressKeyPress = True
    'End If
End Sub

Private Sub Form2_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Space Then
        tbSearch.AppendText("%")
        tbSearch.Text.Trim()
    End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim pict = "https://i.ytimg.com/vi/" + TextBox1.Text + "/hqdefault.jpg?custom=true&w=168&h=94&stc=true&jpg444=true&jpgq=90&sp=68&sigh=6rUlsKOOsNW2_I8q7wgQJZ-z3Mw"
    PictureBox1.ImageLocation = pict
    Dim Link = "http://www.youtube.com/results?search_type=&search_query=" + TextBox1.Text + "&aq=f"

    ProgressBar1.Value = 0

    ProgressBar1.Value = 100
    Form1.TextBox1.Text = Me.TextBox1.Text
    MsgBox("Video Have Been Load And Are Ready To Play...")
    ProgressBar1.Value = 0
    Me.Close()

End Sub

Private Sub BackMainPageToolStripMenuItem_Click(sender As Object, e As EventArgs)

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

End Sub

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click

End Sub

Public Function SwapClipboardHtmlText( _
ByVal replacementHtmlText As String) As String

    Dim returnHtmlText As String = Nothing

    If (Clipboard.ContainsText(TextDataFormat.Html)) Then
        returnHtmlText = Clipboard.GetText(TextDataFormat.Html)
        Clipboard.SetText(replacementHtmlText, TextDataFormat.Html)
    End If

    Return returnHtmlText
    TextBox1.Text = returnHtmlText
End Function

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
    Dim pict = "https://i.ytimg.com/vi/" + TextBox1.Text + "/hqdefault.jpg?custom=true&w=168&h=94&stc=true&jpg444=true&jpgq=90&sp=68&sigh=6rUlsKOOsNW2_I8q7wgQJZ-z3Mw"
    Me.WebBrowser2.ScriptErrorsSuppressed() = True
    Me.WebBrowser1.ScriptErrorsSuppressed() = True
    Dim info = "http://gdata.youtube.com/feeds/api/videos/" + tbSearch.Text

    Me.WebBrowser2.Navigate("https://www.google.pt/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=" + tbSearch.Text + "&*")
    Process.Start("chrome", "https://www.youtube.com/results?search_query=" + tbSearch.Text)

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Process.Start("chrome", "http://www.google.com/search?hl=en&q=" + tbSearch.Text + "&aq=f&oq=")
End Sub

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    tbSearch.Select()
    MsgBox("Type Your Search Keyword And Press Search Youtube")
End Sub
End Class

Body:
You can set the KeyEventArgs.SuppressKeyPress property to True to make it ignore the currently pressed key, but for that to work you must handle the text box's KeyDown event rather than the form's.

Private Sub tbSearch_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbSearch.KeyDown
    If e.KeyCode = Keys.Space Then
        tbSearch.AppendText("%")
        e.SuppressKeyPress = True
    End If
End Sub


问:
Shorten Dynamic SQL Query For Loop
I have a function that builds an sql query and then inserts it into the client-side light sql.

I think im using to many for loops, how would i make this shorter?

```<code>function insert(dataBase,table,row){
    var j = 0;

    var sqlQueryArray = [];

    sqlQueryArray[j++] = 'INSERT INTO ';
    sqlQueryArray[j++] = table
    sqlQueryArray[j++] = ' ('

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = row[i].id + ',';
    };

    sqlQueryArray[j++] = row[(row.length - 1)].id + '';
    sqlQueryArray[j++] = ')'
    var sqlQueryString = ' VALUES ';

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = '?, ';
    };

    sqlQueryArray[j++] = '?';
    sqlQueryArray[j++] = ');'

    for (var i = 0; i < sqlQueryArray.length; i++){
        sqlQueryString += sqlQueryArray[i];
    }
    var rowArray = []
    for (var i = row.length - 1; i >= 0; i--){
        rowArray[i] = row[i].val;
    };

    dataBase.openDatabase.transaction(
        function (transaction) {
            transaction.executeSql(sqlQueryString,
                rowArray,
                dataBase.nullSQLHandler, dataBase.QueryError);
        }
    );
}
</code>```

答:
Whenver Dynamic SQL is created in an application, things are unleashed and children are eaten.

You should really use a parameterized SP for this one for a multitude of security and performance reasons (not to mention readability/maintainability).

Title: Shorten Dynamic SQL Query For Loop

Body:
I have a function that builds an sql query and then inserts it into the client-side light sql.

I think im using to many for loops, how would i make this shorter?

function insert(dataBase,table,row){
    var j = 0;

    var sqlQueryArray = [];

    sqlQueryArray[j++] = 'INSERT INTO ';
    sqlQueryArray[j++] = table
    sqlQueryArray[j++] = ' ('

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = row[i].id + ',';
    };

    sqlQueryArray[j++] = row[(row.length - 1)].id + '';
    sqlQueryArray[j++] = ')'
    var sqlQueryString = ' VALUES ';

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = '?, ';
    };

    sqlQueryArray[j++] = '?';
    sqlQueryArray[j++] = ');'

    for (var i = 0; i < sqlQueryArray.length; i++){
        sqlQueryString += sqlQueryArray[i];
    }
    var rowArray = []
    for (var i = row.length - 1; i >= 0; i--){
        rowArray[i] = row[i].val;
    };

    dataBase.openDatabase.transaction(
        function (transaction) {
            transaction.executeSql(sqlQueryString,
                rowArray,
                dataBase.nullSQLHandler, dataBase.QueryError);
        }
    );
}


问:
Calling Web service methods is the part of model or controller in MVC patterns
As I am preparing for interviews as in iOS developer. Most of the time a question is asked is "If your are using MVC design pattern in your project and you need to write the code for calling web service like fetching user info from server. Where should you write the code 1.In Model class or controller class or some where else"</p>

答:
Its obvious model class.

Web request flow should be: The View Controller gets the web request (via buttons) from the users and send the inputs to the model. The Model will calculate and send the result back to Controller. Lastly, the controller will present the data on screen via a Display view.

MVC:

Model – What your application is about? (Data, Logics, Rules). All communicating code shold be written here.

Controller – How you present your application (model) to the end users?. ViewController, its a mediator bet view and model.

View – The interface which the end users see. Its a depecting part of app see image.


问:
Google JavaScript API returns error on client init
My coworker created a new repo, and on their machine loading the Google JS API loads no problem, but when I try to run gapi.client.init it returns the error below.

```<code>{
  "error" : "invalid_request",
  "error_description" : "invalid login_hint."
}
</code>```

When I look at the request on the network, it sends a string for the value of login_hint as a query string parameter, but I don't have that string anywhere in my codebase.

```<code>login_hint:AJDLj6...iriMjPL4JkmR_A
</code>```

If I create a new set of credentials from the Google API console and use the new client ID it works as I would expect it to. But using the existing set of credentials causes an error, without changing anything else.

My code looks like this:

export class GoogleApiService {

    CLIENT_ID: string = '<removed>.apps.googleusercontent.com';
    DISCOVERY_DOCS = ['<removed>'];
    SCOPES = '<removed>';

    constructor() {
        window['initGapi'] = (ev) => {
            this.handleClientLoad();
        };
        this.loadScript();
    }

    loadScript() {
        let script = document.createElement('script');
        script.src = 'https://apis.google.com/js/api.js?onload=initGapi';
        script.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    handleClientLoad() {
        gapi.load('client:auth2', this.initClient.bind(this));
    }

    initClient() {
        gapi.client.init({
            discoveryDocs: this.DISCOVERY_DOCS,
            clientId: this.CLIENT_ID,
            scope: this.SCOPES
        }).then(() => {
          console.log('loaded');
        },
        (err) => console.error(err));
    }
}
```

I'm not specifying the login_hint, so why is that being sent in the request to Google? Why is it incorrect and how can I prevent the error message from occurring?

答:
For what it's worth, I ended up logging out of my Google account, clicking on the signup link in my app, and in the popup window, signed into my Google account, and it now it all works and I am unable to reproduce. Not sure what caused it originally, but that was my solution.

Hopefully my users never encounter this issue.

Body:
My coworker created a new repo, and on their machine loading the Google JS API loads no problem, but when I try to run gapi.client.init it returns the error below.

{
  "error" : "invalid_request",
  "error_description" : "invalid login_hint."
}

When I look at the request on the network, it sends a string for the value of login_hint as a query string parameter, but I don't have that string anywhere in my codebase.

login_hint:AJDLj6...iriMjPL4JkmR_A

If I create a new set of credentials from the Google API console and use the new client ID it works as I would expect it to. But using the existing set of credentials causes an error, without changing anything else.

My code looks like this:

export class GoogleApiService {

    CLIENT_ID: string = '<removed>.apps.googleusercontent.com';
    DISCOVERY_DOCS = ['<removed>'];
    SCOPES = '<removed>';

    constructor() {
        window['initGapi'] = (ev) => {
            this.handleClientLoad();
        };
        this.loadScript();
    }

    loadScript() {
        let script = document.createElement('script');
        script.src = 'https://apis.google.com/js/api.js?onload=initGapi';
        script.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    handleClientLoad() {
        gapi.load('client:auth2', this.initClient.bind(this));
    }

    initClient() {
        gapi.client.init({
            discoveryDocs: this.DISCOVERY_DOCS,
            clientId: this.CLIENT_ID,
            scope: this.SCOPES
        }).then(() => {
          console.log('loaded');
        },
        (err) => console.error(err));
    }
}

I'm not specifying the login_hint, so why is that being sent in the request to Google? Why is it incorrect and how can I prevent the error message from occurring?


问:
Custom 404 Page for Static Website using AWS S3 buckets not working
I have added in my bucket properties "static website hosting", then "use this bucket to host a website" and added 404.html to the "error document". After that I added the actual 404.html to my bucket. and it still doesn't work. Is there a step I'm missing?

Any help would be appreciated!

答:
If your S3 bucket has "Static website hosting" turned on, you can set an error page.

If there is any engine like Angular js or Reactjs, you can set the error page in the app.

And another option is to put Amazon CloudFront in front of S3, in it you can also customize the error pages, by several status codes (404, 500, etc.):

http://docs.aws.amazon.com/pt_br/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html


问:
Dealing with Flexbox in tablet views
I've been brought in to help deal with a rendering issue with a website. Specifically, a flexbox element goes all wonky when displayed on tablets. Desktop testing has shown that the issue only crops up when the width and height of the page are set to, say, iPad or iPad Pro in chrome dev tools.

 has a section called "Our Top Areas Of Practice". In a desktop or mobile view this section works beautifully but at 768x1024 this section is stuck in a column to the right of the viewport. Any ideas on what would make Flexbox go all wonky like this?

答:
Add this css that would center the elements    </p>

```<code>@media (max-width:768px) {
      .fusion-layout-column .fusion-column-content-centered {
        display: inline-block;
      }
      .fusion-layout-column .fusion-column-content-centered .fusion-column-content {
        text-align: center;
      }
    }
</code>```

Title: Dealing with Flexbox in tablet views

Body:
Add this css that would center the elements

@media (max-width:768px) {
      .fusion-layout-column .fusion-column-content-centered {
        display: inline-block;
      }
      .fusion-layout-column .fusion-column-content-centered .fusion-column-content {
        text-align: center;
      }
    }


问:
Evaluate string from user to comma separated words string
Let's say I have a string given by user in the following form:

```<code>"single, single, double word, single  word, also      single"
</code>```

How I can parse this string to obtain string of comma separated words, where each not single whitespace is treated as a separator and replaced with ',', and each single is replaced with %20 ? So the result would be:

```<code>"single,single,double%20word,single,word,also,single"
</code>```

? can I do it in one step ?

答:
You probably could do it in a single step, but it would be safer to do it in two.

First use a regex to replace \s\s+ with ,

Then replace \s with %20

Body:
Let's say I have a string given by user in the following form:

"single, single, double word, single  word, also      single"

How I can parse this string to obtain string of comma separated words, where each not single whitespace is treated as a separator and replaced with ',', and each single is replaced with %20 ? So the result would be:

"single,single,double%20word,single,word,also,single"

? can I do it in one step ?


问:
if statement within double for loop: specific example
I'm writing a short code which compares two dataframes- list & knownlocation. I want to know for each item in list, whether it falls within a knownlocation.

```<code>colnames(list) <- c("gene_symbol", "chromo", "start", "end")
colnames(knownlocation) <- c("snp", "chr", "s", "e")
</code>```

To find this I wrote the code to make a new column in "list" saying TRUE or FALSE whether it's in any of knownlocation:

```<code>for (i in 1:nrow(list)) {
for (j in 1:nrow(knownlocation)) {
if ( (list[i, 2] == knownlocation[j, 2]) && (list[i, 3] >= knownlocation[j, 3]) && (list[i, 4] <= knownlocation[j, 4]) ) {
list[i, 5] = "TRUE" }
else { list[i, 5] = "FALSE"}
}}
</code>```

This code looks fine to me and it runs with no errors. Problem is the entire list shows FALSE, even if it does fall within a location in knownlocation. Can anyone find something obviously wrong that I'm missing?

答:
Issue is the else clause will overwrite with FALSE on previous instances where TRUE was found. Basically, you only want to store TRUE when condition is met, but initialize all values to FALSE prior to execution of the loop.

Try and remove the else clause.

To initialize column 5 of the list with FALSE do the following right before the the nested looping:

```<code>list$V5 = FALSE
</code>```

Code:

```<code>list$V5=TRUE
for (i in 1:nrow(list)) {
  for (j in 1:nrow(knownlocation)) {
    if ( (list[i, 2] == knownlocation[j, 2]) && (list[i, 3] >= knownlocation[j, 3]) && (list[i, 4] <= knownlocation[j, 4]) ) {
      list[i, 5] = "TRUE" }
}
</code>```

Body:
I'm writing a short code which compares two dataframes- list & knownlocation. I want to know for each item in list, whether it falls within a knownlocation.

colnames(list) <- c("gene_symbol", "chromo", "start", "end")
colnames(knownlocation) <- c("snp", "chr", "s", "e")

To find this I wrote the code to make a new column in "list" saying TRUE or FALSE whether it's in any of knownlocation:

for (i in 1:nrow(list)) {
for (j in 1:nrow(knownlocation)) {
if ( (list[i, 2] == knownlocation[j, 2]) && (list[i, 3] >= knownlocation[j, 3]) && (list[i, 4] <= knownlocation[j, 4]) ) {
list[i, 5] = "TRUE" }
else { list[i, 5] = "FALSE"}
}}

This code looks fine to me and it runs with no errors. Problem is the entire list shows FALSE, even if it does fall within a location in knownlocation. Can anyone find something obviously wrong that I'm missing?

Body:
Issue is the else clause will overwrite with FALSE on previous instances where TRUE was found. Basically, you only want to store TRUE when condition is met, but initialize all values to FALSE prior to execution of the loop.

Try and remove the else clause.

To initialize column 5 of the list with FALSE do the following right before the the nested looping:

list$V5 = FALSE

Code:

list$V5=TRUE
for (i in 1:nrow(list)) {
  for (j in 1:nrow(knownlocation)) {
    if ( (list[i, 2] == knownlocation[j, 2]) && (list[i, 3] >= knownlocation[j, 3]) && (list[i, 4] <= knownlocation[j, 4]) ) {
      list[i, 5] = "TRUE" }
}


问:
Java. How do I make code more effectly, HashMap?
I have started learn Java sometime ago, and now I have interesting quest from my teacher. I will be very grateful for everyone who can help me. And I don`t want to get directly answer for my question, I want to see way which help for me understand core.

This is fragment from my code.

Higher I have some text (String) which was convert to List.

```<code>List<String> list = Arrays.asList( text.split( " "));

Map<String, Integer> hashMap = new HashMap<>();
int uniqueWords = 0;
for (String word: list){
    Integer count = hashMap.get(word);
    hashMap.put(word, count == null ? 1 : count + 1);
    if (count == null){
        uniqueWords++;
    }else if (count == 1){
        uniqueWords --;
    }
}
</code>```

I need to do code more effective. I thinking several days and can`t prupose more effectly code. I need help )

答:
There are number of things just from "theoretical" glance:

You check value of count from map 3 times. You can do it only once

You can still use if statement(s) or you can use switch statement too

as @John Bollinger said String[] right out of split is enough.

Instead of using hasMap.get(word) first and check is count == null you can do hashMap.containsKey(word) first. It does not do much difference, just a matter of taste.

PS. There are more "exotic" ways with List like using indexOf, lastIndexOf, subList...

Body:
I have started learn Java sometime ago, and now I have interesting quest from my teacher. I will be very grateful for everyone who can help me. And I don`t want to get directly answer for my question, I want to see way which help for me understand core.

This is fragment from my code.

Higher I have some text (String) which was convert to List.

List<String> list = Arrays.asList( text.split( " "));

Map<String, Integer> hashMap = new HashMap<>();
int uniqueWords = 0;
for (String word: list){
    Integer count = hashMap.get(word);
    hashMap.put(word, count == null ? 1 : count + 1);
    if (count == null){
        uniqueWords++;
    }else if (count == 1){
        uniqueWords --;
    }
}

I need to do code more effective. I thinking several days and can`t prupose more effectly code. I need help )


问:
Python matcher not matching
I'm trying to write a very simple regex script in python that matches all lowercase characters, but the matcher is returning "None"

Here's my code:

```<code>p = re.compile('[a-z]+')
print(p.match('This is a test'))
p
</code>```

答:
You are using the wrong method, match doesn't search the whole string, it only checks if the string matches starting from the beginning of the string.

Take a look at this documentation

the search function might do it though!

```<code>p = re.compile('[a-z]+')
s = p.search('This is a test')
print(s.group(0))
</code>```

Title: Python matcher not matching

Body:
I'm trying to write a very simple regex script in python that matches all lowercase characters, but the matcher is returning "None"

Here's my code:

p = re.compile('[a-z]+')
print(p.match('This is a test'))
p

Body:
You are using the wrong method, match doesn't search the whole string, it only checks if the string matches starting from the beginning of the string.

Take a look at this documentation

the search function might do it though!

p = re.compile('[a-z]+')
s = p.search('This is a test')
print(s.group(0))


问:
Behavior of Async logger in log4j2
My log4j2.xml contains both sync and async loggers. However, when I use the async loggers I could only get the first (out of 5) log.debug statement to be printed.

Update 3/28 --
If I introduce a Thread.sleep(1) before the log.debug calls..  then I am able to get all the debug messages logged via Async logger --> Rewrite Appender --> Rolling File Appender But not sure how to achieve this without that sleep statement..

```<code><Configuration status="WARN" packages="com.loggy.test">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>

    <!--  Custom Appender Approach below -->
    <Stub name="myapp" fileName="/Users/loggy/logs/myapp.log"
                 filePattern="logs/myapp-%d{MM-dd-yyyy}.log.gz">
         <RegexFilter regex=".* special_log .*" onMatch="ACCEPT" onMismatch="DENY"/>
        <PatternLayout>
                    <pattern>%d %p %c{1.} [%t] %m%n</pattern>
          </PatternLayout>
          <TimeBasedTriggeringPolicy />
    </Stub>
    <!--  Custom Appender Approach above ends here -->

    <RollingFile name="RollingFile" fileName="/Users/loggy/logs/roll_file_app.log"
                 filePattern="logs/app-%d{MM-dd-yyyy}.log.gz">
           <PatternLayout>
                    <pattern>%d %p %c{1.} [%t] %m%n</pattern>
          </PatternLayout>
          <TimeBasedTriggeringPolicy />
    </RollingFile>

    <Rewrite name="Rewrite" ignoreExceptions = "false">
        <CookieAppenderPolicy cookieNeeded="true">
        </CookieAppenderPolicy>
        <AppenderRef ref="RollingFile"/>
    </Rewrite>
  </Appenders>
    <Loggers>
        <AsyncLogger name="com.loggy.test" level="debug" includeLocation="true">
            <AppenderRef ref="Rewrite" />
        </AsyncLogger>
    <Root level="trace">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

package com.loggy.test;

public class TestJ {
    @Inject
    public static void main(String[] args)
    {
        final Logger log4j = LogManager.getLogger(TestJ.class
                .getName());

        log4j.trace(" special_log Trace");

/* When Async logger is used, Only this line below gets printed to the Rewrite Appender and hence to the Rolling File appender */

        log4j.debug(" special_log debug published!");

    log4j.info(" special_log test info");

    log4j.debug(" sd_log test info");

   /* Following lines NEVER gets published to the rolling file appender or to the Rewrite Appender */

    log4j.debug(" special_log debug 2");

    log4j.debug(" special_log debug 3");

    log4j.debug(" special_log debug 4");

    log4j.debug(" special_log debug 5");

}
</code>```

However, if I include the <AppenderRef ref="Rewrite" /> outside the <AsyncLogger> then I get all the lines published.

Any thoughts as to what should be changed with the log4j2.xml so that I get all the appropriate lines when I use the AsyncLogger?

I also noticed that inside log4j2 package theAsyncLoggerConfig.java class the code never gets to the super.callAppenders(event);.

I am assuming that the super.callAppenders(event) has to work for the referenced appenders to be called? How can I make this line be executed via the log4j2.xml?

```<code>/**  AsyncLoggerConfig.java
 * Passes on the event to a separate thread that will call
 * {@link #asyncCallAppenders(LogEvent)}.
 */
@Override
protected void callAppenders(final LogEvent event) {
    // populate lazily initialized fields
    event.getSource();

event.getThreadName();

// pass on the event to a separate thread
if (!helper.callAppendersFromAnotherThread(event)) {
    super.callAppenders(event);
}
}
</code>```

答: This problem has been resolved in later versions of Log4j. The solution is to upgrade from version 2.0-rc1 to the latest version (2.8.1 as of this writing). </p>

Title: Behavior of Async logger in log4j2

Body:
My log4j2.xml contains both sync and async loggers. However, when I use the async loggers I could only get the first (out of 5) log.debug statement to be printed.

Update 3/28 --
If I introduce a Thread.sleep(1) before the log.debug calls..  then I am able to get all the debug messages logged via Async logger --> Rewrite Appender --> Rolling File Appender But not sure how to achieve this without that sleep statement..

<Configuration status="WARN" packages="com.loggy.test">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>

    <Stub name="myapp" fileName="/Users/loggy/logs/myapp.log"
                 filePattern="logs/myapp-%d{MM-dd-yyyy}.log.gz">
         <RegexFilter regex=".* special_log .*" onMatch="ACCEPT" onMismatch="DENY"/>
        <PatternLayout>
                    <pattern>%d %p %c{1.} [%t] %m%n</pattern>
          </PatternLayout>
          <TimeBasedTriggeringPolicy />
    </Stub>

    <RollingFile name="RollingFile" fileName="/Users/loggy/logs/roll_file_app.log"
                 filePattern="logs/app-%d{MM-dd-yyyy}.log.gz">
           <PatternLayout>
                    <pattern>%d %p %c{1.} [%t] %m%n</pattern>
          </PatternLayout>
          <TimeBasedTriggeringPolicy />
    </RollingFile>

    <Rewrite name="Rewrite" ignoreExceptions = "false">
        <CookieAppenderPolicy cookieNeeded="true">
        </CookieAppenderPolicy>
        <AppenderRef ref="RollingFile"/>
    </Rewrite>
  </Appenders>
    <Loggers>
        <AsyncLogger name="com.loggy.test" level="debug" includeLocation="true">
            <AppenderRef ref="Rewrite" />
        </AsyncLogger>
    <Root level="trace">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

package com.loggy.test;

public class TestJ {
    @Inject
    public static void main(String[] args)
    {
        final Logger log4j = LogManager.getLogger(TestJ.class
                .getName());

        log4j.trace(" special_log Trace");

/* When Async logger is used, Only this line below gets printed to the Rewrite Appender and hence to the Rolling File appender */

        log4j.debug(" special_log debug published!");

    log4j.info(" special_log test info");

    log4j.debug(" sd_log test info");

   /* Following lines NEVER gets published to the rolling file appender or to the Rewrite Appender */

    log4j.debug(" special_log debug 2");

    log4j.debug(" special_log debug 3");

    log4j.debug(" special_log debug 4");

    log4j.debug(" special_log debug 5");

}

However, if I include the <AppenderRef ref="Rewrite" /> outside the <AsyncLogger> then I get all the lines published.

Any thoughts as to what should be changed with the log4j2.xml so that I get all the appropriate lines when I use the AsyncLogger?

I also noticed that inside log4j2 package theAsyncLoggerConfig.java class the code never gets to the super.callAppenders(event);.

I am assuming that the super.callAppenders(event) has to work for the referenced appenders to be called? How can I make this line be executed via the log4j2.xml?

/**  AsyncLoggerConfig.java
 * Passes on the event to a separate thread that will call
 * {@link #asyncCallAppenders(LogEvent)}.
 */
@Override
protected void callAppenders(final LogEvent event) {
    // populate lazily initialized fields
    event.getSource();

event.getThreadName();

// pass on the event to a separate thread
if (!helper.callAppendersFromAnotherThread(event)) {
    super.callAppenders(event);
}
}


问:
-- SQL Generating Column and fill it automatically from the other column --
i need to create a query that runs like this; all employees with an education level of 18 or 20 will receive a salary increase of 1200 and their bonus will be cut in half. List the name, education level, new salary and new bonus for these employees. Use names NEW_SALARY and NEW_BONUS for the generated columns

The new salary = salary + 1200 (How can i do this?)
The new bonus = bonus/2 (How can i do this?

答:
After assuming lot of things ::  </p>

```<code>   Select name ,
          ed_level ,
          case when ed_level = 18 or ed_level = 20 then Salary + 1200 else
               salary  end as New_salary,
          case when ed_level = 18 or ed_level = 20 then bonus * 0.5 else bonus
               end  as new_bonus

   from yourTBL
</code>```

Body:
After assuming lot of things ::

   Select name ,
          ed_level ,
          case when ed_level = 18 or ed_level = 20 then Salary + 1200 else
               salary  end as New_salary,
          case when ed_level = 18 or ed_level = 20 then bonus * 0.5 else bonus
               end  as new_bonus

   from yourTBL


问:
JSON and ANDROID
I have a JSONArray:

myArray => [{"key1" : "value1", "key2" : "value2"}, {"key3" : "value3", "key4" : "value4"}]

If I do
    myArray.get(1);
I get a Object.

I want the single keys and values of myArray[1]. How can I do this?
There is a way to have a HashMap that contains {"key3" : "value3", "key4" : "value4"} ?

Please help me, thanks.

答: Instead of using myArray.get(), use myArray.getJSONObject() to return a JSONObject.  You can call getString(key), getDouble(key), getInt(key), etc on the JSONObject to access the values.  See the documentation at http://developer.android.com/reference/org/json/JSONObject.html and http://developer.android.com/reference/org/json/JSONArray.html

Title: JSON and ANDROID


问:
file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true
I'm trying to delete a file, after writing something in it, with FileOutputStream. This is the code I use for writing:

```<code>private void writeContent(File file, String fileContent) {
    FileOutputStream to;
    try {
        to = new FileOutputStream(file);
        to.write(fileContent.getBytes());
        to.flush();
        to.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

As it is seen, I flush and close the stream, but when I try to delete, file.delete() returns false.

I checked before deletion to see if the file exists, and: file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true. Just after calling these methods I try file.delete() and returns false.

Is there anything I've done wrong?

答:
FOR Eclipse/NetBeans

Restart your IDE and run your code again this is only trick work for me after one hour long struggle.

Here is my code:

```<code>File file = new File("file-path");
if(file.exists()){
  if(file.delete()){
     System.out.println("Delete");
  }
  else{

       System.out.println("not delete");
  }
}
</code>```

Output:

Delete

Body:
I'm trying to delete a file, after writing something in it, with FileOutputStream. This is the code I use for writing:

private void writeContent(File file, String fileContent) {
    FileOutputStream to;
    try {
        to = new FileOutputStream(file);
        to.write(fileContent.getBytes());
        to.flush();
        to.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

As it is seen, I flush and close the stream, but when I try to delete, file.delete() returns false.

I checked before deletion to see if the file exists, and: file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true. Just after calling these methods I try file.delete() and returns false.

Is there anything I've done wrong?

Body:
FOR Eclipse/NetBeans

Restart your IDE and run your code again this is only trick work for me after one hour long struggle.

Here is my code:

File file = new File("file-path");
if(file.exists()){
  if(file.delete()){
     System.out.println("Delete");
  }
  else{

       System.out.println("not delete");
  }
}

Output:

Delete


问:
How to open/load asp.net downloaded projects in Visual Studio 2013 without .sln or .csproj file
I'm a beginner at asp.net. I've downloaded a few projects of asp.net but several of them don't contain the .sln file or the .csproj file to run them on MS Visual Studio 13.
Question is how can I open/load downloaded projects on Visual studio 2013 and modify to my own needs. I've tried but couldn't find anything relevant. Any youtube link/step by step guide will be appreciated. Thanks.

答:
The .sln and .csproj files are necessary for VS to perform many actions because they specify important configuration info like compilation instructions, debug settings, etc.

If you need to build the projects using Visual Studio, then you're going to need those files. Since you don't have those presently, it stands to reason that you could create new ones. Create a new ASP.Net project in Visual Studio, select the options that best fit what you're trying to do, and then add the downloaded files to your new solution/projects.

EDIT: or, if you're opening a website, do as SouXin recommended in his answer.


问:
Why do I get a Red Exclamation after I have done a Update?
I have Tortoise SVN installed and am using it in Windows Explorer.  A colleague has updated some files I assume because I had a exclamation point on some folders.  I did a update to get the latest version but I still see a red exclamation point.</p>

答:
I have recently seen the red exclamation mark persist after SVN cleanups and updates due to multiple files having the same name but different casing in the same repository folder. Tortoise SVN allows multiple files to exist in the same location with the same name with mixed casing, but Windows does not.

As an example, at one location in the repository, 2 files existed: file.txt and File.txt. When I would go to SVN update the working copy, file explorer would only allow one of these files to exist, so only one would be included in my working copy after an SVN update.

When I ran “check for modifications” on my working copy, Tortoise SVN reported that the file that couldn’t be checked out was missing, since it was not allowed to be checked out to my working copy folder.
To resolve this, I deleted one of the duplicative files from the SVN repository and ran an update on my working copy.


问:
A more pythonic way to define an enum with dynamic members
I needed to create an enum to represent the ISO country codes. The country code data comes from a json file which can be obtained from: https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

So what I've done is:

```<code>data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
              for i in range(len(data))]

CountryCode = enum.Enum('CountryCode', codes_list,)

names_dict = {int(data[i]['country-code']):data[i]['name']
              for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)

CountryCode.choices = classmethod(lambda cls:((member.value, name)
                                  for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])
</code>```

This code snippet is frankly ugly. I looked at alternative ways to define the enum class but couldn't piece together a solution. Is there a way to define the enum in the following form:

```<code>class CountryCode(enum.Enum):

    data = json.load(open('slim-2.json'))
    # Some code to define the enum members

    @classmethod
    def choices(cls):
    # etc...
</code>```

Any suggestions on how to do this?

答:
Update

Using JSONEnum at the bottom of When should I subclass EnumMeta instead of Enum?, you can do this:

```<code>class Country(JSONEnum):
    _init_ = 'abbr code country_name'  # remove if not using aenum
    _file = 'some_file.json'
    _name = 'alpha-2'
    _value = {
            1: ('alpha-2', None),
            2: ('country-code', lambda c: int(c)),
            3: ('name', None),
            }
</code>```

Original Answer

It looks like you are trying to keep track of three pieces of data:

country name

country code

country 2-letter abbreviaton

You should consider using a technique inspired by a namedtuple mixin as illustrated in this answer:

The stdlib way

We'll need a base class to hold the behavior:

```<code>from enum import Enum
import json

class BaseCountry(Enum):

    def __new__(cls, record):
        member = object.__new__(cls)
        member.country_name = record['name']
        member.code = int(record['country-code'])
        member.abbr = record['alpha-2']
        member._value_ = member.abbr, member.code, member.country_name
        if not hasattr(cls, '_choices'):
            cls._choices = {}
        cls._choices[member.code] = member.country_name
        cls._choices[member.abbr] = member.country_name
        return member

    def __str__(self):
        return self.country_name

    @classmethod
    def choices(cls):
        return cls._choices.copy()
</code>```

Then we can use that to create the actual Country class:

```<code>Country = BaseCountry(
        'Country',
        [(rec['alpha-2'], rec) for rec in json.load(open('slim-2.json'))],
        )
</code>```

The aenum way 1 2

```<code>from aenum import Enum, MultiValue
import json

class Country(Enum, init='abbr code country_name', settings=MultiValue):

    _ignore_ = 'this country'  # do not add these names as members

    # create members
    this = vars()
    for country in json.load(open('slim-2.json')):
        this[country['alpha-2']] = (
                country['alpha-2'],
                int(country['country-code']),
                country['name'],
                )

    # return a dict of choices by abbr or country code to name
    @classmethod
    def choices(cls):
        mapping = {}
        for member in cls:
            mapping[member.code] = member.name
            mapping[member.abbr] = member.name
        return mapping

    # have str() print just the country name
    def __str__(self):
        return self.country_name
</code>```

While I included the choices method, you may not need it:

```<code>>>> Country('AF')
<Country.AF: ('AF', 4, 'Afghanistan')>

>>> Country(4)
<Country.AF: ('AF', 4, 'Afghanistan')>

>>> Country('Afghanistan')
<Country.AF: ('AF', 4, 'Afghanistan')>
</code>```

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.

2 This requires aenum 2.0.5+.

Body:
I needed to create an enum to represent the ISO country codes. The country code data comes from a json file which can be obtained from: https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

So what I've done is:

data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
              for i in range(len(data))]

CountryCode = enum.Enum('CountryCode', codes_list,)

names_dict = {int(data[i]['country-code']):data[i]['name']
              for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)

CountryCode.choices = classmethod(lambda cls:((member.value, name)
                                  for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])

This code snippet is frankly ugly. I looked at alternative ways to define the enum class but couldn't piece together a solution. Is there a way to define the enum in the following form:

class CountryCode(enum.Enum):

    data = json.load(open('slim-2.json'))
    # Some code to define the enum members

    @classmethod
    def choices(cls):
    # etc...

Any suggestions on how to do this?

Body:
Update

Using JSONEnum at the bottom of When should I subclass EnumMeta instead of Enum?, you can do this:

class Country(JSONEnum):
    _init_ = 'abbr code country_name'  # remove if not using aenum
    _file = 'some_file.json'
    _name = 'alpha-2'
    _value = {
            1: ('alpha-2', None),
            2: ('country-code', lambda c: int(c)),
            3: ('name', None),
            }

Original Answer

It looks like you are trying to keep track of three pieces of data:

country name

country code

country 2-letter abbreviaton

You should consider using a technique inspired by a namedtuple mixin as illustrated in this answer:

The stdlib way

We'll need a base class to hold the behavior:

from enum import Enum
import json

class BaseCountry(Enum):

    def __new__(cls, record):
        member = object.__new__(cls)
        member.country_name = record['name']
        member.code = int(record['country-code'])
        member.abbr = record['alpha-2']
        member._value_ = member.abbr, member.code, member.country_name
        if not hasattr(cls, '_choices'):
            cls._choices = {}
        cls._choices[member.code] = member.country_name
        cls._choices[member.abbr] = member.country_name
        return member

    def __str__(self):
        return self.country_name

    @classmethod
    def choices(cls):
        return cls._choices.copy()

Then we can use that to create the actual Country class:

Country = BaseCountry(
        'Country',
        [(rec['alpha-2'], rec) for rec in json.load(open('slim-2.json'))],
        )

The aenum way 1 2

from aenum import Enum, MultiValue
import json

class Country(Enum, init='abbr code country_name', settings=MultiValue):

    _ignore_ = 'this country'  # do not add these names as members

    # create members
    this = vars()
    for country in json.load(open('slim-2.json')):
        this[country['alpha-2']] = (
                country['alpha-2'],
                int(country['country-code']),
                country['name'],
                )

    # return a dict of choices by abbr or country code to name
    @classmethod
    def choices(cls):
        mapping = {}
        for member in cls:
            mapping[member.code] = member.name
            mapping[member.abbr] = member.name
        return mapping

    # have str() print just the country name
    def __str__(self):
        return self.country_name

While I included the choices method, you may not need it:

>>> Country('AF')
<Country.AF: ('AF', 4, 'Afghanistan')>

>>> Country(4)
<Country.AF: ('AF', 4, 'Afghanistan')>

>>> Country('Afghanistan')
<Country.AF: ('AF', 4, 'Afghanistan')>

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.

2 This requires aenum 2.0.5+.


问:
Single click breakpoint in Eclipse
I know I can set breakpoint in Eclipse via double click, but is there any way I can change it to single click instead?</p>

答: No, the double-click behavior is set within code and not a preference. You can, however, right-click in the same area and toggle breakpoints from the menu that pops up. </p>

Title: Single click breakpoint in Eclipse


问:
Elastic search creating new mapping rather than joining the one already defined?
I created a index with mapping given below. And the index is empty

```<code>{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

When i am inserting a document like this :

```<code>PUT content/university/1
    {
      "university": [
        {
          "state": {
            "region": "usa",
            "pincode": 5693
          }
        }
      ]
    }
</code>```

It is creating a new mapping rather than joining in the one that defined previously.

```<code>{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          },
          "university": {
            "properties": {
              "state": {
                "properties": {
                  "pincode": {
                    "type": "long"
                  },
                  "region": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

How i can avoid this in elasticsearch?

Whether i have to use inline scripts for this?

答:
If your type is university you should create a mapping as follows:

```<code>{
  "test" : {
    "mappings" : {
      "university" : {
        "properties" : {
          "state" : {
            "type" : "nested",
            "properties" : {
              "pincode" : {
                "type" : "long"
              },
              "region" : {
                "type" : "string",
                "index" : "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

so either your mapping or the document you are trying to insert are wrong. Could you please edit the question with the full mapping and document?

Body:
I created a index with mapping given below. And the index is empty

{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}

When i am inserting a document like this :

PUT content/university/1
    {
      "university": [
        {
          "state": {
            "region": "usa",
            "pincode": 5693
          }
        }
      ]
    }

It is creating a new mapping rather than joining in the one that defined previously.

{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          },
          "university": {
            "properties": {
              "state": {
                "properties": {
                  "pincode": {
                    "type": "long"
                  },
                  "region": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

How i can avoid this in elasticsearch?

Whether i have to use inline scripts for this?

Body:
If your type is university you should create a mapping as follows:

{
  "test" : {
    "mappings" : {
      "university" : {
        "properties" : {
          "state" : {
            "type" : "nested",
            "properties" : {
              "pincode" : {
                "type" : "long"
              },
              "region" : {
                "type" : "string",
                "index" : "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}

so either your mapping or the document you are trying to insert are wrong. Could you please edit the question with the full mapping and document?