问:
Data Copy from s3 to Redshift: Manifest is in different bucket than files I need to download
I am trying to copy data from a large number of files in s3 over to Redshift. I have read-only access to the s3 bucket which contains these files. In order to COPY them efficiently, I created a manifest file that contains the links to each of the files I need copied over.

```<code>Bucket 1:
 - file1.gz
 - file2.gz
 - ...

Bucket 2:
 - manifest
</code>```

Here is the command I've tried to copy data from bucket 1 using the manifest in bucket 2:

```<code>-- Load data from s3
copy data_feed_eval from 's3://bucket-2/data_files._manifest'
CREDENTIALS 'aws_access_key_id=bucket_1_key;aws_secret_access_key=bucket_1_secret'
manifest
csv gzip delimiter ',' dateformat 'YYYY-MM-DD' timeformat 'YYYY-MM-DD HH:MI:SS'
maxerror 1000 TRUNCATECOLUMNS;
</code>```

However, when running this command, I get the following error:

```<code>09:45:32  [COPY - 0 rows, 7.576 secs]  [Code: 500310, SQL State: XX000]  [Amazon](500310) Invalid operation: Problem reading manifest file - S3ServiceException:Access Denied,Status 403,Error AccessDenied,Rid 901E02533CC5010D,ExtRid tEvf/TVfZzPfSNAFa8iTYjTBjvaHnMMPmuwss58SwopY/sZSkhUBe3yMGHTDyA0yDhDCD7ybX9gl45pV/eQ=,CanRetry 1
Details:
 -----------------------------------------------
  error:  Problem reading manifest file - S3ServiceException:Access Denied,Status 403,Error AccessDenied,Rid 901E02533CC5010D,ExtRid tEvf/TVfZzPfSNAFa8iTYjTBjvaHnMMPmuwss58SwopY/sZSkhUBe3yMGHTDyA0yDhDCD7ybX9gl45pV/eQ=,CanRetry 1
  code:      8001
  context:   s3://bucket-2/data_files._manifest
  query:     2611231
  location:  s3_utility.cpp:284
  process:   padbmaster [pid=10330]
  -----------------------------------------------;
</code>```

I believe the issue here is I'm passing bucket_1 credentials in my COPY command. Is it possible to pass credentials for multiple buckets (bucket_1 with the actual files, and bucket_2 with the manifest) to the COPY command? How should I approach this assuming I don't have write access to bucket_1?

答:
You have indicated that bucket_1_key key (which is IAM user) has permissions limited to "read-only" from bucket_1. If this is the case then the error occurs because that key has no permission read from bucket_2. You have mentioned this a possible cause already and it is exactly that.

There is no option to supply two sets of keys to COPY command. But, you should consider the following options:

Option 1

According to this "You can specify the files to be loaded by using an Amazon S3 object prefix or by using a manifest file."
If there is a common prefix for the set of files you want to load, you can use that prefix in bucket_1 in COPY command.
See http://docs.aws.amazon.com/redshift/latest/dg/t_loading-tables-from-s3.html

You have mentioned you have read-only access to bucket 1. Make sure this is sufficient access as defined in http://docs.aws.amazon.com/redshift/latest/dg/copy-usage_notes-access-permissions.html#copy-usage_notes-iam-permissions

All the other options require changes to your key/IAM user permissions or Redshift itself.

Option 2

Extend permissions of bucket_1_key key to be able to read from bucket_2 as well. You will have to make sure that your bucket_1_key key has LIST access to bucket_2 and GET access for the bucket_2 objects (as documented here).
This way you can continue using bucket_1_key key in COPY command. This method is referred to as Key-Based Access Control and uses plain-text access key ID and secret access key. AWS recommends to use Role-Based Access Control (option 3) instead.

Option 3

Use IAM role in COPY command instead of key (option 2). This is referred to as Role-Based Access Control. This is also strongly recommended authentication option to use in COPY command.
This IAM role would have to privileges to LIST access on buckets 1 and 2 and GET access for the objects in those buckets.

More info about Key-Based and Role-Based Access Control is here.

Body:
I am trying to copy data from a large number of files in s3 over to Redshift. I have read-only access to the s3 bucket which contains these files. In order to COPY them efficiently, I created a manifest file that contains the links to each of the files I need copied over.

Bucket 1:
 - file1.gz
 - file2.gz
 - ...

Bucket 2:
 - manifest

Here is the command I've tried to copy data from bucket 1 using the manifest in bucket 2:

-- Load data from s3
copy data_feed_eval from 's3://bucket-2/data_files._manifest'
CREDENTIALS 'aws_access_key_id=bucket_1_key;aws_secret_access_key=bucket_1_secret'
manifest
csv gzip delimiter ',' dateformat 'YYYY-MM-DD' timeformat 'YYYY-MM-DD HH:MI:SS'
maxerror 1000 TRUNCATECOLUMNS;

However, when running this command, I get the following error:

09:45:32  [COPY - 0 rows, 7.576 secs]  [Code: 500310, SQL State: XX000]  [Amazon](500310) Invalid operation: Problem reading manifest file - S3ServiceException:Access Denied,Status 403,Error AccessDenied,Rid 901E02533CC5010D,ExtRid tEvf/TVfZzPfSNAFa8iTYjTBjvaHnMMPmuwss58SwopY/sZSkhUBe3yMGHTDyA0yDhDCD7ybX9gl45pV/eQ=,CanRetry 1
Details:
 -----------------------------------------------
  error:  Problem reading manifest file - S3ServiceException:Access Denied,Status 403,Error AccessDenied,Rid 901E02533CC5010D,ExtRid tEvf/TVfZzPfSNAFa8iTYjTBjvaHnMMPmuwss58SwopY/sZSkhUBe3yMGHTDyA0yDhDCD7ybX9gl45pV/eQ=,CanRetry 1
  code:      8001
  context:   s3://bucket-2/data_files._manifest
  query:     2611231
  location:  s3_utility.cpp:284
  process:   padbmaster [pid=10330]
  -----------------------------------------------;

I believe the issue here is I'm passing bucket_1 credentials in my COPY command. Is it possible to pass credentials for multiple buckets (bucket_1 with the actual files, and bucket_2 with the manifest) to the COPY command? How should I approach this assuming I don't have write access to bucket_1?


来源: stackexchange

问:
log4j doesn't write in log file on tomcat7 (ubuntu server)
This is my log4j.properties file:

```<code># LOG4J configuration
log4j.rootLogger=INFO, Appender1,Appender2
log4j.logger.org.hibernate=info
log4j.logger.org.quartz=info

log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n

log4j.appender.Appender2=org.apache.log4j.FileAppender
log4j.appender.Appender2.File=/home/diego/proyect/log/general.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n
</code>```

Locally works on my windows machine, but on the server (ubuntu 16.04) side the web application cannot write on the .log file, already modified permissions for the file:

```<code>chmod 777 /home/diego/proyect/log/general.log
</code>```

this is the resuls of ls -lhs on the log directory:

```<code>-rwxrwxrwx 1 diego diego 0 Nov 16 14:23 general.log
</code>```

Also not sure which is the tomcat user on the server.

答:
The fact that it is working  on local environment mean that your configuration is correct. I think there is an issue with your environment. Here are a few things to check:

Does the tomcat process has permissions to write in file . i.e. are administrator rights required to write?

Check that there aren't any temporary files near tomcat's directories which may be preventing your changes.

Check that you don't have any other log4j config files on your classpath, as these could override your log4j file and preventing it . To double check this, you could try temporarily removing your log4j.properties file .

ContentLicense: CC BY-SA 3.0

Body:
This is my log4j.properties file:

# LOG4J configuration
log4j.rootLogger=INFO, Appender1,Appender2
log4j.logger.org.hibernate=info
log4j.logger.org.quartz=info

log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n

log4j.appender.Appender2=org.apache.log4j.FileAppender
log4j.appender.Appender2.File=/home/diego/proyect/log/general.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n

Locally works on my windows machine, but on the server (ubuntu 16.04) side the web application cannot write on the .log file, already modified permissions for the file:

chmod 777 /home/diego/proyect/log/general.log

this is the resuls of ls -lhs on the log directory:

-rwxrwxrwx 1 diego diego 0 Nov 16 14:23 general.log

Also not sure which is the tomcat user on the server.


问:
write the result into input field
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span> <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;"> <br>
        <input type="button" onClick="cal();">
        <span style="font-size:20px;" >Our Fee (10%):</span><input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;"><br>
        <span style="font-size:20px;">You'll paid:</span> <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

答:
Abu Machi.

You are using the wrong function for the job or you have not understood exactly how it works. The function GetElementsByName, as the function names says, gets more than one element. So you need to work with a list of elements, if that's the case.

As you can see in the docs, getElementsByName is used when you need to work with more than one similar element. Otherwise, the best function for this work is getElementById. (And if you're working on modern browsers, IE8+, you can use the helpers querySelector and querySelectorAll)

Besides this issue within your code, there's one more thing to correct. When the bid value is supposedly taken, you just get the element, and not the value itself.

Anyway, let's get to what you can do. You can:

Use getElementsByName the "correct" way.

function cal(){
  var bid = Number(document.getElementsByName("bid")[0].value);
  var result1 = bid * 0.1;
  var result2 = bid - result1;
  document.getElementsByName("fee")[0].value = result1;
  document.getElementsByName("get")[0].value = result2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span>
<input type="number" name="bid" class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<input type="button" onclick="cal()">
<span style="font-size:20px;" >Our Fee (10%):</span>
<input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<span style="font-size:20px;">You'll paid:</span>
<input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

Use getElementById.

function cal(){
  var bid = Number(document.getElementById("bid").value);
  var result1 = bid * 0.1;
  var result2 = bid - result1;
  document.getElementById("fee").value = result1;
  document.getElementById("get").value = result2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span>
<input type="number" id="bid" class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<input type="button" onclick="cal()">
<span style="font-size:20px;" >Our Fee (10%):</span>
<input type="number" id="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<span style="font-size:20px;">You'll paid:</span>
<input type="number"  id="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

Use querySelector.

function cal(){
  var bid = Number(document.querySelector("#bid").value);
  var result1 = bid * 0.1;
  var result2 = bid - result1;
  document.querySelector("#fee").value = result1;
  document.querySelector("#get").value = result2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span>
<input type="number" id="bid" class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<input type="button" onclick="cal()">
<span style="font-size:20px;" >Our Fee (10%):</span>
<input type="number" id="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<span style="font-size:20px;">You'll paid:</span>
<input type="number"  id="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

And as you asked, if you want that the value change without the need to click on the button, you just need to make the of onKeyUp event on your bid input, like this:

function cal(){
  var bid = Number(document.querySelector("#bid").value);
  var result1 = bid * 0.1;
  var result2 = bid - result1;
  document.querySelector("#fee").value = result1;
  document.querySelector("#get").value = result2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span>
<input type="number" id="bid" class="form-control" style="max-width:250px; margin-top:10px;" onkeyup="cal()">
<br>
<span style="font-size:20px;" >Our Fee (10%):</span>
<input type="number" id="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<span style="font-size:20px;">You'll paid:</span>
<input type="number"  id="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

I hope it can be any helpful.

Title: write the result into input field

Body:
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

Your bid: <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;">

        <input type="button" onClick="cal();">
        Our Fee (10%):<input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">

        You'll paid: <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

Body:
Abu Machi.

You are using the wrong function for the job or you have not understood exactly how it works. The function GetElementsByName, as the function names says, gets more than one element. So you need to work with a list of elements, if that's the case.

As you can see in the docs, getElementsByName is used when you need to work with more than one similar element. Otherwise, the best function for this work is getElementById. (And if you're working on modern browsers, IE8+, you can use the helpers querySelector and querySelectorAll)

Besides this issue within your code, there's one more thing to correct. When the bid value is supposedly taken, you just get the element, and not the value itself.

Anyway, let's get to what you can do. You can:

Use getElementsByName the "correct" way.

function cal(){
  var bid = Number(document.getElementsByName("bid")[0].value);
  var result1 = bid * 0.1;
  var result2 = bid - result1;
  document.getElementsByName("fee")[0].value = result1;
  document.getElementsByName("get")[0].value = result2;
}

<span style="font-size:20px;">Your bid:</span>
<input type="number" name="bid" class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<input type="button" onclick="cal()">
<span style="font-size:20px;" >Our Fee (10%):</span>
<input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<span style="font-size:20px;">You'll paid:</span>
<input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

Use getElementById.

function cal(){
  var bid = Number(document.getElementById("bid").value);
  var result1 = bid * 0.1;
  var result2 = bid - result1;
  document.getElementById("fee").value = result1;
  document.getElementById("get").value = result2;
}

<span style="font-size:20px;">Your bid:</span>
<input type="number" id="bid" class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<input type="button" onclick="cal()">
<span style="font-size:20px;" >Our Fee (10%):</span>
<input type="number" id="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<span style="font-size:20px;">You'll paid:</span>
<input type="number"  id="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

Use querySelector.

function cal(){
  var bid = Number(document.querySelector("#bid").value);
  var result1 = bid * 0.1;
  var result2 = bid - result1;
  document.querySelector("#fee").value = result1;
  document.querySelector("#get").value = result2;
}

<span style="font-size:20px;">Your bid:</span>
<input type="number" id="bid" class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<input type="button" onclick="cal()">
<span style="font-size:20px;" >Our Fee (10%):</span>
<input type="number" id="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<span style="font-size:20px;">You'll paid:</span>
<input type="number"  id="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

And as you asked, if you want that the value change without the need to click on the button, you just need to make the of onKeyUp event on your bid input, like this:

function cal(){
  var bid = Number(document.querySelector("#bid").value);
  var result1 = bid * 0.1;
  var result2 = bid - result1;
  document.querySelector("#fee").value = result1;
  document.querySelector("#get").value = result2;
}

<span style="font-size:20px;">Your bid:</span>
<input type="number" id="bid" class="form-control" style="max-width:250px; margin-top:10px;" onkeyup="cal()">
<br>
<span style="font-size:20px;" >Our Fee (10%):</span>
<input type="number" id="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">
<br>
<span style="font-size:20px;">You'll paid:</span>
<input type="number"  id="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

I hope it can be any helpful.


问:
Modal to show upon redirect (Laravel)
I am trying to get a modal to show upon redirect to a page.

I am following this response (Laravel how to redirect back to boostrap modal dialog window)

My controller:

```<code>return redirect('postings')->with('welcome_msg');
</code>```

My view:

```<code>@if(Session::has('welcome_msg'))
<script>
$(function() {
$('#myModal').modal('show');
});
</script>
@endif

<div class="modal fade" id="myModal role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
  <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
    ...
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
  </div>
</div>
</code>```

However, the modal is not showing upon pop-up. What am I doing wrong?

答:
```<code><div class="modal fade" id="myModal role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
  <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
    ...
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
  </div>
</div>

@if(Session::has('welcome_msg'))
<script>
$(function() {
$('#myModal').modal('show');
});
</script>
@endif
</code>```

This may fix it. HTML has to load before javascript.

Title: Modal to show upon redirect (Laravel)

Body:
I am trying to get a modal to show upon redirect to a page.

I am following this response (Laravel how to redirect back to boostrap modal dialog window)

My controller:

return redirect('postings')->with('welcome_msg');

My view:

@if(Session::has('welcome_msg'))

@endif

Modal title

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      ×
    </button>

    ...

    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

However, the modal is not showing upon pop-up. What am I doing wrong?

Body:
<div class="modal fade" id="myModal role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
  <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    ...
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
  </div>
</div>

@if(Session::has('welcome_msg'))
<script>
$(function() {
$('#myModal').modal('show');
});
</script>
@endif

This may fix it. HTML has to load before javascript.


问:
Jenkins Pipeline Wipe Out Workspace
We are running Jenkins 2.x and love the new Pipeline plugin.  However, with so many branches in a repository, disk space fills up quickly.  </p>

<p>Is there any plugin that's compatible with Pipeline that I can wipe out the workspace on a successful build? </p>

答:
Using the 'WipeWorkspace' extension seems to work as well.  It requires the longer form:

```<code>checkout([
   $class: 'GitSCM',
   branches: scm.branches,
   extensions: scm.extensions + [[$class: 'WipeWorkspace']],
   userRemoteConfigs: scm.userRemoteConfigs
])
</code>```

More details here: https://support.cloudbees.com/hc/en-us/articles/226122247-How-to-Customize-Checkout-for-Pipeline-Multibranch-

Available GitSCM extensions here: https://github.com/jenkinsci/git-plugin/tree/master/src/main/java/hudson/plugins/git/extensions/impl

Title: Jenkins Pipeline Wipe Out Workspace

Body:
We are running Jenkins 2.x and love the new Pipeline plugin.  However, with so many branches in a repository, disk space fills up quickly.

Is there any plugin that's compatible with Pipeline that I can wipe out the workspace on a successful build?

Body:
Using the 'WipeWorkspace' extension seems to work as well.  It requires the longer form:

checkout([
   $class: 'GitSCM',
   branches: scm.branches,
   extensions: scm.extensions + [[$class: 'WipeWorkspace']],
   userRemoteConfigs: scm.userRemoteConfigs
])

More details here: https://support.cloudbees.com/hc/en-us/articles/226122247-How-to-Customize-Checkout-for-Pipeline-Multibranch-

Available GitSCM extensions here: https://github.com/jenkinsci/git-plugin/tree/master/src/main/java/hudson/plugins/git/extensions/impl


问:
How to setup jenkins git url for single project from repository
I am working on jenkins android setup,my bitbucket repository contains libraries and android project.I want to generate apk for that android project using jenkins for that i need to serve git url but if i take clone it contains all projects.So how can i take only android project git url to setup in jenkins</p>

答: git clone always pulls the entire repository. If you only need certain parts then you'll either need to split the repo into smaller things or to clone the whole thing and then strip out the unnecessary things.


问:
FCM Push notification not working in iOS 11
I need to handle push notification and that's done with a lower version of ios but in ios 11 never receive any push notification. I using Firebase Cloud Messaging. please, anyone has a solution then please share.</p>

答:
Problem seems to be with

FirebaseInstanceID Version less than  1.0.9

FirebaseInstanceID Version between 2.0.1 - 2.0.3

Set your pod file as below :

For Swift 2.3 and Xcode 8 : (FirebaseInstanceID v1.1.0 gets installed)

```<code>pod 'Firebase/Core', '3.8.0'
pod 'Firebase/Messaging'
</code>```

For Swift 3 and Xcode 9 :

```<code>pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'FirebaseInstanceID', "2.0.0
</code>```

I didn't want to upgrade to FirebaseInstanceID 2.0.0 to fix the issue as I wanted use Swift 2.3 only

Body:
Problem seems to be with

FirebaseInstanceID Version less than  1.0.9

FirebaseInstanceID Version between 2.0.1 - 2.0.3

Set your pod file as below :

For Swift 2.3 and Xcode 8 : (FirebaseInstanceID v1.1.0 gets installed)

pod 'Firebase/Core', '3.8.0'
pod 'Firebase/Messaging'

For Swift 3 and Xcode 9 :

pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'FirebaseInstanceID', "2.0.0

I didn't want to upgrade to FirebaseInstanceID 2.0.0 to fix the issue as I wanted use Swift 2.3 only


问:
Replacing NaN with other value (mean) in MATLAB
I have matrix A such as:

```<code>A = [1  2  3 NaN;
     1 NaN 2 NaN;
     NaN 2 3 4]
</code>```

I would like to replace every NaN in A with a predefined value such as my columns vector B:

```<code>B = [2; 1.5; 3]
</code>```

So for the second row, I'd like to obtain a new matrix, where every NaN in this particular row is replaced by 1.5. It would be 2 in the first row and 3 in the third row.

Is there a better way to do so other than looping through the entire matrix? I used a for loop with the if and else conditions. However, this solution does not execute very fast.

答:
Here is a solution using repelem (introduced in R2015a). The trick is to repeat the entries of B according to the number of times NaN appears in each row of A.

```<code>req = A.';
req(isnan(req)) = repelem(B, sum(isnan(req)));
req = req.';
</code>```

If you also want to calculate B, use mean with the 'omitnan' flag (introduced in R2015a) i.e.

```<code>B = mean(A,2,'omitnan');
</code>```

Body:
I have matrix A such as:

A = [1  2  3 NaN;
     1 NaN 2 NaN;
     NaN 2 3 4]

I would like to replace every NaN in A with a predefined value such as my columns vector B:

B = [2; 1.5; 3]

So for the second row, I'd like to obtain a new matrix, where every NaN in this particular row is replaced by 1.5. It would be 2 in the first row and 3 in the third row.

Is there a better way to do so other than looping through the entire matrix? I used a for loop with the if and else conditions. However, this solution does not execute very fast.

Body:
Here is a solution using repelem (introduced in R2015a). The trick is to repeat the entries of B according to the number of times NaN appears in each row of A.

req = A.';
req(isnan(req)) = repelem(B, sum(isnan(req)));
req = req.';

If you also want to calculate B, use mean with the 'omitnan' flag (introduced in R2015a) i.e.

B = mean(A,2,'omitnan');


问:
log4j2 Modify stacktrace format
Is it possible to configure log4j2 in such a way that the stacktraces don't show the source and maybe not the line numbers?

In case you are wondering why I would want that, I need this for unit tests, that need to test if exceptions get logged correctly. So if for example the JRE version is not the same as the one I copied the original stacktrace, from the tests fail. So if the source wasn't included in the stacktrace it would be a lot more version independend.

Example:

Currently a line from the stacktrace looks like this:

```<code>    at java.lang.Object.wait(Object.java:502) ~[?:1.8.0_144]
</code>```

I would like it to look like this (but only for log4j2):

```<code>    at java.lang.Object.wait(Object.java:502)
</code>```

Maybe even like this:

```<code>    at java.lang.Object.wait(Object.java)
</code>```

Or even shorter:

```<code>    at java.lang.Object.wait
</code>```

(Any of the shortened versions would be acceptable. As currently only the source (~[?:1.8.0_144] vs ~[?:1.8.0_151] for example) differs.)

Update:

I just found this in the offical documentation: https://logging.apache.org/log4j/2.x/manual/layouts.html#Patterns I think using %ex{full} should be what I want. Will test it.

There are also several other available formats.

答:
To achieve the wanted effect, the pattern needs to be changed.

For example if it was

```<code>... %msg%n
</code>```

It needs to be

```<code>... %msg%n%ex{full}
</code>```

(Read https://logging.apache.org/log4j/2.x/manual/layouts.html#Patterns for more info)

Title: log4j2 Modify stacktrace format

Body:
Is it possible to configure log4j2 in such a way that the stacktraces don't show the source and maybe not the line numbers?

In case you are wondering why I would want that, I need this for unit tests, that need to test if exceptions get logged correctly. So if for example the JRE version is not the same as the one I copied the original stacktrace, from the tests fail. So if the source wasn't included in the stacktrace it would be a lot more version independend.

Example:

Currently a line from the stacktrace looks like this:

    at java.lang.Object.wait(Object.java:502) ~[?:1.8.0_144]

I would like it to look like this (but only for log4j2):

    at java.lang.Object.wait(Object.java:502)

Maybe even like this:

    at java.lang.Object.wait(Object.java)

Or even shorter:

    at java.lang.Object.wait

(Any of the shortened versions would be acceptable. As currently only the source (~[?:1.8.0_144] vs ~[?:1.8.0_151] for example) differs.)

Update:

I just found this in the offical documentation: https://logging.apache.org/log4j/2.x/manual/layouts.html#Patterns I think using %ex{full} should be what I want. Will test it.

There are also several other available formats.

Body:
To achieve the wanted effect, the pattern needs to be changed.

For example if it was

... %msg%n

It needs to be

... %msg%n%ex{full}

(Read https://logging.apache.org/log4j/2.x/manual/layouts.html#Patterns for more info)


问:
What is the best way to remove .mp3 from this list in Python?
So I'm making a bot, and so far I have a command that prints out a directory of all available songs seen here:

```<code>@bot.command()
async def songs(ctx):
    msg = os.listdir("songs")
    await ctx.send(msg)
</code>```

Which works as expected, it prints the list of songs in that folder.

```<code>['song1.mp3']
</code>```

However, my main problem here is that it shows the file extension on the end, which I don't want. What would be the best way to go about removing the file extension (.mp3) before printing it?

答:
Many ways:</p>

```<code>msg = [f.split('.')[0] for f in msg]

msg = [f.replace('.mp3', '') for f in msg]
</code>```

Body:
So I'm making a bot, and so far I have a command that prints out a directory of all available songs seen here:

@bot.command()
async def songs(ctx):
    msg = os.listdir("songs")
    await ctx.send(msg)

Which works as expected, it prints the list of songs in that folder.

['song1.mp3']

However, my main problem here is that it shows the file extension on the end, which I don't want. What would be the best way to go about removing the file extension (.mp3) before printing it?

Body:
Many ways:

msg = [f.split('.')[0] for f in msg]

msg = [f.replace('.mp3', '') for f in msg]


答:
A simple list iteration to remove them would work.

```<code>[x.rsplit(".", 1)[0] for x in os.listdir("songs")]
</code>```

I have used rsplit so that if the filename contains a . aside from the file extension, it would be included still. The argument forces a maximum of 1 split - so if the file doesn't have a dot at all it'll still return the full filename.

Note that this will return all files in the directory. If you want to limit it to just mp3s, then you could do this;

```<code>[x.rsplit(".", 1)[0] for x in os.listdir("songs") if x.endswith(".mp3")]
</code>```

Title: What is the best way to remove .mp3 from this list in Python?

Body:
A simple list iteration to remove them would work.

[x.rsplit(".", 1)[0] for x in os.listdir("songs")]

I have used rsplit so that if the filename contains a . aside from the file extension, it would be included still. The argument forces a maximum of 1 split - so if the file doesn't have a dot at all it'll still return the full filename.

Note that this will return all files in the directory. If you want to limit it to just mp3s, then you could do this;

[x.rsplit(".", 1)[0] for x in os.listdir("songs") if x.endswith(".mp3")]


问:
Output should be String when Condition is right SQL
I have a little problem here. I have the following Select

```<code>SELECT ProjektName, Budget  FROM projekt p1  WHERE p1.Budget=(
    SELECT MAX(p2.Budget) FROM projekt p2
)
UNION
SELECT ProjektName, Budget   FROM projekt p1  WHERE p1.Budget=(
    SELECT MIN(p2.Budget) FROM projekt p2
)
</code>```

which delivers this result:

```<code>Projektname     Budget
projekt1        100000
projekt2        30000
</code>```

But instead of the Value I want to write a string which says something like "this is the max Budget"

Like this:

```<code>Projektname     Budget
projekt1        This is the max Budget
projekt2        This is the min Budget
</code>```

Searched everywhere but only found solutions for changing the Budget in the Select but not the result.

Thank you in advance!

答:
Just put a literal string in the SELECT list.

```<code>SELECT ProjektName, 'This is the max Budget' AS Budget
FROM projekt p1
WHERE p1.Budget=(
    SELECT MAX(p2.Budget) FROM projekt p2
)
UNION
SELECT ProjektName, 'This is the min Budget' AS Budget
FROM projekt p1
WHERE p1.Budget=(
    SELECT MIN(p2.Budget) FROM projekt p2
)
</code>```

Body:
I have a little problem here. I have the following Select

SELECT ProjektName, Budget  FROM projekt p1  WHERE p1.Budget=(
    SELECT MAX(p2.Budget) FROM projekt p2
)
UNION
SELECT ProjektName, Budget   FROM projekt p1  WHERE p1.Budget=(
    SELECT MIN(p2.Budget) FROM projekt p2
)

which delivers this result:

Projektname     Budget
projekt1        100000
projekt2        30000

But instead of the Value I want to write a string which says something like "this is the max Budget"

Like this:

Projektname     Budget
projekt1        This is the max Budget
projekt2        This is the min Budget

Searched everywhere but only found solutions for changing the Budget in the Select but not the result.

Thank you in advance!

Body:
Just put a literal string in the SELECT list.

SELECT ProjektName, 'This is the max Budget' AS Budget
FROM projekt p1
WHERE p1.Budget=(
    SELECT MAX(p2.Budget) FROM projekt p2
)
UNION
SELECT ProjektName, 'This is the min Budget' AS Budget
FROM projekt p1
WHERE p1.Budget=(
    SELECT MIN(p2.Budget) FROM projekt p2
)


答:
You can replace '.mp3' with '' as follows:

```<code>msg = [s.replace('.mp3','') for s in os.listdir("songs")]
</code>```

Body:
You can replace '.mp3' with '' as follows:

msg = [s.replace('.mp3','') for s in os.listdir("songs")]


问:
Different behavior of flexbox with (overflow-y) scroll on Safari, Firefox and Edge VS Chrome
In this page on plunker (https://plnkr.co/edit/gMbgxvUqHNDsQVe4P7ny?p=preview) there is a weird problem.

On Chrome on Windows and Android (Canary also) everything works good. I can scroll the two areas (on the left and on the right) and the top and bottom div of the page are on the top and on the bottom of my device screen. I see them anytime (see the picture below).

On iPad or iPhone, iOS, with Safari or Chrome, this is not what I get. And also on Firefox 47.0.1 on Windows.

The page is long and there is just one scroll on the right, like if there is no flexbox on the page, this code is just ignored:

```<code>.bigone {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.main {
    flex: 1 1 0;
    display: flex;
}
.container-fluid {
  display: flex;
}
.col-6 {
  overflow-y: auto;
}
</code>```

Quirk example:

You can see on the iPad or iPhone just by a click on this button:

Why this behaviour?
Safari and Firefox bug or Chrome's one?
Why on Chrome everything good on Windows and Android?
And if in the new Safari in the future this will work good, how to do with the older devices with older iOS and firefox?

I will appreciate any answer. Thanks.

答:
Try:

```<code>margin: auto;
</code>```

in the css for the flex-item - that did the trick for me (seems like the auto does the magic here ...)

Wanted to share that finding, as min-height, overflow-x, etc ... did not work reliably for me neither.

Body:
In this page on plunker (https://plnkr.co/edit/gMbgxvUqHNDsQVe4P7ny?p=preview) there is a weird problem.

On Chrome on Windows and Android (Canary also) everything works good. I can scroll the two areas (on the left and on the right) and the top and bottom div of the page are on the top and on the bottom of my device screen. I see them anytime (see the picture below).

On iPad or iPhone, iOS, with Safari or Chrome, this is not what I get. And also on Firefox 47.0.1 on Windows.

The page is long and there is just one scroll on the right, like if there is no flexbox on the page, this code is just ignored:

.bigone {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.main {
    flex: 1 1 0;
    display: flex;
}
.container-fluid {
  display: flex;
}
.col-6 {
  overflow-y: auto;
}

Quirk example:

You can see on the iPad or iPhone just by a click on this button:

Why this behaviour?
Safari and Firefox bug or Chrome's one?
Why on Chrome everything good on Windows and Android?
And if in the new Safari in the future this will work good, how to do with the older devices with older iOS and firefox?

I will appreciate any answer. Thanks.

Body:
Try:

margin: auto;

in the css for the flex-item - that did the trick for me (seems like the auto does the magic here ...)

Wanted to share that finding, as min-height, overflow-x, etc ... did not work reliably for me neither.


问:
Return nested collection from firestore as object for angularfire2 and firebase
Let's say you have the following structure:

```<code>shopping-carts (collection)
 - shopping-cart 1(doc)
  -- dateCreated (field)
  -- items (collection)
 - shopping-cart 2(doc
  -- dateCreated
  -- items
 .
 .
 .
</code>```

So, how would we go about getting the entire shopping-cart(doc) as an ShoppingCart object that we defined as

```<code>export interface ShoppingCart {
  items: ShoppingCartItem[]
  dateCreated: string
}
</code>```

afs.doc('shopping-cart/id').valueChanges() only returns the dateCreated

afs.doc('shopping-cart/id').collection('items').valueChanges() returns the items.

Easy way to get all in one and create it as an object?

答:
Probably not the best solution, but couldn't find a better one yet.

```<code>this.shoppingCartsCollection = afs.collection<Servicio>('shopping-carts',
        ref => ref.orderBy('dateCreated', 'asc'));

this.shoppingCarts = this.shoppingCartsCollection
    .snapshotChanges()
    .map(values => {
       return values.map(value => {

          const shopping-cart = value.payload.doc.data();
          const itemsArray = shopping-cart.items;
          shopping-cart.observableItems = [];

          for (var i = 0, len = itemsArray.length; i < len; i++) {
             itemDocRef = itemsArray[i];
             value.observableItems.push(afs.doc('items/'+ itemDocRef.id).valueChanges());
          }

          return shopping-cart;
       });
    });
</code>```

access your items data, like any other observable

```<code><div *ngFor="let shoppingCart of shoppingCarts | async">
   <p *ngFor="let observableItem of shoppingCart.observableItems">
      {{(observableItem | async)?.displayName}}
   </p>
</div>
</code>```

Body:
Let's say you have the following structure:

shopping-carts (collection)
 - shopping-cart 1(doc)
  -- dateCreated (field)
  -- items (collection)
 - shopping-cart 2(doc
  -- dateCreated
  -- items
 .
 .
 .

So, how would we go about getting the entire shopping-cart(doc) as an ShoppingCart object that we defined as

export interface ShoppingCart {
  items: ShoppingCartItem[]
  dateCreated: string
}

afs.doc('shopping-cart/id').valueChanges() only returns the dateCreated

afs.doc('shopping-cart/id').collection('items').valueChanges() returns the items.

Easy way to get all in one and create it as an object?

Body:
Probably not the best solution, but couldn't find a better one yet.

this.shoppingCartsCollection = afs.collection<Servicio>('shopping-carts',
        ref => ref.orderBy('dateCreated', 'asc'));

this.shoppingCarts = this.shoppingCartsCollection
    .snapshotChanges()
    .map(values => {
       return values.map(value => {

          const shopping-cart = value.payload.doc.data();
          const itemsArray = shopping-cart.items;
          shopping-cart.observableItems = [];

          for (var i = 0, len = itemsArray.length; i < len; i++) {
             itemDocRef = itemsArray[i];
             value.observableItems.push(afs.doc('items/'+ itemDocRef.id).valueChanges());
          }

          return shopping-cart;
       });
    });

access your items data, like any other observable

<div *ngFor="let shoppingCart of shoppingCarts | async">
   <p *ngFor="let observableItem of shoppingCart.observableItems">
      {{(observableItem | async)?.displayName}}
   </p>
</div>


问:
Yii2: Validate content of a file before submitting
In my form I have a field for the user to upload an XML file. But before submitting the XML, I have to validate it. How can I create a validation function for this?

My view:

```<code>...
<?= $form->field($model, 'upload_file')->fileInput(['accept' => 'text/xml']) ?>
...
</code>```

My Model:

```<code>...
['upload_file', 'validateFile'],
...
public function validateFile($attribute, $params)
{
// TODO
}
...
</code>```

I can access and validate the contents of the XML file in the controller, but this validation is already after the file is submitted ... I wanted before submitting!
Exemple in controller:

```<code>if ($model->load(Yii::$app->request->post()) {
    $file = UploadedFile::getInstance($model, 'upload_file');
    $file = file_get_contents($file->tempName);
    // xml of the upload_file
    $xml = simplexml_load_string($file);
</code>```

I want to pass this code that is on top, to the validation function.

答:
Add this to your model rules:</p>

```<code>public function rules()
{
     return [
          [['uploaded_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'xml', 'mimeTypes' => 'text/xml, application/xml'],
     ];
}
</code>```

Body:
In my form I have a field for the user to upload an XML file. But before submitting the XML, I have to validate it. How can I create a validation function for this?

My view:

...
<?= $form->field($model, 'upload_file')->fileInput(['accept' => 'text/xml']) ?>
...

My Model:

...
['upload_file', 'validateFile'],
...
public function validateFile($attribute, $params)
{
// TODO
}
...

I can access and validate the contents of the XML file in the controller, but this validation is already after the file is submitted ... I wanted before submitting!
Exemple in controller:

if ($model->load(Yii::$app->request->post()) {
    $file = UploadedFile::getInstance($model, 'upload_file');
    $file = file_get_contents($file->tempName);
    // xml of the upload_file
    $xml = simplexml_load_string($file);

I want to pass this code that is on top, to the validation function.

Body:
Add this to your model rules:

public function rules()
{
     return [
          [['uploaded_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'xml', 'mimeTypes' => 'text/xml, application/xml'],
     ];
}


问:
How can I erase my data from textarea using javascript?
How can i erase my data from textarea using javascript ?

This code:

```<code><textarea class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >يمكنك إضافة أكثر من بريد إلكتروني. أضف "," بين كل إدخال</textarea>
</code>```

答:
the correct way of doing this is by setting the value property to an empty string.

Even if you don't set any property, the browser attaches all the specific properties to an element wen it's added to the dom.

However, if you are sceptic about the ".value" prop , you could try to alter the innerHTML of the element :

```
document.getElementById("edit-text").innerHTML = '';
```

ContentLicense: CC BY-SA 4.0

Body:
How can i erase my data from textarea using javascript ?

This code:

<textarea class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >يمكنك إضافة أكثر من بريد إلكتروني. أضف "," بين كل إدخال</textarea>

Body:
the correct way of doing this is by setting the value property to an empty string.

Even if you don't set any property, the browser attaches all the specific properties to an element wen it's added to the dom.

However, if you are sceptic about the ".value" prop , you could try to alter the innerHTML of the element :

document.getElementById("edit-text").innerHTML = '';

ContentLicense: CC BY-SA 2.5


答:
You can do it likes the following: </p>

```<code>is_NaN = find(isnan(A) > 0); % find index of NaNs
[I,~] = ind2sub(size(A), is_NaN); %transform from linear index to sub index
A(is_NaN) = B(I); % replace all using the row number of each found index
</code>```

Title: Replacing NaN with other value (mean) in MATLAB

Body:
I have matrix A such as:

A = [1  2  3 NaN;
     1 NaN 2 NaN;
     NaN 2 3 4]

I would like to replace every NaN in A with a predefined value such as my columns vector B:

B = [2; 1.5; 3]

So for the second row, I'd like to obtain a new matrix, where every NaN in this particular row is replaced by 1.5. It would be 2 in the first row and 3 in the third row.

Is there a better way to do so other than looping through the entire matrix? I used a for loop with the if and else conditions. However, this solution does not execute very fast.

Body:
You can do it likes the following:

is_NaN = find(isnan(A) > 0); % find index of NaNs
[I,~] = ind2sub(size(A), is_NaN); %transform from linear index to sub index
A(is_NaN) = B(I); % replace all using the row number of each found index


问:
I need help getting my code to look like this:
I need help getting my code output to look like the image below and I am not sure what I am doing wrong and I need to have my code output indented and cant remember how to indent it.

Here is my code currently:

```<code>// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.

public class Assignment_6_1
{
    // recursive method factorial (assumes its parameter is >= 0
    static StringBuilder s = new StringBuilder();

    public static long factorial(long number)
{
        if (number == 0) // test for base case
        {
            return 1;
        } else {// recursion step
            if (s.length() == 0) {
                s.append(number).append("*").append(number - 1);
            } else {
                for (int i = 0; i < s.length(); i++) {

                }
                System.out.println(number + " * " + (number - 1) + "!");
                s.append("*").append(number).append("*").append(number - 1);
            }
            return number * factorial(number - 1);
        }
    }

    // output factorials for values 0-21
    public static void main(String[] args) {
        System.out.println("Hannah Coffey - Lab 6");
        // calculate the factorials of 0 through 20
        for (int counter = 0; counter < 25; counter++) {
            s = new StringBuilder();
            System.out.println(counter + "!");
            System.out.printf("%d! = %d%n", counter, factorial(counter));
        }
    }
} // end class FactorialCalculator
</code>```

Here is what I need it to look like and not sure what I am doing wrong:

Any Help would be greatly appreciated.

My program currently looks like this:
enter image description here

答:
You can pad a String using String.format like this :

```<code>String.format("%10s", "foo");
</code>```

It will create a left padding of 7 spaces 7 + foo.length = 10;

Now, we can render that dynamic like :

```<code>public static String padding( int i ) {
    return i == 0 ? "" : String.format( "%" + i + "s", "" );
}
</code>```

Just pass the number of spaces and let the formatter do the job.

```<code>for(int i = 5; i >= 0; --i){
    System.out.println(padding(i) + "i");
}
</code>```

Output :

```<code>     5
    4
   3
  2
 1
0
</code>```

Body:
I need help getting my code output to look like the image below and I am not sure what I am doing wrong and I need to have my code output indented and cant remember how to indent it.

Here is my code currently:

// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.

public class Assignment_6_1
{
    // recursive method factorial (assumes its parameter is >= 0
    static StringBuilder s = new StringBuilder();

    public static long factorial(long number)
{
        if (number == 0) // test for base case
        {
            return 1;
        } else {// recursion step
            if (s.length() == 0) {
                s.append(number).append("*").append(number - 1);
            } else {
                for (int i = 0; i < s.length(); i++) {

                }
                System.out.println(number + " * " + (number - 1) + "!");
                s.append("*").append(number).append("*").append(number - 1);
            }
            return number * factorial(number - 1);
        }
    }

    // output factorials for values 0-21
    public static void main(String[] args) {
        System.out.println("Hannah Coffey - Lab 6");
        // calculate the factorials of 0 through 20
        for (int counter = 0; counter < 25; counter++) {
            s = new StringBuilder();
            System.out.println(counter + "!");
            System.out.printf("%d! = %d%n", counter, factorial(counter));
        }
    }
} // end class FactorialCalculator

Here is what I need it to look like and not sure what I am doing wrong:

Any Help would be greatly appreciated.

My program currently looks like this:
enter image description here

Body:
You can pad a String using String.format like this :

String.format("%10s", "foo");

It will create a left padding of 7 spaces 7 + foo.length = 10;

Now, we can render that dynamic like :

public static String padding( int i ) {
    return i == 0 ? "" : String.format( "%" + i + "s", "" );
}

Just pass the number of spaces and let the formatter do the job.

for(int i = 5; i >= 0; --i){
    System.out.println(padding(i) + "i");
}

Output :

     5
    4
   3
  2
 1
0


问:
returning a pointer that points to char array. How do i print out the entire contents of the array?
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

```<code>#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //
</code>```

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

答:
You are already using std::string, so why not use it to reverse the string?

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

std::string ReverseString(std::string const &str)
{
    return std::string(str.crbegin(), str.crend());
}

int main()
{
    std::string str("1234");
    std::cout << ReverseString(str);

    return 0;
}
</code>```

Prints

```<code>4321
</code>```

Body:
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

Body:
You are already using std::string, so why not use it to reverse the string?

#include <iostream>
#include <string>

std::string ReverseString(std::string const &str)
{
    return std::string(str.crbegin(), str.crend());
}

int main()
{
    std::string str("1234");
    std::cout << ReverseString(str);

    return 0;
}

Prints

4321


问:
Highlighting words and then unhighlighting using tkinter
I have a program that will highlight a word in a textbox, however, what I would like to be able to achieve is when the same word is clicked again the word will then be unhighlighted. Is this possible? Below is the section of code that does stuff when a word is clicked. I hope you are able to help.

```<code>def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.text = tk.Text(self, wrap="none")
        self.text.pack(fill="both", expand=True)

        self.text.bind("<ButtonRelease-1>", self._on_click)
        self.text.tag_configure("highlight", background="green", foreground="black")

        with open(__file__, "rU") as f:
            data = f.read()
            self.text.insert("1.0", data)

def _on_click(self, event):
            self.text.tag_add("highlight", "insert wordstart", "insert wordend")
</code>```

I have attempted it by using:

```<code>def _on_click(self, event):
    self.text.tag_remove("highlight", "1.0", "end")
    self.text.tag_add("highlight", "insert wordstart", "insert wordend")
    if self.text.tag_names == ('sel', 'highlight'):
        self.text.tag_add("highlight", "insert wordstart", "insert wordend")
    else:
        self.text.tag_remove("highlight", "1.0", "end")
</code>```

but that has no luck.

答:
You can use tag_names to get a list of tags at a certain index. Then it's just a matter of calling tag_add or tag_remove depending on whether the tag is present on the current word or not.

Example:

```<code>import tkinter as tk

class Example(object):
    def __init__(self):
        self.root = tk.Tk()
        self.text = tk.Text(self.root)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.bind("<ButtonRelease-1>", self._on_click)
        self.text.tag_configure("highlight", background="bisque")

        with open(__file__, "r") as f:
            self.text.insert("1.0", f.read())

    def start(self):
        self.root.mainloop()

    def _on_click(self, event):
        tags = self.text.tag_names("insert wordstart")
        if "highlight" in tags:
            self.text.tag_remove("highlight", "insert wordstart", "insert wordend")
        else:
            self.text.tag_add("highlight", "insert wordstart", "insert wordend")

if __name__ == "__main__":
    Example().start()
</code>```

Body:
I have a program that will highlight a word in a textbox, however, what I would like to be able to achieve is when the same word is clicked again the word will then be unhighlighted. Is this possible? Below is the section of code that does stuff when a word is clicked. I hope you are able to help.

def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.text = tk.Text(self, wrap="none")
        self.text.pack(fill="both", expand=True)

        self.text.bind("<ButtonRelease-1>", self._on_click)
        self.text.tag_configure("highlight", background="green", foreground="black")

        with open(__file__, "rU") as f:
            data = f.read()
            self.text.insert("1.0", data)

def _on_click(self, event):
            self.text.tag_add("highlight", "insert wordstart", "insert wordend")

I have attempted it by using:

def _on_click(self, event):
    self.text.tag_remove("highlight", "1.0", "end")
    self.text.tag_add("highlight", "insert wordstart", "insert wordend")
    if self.text.tag_names == ('sel', 'highlight'):
        self.text.tag_add("highlight", "insert wordstart", "insert wordend")
    else:
        self.text.tag_remove("highlight", "1.0", "end")

but that has no luck.

Body:
You can use tag_names to get a list of tags at a certain index. Then it's just a matter of calling tag_add or tag_remove depending on whether the tag is present on the current word or not.

Example:

import tkinter as tk

class Example(object):
    def __init__(self):
        self.root = tk.Tk()
        self.text = tk.Text(self.root)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.bind("<ButtonRelease-1>", self._on_click)
        self.text.tag_configure("highlight", background="bisque")

        with open(__file__, "r") as f:
            self.text.insert("1.0", f.read())

    def start(self):
        self.root.mainloop()

    def _on_click(self, event):
        tags = self.text.tag_names("insert wordstart")
        if "highlight" in tags:
            self.text.tag_remove("highlight", "insert wordstart", "insert wordend")
        else:
            self.text.tag_add("highlight", "insert wordstart", "insert wordend")

if __name__ == "__main__":
    Example().start()


问:
efficiency loss due to use of function pointer in place of if-block
Suppose we have a Fortran function (for example a mathematical optimization algorithm) that takes as input, another Fortran function:

```<code>myOptimizer(func)
</code>```

Now depending on the user's choice, the input function could be from a list of several different functions. This list of choices can be implemented via an if-block:

```<code>if (userChoice=='func1') then
    myOptimizer(func1)
elseif (userChoice=='func2') then
    myOptimizer(func2)
elseif (userChoice=='func3') then
    myOptimizer(func3)
end if
</code>```

Alternatively, I could also define function pointers, and write this as,

```<code>if (userChoice=='func1') then
    func => func1
elseif (userChoice=='func2') then
    func => func2
elseif (userChoice=='func3') then
    func => func3
end if
myOptimizer(func)
</code>```

Based on my tests with Intel Fortran Compiler 2017 with O2 flag, the second implementation happens to be slower by several factors (4-5 times slower than the if-block implementation). From the software development perspective, I would strongly prefer the second approach since it results in much more concise and cleaner code, at least in my problem where there is a fixed workflow, with different possible input functions to the workflow. However, performance also equally matters in the problem.

Is this loss of performance by indirect function calls, expected in all Fortran codes? or is it a compiler-dependent issue? Is there a solution to using indirect function calls without performance loss? How about other languages such as C/C++?

答:
This is a pure guess based on how compilers generally work and what might explain the 4-5x perf difference.

In the first version, maybe the compiler is inlining myOptimizer() into each call site with func1, func2, and func3 inlined into the optimizer, so when it runs there's no actual function pointer or function call happening.

An indirect function-call isn't much more expensive than a regular function call on modern x86 hardware.  It's the lack of inlining that really hurts, especially for FP code.  Spilling / reloading all the floating-point registers around a function call is expensive, especially if the function is fairly small.

i.e. what's probably hurting you is that your 2nd version convinces the compiler not to undo the indirection.  This would be true in C / C++ as well.

Hand-holding your compiler into making fast asm probably means you have to write it the first way, unless there's a profile-guided optimization option you can use that might make the compiler realize this is a hot spot and it's worth trying harder with the source written the 2nd way.  (Sorry I don't use Fortran, and I only know a few of the options for Intel's C/C++ compiler from looking at its asm output vs. gcc and clang on http://gcc.godbolt.org/)

To see if my hypothesis is right, check the compiler-generated asm.  If the first version doesn't actually pass a function pointer to a stand-alone definition of myOptimizer, but the 2nd one does, that's probably all there is to it.

See How to remove "noise" from GCC/clang assembly output? for more about looking at compiler output.  Matt Godbolt's CppCon2017 talk: “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid” is a good intro to reading compiler output and why you might want to.

Body:
Suppose we have a Fortran function (for example a mathematical optimization algorithm) that takes as input, another Fortran function:

myOptimizer(func)

Now depending on the user's choice, the input function could be from a list of several different functions. This list of choices can be implemented via an if-block:

if (userChoice=='func1') then
    myOptimizer(func1)
elseif (userChoice=='func2') then
    myOptimizer(func2)
elseif (userChoice=='func3') then
    myOptimizer(func3)
end if

Alternatively, I could also define function pointers, and write this as,

if (userChoice=='func1') then
    func => func1
elseif (userChoice=='func2') then
    func => func2
elseif (userChoice=='func3') then
    func => func3
end if
myOptimizer(func)

Based on my tests with Intel Fortran Compiler 2017 with O2 flag, the second implementation happens to be slower by several factors (4-5 times slower than the if-block implementation). From the software development perspective, I would strongly prefer the second approach since it results in much more concise and cleaner code, at least in my problem where there is a fixed workflow, with different possible input functions to the workflow. However, performance also equally matters in the problem.

Is this loss of performance by indirect function calls, expected in all Fortran codes? or is it a compiler-dependent issue? Is there a solution to using indirect function calls without performance loss? How about other languages such as C/C++?


问:
Microservices internal communication
I'm learning APIs with microservies architect. Here is small description about the setup

I've two microservice applications and API gateway

All the applications including API gateway is nodeJs - express app.

Auth logic - JWT, handled on API gateway

Pass each incoming API gateway request to each of the microservice applications using http-proxy.

Also passes the user info as proxy header.

Client request flow:

Client requesting API1 from microservice1 with JWT token which will be authenticated at API gateway and then information will be served from microservice1. which is fine.

But I've one private API2 which should not be allowed from client side. Only internal applications can use it, but it should be callable upon another request from the client side.

eg.

```<code>client request -> /API/Gateway1 (has JWT)
/API/Gateway1 -> API1 (has valid user)
API1 -> /API/Gateway2 (has valid user)
/API/Gateway2 -> API2 (has valid user)
</code>```

Question:

How can I protect API2 from the client side, what if client fakes the valid user header.

答:
Seems like you don't need REST Endpoint on API2 at all.
 The suggestions above by @Dayo Adeyemi are correct, but if there is a service that you need to keep private then there is no need to write the REST Endpoint codes in there.

Title: Microservices internal communication

Body:
I'm learning APIs with microservies architect. Here is small description about the setup

I've two microservice applications and API gateway

All the applications including API gateway is nodeJs - express app.

Auth logic - JWT, handled on API gateway

Pass each incoming API gateway request to each of the microservice applications using http-proxy.

Also passes the user info as proxy header.

Client request flow:

Client requesting API1 from microservice1 with JWT token which will be authenticated at API gateway and then information will be served from microservice1. which is fine.

But I've one private API2 which should not be allowed from client side. Only internal applications can use it, but it should be callable upon another request from the client side.

eg.

client request -> /API/Gateway1 (has JWT)
/API/Gateway1 -> API1 (has valid user)
API1 -> /API/Gateway2 (has valid user)
/API/Gateway2 -> API2 (has valid user)

Question:

How can I protect API2 from the client side, what if client fakes the valid user header.


问:
Powermock/Easymock tests take 10x as long when not on VPN
I'll be as specific as I can with this...

Basically, the current unit tests for a large java project take around 19m30s to run when not on an OpenVPN network. When on the OpenVPN network, the tests take about 2m0s to run. Why is this?

From what I can tell, there are no external calls being made. One specific test takes 1m36s off VPN and then 1s when on VPN. Are the tests written inefficiently? Where should I start looking to improve the time it takes off the VPN? What could cause issues like this?

We are using Powermock and Easymock to do the unit tests. The specific test above uses an in-memory database.

答:
First of all, make sure that no network calls are made. For example, if you use SOAP services the wsdl file could be retrieved implicitly. Use wireshark, fiddler or other software for network analysis. </p>

<p>Secondly, run JVM profiling and see where the most of the time being spent. Having this huge difference (1 minute vs 1 second)   should be easy to pinpoint the problem. </p>

Body:
First of all, make sure that no network calls are made. For example, if you use SOAP services the wsdl file could be retrieved implicitly. Use wireshark, fiddler or other software for network analysis.

Secondly, run JVM profiling and see where the most of the time being spent. Having this huge difference (1 minute vs 1 second)   should be easy to pinpoint the problem.


问:
How do you Parse this String in Lua "1 2 3 4"?
I am brand new to Lua from a pure VB.Net background.  I have a large file of maplines that I need to iterate through.  The data is in the form of:

;XX.XXX  YY.YYY  Name
;
[Airways]
58.50 -12.44 58.21 -13.73

58.21 -13.73 57.89 -15.02

57.89 -15.02 57.54 -16.30

57.54 -16.30 57.17 -17.58

57.17 -17.58 56.76 -18.84

56.76 -18.84 56.33 -20.10

56.33 -20.10 55.87 -21.35

54.33 -25.02 53.77 -26.22

I have tried this but keep getting an error.

```<code>local mapLines = {}

local filePath = system.pathForFile( "data.ini", system.DocumentsDirectory )

local file = io.open( filePath, "r" )

if file then
local contents = file:read( "*a" )

--print( "Contents of " .. filePath )
--print( contents )

io.close( file )

local t = display.newText( "Contents of ", 5, 80, nil, 16 );
t:setTextColor( 255, 255, 136, 255 );
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setTextColor( 255, 255, 136, 255 );

local ylast = 130
for line in io.lines(filePath) do
    local t = display.newText( line, 15, ylast, nil, 14 );
    t:setTextColor( 255, 255, 255 );
    ylast = ylast + 20

    n = tonumber(line);
    if n == nil then

        local f = {}
        s = "1 2 3 4"
        for k, v in string.gmatch(s, "(%w+) (%w+)") do
        f[k] = v
          end

local myLine = newLine(tonumber(f[1]), tonumber(f[2]), tonumber(f[3]), tonumber(f[4]))
        table.insert( mapLines, myLine )
    end
  end
end

-- Example of shape drawing func

local function newLine(x,y,x1,y1)

-- need initial segment to start
local Line = display.newLine( x, y, x1, y1 )

Line:setColor( 30, 155, 30, 100 )
Line.width = 3

return Line
end

Runtime:addEventListener( "enterFrame", mapLines )
</code>```

Any help would be greatly appreciated!

Dave

答:
answering the question in the topic:

```<code>local string_to_parse = '1 2 3 4'

for s in string_to_parse:gmatch('%d+') do
   print(s)
end
</code>```

sample code on codepad

Body:
I am brand new to Lua from a pure VB.Net background.  I have a large file of maplines that I need to iterate through.  The data is in the form of:

;XX.XXX  YY.YYY  Name
;
[Airways]
58.50 -12.44 58.21 -13.73

58.21 -13.73 57.89 -15.02

57.89 -15.02 57.54 -16.30

57.54 -16.30 57.17 -17.58

57.17 -17.58 56.76 -18.84

56.76 -18.84 56.33 -20.10

56.33 -20.10 55.87 -21.35

54.33 -25.02 53.77 -26.22

I have tried this but keep getting an error.

local mapLines = {}

local filePath = system.pathForFile( "data.ini", system.DocumentsDirectory )

local file = io.open( filePath, "r" )

if file then
local contents = file:read( "*a" )

--print( "Contents of " .. filePath )
--print( contents )

io.close( file )

local t = display.newText( "Contents of ", 5, 80, nil, 16 );
t:setTextColor( 255, 255, 136, 255 );
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setTextColor( 255, 255, 136, 255 );

local ylast = 130
for line in io.lines(filePath) do
    local t = display.newText( line, 15, ylast, nil, 14 );
    t:setTextColor( 255, 255, 255 );
    ylast = ylast + 20

    n = tonumber(line);
    if n == nil then

        local f = {}
        s = "1 2 3 4"
        for k, v in string.gmatch(s, "(%w+) (%w+)") do
        f[k] = v
          end

local myLine = newLine(tonumber(f[1]), tonumber(f[2]), tonumber(f[3]), tonumber(f[4]))
        table.insert( mapLines, myLine )
    end
  end
end

-- Example of shape drawing func

local function newLine(x,y,x1,y1)

-- need initial segment to start
local Line = display.newLine( x, y, x1, y1 )

Line:setColor( 30, 155, 30, 100 )
Line.width = 3

return Line
end

Runtime:addEventListener( "enterFrame", mapLines )

Any help would be greatly appreciated!

Dave

Body:
answering the question in the topic:

local string_to_parse = '1 2 3 4'

for s in string_to_parse:gmatch('%d+') do
   print(s)
end

sample code on codepad


答:
I think you just need the filenames without the file extensions. So, I encourage you to do this.

```<code>lst = [os.path.splitext(x)[0] for x in os.listdir("songs")]
</code>```

If you have audio files with different extensions, say, mp3, wav etc., the above code will handle all of them.

Body:
So I'm making a bot, and so far I have a command that prints out a directory of all available songs seen here:

@bot.command()
async def songs(ctx):
    msg = os.listdir("songs")
    await ctx.send(msg)

Which works as expected, it prints the list of songs in that folder.

['song1.mp3']

However, my main problem here is that it shows the file extension on the end, which I don't want. What would be the best way to go about removing the file extension (.mp3) before printing it?

Body:
I think you just need the filenames without the file extensions. So, I encourage you to do this.

lst = [os.path.splitext(x)[0] for x in os.listdir("songs")]

If you have audio files with different extensions, say, mp3, wav etc., the above code will handle all of them.


问:
ggplot Modification Theme change geom_area,
How can I change the fill "names" ie : psavert to "personal saving rate" and "uempmed" to "median unemployment duration in weeks"
also i want to add % sign in the returns on the 7 y axis, unable to use scale_x_discrete() and modify it.

can someone please help?

attached is the image and below is the code

```<code>library(ggplot2)

library(lubridate)

theme_set(theme_bw())

df <- economics[, c("date", "psavert", "uempmed")]

df <- df[lubridate::year(df$date) %in% c(1967:1981), ]

# labels and breaks for X axis text
brks <- df$date[seq(1, length(df$date), 12)]

lbls <- lubridate::year(brks)

# plot
ggplot(df, aes(x=date)) +

     geom_area(aes(y=psavert+uempmed, fill="psavert")) +

     geom_area(aes(y=uempmed, fill="uempmed")) +

     labs(title="Area Chart of Returns Percentage",
          subtitle="From Wide Data format",
          caption="Source: Economics",
          y="Returns %") +  # title and caption

     scale_x_date(labels = lbls, breaks = brks) +  # change to monthly ticks and

labels

     scale_fill_manual(name="",
                    values = c("psavert"="#00ba38", "uempmed"="#f8766d")) +  #
line color

  theme(panel.grid.minor = element_blank()) + # turn off minor grid

  annotate("text", x=as.Date("1975-04-01"), y=25, label="Year with highest returns") #annotation layer
</code>```

答:
The first example below is how to do it with your original plot code. The second is a more "ggplot-like" approach that first reshapes the data to "long" format and recodes the names of the values.

```<code>library(tidyverse)
library(lubridate)

theme_set(theme_bw() + theme(panel.grid.minor=element_blank()))

ggplot(df, aes(x=date)) +
  geom_area(aes(y=psavert+uempmed, fill="Personal Saving Rate")) +
  geom_area(aes(y=uempmed, fill="Unemployment Rate")) +
  labs(title="Area Chart of Returns Percentage",
       subtitle="From Wide Data format",
       caption="Source: Economics",
       y="Returns %") +  # title and caption
  scale_x_date(labels = lbls, breaks = brks) +  # change to monthly ticks and labels
  scale_fill_manual(name="",
                    values = c("Personal Saving Rate"="#00ba38", "Unemployment Rate"="#f8766d")) +  # line color
  scale_y_continuous(breaks=seq(0,30,10), labels=paste0(seq(0,30,10),"%")) +
  annotate("text", x=as.Date("1975-04-01"), y=25, label="Year with highest returns")
</code>```

The alternative below also uses the date_breaks and date_labels arguments to scale_x_date so there's no need to create the breaks and label vectors before creating the plot.

```<code>ggplot(df %>% gather(key, value, -date) %>%
         mutate(key=recode(key, "psavert"="Personal Saving Rate", "uempmed"="Unemployment Rate")),
       aes(x=date, y=value, fill=key)) +
  geom_area() +
  labs(title="Area Chart of Returns Percentage",
       subtitle="From Wide Data format",
       caption="Source: Economics",
       y="Returns %",
       fill="") +
  scale_x_date(date_breaks="1 year", date_labels="%Y") +
  scale_fill_manual(name="", values = c("#00ba38", "#f8766d")) +
  scale_y_continuous(breaks=seq(0,30,10), labels=paste0(seq(0,30,10),"%")) +
  annotate("text", x=as.Date("1975-04-01"),
           y=df %>% mutate(sum=psavert+uempmed) %>% pull(sum) %>% max + 1,
           label="Year with highest returns")
</code>```

Body:
How can I change the fill "names" ie : psavert to "personal saving rate" and "uempmed" to "median unemployment duration in weeks"
also i want to add % sign in the returns on the 7 y axis, unable to use scale_x_discrete() and modify it.

can someone please help?

attached is the image and below is the code

library(ggplot2)

library(lubridate)

theme_set(theme_bw())

df <- economics[, c("date", "psavert", "uempmed")]

df <- df[lubridate::year(df$date) %in% c(1967:1981), ]

# labels and breaks for X axis text
brks <- df$date[seq(1, length(df$date), 12)]

lbls <- lubridate::year(brks)

# plot
ggplot(df, aes(x=date)) +

     geom_area(aes(y=psavert+uempmed, fill="psavert")) +

     geom_area(aes(y=uempmed, fill="uempmed")) +

     labs(title="Area Chart of Returns Percentage",
          subtitle="From Wide Data format",
          caption="Source: Economics",
          y="Returns %") +  # title and caption

     scale_x_date(labels = lbls, breaks = brks) +  # change to monthly ticks and

labels

     scale_fill_manual(name="",
                    values = c("psavert"="#00ba38", "uempmed"="#f8766d")) +  #
line color

  theme(panel.grid.minor = element_blank()) + # turn off minor grid

  annotate("text", x=as.Date("1975-04-01"), y=25, label="Year with highest returns") #annotation layer

Body:
The first example below is how to do it with your original plot code. The second is a more "ggplot-like" approach that first reshapes the data to "long" format and recodes the names of the values.

library(tidyverse)
library(lubridate)

theme_set(theme_bw() + theme(panel.grid.minor=element_blank()))

ggplot(df, aes(x=date)) +
  geom_area(aes(y=psavert+uempmed, fill="Personal Saving Rate")) +
  geom_area(aes(y=uempmed, fill="Unemployment Rate")) +
  labs(title="Area Chart of Returns Percentage",
       subtitle="From Wide Data format",
       caption="Source: Economics",
       y="Returns %") +  # title and caption
  scale_x_date(labels = lbls, breaks = brks) +  # change to monthly ticks and labels
  scale_fill_manual(name="",
                    values = c("Personal Saving Rate"="#00ba38", "Unemployment Rate"="#f8766d")) +  # line color
  scale_y_continuous(breaks=seq(0,30,10), labels=paste0(seq(0,30,10),"%")) +
  annotate("text", x=as.Date("1975-04-01"), y=25, label="Year with highest returns")

The alternative below also uses the date_breaks and date_labels arguments to scale_x_date so there's no need to create the breaks and label vectors before creating the plot.

ggplot(df %>% gather(key, value, -date) %>%
         mutate(key=recode(key, "psavert"="Personal Saving Rate", "uempmed"="Unemployment Rate")),
       aes(x=date, y=value, fill=key)) +
  geom_area() +
  labs(title="Area Chart of Returns Percentage",
       subtitle="From Wide Data format",
       caption="Source: Economics",
       y="Returns %",
       fill="") +
  scale_x_date(date_breaks="1 year", date_labels="%Y") +
  scale_fill_manual(name="", values = c("#00ba38", "#f8766d")) +
  scale_y_continuous(breaks=seq(0,30,10), labels=paste0(seq(0,30,10),"%")) +
  annotate("text", x=as.Date("1975-04-01"),
           y=df %>% mutate(sum=psavert+uempmed) %>% pull(sum) %>% max + 1,
           label="Year with highest returns")


问:
Handle Button click inside a row in RecyclerView
I am using following code for handling row clicks. (source)

```<code>static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }
}
</code>```

This works however, if I want to have say a delete button on each row. I am not sure to how to implement that with this.

I attached OnClick listener to delete button which works (deletes the row) but it also fires the onclick on full row.

Can anybody help me in how to avoid full row click if a single button is clicked.

Thanks.

答:
You can check if you have any similar entries first, if you get a collection with size 0, start a new query to save.

OR

more professional and faster way.
create a cloud trigger (before save)

check out this answer
https://stackoverflow.com/a/35194514/1388852

Body:
I am using following code for handling row clicks. (source)

static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }
}

This works however, if I want to have say a delete button on each row. I am not sure to how to implement that with this.

I attached OnClick listener to delete button which works (deletes the row) but it also fires the onclick on full row.

Can anybody help me in how to avoid full row click if a single button is clicked.

Thanks.


问:
Macro increment
I have table lookup values as below

```<code>sno date
1   200101
2   200102
3   200103
4   200104
</code>```

I wrote below macro

```<code>%let date=200102
 proc sql;
 select sno into :no from lookup where date=&date.;
 quit;
</code>```

I need a help on how to convert the entire table lookup into macro increment by creating first s.no and date as two macro variable then increment. So that i don’t need to update dates in my table lookup every time. So if i look up for date 201304 i need to get its corresponding s.no

答:
Is there pattern to the SNO values?  Are you basically numbering the months since 01JAN2001?  If so then use INTCK() function.

```<code>data test;
  input date yymmdd8. ;
  format date yymmdd10. ;
  sno = 1+intck('month','01JAN2001'd,date);
cards;
20010112
20010213
20010314
20010415
;
</code>```

So you could create two macro variables. One with the base date and the other with the base SNO value.

```<code>36   %let basedate='01JAN2001'd ;
37   %let basesno=1;
38   %let date='01JAN2001'd ;
39   %let sno=%eval(&basesno + %sysfunc(intck(month,&basedate,&date)));
40   %put &=date &=sno;
DATE='01JAN2001'd SNO=1
41
42   %let date="%sysfunc(today(),date9)"d;
43   %let sno=%eval(&basesno + %sysfunc(intck(month,&basedate,&date)));
44   %put &=date &=sno;
DATE="16NOV2017"d SNO=203
</code>```

Title: Macro increment

Body:
I have table lookup values as below

sno date
1   200101
2   200102
3   200103
4   200104

I wrote below macro

%let date=200102
 proc sql;
 select sno into :no from lookup where date=&date.;
 quit;

I need a help on how to convert the entire table lookup into macro increment by creating first s.no and date as two macro variable then increment. So that i don’t need to update dates in my table lookup every time. So if i look up for date 201304 i need to get its corresponding s.no

Body:
Is there pattern to the SNO values?  Are you basically numbering the months since 01JAN2001?  If so then use INTCK() function.

data test;
  input date yymmdd8. ;
  format date yymmdd10. ;
  sno = 1+intck('month','01JAN2001'd,date);
cards;
20010112
20010213
20010314
20010415
;

So you could create two macro variables. One with the base date and the other with the base SNO value.

36   %let basedate='01JAN2001'd ;
37   %let basesno=1;
38   %let date='01JAN2001'd ;
39   %let sno=%eval(&basesno + %sysfunc(intck(month,&basedate,&date)));
40   %put &=date &=sno;
DATE='01JAN2001'd SNO=1
41
42   %let date="%sysfunc(today(),date9)"d;
43   %let sno=%eval(&basesno + %sysfunc(intck(month,&basedate,&date)));
44   %put &=date &=sno;
DATE="16NOV2017"d SNO=203


问:
upgrading wso2 Identity server mapping database
I am following https://docs.wso2.com/display/IS530/Upgrading+from+a+Previous+Release#UpgradingfromaPreviousRelease-step11  To upgrade Idenity server to upgrade Identity server from 5.2.0 to 5.3.0 .

In the old version p[5.2.0] , custom database used where i pointed conf/datasources/master-datasources.xml , repository/conf/user-mgt.xml Changes to my own cloud database.

Shouldnt i be doing that in the migration ?Should the same files have to be pointed to my cloud database?

Should I do that before i run
sh wso2server.sh -Dmigrate -Dcomponent=identity

One more question. Should i always  have to start server using the option Dmigrate -Dcomponent=identity . Or is it just one time?

Also should we go through https://docs.wso2.com/display/AM210/Configuring+WSO2+Identity+Server+as+a+Key+Manager#ConfiguringWSO2IdentityServerasaKeyManager-Step2-DownloadWSO2API-MandWSO2IS  And do each steps even if we are migrating?

答: I think you would only run -Dmigrate once. To my knowledge, I'd think you would need to configure your master-datasources.xml and user-mgt.xml to point to the same paths that you initially defined in v5.2.0. There aren't a lot of changes that happen in minor updates, so it should be fine.</p>


问:
Twilio TwiML app XML error
I have a TwiML app with this code in the Connect action of the CallController. This code is taken straight from the Twilio demos.

```<code>[HttpPost]
public virtual ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    var dial = new Dial(callerId: "+6138595????");
    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        dial.Client("support_agent");
    }
    response.Dial(dial);

    return TwiML(response);
}
</code>```

When this is called it raises the error "Data at the root level is invalid. Line 1, position 1."

The XML this generates is

```<code><?xml version="1.0" encoding="utf-8"?>
<Response>
  <Dial callerId="+6138595????">
    <Client>support_agent</Client>
  </Dial>
</Response>
</code>```

答:
Twilio Evangelist here.

A quick question - is this happening every time the method is invoked, or only when specific inputs are provided? Needing to build the string manually is of course not desired. So I would like to get to the bottom of what triggered this result.

Title: Twilio TwiML app XML error

Body:
I have a TwiML app with this code in the Connect action of the CallController. This code is taken straight from the Twilio demos.

[HttpPost]
public virtual ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    var dial = new Dial(callerId: "+6138595????");
    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        dial.Client("support_agent");
    }
    response.Dial(dial);

    return TwiML(response);
}

When this is called it raises the error "Data at the root level is invalid. Line 1, position 1."

The XML this generates is

<?xml version="1.0" encoding="utf-8"?>
<Response>
  <Dial callerId="+6138595????">
    <Client>support_agent</Client>
  </Dial>
</Response>


问:
Remove page break lines from worksheet
Microsoft Excel adds dashed lines to your worksheets when you use the print preview feature, as a way to adjust page breaks. When you leave print preview though, you can often be stuck with those annoying lines in your worksheet. How can you remove them from the worksheet?

For example, if you have an Excel worksheet, you go into Page Break Preview to see (and to set) where page breaks are in your worksheet for printing:

In this example, the worksheet will print as 1 page that contains the contents of cells A1:C7

The issue occurs when you use the View ribbon to turn off Page Break Preview, and go back to Normal view of the worksheet. Then you see these annoying lines drawn in the worksheet where the page breaks are located. They appear as either dashed or solid lines.

These lines look like cell borders, although they are not. How do you disable them once they are turned on?!

答:
These lines are indeed not cell borders, and are only visible in Excel as a guide for where the page breaks are located. Microsoft Office Support suggests this to clear them:

Click Options in the File menu

In the Advanced category, scroll down to the Display options for this worksheet section, and clear the Show page breaks check box

Repeat this procedure for each worksheet in your workbook that contains print preview lines.

This manual procedure can be time consuming if you have multiple worksheets with this issue. In that case, you can use this VBA macro to remove print preview lines for all worksheets in your workbook.

```<code>Option Explicit

Public Sub disableAllPageBreaks()

  Dim ws as Worksheet

  For Each ws In ActiveWorkbook.Worksheets
    ws.DisplayPageBreaks = False
  Next ws

End Sub
</code>```

Title: Remove page break lines from worksheet

Body:
These lines are indeed not cell borders, and are only visible in Excel as a guide for where the page breaks are located. Microsoft Office Support suggests this to clear them:

Click Options in the File menu

In the Advanced category, scroll down to the Display options for this worksheet section, and clear the Show page breaks check box

Repeat this procedure for each worksheet in your workbook that contains print preview lines.

This manual procedure can be time consuming if you have multiple worksheets with this issue. In that case, you can use this VBA macro to remove print preview lines for all worksheets in your workbook.

Option Explicit

Public Sub disableAllPageBreaks()

  Dim ws as Worksheet

  For Each ws In ActiveWorkbook.Worksheets
    ws.DisplayPageBreaks = False
  Next ws

End Sub


问:
How do I validate nested properties using anyOf
I'm struggling to write a validation rule using json-schema. Here is my data in json format:

```<code>{
    "headers" : {
        "api_key" : "aaa-bbb-ccc-ddd-eee"
    },
    "query_string" : {
        "apikey" : "aaa-bbb-ccc-ddd-eee"
    }
}
</code>```

I need a rule that says:

At least "headers->api_key" or "query_string->apikey" needs to be present in the json, but not both.

Here is my schema validation so far:

```<code>{
  "title": "Application Get Single",
  "type": "object",
  "properties": {
    "headers": {
      "type": "object",
      "properties": {
        "api_key": {
          "type": "string"
        }
      }
    },
    "query_string": {
      "type": "object",
      "properties": {
        "apikey": {
          "type": "string"
        }
      }
    }
  },
  "anyOf": [
    {"required": ["headers"["api_key"]]}, // what should this be??
    {"required": ["query_string"["apikey"]]} // what should this be??
  ]
}
</code>```

I think it's anyOf I'm looking for but I don't know how to refer to a nested json items above.

At the moment I get an error:

JSON syntax is malformed

I'm using Justin Rainbow as I'm working with PHP for this.

答:
There are a couple ways.  The most straightforward is:

```<code>{
  "title": "Application Get Single",
  "type": "object",
  "properties": {
    "headers": {
      "type": "object",
      "properties": {
        "api_key": {
          "type": "string"
        }
      }
    },
    "query_string": {
      "type": "object",
      "properties": {
        "apikey": {
          "type": "string"
        }
      }
    }
  },
  "anyOf": [
    {
      "properties": {
        "headers": {
            "type": "object",
            "required":["api_key"]
        }
      }
    },
    {
      "properties": {
        "query_string": {
            "type": "object",
            "required":["apikey"]
        }
      }
    }
  ]
}
</code>```

You would probably also want "minProperties": 1 on the root object in order to ensure that either headers or query_string exist.

EDIT: Just re-read the question and if headers.api_key and query_string.apikey are mutually exclusive change anyOf to oneOf

Body:
I'm struggling to write a validation rule using json-schema. Here is my data in json format:

{
    "headers" : {
        "api_key" : "aaa-bbb-ccc-ddd-eee"
    },
    "query_string" : {
        "apikey" : "aaa-bbb-ccc-ddd-eee"
    }
}

I need a rule that says:

At least "headers->api_key" or "query_string->apikey" needs to be present in the json, but not both.

Here is my schema validation so far:

{
  "title": "Application Get Single",
  "type": "object",
  "properties": {
    "headers": {
      "type": "object",
      "properties": {
        "api_key": {
          "type": "string"
        }
      }
    },
    "query_string": {
      "type": "object",
      "properties": {
        "apikey": {
          "type": "string"
        }
      }
    }
  },
  "anyOf": [
    {"required": ["headers"["api_key"]]}, // what should this be??
    {"required": ["query_string"["apikey"]]} // what should this be??
  ]
}

I think it's anyOf I'm looking for but I don't know how to refer to a nested json items above.

At the moment I get an error:

JSON syntax is malformed

I'm using Justin Rainbow as I'm working with PHP for this.

Body:
There are a couple ways.  The most straightforward is:

{
  "title": "Application Get Single",
  "type": "object",
  "properties": {
    "headers": {
      "type": "object",
      "properties": {
        "api_key": {
          "type": "string"
        }
      }
    },
    "query_string": {
      "type": "object",
      "properties": {
        "apikey": {
          "type": "string"
        }
      }
    }
  },
  "anyOf": [
    {
      "properties": {
        "headers": {
            "type": "object",
            "required":["api_key"]
        }
      }
    },
    {
      "properties": {
        "query_string": {
            "type": "object",
            "required":["apikey"]
        }
      }
    }
  ]
}

You would probably also want "minProperties": 1 on the root object in order to ensure that either headers or query_string exist.

EDIT: Just re-read the question and if headers.api_key and query_string.apikey are mutually exclusive change anyOf to oneOf