问:
__copy_helper_block_ crash in AVFoundation
I have a strange crash in my video processing app. It uses AVFoundation to work with video & audio and GPUImage for filtering. I have never faced this issue myself but after releasing it to the App Store it appeared in Crashlytics quite often. Here is the log of the crash:

```<code>Thread : Crashed: AVPlayerItemOutput queue
0  libobjc.A.dylib                0x00000001986f80b4 objc_retain + 20
1  libsystem_blocks.dylib         0x0000000198d79bf8 _Block_object_assign + 320
2  AVFoundation                   0x0000000186895a34 __copy_helper_block_171 + 36
3  libsystem_blocks.dylib         0x0000000198d79738 _Block_copy_internal + 384
4  libdispatch.dylib              0x0000000198d252fc _dispatch_Block_copy + 36
5  libdispatch.dylib              0x0000000198d2685c dispatch_async + 68
6  AVFoundation                   0x00000001868959ac -[AVPlayerItemVideoOutput _dispatchOutputSequenceWasFlushed] + 112
7  libdispatch.dylib              0x0000000198d2536c _dispatch_client_callout + 16
8  libdispatch.dylib              0x0000000198d2e6e8 _dispatch_barrier_sync_f_invoke + 76
9  AVFoundation                   0x00000001868940a8 AVPlayerItemVideoOutput_figVCSequentialAvailable + 196
10 MediaToolbox                   0x000000018a3c16f8 FigVisualContextImageAvailableSequential + 108
11 MediaToolbox                   0x000000018a348ce8 itemremote_postNotificationWithPayload + 3996
12 MediaToolbox                   0x000000018a342d60 FigPlayerRemoteCallbacksServer_SendNotifyPing + 924
13 MediaToolbox                   0x000000018a342998 _XSendNotifyPing + 60
14 MediaToolbox                   0x000000018a33f0d4 figmoviecallbacks_server + 112
15 MediaToolbox                   0x000000018a33f018 fpr_ClientPortCallBack + 208
16 CoreFoundation                 0x0000000187f44ce0 __CFMachPortPerform + 180
17 CoreFoundation                 0x0000000187f598fc __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 56
18 CoreFoundation                 0x0000000187f5985c __CFRunLoopDoSource1 + 436
19 CoreFoundation                 0x0000000187f577dc __CFRunLoopRun + 1640
20 CoreFoundation                 0x0000000187e851f4 CFRunLoopRunSpecific + 396
21 GraphicsServices               0x00000001910135a4 GSEventRunModal + 168
22 UIKit                          0x000000018c7b6784 UIApplicationMain + 1488
23 MerryVideoEditor               0x000000010024b804 main (main.m:16)
24 libdyld.dylib                  0x0000000198d4ea08 start + 4
</code>```

This is how I connect AVFoundation to GPUImage:

```<code>class ProjectEditorViewController: UIViewController {
   private var videoPlayerView = VideoPlayerView()
   private var movieFile: GPUImageMovie!
   private var currentComposition: AVComposition!
   //...and other properties
}

// MARK: - Filtering & Playback
extension ProjectEditorViewController{
   func updatePlayer() {

      currentFilter.removeAllTargets()
      movieFile?.removeAllTargets()
      movieFile?.endProcessing()

      let time = self.videoPlayerView.player?.currentItem.currentTime() ?? kCMTimeZero

      let (composition, audioMix) = compositionBuilder.buildCompositionFromTimeLine(timeLine)
      videoPlayerView.setAsset(composition)
      videoPlayerView.playerItem.audioMix = audioMix

      movieFile = GPUImageMovie(playerItem: videoPlayerView.player.currentItem)
      currentFilter.applyFromOutput(movieFile, toInput: gpuPlayerView)
      movieFile.startProcessing()

      addSyncLayerIfNeededForComposition(composition)

      videoPlayerView.player.seekToTime(time, toleranceBefore: kPlayerToleranceSeekTime, toleranceAfter: kPlayerToleranceSeekTime)
      currentComposition = composition

   }

   func updatePlayerFilter(){
      if movieFile != nil{
         movieFile.removeAllTargets()
         currentFilter.applyFromOutput(movieFile, toInput: gpuPlayerView)
         if(!videoPlayerView.isPlaying) { movieFile.startProcessing() }
         addSyncLayerIfNeededForComposition(currentComposition)
      }else{
         updatePlayer()
      }
   }
}
</code>```

Any ideas what is wrong with my code? Any questions, comments, hints and answers are highly appreciated.

答:
I agree with Igor, but setting playerItemOutput's delegate to nil didn't help me.
So I added

```<code>runSynchronouslyOnVideoProcessingQueue(^{

    [playerItemOutput setDelegate: nil
                            queue: nil];
    [_playerItem removeOutput: playerItemOutput];
    playerItemOutput = nil;
  });
</code>```

in endProcessing method after invalidating displayLink.

Hope that helps.

Body:
I have a strange crash in my video processing app. It uses AVFoundation to work with video & audio and GPUImage for filtering. I have never faced this issue myself but after releasing it to the App Store it appeared in Crashlytics quite often. Here is the log of the crash:

Thread : Crashed: AVPlayerItemOutput queue
0  libobjc.A.dylib                0x00000001986f80b4 objc_retain + 20
1  libsystem_blocks.dylib         0x0000000198d79bf8 _Block_object_assign + 320
2  AVFoundation                   0x0000000186895a34 __copy_helper_block_171 + 36
3  libsystem_blocks.dylib         0x0000000198d79738 _Block_copy_internal + 384
4  libdispatch.dylib              0x0000000198d252fc _dispatch_Block_copy + 36
5  libdispatch.dylib              0x0000000198d2685c dispatch_async + 68
6  AVFoundation                   0x00000001868959ac -[AVPlayerItemVideoOutput _dispatchOutputSequenceWasFlushed] + 112
7  libdispatch.dylib              0x0000000198d2536c _dispatch_client_callout + 16
8  libdispatch.dylib              0x0000000198d2e6e8 _dispatch_barrier_sync_f_invoke + 76
9  AVFoundation                   0x00000001868940a8 AVPlayerItemVideoOutput_figVCSequentialAvailable + 196
10 MediaToolbox                   0x000000018a3c16f8 FigVisualContextImageAvailableSequential + 108
11 MediaToolbox                   0x000000018a348ce8 itemremote_postNotificationWithPayload + 3996
12 MediaToolbox                   0x000000018a342d60 FigPlayerRemoteCallbacksServer_SendNotifyPing + 924
13 MediaToolbox                   0x000000018a342998 _XSendNotifyPing + 60
14 MediaToolbox                   0x000000018a33f0d4 figmoviecallbacks_server + 112
15 MediaToolbox                   0x000000018a33f018 fpr_ClientPortCallBack + 208
16 CoreFoundation                 0x0000000187f44ce0 __CFMachPortPerform + 180
17 CoreFoundation                 0x0000000187f598fc __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 56
18 CoreFoundation                 0x0000000187f5985c __CFRunLoopDoSource1 + 436
19 CoreFoundation                 0x0000000187f577dc __CFRunLoopRun + 1640
20 CoreFoundation                 0x0000000187e851f4 CFRunLoopRunSpecific + 396
21 GraphicsServices               0x00000001910135a4 GSEventRunModal + 168
22 UIKit                          0x000000018c7b6784 UIApplicationMain + 1488
23 MerryVideoEditor               0x000000010024b804 main (main.m:16)
24 libdyld.dylib                  0x0000000198d4ea08 start + 4

This is how I connect AVFoundation to GPUImage:

class ProjectEditorViewController: UIViewController {
   private var videoPlayerView = VideoPlayerView()
   private var movieFile: GPUImageMovie!
   private var currentComposition: AVComposition!
   //...and other properties
}

// MARK: - Filtering & Playback
extension ProjectEditorViewController{
   func updatePlayer() {

      currentFilter.removeAllTargets()
      movieFile?.removeAllTargets()
      movieFile?.endProcessing()

      let time = self.videoPlayerView.player?.currentItem.currentTime() ?? kCMTimeZero

      let (composition, audioMix) = compositionBuilder.buildCompositionFromTimeLine(timeLine)
      videoPlayerView.setAsset(composition)
      videoPlayerView.playerItem.audioMix = audioMix

      movieFile = GPUImageMovie(playerItem: videoPlayerView.player.currentItem)
      currentFilter.applyFromOutput(movieFile, toInput: gpuPlayerView)
      movieFile.startProcessing()

      addSyncLayerIfNeededForComposition(composition)

      videoPlayerView.player.seekToTime(time, toleranceBefore: kPlayerToleranceSeekTime, toleranceAfter: kPlayerToleranceSeekTime)
      currentComposition = composition

   }

   func updatePlayerFilter(){
      if movieFile != nil{
         movieFile.removeAllTargets()
         currentFilter.applyFromOutput(movieFile, toInput: gpuPlayerView)
         if(!videoPlayerView.isPlaying) { movieFile.startProcessing() }
         addSyncLayerIfNeededForComposition(currentComposition)
      }else{
         updatePlayer()
      }
   }
}

Any ideas what is wrong with my code? Any questions, comments, hints and answers are highly appreciated.

Body:
I agree with Igor, but setting playerItemOutput's delegate to nil didn't help me.
So I added

runSynchronouslyOnVideoProcessingQueue(^{

    [playerItemOutput setDelegate: nil
                            queue: nil];
    [_playerItem removeOutput: playerItemOutput];
    playerItemOutput = nil;
  });

in endProcessing method after invalidating displayLink.

Hope that helps.


来源: stackexchange

问:
Make all keys in s3 bucket private
I have a bucket with 10^6 keys in it. I want to make all objects in it private.

I tried s3cmd which fails after sometime.
I tried it with boto3, but it is painfully slow.

```<code>import boto3

boto3.setup_default_session(aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key)
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3')

bucket = s3_resource.Bucket(bucket_name)
bucket_acl = bucket.Acl()

i = 0

for object_summary in bucket.objects.all():
    i += 1
    object_acl = object_summary.Acl()
    if i % 100 == 1:
        print('{} {}'.format(i, object_summary.key))

    object_acl.put(ACL='private')
</code>```

Is there any way to do batch operation or do everything private by setting some bucket policy.

Any other suggestion is also welcome.

答:
You don't need to do anything. Objects in Amazon S3 are private by default.

Things that make them public are:

Bucket Polices on the bucket containing the objects

Permissions granted to Users, Groups and Roles in Amazon IAM

Permissions applied specifically to each object ("ACLs")

ContentLicense: CC BY-SA 3.0

Title: Make all keys in s3 bucket private

Body:
I have a bucket with 10^6 keys in it. I want to make all objects in it private.

I tried s3cmd which fails after sometime.
I tried it with boto3, but it is painfully slow.

import boto3

boto3.setup_default_session(aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key)
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3')

bucket = s3_resource.Bucket(bucket_name)
bucket_acl = bucket.Acl()

i = 0

for object_summary in bucket.objects.all():
    i += 1
    object_acl = object_summary.Acl()
    if i % 100 == 1:
        print('{} {}'.format(i, object_summary.key))

    object_acl.put(ACL='private')

Is there any way to do batch operation or do everything private by setting some bucket policy.

Any other suggestion is also welcome.


问:
WCF REST GET returns "Endpoint not found"
So I am trying to create a very basic WCF service with REST GET but there is only "Endpoint not found". I am sending GET via Postman App to address:

```<code>http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/json
</code>```

Service is hosted by IIS; Here's all my code:

```<code>namespace RESTfulTest
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        string GetText();
    }
}

namespace RESTfulTest
{
    [ServiceBehavior(InstanceContextMode =InstanceContextMode.Single)]
    public class Service1 : IService1
    {
        public string GetText()
        {
            return "Hello REST";
        }
    }

}
</code>```

And App.config file:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="RESTfulTest.Service1">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/" />
          </baseAddresses>
        </host>
        <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="RESTfulTest.IService1"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

  </system.serviceModel>

</configuration>
</code>```

What am I missing here?

答:
So everything was set up properly. The endpoint address that I was asking was incorrect. It should be http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/json/GetText
I didn't know that function name should be added to the address, that's the point.

Body:
So I am trying to create a very basic WCF service with REST GET but there is only "Endpoint not found". I am sending GET via Postman App to address:

http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/json

Service is hosted by IIS; Here's all my code:

namespace RESTfulTest
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        string GetText();
    }
}

namespace RESTfulTest
{
    [ServiceBehavior(InstanceContextMode =InstanceContextMode.Single)]
    public class Service1 : IService1
    {
        public string GetText()
        {
            return "Hello REST";
        }
    }

}

And App.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="RESTfulTest.Service1">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/" />
          </baseAddresses>
        </host>
        <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="RESTfulTest.IService1"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

  </system.serviceModel>

</configuration>

What am I missing here?


问:
How to write validations on below code in jquery
I am displaying form details in table format. But I want to apply validation for duplicate values.

I have two validations.

first time I will enter min value 1 and max value 100, now these values will display in table format on same page.

Now I will enter second time min value 101 and max value 200 or infinity, suppose I will enter min value between 1 to 100 it should not allow this because I already entered max value 100, so next it takes 101 too.

It is Possible in jquery or javascript?.

```<code><table id="transaction" class="display" width="100%" cellspacing="0">
   <thead>
      <tr>
         <th>Name</th>
         <th>Email</th>
         <th>Min</th>
         <th>Max</th>
      </tr>
   </thead>
   <tbody>
   </tbody>
</table>
<form id="localStorageTest" method="post" action="">
   <label>Name:</label>
   <input type="text" name="name" id="name" class="stored" value="" />
   <label>Email:</label>
   <input type="email" name="email" id="email" class="stored" value="" />
   <label>Min:</label>
   <input type="text" name="min" id="min" class="stored" value="" />
   <label>Max:</label>
   <input type="text" name="max" id="max" class="stored" value="" />
   <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;" id="savebutton"><i class="icon-check-sign" aria-hidden="false"></i> Save </button>
</form>
</code>```

答: Yes you can check the values in javascript using onChange or onkeyup events for the textbox that you need to validate. You just need to compare the values with the values that you have stored earlier.</p>

Body:
I am displaying form details in table format. But I want to apply validation for duplicate values.

I have two validations.

first time I will enter min value 1 and max value 100, now these values will display in table format on same page.

Now I will enter second time min value 101 and max value 200 or infinity, suppose I will enter min value between 1 to 100 it should not allow this because I already entered max value 100, so next it takes 101 too.

It is Possible in jquery or javascript?.

         Name
         Email
         Min
         Max

<form id="localStorageTest" method="post" action="">
   Name:
   <input type="text" name="name" id="name" class="stored" value="" />
   Email:
   <input type="email" name="email" id="email" class="stored" value="" />
   Min:
   <input type="text" name="min" id="min" class="stored" value="" />
   Max:
   <input type="text" name="max" id="max" class="stored" value="" />
   <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;" id="savebutton"> Save </button>
</form>


问:
jQuery UI sortable and live() click problem -- need to click twice after sorting for click to register
I have a table I'm using jQuery UI's "sortable" on. In the table, I have rows consisting of a "drag handle" to grab and reorder the table, and cells with clickable items, like this:

```<code><table id="test-table">
    <tbody>
    <tr>
        <td class="handle"><div class="ui-icon ui-icon-arrowthick-2-n-s" /></td>
        <td class="clickycell"><a href="#">Testing 1</a></td>
    </tr>
    <tr>
        <td class="handle"><div class="ui-icon ui-icon-arrowthick-2-n-s" /></td>
        <td class="clickycell"><a href="#">Testing 2</a></td></td>
    <tr>
        <td class="handle"><div class="ui-icon ui-icon-arrowthick-2-n-s" /></td>
        <td class="clickycell"><a href="#">Testing 3</a></td></td>
    </tr>
    </tbody>
</table>
</code>```

In my code, I make the table sortable, and also use jQuery's live() to bind a click event to the clickable items, like this:

```<code>$(function() {
    /*
       Using live() because in my real code table rows are dynamically added.
       However, if I use click() instead, as in the commented-out code, it works
       fine, without any need to click twice.

    */
    // $(".clickycell a").click(function() {
    $(".clickycell a").live('click', function() {
        alert("Successful click");
        return false;
    });
    $("#test-table tbody").sortable({
        handle: "td.handle", /* Use the draggy handle to move, not the whole row */
        cursor: "move"
    });
});
</code>```

I'm using live() because rows can be dynamically added to the table in the real code.

My problem is this: if I click on any of the clickable items before sorting, they work fine. After the user drags the rows to reorder them, though, I have to click twice for a click to register. After that second click, the clickable items go back to "normal", needing only one click, until the next time rows are dragged around.

If I use click() rather than live() -- as in the commented-out code -- then a single-click works fine at all times, but I'd rather use live(), as I said. And I'm curious as to why it's not working.

There's a live jsFiddle example here. Try dragging a row into a different position, then clicking on any of the "Testing..." links. In Firefox, at least, I need to click twice to get the "Successful click" alert.

Any ideas?

答: It's unfortunate to end with the answer "It is a bug," but I guess sometimes that happens.  Maybe I'll dust off my GitHub login and fork it to see if I can track it down and discover a fix.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a table I'm using jQuery UI's "sortable" on. In the table, I have rows consisting of a "drag handle" to grab and reorder the table, and cells with clickable items, like this:

        Testing 1

        Testing 2

        Testing 3

In my code, I make the table sortable, and also use jQuery's live() to bind a click event to the clickable items, like this:

$(function() {
    /*
       Using live() because in my real code table rows are dynamically added.
       However, if I use click() instead, as in the commented-out code, it works
       fine, without any need to click twice.

    */
    // $(".clickycell a").click(function() {
    $(".clickycell a").live('click', function() {
        alert("Successful click");
        return false;
    });
    $("#test-table tbody").sortable({
        handle: "td.handle", /* Use the draggy handle to move, not the whole row */
        cursor: "move"
    });
});

I'm using live() because rows can be dynamically added to the table in the real code.

My problem is this: if I click on any of the clickable items before sorting, they work fine. After the user drags the rows to reorder them, though, I have to click twice for a click to register. After that second click, the clickable items go back to "normal", needing only one click, until the next time rows are dragged around.

If I use click() rather than live() -- as in the commented-out code -- then a single-click works fine at all times, but I'd rather use live(), as I said. And I'm curious as to why it's not working.

There's a live jsFiddle example here. Try dragging a row into a different position, then clicking on any of the "Testing..." links. In Firefox, at least, I need to click twice to get the "Successful click" alert.

Any ideas?

ContentLicense: CC BY-SA 2.5


问:
captcha code are not working
code:

```<code><?php
    session_start();
    if(isset($_POST['insert']) && !empty($_POST['insert']))
      {
        extract($_POST);
      $query = "select * from enquires2 where email = '$email'";
      $result = mysqli_query($link,$query);
      $row = mysqli_fetch_array($result);
      if($row > 0 )
      {
        $msg .="<h5 style='text-align:center;color:red;'>EmailId already exists please login with different emailid</h5>";
      }
      else
      {
        if(!empty($_POST['captcha_code']))
        {
          $captchaCode = $_SESSION['captchaCode'];
          $enteredcaptchaCode = $_POST['captcha_code'];
          $sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
          $result=mysqli_query($link,$sql);
          if($result == true)
          {
          $msg .="<h4 style='text-align:center;color:green;'>Your Data Has Been Submitted.</h4>";

          }
          else
          {
            $errMsg = 'Captcha code not matched, please try again.';
          }
        }
          else
          {
            $msg .="<h4 style='text-align:center;color:red;'>Error</h4>";
          }
      }
      }
    ?>
</code>```

html code:

```<code><?php echo $msg; ?>
            <?php if(!empty($errMsg)) echo '<p style="color:#EA4335;">'.$errMsg.'</p>';?>
            <?php if(!empty($succMsg)) echo '<p style="color:#34A853;">'.$succMsg.'</p>';?>
            <form method="post">
              <input type="text" name="name" id="name" placeholder="Enter Your Name">
              <input type="text" name="email" id="email" placeholder="Enter Your Email">
              <input type="text" name="phone" id="phone" placeholder="Enter Your Phone">
              <input type="text" name="message" id="message" placeholder="Enter Your Message" >
              <input name="captcha_code" type="text" value="" placeholder="Enter the code" >
              <img src="captcha.php" id="capImage"/>
              <br/>Can't read the image? click here to  <a href="javascript:void(0);" onclick="javascript:$('#capImage').attr('src','captcha.php');">refresh</a>.
              <input type="submit" name="insert" value="Submit" placeholder="Enter Your Message" >
          </form>
</code>```

When I click on submit button it shows data has been submitted successfully while captcha code is right or worng it insert form value into database. So, how can I fix this problem ?

Thank You

答:
```<code>Please use this code:
<?php
session_start();
if(isset($_POST['insert']) && !empty($_POST['insert']))
  {
    extract($_POST);
  $query = "select * from enquires2 where email = '$email'";
  $result = mysqli_query($link,$query);
  $row = mysqli_fetch_array($result);
  if($row > 0 )
  {
    $msg .="<h5 style='text-align:center;color:red;'>EmailId already exists please login with different emailid</h5>";
  }
  else
  {
    if(!empty($_POST['captcha_code']))
    {
      $captchaCode = $_SESSION['captchaCode'];
      $enteredcaptchaCode = $_POST['captcha_code'];
      if($captchaCode == $enteredcaptchaCode)
      {
        $sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
        $result=mysqli_query($link,$sql);
        if($result == true)
        {
          $msg .="<h4 style='text-align:center;color:green;'>Your Data Has Been Submitted.</h4>";
        }
        else
        {
          $msg .= "<h4 style='text-align:center;color:green;'>Your Data Has Not Been Submitted.</h4>";
        }
      }
      else
      {
        $errMsg = 'Captcha code not matched, please try again.';
      }
    }
      else
      {
        $msg .="<h4 style='text-align:center;color:red;'>Error</h4>";
      }
    }
  }
?>
</code>```

Title: captcha code are not working

Body:
code:

<?php
    session_start();
    if(isset($_POST['insert']) && !empty($_POST['insert']))
      {
        extract($_POST);
      $query = "select * from enquires2 where email = '$email'";
      $result = mysqli_query($link,$query);
      $row = mysqli_fetch_array($result);
      if($row > 0 )
      {
        $msg .="
EmailId already exists please login with different emailid
";
      }
      else
      {
        if(!empty($_POST['captcha_code']))
        {
          $captchaCode = $_SESSION['captchaCode'];
          $enteredcaptchaCode = $_POST['captcha_code'];
          $sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
          $result=mysqli_query($link,$sql);
          if($result == true)
          {
          $msg .="
Your Data Has Been Submitted.
";

          }
          else
          {
            $errMsg = 'Captcha code not matched, please try again.';
          }
        }
          else
          {
            $msg .="
Error
";
          }
      }
      }
    ?>

html code:

<?php echo $msg; ?>
            <?php if(!empty($errMsg)) echo '
'.$errMsg.'
';?>
            <?php if(!empty($succMsg)) echo '
'.$succMsg.'
';?>
            <form method="post">
              <input type="text" name="name" id="name" placeholder="Enter Your Name">
              <input type="text" name="email" id="email" placeholder="Enter Your Email">
              <input type="text" name="phone" id="phone" placeholder="Enter Your Phone">
              <input type="text" name="message" id="message" placeholder="Enter Your Message" >
              <input name="captcha_code" type="text" value="" placeholder="Enter the code" >

Can't read the image? click here to  refresh.
              <input type="submit" name="insert" value="Submit" placeholder="Enter Your Message" >
          </form>

When I click on submit button it shows data has been submitted successfully while captcha code is right or worng it insert form value into database. So, how can I fix this problem ?

Thank You


问:
Parsing YAML with Scala
I have a simple YAML file, which is a map of maps:

```<code>top_level_1:
  entry_1: value_1
  entry_2: value_2
top_level_2:
  entry_3: value_3
  entry_4: value_4
</code>```

How can I parse it to map of maps in Scala?

```<code>Map("top_level_1" -> Map("entry_1" -> "value_1",
                         "entry_2" -> "value_2"),
    "top_level_2" -> Map("entry_3" -> "value_3",
                         "entry_4" -> "value_4"))
</code>```

答: SnakeYAML is a high-quality YAML library for Java. You can use it from Scala.</p>

Title: Parsing YAML with Scala

Body:
I have a simple YAML file, which is a map of maps:

top_level_1:
  entry_1: value_1
  entry_2: value_2
top_level_2:
  entry_3: value_3
  entry_4: value_4

How can I parse it to map of maps in Scala?

Map("top_level_1" -> Map("entry_1" -> "value_1",
                         "entry_2" -> "value_2"),
    "top_level_2" -> Map("entry_3" -> "value_3",
                         "entry_4" -> "value_4"))


问:
Webkit : Css text selection styling can not make background white?
So text selection was made stylable trough the ::selection pseudo element in order to override the browser's default selection color. But to me, it seems that white as a selection background color is forbidden in favor of a greyish, opaque color.

::selection      { color: black;  background: white; }
::-moz-selection { color: black;  background: white; }

body {
    background: black;
    color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>So selecting me is supposed to invert the text and background colors. But the selected text background color is not white, but grey.</code>```

Why does this not create a perfectly white background ? Instead, it shows a grey background (#989898)

Also see this snippet on https://jsfiddle.net/duk3/hzodm1sh/

答:
Ok so following this question I found the answer :

For some reason Chrome forces it to be semi-transparent. However, you
  can get around this by setting the background using rgba. I have set
  the alpha value to be just 0.01 less than 1.

::selection { color: black;  background: rgba(255, 255, 255, 0.996);
; }

body {
    background: black;
    color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Selecting me DOES invert the text and background colors. Well, almost, but it looks like perfect white.</code>```

Body:
So text selection was made stylable trough the ::selection pseudo element in order to override the browser's default selection color. But to me, it seems that white as a selection background color is forbidden in favor of a greyish, opaque color.

::selection      { color: black;  background: white; }
::-moz-selection { color: black;  background: white; }

body {
    background: black;
    color: white;
}

So selecting me is supposed to invert the text and background colors. But the selected text background color is not white, but grey.

Why does this not create a perfectly white background ? Instead, it shows a grey background (#989898)

Also see this snippet on https://jsfiddle.net/duk3/hzodm1sh/

Body:
Ok so following this question I found the answer :

For some reason Chrome forces it to be semi-transparent. However, you
  can get around this by setting the background using rgba. I have set
  the alpha value to be just 0.01 less than 1.

::selection { color: black;  background: rgba(255, 255, 255, 0.996);
; }

body {
    background: black;
    color: white;
}

Selecting me DOES invert the text and background colors. Well, almost, but it looks like perfect white.


问:
Anybody interested in possible operation/use of quantum computers?
I went through a period of being interested in how quantum computers work and what they might be good for if they ever become practical. I know they are talked about for code-breaking. I was interested is using them for validating software by essentially trying all possible inputs (in parallel) and seeing if any error states are reached.

I know it's a bit of a blue-sky question, but I wonder if others are interested in quantum computers, how they might work, and what they would be useful for.

Added: Just for fun, let me throw out a mini-tutorial:

Suppose you've got N bits of memory to play with. Suppose you can load those bits (or some of them) with your input data. Then suppose there is a finite sequence of operations you can do on them (without using any additional memory) leaving the answer in them.

To do this with a quantum computer, it is only necessary that you make sure that the entire computation is reversible, by reserving some of the bits to record branches you took, so you can undo them. If you do that, then all the operations can be written as simple unitary matrix transformations on the N bits. (A unitary transform is a pure rotation in the N-dimensional coordinate system.) So performing the computation consists of applying a succession of pure rotations on the bit-vector.

If you do this, then if the N-bit vector is in a quantum computer, it can be initialized into a state where all 2^N (or fewer) possible inputs are superimposed at the same time in "parallel universes". Then if you do the computation, it is doing them all at the same time.

Now all you have to do to see if one of the inputs gives you a particular answer is to let it run to a particular state. If you halt it and examine the state, what it does is choose one of the universes at random and throw away all the rest. So what the Grover algorithm lets you do is, without halting it, accentuate the probability of the universes with the answer state. Then you run it forward, then backward, then forward, and so on for a number of iterations until the answer universe has very high probability. Then if you examine it, you have a high probability of seeing the answer you want.

Whew...

答:
Are you kidding?

If half of what David Deutsch says is right this will be either the end of encryption or the end of encryption-breaking, and will make the central problems in chemistry, physics, and nano-tech knowing the question not finding the answer.

OwnerDisplayName: Mike Dunlavey

LastEditorDisplayName: Mike Dunlavey

OwnerDisplayName: annakata


问:
Help in ICMP spoofing
I wanted to learn this concept as per course syllabus. I need some idea to do the ICMP spoofing. I found the ICMP spoofing program online but I have to do something like this: When a host pings an unknown ip address whether it exists or not there has to be echo reply packet making the unknown host alive for the person who is pinging. How do I achieve this.

Can someone help me with this concept what I can do..

答:
This is usually difficult (but not impossible) to achieve. Your spoofing server has to be able to listen to all traffic on the network to be able to receive the pings that are not intended to go to itself. This is typically not the case on a switched network, but can be worked around, for example via MAC Flooding, or by connecting your spoofing server to a monitoring port on your switch.

You can probably find a lot of informations on the Ping page.

Edit:

So, your spoofing server has to listen to all ICMP ECHO REQUEST trafic, and generate an appropriate response. You could also have a look at packETH, which is a tool that can generate those packets.

Title: Help in ICMP spoofing


问:
GTK How to set font for a text_view
How can I set the font name and size for a text_view? Or do I have to set the font information at the buffer or at the window? Do I have to create some sort of style-sheet?</p>

```<code>#include <gtk/gtk.h>

int main(int argc, char *argv[]) {

    GtkWidget *window;
    GtkWidget *view;
    GtkTextBuffer *buffer;

    gtk_init(&argc, &argv);

    view = gtk_text_view_new();

    buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(view));

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_window_set_default_size(GTK_WINDOW(window), 350, 300);

    gtk_container_add(GTK_CONTAINER(window), view);
    gtk_widget_show_all(window);

    gtk_main();

    return 0;
}
</code>```

答:
The following code works.

my.c

```<code>#include <gtk/gtk.h>

int main(int argc, char *argv[]) {
    GtkWidget *view;
    GtkTextBuffer *buffer;
    GtkWidget *window;

    GdkDisplay *display;
    GdkScreen *screen;
    GtkCssProvider *provider;

    GError *error;

    gtk_init(&argc, &argv);

    view = gtk_text_view_new();
    buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(view));

    display = gdk_display_get_default ();
    screen = gdk_display_get_default_screen (display);
    provider = gtk_css_provider_new();
    gtk_style_context_add_provider_for_screen (screen, GTK_STYLE_PROVIDER (provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    error = NULL;
    gtk_css_provider_load_from_file (provider, g_file_new_for_path("my.css"), &error);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_window_set_default_size(GTK_WINDOW(window), 350, 300);

    gtk_container_add(GTK_CONTAINER(window), view);
    gtk_widget_show_all(window);

    gtk_main();

    return 0;
}
</code>```

my.css

```<code>GtkTextView
{
    font:Monospace 10;
}.
</code>```

Title: GTK How to set font for a text_view

Body:
How can I set the font name and size for a text_view? Or do I have to set the font information at the buffer or at the window? Do I have to create some sort of style-sheet?

#include <gtk/gtk.h>

int main(int argc, char *argv[]) {

    GtkWidget *window;
    GtkWidget *view;
    GtkTextBuffer *buffer;

    gtk_init(&argc, &argv);

    view = gtk_text_view_new();

    buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(view));

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_window_set_default_size(GTK_WINDOW(window), 350, 300);

    gtk_container_add(GTK_CONTAINER(window), view);
    gtk_widget_show_all(window);

    gtk_main();

    return 0;
}

Body:
The following code works.

my.c

#include <gtk/gtk.h>

int main(int argc, char *argv[]) {
    GtkWidget *view;
    GtkTextBuffer *buffer;
    GtkWidget *window;

    GdkDisplay *display;
    GdkScreen *screen;
    GtkCssProvider *provider;

    GError *error;

    gtk_init(&argc, &argv);

    view = gtk_text_view_new();
    buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(view));

    display = gdk_display_get_default ();
    screen = gdk_display_get_default_screen (display);
    provider = gtk_css_provider_new();
    gtk_style_context_add_provider_for_screen (screen, GTK_STYLE_PROVIDER (provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    error = NULL;
    gtk_css_provider_load_from_file (provider, g_file_new_for_path("my.css"), &error);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_window_set_default_size(GTK_WINDOW(window), 350, 300);

    gtk_container_add(GTK_CONTAINER(window), view);
    gtk_widget_show_all(window);

    gtk_main();

    return 0;
}

my.css

GtkTextView
{
    font:Monospace 10;
}.


问:
Not able to convert image from url into byte array
I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:

Cannot Resolve ByteArrayBuffer

This is the code:

```<code> private byte[] getLogoImage(String url){
    try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
             Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}
</code>```

答:
Use This</p>

```<code>BitmapFactory.Options options = null;
            options = new BitmapFactory.Options();
            options.inSampleSize = 3;
            Bitmap bitmap = BitmapFactory.decodeFile(url,
                    options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] byte_arr = stream.toByteArray();
</code>```

Body:
I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:

Cannot Resolve ByteArrayBuffer

This is the code:

 private byte[] getLogoImage(String url){
    try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
             Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}

Body:
Use This

BitmapFactory.Options options = null;
            options = new BitmapFactory.Options();
            options.inSampleSize = 3;
            Bitmap bitmap = BitmapFactory.decodeFile(url,
                    options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] byte_arr = stream.toByteArray();


问:
EditText with DatePicker dialog not showing error text when date is not selected
i am working in a app that triggers local notification. for that i have coded to display a date in Edittext, such that when a user clicks on edit text, a date picker dialog opens.

In a case, if edittext is null, i have to show a error to the user and i have coded the below for that.

```<code>  btn_save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
       if (et_reminderDate.getText().toString().trim().length() == 0) {
                        et_reminderDate.requestFocus();
                        et_reminderDate.setError(getResources().getString(R.string.reminder_selectDate));
                    } else if (et_reminderTime.getText().toString().trim().length() == 0) {
                        et_reminderTime.requestFocus();
                        et_reminderTime.setError(getResources().getString(R.string.reminder_time));
                    } else if (et_dateDue.getText().toString().toString().length() != 0) {
                        et_dateDue.setError(null);
                        et_dateDue.clearFocus();
                    } else if (et_reminderDate.getText().toString().toString().length() != 0) {
                        et_reminderDate.setError(null);
                        et_reminderDate.clearFocus();
                    }else{
My project coding goes here!
}
                            }
</code>```

But i am just getting the error icon. The error text is not shown.
As of my assumption, i have validated for text in edittext. Is that i have to validate for date in Edittext to find whether the date is null?

Note: In the same code, i am getting error message for edittext with text values. For example, edittext where user can enter name. Only for
Edittext with date picker i am not getting the error message!

Any help thanks!

答: To show date picker on single click you must have set android:focusable="true" on EditText so either remove android:focusable="true" or make it android:focusable="false" and you are done.

Body:
i am working in a app that triggers local notification. for that i have coded to display a date in Edittext, such that when a user clicks on edit text, a date picker dialog opens.

In a case, if edittext is null, i have to show a error to the user and i have coded the below for that.

  btn_save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
       if (et_reminderDate.getText().toString().trim().length() == 0) {
                        et_reminderDate.requestFocus();
                        et_reminderDate.setError(getResources().getString(R.string.reminder_selectDate));
                    } else if (et_reminderTime.getText().toString().trim().length() == 0) {
                        et_reminderTime.requestFocus();
                        et_reminderTime.setError(getResources().getString(R.string.reminder_time));
                    } else if (et_dateDue.getText().toString().toString().length() != 0) {
                        et_dateDue.setError(null);
                        et_dateDue.clearFocus();
                    } else if (et_reminderDate.getText().toString().toString().length() != 0) {
                        et_reminderDate.setError(null);
                        et_reminderDate.clearFocus();
                    }else{
My project coding goes here!
}
                            }

But i am just getting the error icon. The error text is not shown.
As of my assumption, i have validated for text in edittext. Is that i have to validate for date in Edittext to find whether the date is null?

Note: In the same code, i am getting error message for edittext with text values. For example, edittext where user can enter name. Only for
Edittext with date picker i am not getting the error message!

Any help thanks!


问:
How to find a list of nodes by two conditions in cypher?
I have 3 kinds of nodes: tag, city and place.

I want to write a query which takes 2 lists

```<code> [tag1,tag2,....]
</code>```

and

```<code> [city1,city2,....].
</code>```

I want to find a list of places located in one of these cities and order them from the one has as much tags as possible to the ones with fewer tags.

```<code> MATCH (spot:Spot)-[:located_at]->(city:City )
 where city.id IN ["22","23"]
 with spot as sp,city as cy
 MATCH (sp:Spot)-[rels:tagged_by]->(tag:Tag)
 where tag.id IN ["16", "10151", "21"]
 with sp as fsp, tag
 RETURN fsp, tag,    count(distinct fsp.id) AS cnt
 order by cnt desc
</code>```

I tried that query and somehow could not list the nodes and their tags.

Please help!
Thanks in advance!

答:
Try the subquery apporach:

Pick city - > find spots -> find tags for that spot

```<code>MATCH (city:City)
OPTIONAL MATCH (spot:Spot)-[:located_at]->(city)
OPTIONAL MATCH (spot)-[rels:tagged_by]->(tag:Tag)
where city.id IN ["22","23"]
where tag.id IN ["16", "10151", "21"]
RETURN spot, tag, count(distinct fsp.id) AS cnt
order by cnt desc
</code>```

Body:
I have 3 kinds of nodes: tag, city and place.

I want to write a query which takes 2 lists

 [tag1,tag2,....]

and

 [city1,city2,....].

I want to find a list of places located in one of these cities and order them from the one has as much tags as possible to the ones with fewer tags.

 MATCH (spot:Spot)-[:located_at]->(city:City )
 where city.id IN ["22","23"]
 with spot as sp,city as cy
 MATCH (sp:Spot)-[rels:tagged_by]->(tag:Tag)
 where tag.id IN ["16", "10151", "21"]
 with sp as fsp, tag
 RETURN fsp, tag,    count(distinct fsp.id) AS cnt
 order by cnt desc

I tried that query and somehow could not list the nodes and their tags.

Please help!
Thanks in advance!

Body:
Try the subquery apporach:

Pick city - > find spots -> find tags for that spot

MATCH (city:City)
OPTIONAL MATCH (spot:Spot)-[:located_at]->(city)
OPTIONAL MATCH (spot)-[rels:tagged_by]->(tag:Tag)
where city.id IN ["22","23"]
where tag.id IN ["16", "10151", "21"]
RETURN spot, tag, count(distinct fsp.id) AS cnt
order by cnt desc


问:
Finding out whether a string is numeric or not
How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.</p>

```<code>NSString *newString = [myString substringWithRange:NSMakeRange(2,3)];
</code>```

答:
Swift 3 solution if need to verify that the string has only digits:</p>

```<code>CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: myString))
</code>```

Body:
How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.

NSString *newString = [myString substringWithRange:NSMakeRange(2,3)];

Body:
Swift 3 solution if need to verify that the string has only digits:

CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: myString))


问:
pic18f communicating with lcd module
I'm developing on a pic 18Fxxx (18F452) in assembly. I'm in a learning phase so I'm doing different simple exercise with the final goal to develop a "real" project.

At the moment I'm stuck with the LCD Module, I couldn't find any examples of a working protocol to comunicate with the screen (on 4 bit). Can someone please link me some code or a to-be-implemented procedure from which I can understand how all this works?

Thank you.

note: My IDE is MPLAB and I'm using PIC18 Simulator IDE to check how my code works.

答:
You can take a look at these links, they cover the topics of LCD, PIC and ASM at diferent levels:

http://www.spickles.org/projects/4-bit-lcd

http://home.iae.nl/users/pouweha/lcd/lcd.shtml

http://www.winpicprog.co.uk/pic_tutorial.htm

As well I would like to recommend you to move on to C (if you don't need the ASM for something specific). Now it's common to develop for the PIC in C, the compilers are nice and the code is fast, you can learn the ASM and leave it for some "important" routines like interrupt handlers. After if you move to the 16bit or even 32bit pics the C will be a must.

I use the MikroC compiler for PIC from Mikroelektronica and it is working very well. You can find too free tools for C development. As a last point I recommend you to move on to the pic 18F4520, is pin comaptible with the 18F452 but is newer and powerfuller. (the 452 is discontinued i think)

Title: pic18f communicating with lcd module


问:
Row Level Security (RLS) for a SSAS Tabular Model
I am new to SSAS technologies for developing analytical models. I have to build several tabular models for a huge application in which security is quite relevant. What I would like to do is to re-use the row level security existing in the sources of the cube and apply it to the cube itself.

For example, if I build a tabular model from two tables of a schema, and these two table have RLS enabled, I would like the cube to take this security into account, so that when I access reports and log in as user, I will only see aggregated data according to the permissions I have.

Searching through the web I found ways of implementing RLS within the cube, but none about inheriting it from the sources. But again, I am new to the technology, so I preferred to ask here.
Thanks

答:
The most obvious solution to your request is running SSAS Tabular in thin mode (called DirectQuery mode). As long as in the Existing Connections dialog in Visual Studio you set ImpersonateCurrentUser, when a user queries the SSAS model, SSAS will in turn send one or more SQL queries to the database under the end user's credentials. RLS in the SQL database will come into play here.

One caveat is that I would only recommend DirectQuery in SSAS 2016 not prior. Another caveat is that performance will be slow compared to a cached model in SSAS. So if performance isn't acceptable then turn off DirectQuery and reimplement RLS inside SSAS. Also DirectQuery uses zero caching of results currently so the load against SQL will not be offloaded to SSAS at all. Finally, if you use DirectQuery and ImpersonateCurrentUser you may have to setup Kerberos if your SQL server isn't on the same server as SSAS so that user credentials can double hop.


问:
Selenium script fails with TestNG annotation
Steps:
1. In eclipse I've created a new project named 'ForSe'.

Under 'src' folder → 'default package' I created a class named Login.java.

My code inside this class is like this:

```<code>public class Login_Valid {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","*my path*");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("*URL of prject ForSe*");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*@id='email_address']")).sendKeys("*email address*");
        driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");
        driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
    }
}
</code>```

The scripts run very well when I run with run as java application.
But when I use the same script with TestNG, it skips/fails my test.

Steps taken to create TestNG script is as follows:

Installed TestNG and under same src creates a new package named ForSe_TestCases.java

My TestNG scripts is as follows:

```<code>public class ForSe_TestCases
{
    WebDriver driver;
    String url = "*project's URL*";

    @Test (priority = 0)
    public void IO_login(WebDriver driver)
    {

        //ForSe test environment URL
        driver.navigate().to(url);

        //this is official email address of IO
        driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("*email address*");

        //this is password
        driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");

        //click on submit button to login
        driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
        System.out.println("Login button pressed");
    }

    @BeforeTest
    public void setup()
    {
        // Set property for Chrome
        System.setProperty("webdriver.chrome.driver","*my path*");
        WebDriver driver = new ChromeDriver();

        //apply implicit wait
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        //maximize window
        driver.manage().window().maximize();
    }
}
</code>```

I'm unable to understand at which step I'm going wrong. This the error message I get on running my test by Run as TestNG

```<code>    [Utils] [ERROR] [Error] org.testng.TestNGException:
    Cannot inject @Test annotated Method [IO_login] with [interface org.openqa.selenium.WebDriver].

    ===============================================
    Default test
        Tests run: 1, Failures: 1, Skips: 0
    ===============================================
    ===============================================
    Default suite
    Total tests run: 1, Failures: 1, Skips: 0
    ===============================================
</code>```

答:
These can be a few of the issues:

"my path" is not a valid variable name. Change it to "my_path".

Define a String my_path = "C:\\Utility\\BrowserDrivers\\chromedriver.exe"; as a global variable.

Check the variable when you provide System.setProperty("webdriver.chrome.driver","my_path");

Don't use driver.manage().window().maximize(); instead handle it with Options Class.

WebDriver driver is defined globally at Class level, you don't have to pass it as an argument in IO_login()

Check this code:

```<code>public class TestAnyURL_TestNG
{
WebDriver driver;
String url = "http://google.com";
String my_path = "C:\\Utility\\BrowserDrivers\\chromedriver.exe";

@Test (priority = 0)
public void IO_login()
{

    //ForSe test environment URL
    driver.navigate().to(url);

    //this is official email address of IO
    driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("*email address*");

    //this is password
    driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");

    //click on submit button to login
    driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
    System.out.println("Login button pressed");
}

@BeforeTest
public void setup()
{
    System.setProperty("webdriver.chrome.driver", my_path);
    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    driver = new ChromeDriver(options);
}
}
</code>```

Remember to:

Replace http://google.com with your own_test_URL.

Replace package demo by package your_package_name.

Replace public class TestAnyURL_TestNG with public class your_class_name

Run as "TestNG Test"

Update me the status.

Body:
Steps:
1. In eclipse I've created a new project named 'ForSe'.

Under 'src' folder → 'default package' I created a class named Login.java.

My code inside this class is like this:

public class Login_Valid {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","*my path*");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("*URL of prject ForSe*");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*@id='email_address']")).sendKeys("*email address*");
        driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");
        driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
    }
}

The scripts run very well when I run with run as java application.
But when I use the same script with TestNG, it skips/fails my test.

Steps taken to create TestNG script is as follows:

Installed TestNG and under same src creates a new package named ForSe_TestCases.java

My TestNG scripts is as follows:

public class ForSe_TestCases
{
    WebDriver driver;
    String url = "*project's URL*";

    @Test (priority = 0)
    public void IO_login(WebDriver driver)
    {

        //ForSe test environment URL
        driver.navigate().to(url);

        //this is official email address of IO
        driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("*email address*");

        //this is password
        driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");

        //click on submit button to login
        driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
        System.out.println("Login button pressed");
    }

    @BeforeTest
    public void setup()
    {
        // Set property for Chrome
        System.setProperty("webdriver.chrome.driver","*my path*");
        WebDriver driver = new ChromeDriver();

        //apply implicit wait
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        //maximize window
        driver.manage().window().maximize();
    }
}

I'm unable to understand at which step I'm going wrong. This the error message I get on running my test by Run as TestNG

    [Utils] [ERROR] [Error] org.testng.TestNGException:
    Cannot inject @Test annotated Method [IO_login] with [interface org.openqa.selenium.WebDriver].

    ===============================================
    Default test
        Tests run: 1, Failures: 1, Skips: 0
    ===============================================
    ===============================================
    Default suite
    Total tests run: 1, Failures: 1, Skips: 0
    ===============================================

Body:
These can be a few of the issues:

"my path" is not a valid variable name. Change it to "my_path".

Define a String my_path = "C:\\Utility\\BrowserDrivers\\chromedriver.exe"; as a global variable.

Check the variable when you provide System.setProperty("webdriver.chrome.driver","my_path");

Don't use driver.manage().window().maximize(); instead handle it with Options Class.

WebDriver driver is defined globally at Class level, you don't have to pass it as an argument in IO_login()

Check this code:

public class TestAnyURL_TestNG
{
WebDriver driver;
String url = "http://google.com";
String my_path = "C:\\Utility\\BrowserDrivers\\chromedriver.exe";

@Test (priority = 0)
public void IO_login()
{

    //ForSe test environment URL
    driver.navigate().to(url);

    //this is official email address of IO
    driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("*email address*");

    //this is password
    driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");

    //click on submit button to login
    driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
    System.out.println("Login button pressed");
}

@BeforeTest
public void setup()
{
    System.setProperty("webdriver.chrome.driver", my_path);
    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    driver = new ChromeDriver(options);
}
}

Remember to:

Replace http://google.com with your own_test_URL.

Replace package demo by package your_package_name.

Replace public class TestAnyURL_TestNG with public class your_class_name

Run as "TestNG Test"

Update me the status.


问:
How to set object that is being refereed in private inner class while creating Junit?
I have 2 java classes.

```<code>1) class1.java

public class class1
{
  private class ParameterVariable
  {
   class2 c1;
   String s;
   ParameterVariable(String s)
   {
        this.s =s;
   }
  }

   public void methodToTest(String s)
   {
        try
        {
            ParameterVariable pv = new ParameterVariable(s)
            if(StringUtils.isNotEmpty(pv.c1.getPartNo()))
            {
               // Some Code
            }
        }
        finally
        {
        // Some code
        }

   }
}

2) class2.java
public class class2
{
    // pojo class
    String partNo;
    public String getPartNo()
    {
        return partNo;
    }
    public void setPartNo(String partNo)
    {
        this.partNo = partNo;
    }
}
</code>```

Now I want to create a Junit test case for my method. I am not able to get runtime value for class2 object.
Here is my work

```<code>private class1 = null;

protected Object createParamterVariableObject ( String s ) throws ClassNotFoundException,  InstantiationException,
                                                                                IllegalAccessException,  InvocationTargetException,
                                                                                NoSuchMethodException, SecurityException
{
    Class clazz = Whitebox.getInnerClassType(class1.class, "ParameterVariable");
    Constructor constructorForParameterVariable = clazz.getConstructor(String.java)

    Object parameterVariableObject = constructorForParameterVariable.newInstance(String.java)
    return parameterVariableObject;
}

@Test
public void junitTestCase() throws Exception
{
  String s = "Sample";
  Class clazz = null;
    Object parameterVariableObject = null;
  class2 cls2Object = new clsObject;

    try
    {
        parameterVariableObject = createParamterVariableObject(s);

        clazz = Whitebox.getInnerClassType(SupersedeImpl.class, "ParameterVariable");
    }
    catch (Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    class2 c2Object = new class2();
    c2Object.setPartNo("NEW_PART_NO");
    Field C1Field = (Field) parameterVariableObject.getClass().getDeclaredField("c1");
    C1Field.set(parameterVariableObject, C1Field);

    PowerMockito.whenNew(clazz).withArguments(s).thenReturn(parameterVariableObject);

    class1 = PowerMockito.spy(class1);

    class1.methodToTest(s);

    // some assertion
}
</code>```

I want to set some mocking value of part no that is object of class2.
Because my method is based on it.
I am getting null using these code. Can you please help me?

答:
My suggestion: make your life easier:

Change that inner class to a normal class

Create a factory that returns instances of that class

And then use dependency injection to give such a factory to your class under test. And use any ordinary mocking framework to create those objects.

Done. And not only do you avoid all those issues that complicate mocking in your version; you also end up with code that is less tightly coupled.

Body:
I have 2 java classes.

1) class1.java

public class class1
{
  private class ParameterVariable
  {
   class2 c1;
   String s;
   ParameterVariable(String s)
   {
        this.s =s;
   }
  }

   public void methodToTest(String s)
   {
        try
        {
            ParameterVariable pv = new ParameterVariable(s)
            if(StringUtils.isNotEmpty(pv.c1.getPartNo()))
            {
               // Some Code
            }
        }
        finally
        {
        // Some code
        }

   }
}

2) class2.java
public class class2
{
    // pojo class
    String partNo;
    public String getPartNo()
    {
        return partNo;
    }
    public void setPartNo(String partNo)
    {
        this.partNo = partNo;
    }
}

Now I want to create a Junit test case for my method. I am not able to get runtime value for class2 object.
Here is my work

private class1 = null;

protected Object createParamterVariableObject ( String s ) throws ClassNotFoundException,  InstantiationException,
                                                                                IllegalAccessException,  InvocationTargetException,
                                                                                NoSuchMethodException, SecurityException
{
    Class clazz = Whitebox.getInnerClassType(class1.class, "ParameterVariable");
    Constructor constructorForParameterVariable = clazz.getConstructor(String.java)

    Object parameterVariableObject = constructorForParameterVariable.newInstance(String.java)
    return parameterVariableObject;
}

@Test
public void junitTestCase() throws Exception
{
  String s = "Sample";
  Class clazz = null;
    Object parameterVariableObject = null;
  class2 cls2Object = new clsObject;

    try
    {
        parameterVariableObject = createParamterVariableObject(s);

        clazz = Whitebox.getInnerClassType(SupersedeImpl.class, "ParameterVariable");
    }
    catch (Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    class2 c2Object = new class2();
    c2Object.setPartNo("NEW_PART_NO");
    Field C1Field = (Field) parameterVariableObject.getClass().getDeclaredField("c1");
    C1Field.set(parameterVariableObject, C1Field);

    PowerMockito.whenNew(clazz).withArguments(s).thenReturn(parameterVariableObject);

    class1 = PowerMockito.spy(class1);

    class1.methodToTest(s);

    // some assertion
}

I want to set some mocking value of part no that is object of class2.
Because my method is based on it.
I am getting null using these code. Can you please help me?


问:
You do not have the rights to perform the requested action. while filling content rating in android play store
I am trying publish my application in android store . All is working fine except content rating . I am clicking on content rating and when I click next I am getting following error :

```<code>You do not have the rights to perform the requested action
</code>```

so is there any permission issue with my developer account ?

答: I gave access to user as "Edit store listing, pricing & distribution". Now, I am able to update content rating.</p>

Body:
I am trying publish my application in android store . All is working fine except content rating . I am clicking on content rating and when I click next I am getting following error :

You do not have the rights to perform the requested action

so is there any permission issue with my developer account ?


问:
Error type mismatch - How do I create a .txt file from all of the data in column A sheet 1
I keep getting the type mismatch error on this line of code.

```<code>stream.WriteLine CellData
</code>```

Full code below

```<code>Sub Write_to_File()

Dim FilePath As String
Dim CellData As Variant
Dim LastCol As Long
Dim LastRow As Long

Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim stream As TextStream

' Create a TextStream.
Set stream = fso.OpenTextFile("C:\...\test_labs.txt", ForWriting, True)

var3 = Worksheets("label").Columns(1)

CellData = ""

     CellData = var3
     stream.WriteLine CellData

stream.Close
MsgBox ("Done")

End Sub
</code>```

I am trying to get all of column A in sheet 1 to write to the text file. This code is run from a command button in sheet 2. I'm still new to VBA so any help is appreciated.

Thanks

答:
The following would work, but I wouldn't recommend you dump the entire column into a file, it may take some time. Better to limit it to non-empty lines, or perhaps find the last used cell and only output up to that point?

```<code>' Create a TextStream.
Set stream = fso.OpenTextFile("K:\test_labs.txt", ForWriting, True)

For Each CellData In Worksheets("label").Columns(1).Cells
     stream.WriteLine CellData
Next
stream.Close
MsgBox ("Done")
End Sub
</code>```

The following section would look for the last row populated in column A (stores it in your LastRow variable that you already declared) and stops there:

```<code>' Create a TextStream.
Set stream = fso.OpenTextFile("K:\test_labs.txt", ForWriting, True)
With Worksheets("label")
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    For Each CellData In .Range("A1:A" & LastRow).Cells
         stream.WriteLine CellData
    Next
End With
stream.Close
MsgBox ("Done")
End Sub
</code>```

For information: the reason that you were getting the error in the first place was because stream.WriteLine expects a scalar String input argument, but this line:

```<code>var3 = Worksheets("label").Columns(1)
</code>```

sets var3 to an array.

Body:
I keep getting the type mismatch error on this line of code.

stream.WriteLine CellData

Full code below

Sub Write_to_File()

Dim FilePath As String
Dim CellData As Variant
Dim LastCol As Long
Dim LastRow As Long

Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim stream As TextStream

' Create a TextStream.
Set stream = fso.OpenTextFile("C:\...\test_labs.txt", ForWriting, True)

var3 = Worksheets("label").Columns(1)

CellData = ""

     CellData = var3
     stream.WriteLine CellData

stream.Close
MsgBox ("Done")

End Sub

I am trying to get all of column A in sheet 1 to write to the text file. This code is run from a command button in sheet 2. I'm still new to VBA so any help is appreciated.

Thanks

Body:
The following would work, but I wouldn't recommend you dump the entire column into a file, it may take some time. Better to limit it to non-empty lines, or perhaps find the last used cell and only output up to that point?

' Create a TextStream.
Set stream = fso.OpenTextFile("K:\test_labs.txt", ForWriting, True)

For Each CellData In Worksheets("label").Columns(1).Cells
     stream.WriteLine CellData
Next
stream.Close
MsgBox ("Done")
End Sub

The following section would look for the last row populated in column A (stores it in your LastRow variable that you already declared) and stops there:

' Create a TextStream.
Set stream = fso.OpenTextFile("K:\test_labs.txt", ForWriting, True)
With Worksheets("label")
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    For Each CellData In .Range("A1:A" & LastRow).Cells
         stream.WriteLine CellData
    Next
End With
stream.Close
MsgBox ("Done")
End Sub

For information: the reason that you were getting the error in the first place was because stream.WriteLine expects a scalar String input argument, but this line:

var3 = Worksheets("label").Columns(1)

sets var3 to an array.


问:
How to Store Previous Value Of Loop in variable
JSONObject jsonRoot = new JSONObject(response);

```<code>    ArrayList<Level2_Women> alUser = new ArrayList<>();
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            user.setCategory(finalObject.getString("category"));
            String catid = finalObject.getString("category_id");

    }
    return user;
}
</code>```

I am Using this loop.In my Loop there are 12 elements,But its print only last value.How i can print all element in Listview?

答:
Error 1: You are always returning user object instead of list alUser.

Error 2: Inside for loop, you didn't added individual user to list alUser.

Update your method as below:

```<code>public ArrayList<Level2_Women> YOUR_METHOD_NAME(String response)
{
    // User List
    ArrayList<Level2_Women> alUser = new ArrayList<>();

    JSONObject jsonRoot = new JSONObject(response);
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    // Not used!
    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

        JSONObject finalObject = parentArray.getJSONObject(j);

        // User
        Level2_Women user = new Level2_Women();

        // Set user values
        user.setCategory(finalObject.getString("category"));

        // Not used!
        String catid = finalObject.getString("category_id");

        // Add user to list
        alUser.add(user)
    }

    // Finally return user list
    return alUser;
}
</code>```

FYI, If you are facing problem with list update then use adapter notifyDataSetChanged() method to update data on ListView/RecyclerView.

Hope this will help~

Body:
JSONObject jsonRoot = new JSONObject(response);

    ArrayList<Level2_Women> alUser = new ArrayList<>();
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            user.setCategory(finalObject.getString("category"));
            String catid = finalObject.getString("category_id");

    }
    return user;
}

I am Using this loop.In my Loop there are 12 elements,But its print only last value.How i can print all element in Listview?

Body:
Error 1: You are always returning user object instead of list alUser.

Error 2: Inside for loop, you didn't added individual user to list alUser.

Update your method as below:

public ArrayList<Level2_Women> YOUR_METHOD_NAME(String response)
{
    // User List
    ArrayList<Level2_Women> alUser = new ArrayList<>();

    JSONObject jsonRoot = new JSONObject(response);
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    // Not used!
    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

        JSONObject finalObject = parentArray.getJSONObject(j);

        // User
        Level2_Women user = new Level2_Women();

        // Set user values
        user.setCategory(finalObject.getString("category"));

        // Not used!
        String catid = finalObject.getString("category_id");

        // Add user to list
        alUser.add(user)
    }

    // Finally return user list
    return alUser;
}

FYI, If you are facing problem with list update then use adapter notifyDataSetChanged() method to update data on ListView/RecyclerView.

Hope this will help~


问:
Remove previous query strings on router redirect
My aurelia application has two roots, an app-login and the app root. When users try to access the application and are not logged in, they are sent to the app-login route, which only has 1 route configured, login.

If an unauthenticated user tries to access the app as though they were logged in, (e.g. localhost:3000/#/needsAuthenticationRoute), I want the user to be taken to the login page, however, upon successfully logging in, have them be redirect to the page they were initially trying to access.

I try to handle the issue as follows:

```<code>config.mapUnknownRoutes((instruction) => {
  let redirectUrl = 'login';
  console.log(instruction);

  if(instruction.fragment !== '/') {
    let redirect = instruction.fragment;
    if(instruction.queryString) {
      redirect = redirect + '?' + instruction.queryString;
    }
    redirectUrl = router.generate('login', {redirect});
  }
  return {redirect: redirectUrl };
});
</code>```

So from the app-login route, if they try to access needsAuthenticationRoute, they would be redirected back to the login page with a redirect parameter (the user would be sent to localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute in this case).

However, when the user tries to access a route with a query string (e.g. needsAuthenticationRoute?param=value), I would want the user to be redirected to localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute%3Fparam%3Dvalue. However, the redirect keeps around the query parameter and I am left with a route that looks like
localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute%3Fparam%3Dvalue?param=value.

Does anybody know how to clear query the query params when specifying a redirect instruction? Or have an alternative solution to what I am proposing?

答:
I have recently just implemented the exact functionality you describe (I also have a blog post in draft about this topic too - when I get round to publishing it...)

I have a bunch of routes, some that have query strings, some which don't. If the user isn't logged in i want to redirect them to the login page, then after successful login I want to redirect them to where they were going before.

Also, I wanted to keep the "?returnUrl=" query string out of the url, it works, but just felt a bit messy to me - considering that this is all client side routing, i knew i could store it somewhere and "hide" it/

So firstly, we need to stash the route they were going to before login, this is done in a defined AuthorizeStep Aurelia AuthorizeStep

```<code>@inject(MyApi)
class AuthorizeStep implements PipelineStep {
    constructor(private api: MyApi) { }

    public run(navigationInstruction: NavigationInstruction, next: Next): Promise<any> {
        if (navigationInstruction.getAllInstructions().some(i => i.config.settings.roles.indexOf("Client") !== -1)) {
            if (!this.api.LoggedIn && navigationInstruction.config.name !== "login") {
                this.api.RouteFragment = navigationInstruction.fragment;
                return next.cancel(new Redirect("login"));
            }
        }
        return next();
    }
}
</code>```

Finally, the login page needs to be made aware that after logging in, the user might be going somewhere. So after a successful login we check to see if anything has been stashed in the RouteFragment

```<code>if (loginResult.Success) {
    if (this.api.RouteFragment && this.api.RouteFragment.length > 0) {
        // Navigate to where the user was trying to go before Logging In
        this.router.navigate(this.api.RouteFragment);
    } else {
        this.router.navigate("/dashboard");
    }
}
</code>```

Body:
My aurelia application has two roots, an app-login and the app root. When users try to access the application and are not logged in, they are sent to the app-login route, which only has 1 route configured, login.

If an unauthenticated user tries to access the app as though they were logged in, (e.g. localhost:3000/#/needsAuthenticationRoute), I want the user to be taken to the login page, however, upon successfully logging in, have them be redirect to the page they were initially trying to access.

I try to handle the issue as follows:

config.mapUnknownRoutes((instruction) => {
  let redirectUrl = 'login';
  console.log(instruction);

  if(instruction.fragment !== '/') {
    let redirect = instruction.fragment;
    if(instruction.queryString) {
      redirect = redirect + '?' + instruction.queryString;
    }
    redirectUrl = router.generate('login', {redirect});
  }
  return {redirect: redirectUrl };
});

So from the app-login route, if they try to access needsAuthenticationRoute, they would be redirected back to the login page with a redirect parameter (the user would be sent to localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute in this case).

However, when the user tries to access a route with a query string (e.g. needsAuthenticationRoute?param=value), I would want the user to be redirected to localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute%3Fparam%3Dvalue. However, the redirect keeps around the query parameter and I am left with a route that looks like
localhost:3000/#/login?redirect=%2FneedsAuthenticationRoute%3Fparam%3Dvalue?param=value.

Does anybody know how to clear query the query params when specifying a redirect instruction? Or have an alternative solution to what I am proposing?

Body:
I have recently just implemented the exact functionality you describe (I also have a blog post in draft about this topic too - when I get round to publishing it...)

I have a bunch of routes, some that have query strings, some which don't. If the user isn't logged in i want to redirect them to the login page, then after successful login I want to redirect them to where they were going before.

Also, I wanted to keep the "?returnUrl=" query string out of the url, it works, but just felt a bit messy to me - considering that this is all client side routing, i knew i could store it somewhere and "hide" it/

So firstly, we need to stash the route they were going to before login, this is done in a defined AuthorizeStep Aurelia AuthorizeStep

@inject(MyApi)
class AuthorizeStep implements PipelineStep {
    constructor(private api: MyApi) { }

    public run(navigationInstruction: NavigationInstruction, next: Next): Promise<any> {
        if (navigationInstruction.getAllInstructions().some(i => i.config.settings.roles.indexOf("Client") !== -1)) {
            if (!this.api.LoggedIn && navigationInstruction.config.name !== "login") {
                this.api.RouteFragment = navigationInstruction.fragment;
                return next.cancel(new Redirect("login"));
            }
        }
        return next();
    }
}

Finally, the login page needs to be made aware that after logging in, the user might be going somewhere. So after a successful login we check to see if anything has been stashed in the RouteFragment

if (loginResult.Success) {
    if (this.api.RouteFragment && this.api.RouteFragment.length > 0) {
        // Navigate to where the user was trying to go before Logging In
        this.router.navigate(this.api.RouteFragment);
    } else {
        this.router.navigate("/dashboard");
    }
}


问:
How To Create And Start Docker Container with specific port, detached mode using docker-java
I want to create and run docker using docker java client. I want running something like this :

```<code>docker run -d -p 4444:4444 --name selenium-hub selenium/hub:2.53.0
</code>```

How to implement this command on docker-java client? Here is my code so far :

```<code>CreateContainerResponse response = dockerClient.createContainerCmd("selenium/hub")
               .withName(name)
               .exec();
</code>```

Actually IDK how to specify -d (for running in background). and -p.
please help me. sorry I am new in Docker.

答:
Found the solution... if someone find a better one please post in here. I already modify the code to be like this :</p>

```<code>  ExposedPort tcp4444 = ExposedPort.tcp(4444);
   Ports portBindings = new Ports();
   portBindings.bind(tcp4444,Ports.Binding.bindPort(4444));

   CreateContainerResponse response = dockerClient.
           createContainerCmd("selenium/hub")
           .withName(name)
           .withImage("selenium/hub:"+version)
           .withExposedPorts(tcp4444)
           .withPortBindings(portBindings)
           .withAttachStderr(false)
           .withAttachStdin(false)
           .withAttachStdout(false)
           .exec();`
</code>```

Body:
I want to create and run docker using docker java client. I want running something like this :

docker run -d -p 4444:4444 --name selenium-hub selenium/hub:2.53.0

How to implement this command on docker-java client? Here is my code so far :

CreateContainerResponse response = dockerClient.createContainerCmd("selenium/hub")
               .withName(name)
               .exec();

Actually IDK how to specify -d (for running in background). and -p.
please help me. sorry I am new in Docker.

Body:
Found the solution... if someone find a better one please post in here. I already modify the code to be like this :

  ExposedPort tcp4444 = ExposedPort.tcp(4444);
   Ports portBindings = new Ports();
   portBindings.bind(tcp4444,Ports.Binding.bindPort(4444));

   CreateContainerResponse response = dockerClient.
           createContainerCmd("selenium/hub")
           .withName(name)
           .withImage("selenium/hub:"+version)
           .withExposedPorts(tcp4444)
           .withPortBindings(portBindings)
           .withAttachStderr(false)
           .withAttachStdin(false)
           .withAttachStdout(false)
           .exec();`


问:
Google Maps iOS API key not working
I have a simple iOS app into which I am integrating Google Maps. However, the API key I've provided results in several of these error messages when my map view is displayed:

ClientParametersRequest failed, 3 attempts remaining (0 vs 5). Error Domain=com.google.HTTPStatus Code=400 "The operation couldn’t be completed. (com.google.HTTPStatus error 400.)" UserInfo=0x1818bf40 {data=<CFData 0x18137410 [0x302aec8]>{length = 145, capacity = 256, bytes = ...}}

Here is what I have already tried to no avail:

Calling [GMSServices provideAPIKey:] as the first line of code within didFinishLaunchingWithOptions

Double-checking that my API key is correct and is an iOS API key (I copy/pasted it directly from the Google Cloud Console into my app)

Providing the API key both with {} and without

Confirming my bundle name by outputting it with [[Bundle mainBundle] bundleIdentifier]

Omitting bundle identifier restrictions altogether

Regenerating the API key

I am not sure what else to try. My bundle name is in this format: net.company.MyApp and I have entered it exactly that way into the Google Cloud Console (I know bundle IDs are case-sensitive).

Could it be that Google doesn't support bundle identifiers of a certain type (e.g., with upper-case letters or beginning with net.)?

答: if you are doing a manual integration of SDK, it is no longer supported in latest version. Also GoogleMapsM4B version needs to be deleted and only keep GoogleMaps SDK in your project. This worked for me.</p>

Title: Google Maps iOS API key not working


问:
plyr summarize only calls global functions
I'm trying to pass a function (weight.func) to a different function (wrapper) that calls ddply. I want ddply to use that function (weight.func) as part of its calculations. I get the output I want when weight.func is set 'globally' but not when it is passes as an anonymous function to the wrapper.

Can I get ddply to do what I want? Here is a code example:

```<code>> print(sampleData)
   studentId   problem  part       workerId rating
1       8001 problem26 partA A127R5QI5OGBIK    0.0
2       8001 problem26 partA A1FCLYRBAB430F    0.0
3       8001 problem26 partA A25FZQY34C6RVO    0.0
4       8001 problem26 partA A3G0MO562MHMZ3    0.5
5       8001 problem26 partA A3RB9ZOIUC3NWG    2.0
6       8001 problem26 partB A1FCLYRBAB430F    0.5
7       8001 problem26 partB A1XRDZKSJBWY8Q    0.5
8       8001 problem26 partB A22CRWMZUX7FFR    0.5
9       8001 problem26 partB A25FZQY34C6RVO    1.0
10      8001 problem26 partB A3G0MO562MHMZ3    0.5
11      8001 problem27 partA A1ET309DW6M2XA    2.0
12      8001 problem27 partA A1FCLYRBAB430F    0.0
13      8001 problem27 partA A22CRWMZUX7FFR    0.0
14      8001 problem27 partA A25FZQY34C6RVO    0.0
15      8001 problem27 partA A3G0MO562MHMZ3    0.0
16      8001 problem27 partB A1FCLYRBAB430F    1.0
17      8001 problem27 partB A22CRWMZUX7FFR    0.0
18      8001 problem27 partB A25FZQY34C6RVO    0.0
19      8001 problem27 partB A2U9676210WST5    0.0
20      8001 problem27 partB A3G0MO562MHMZ3    0.0
21      8002 problem26 partA A127R5QI5OGBIK    0.0
22      8002 problem26 partA A1FCLYRBAB430F    0.5
23      8002 problem26 partA A22CRWMZUX7FFR    0.0
24      8002 problem26 partA A25FZQY34C6RVO    2.0
25      8002 problem26 partA A3G0MO562MHMZ3    0.5
26      8002 problem26 partB A17EHJZNJGNRAN    2.0
27      8002 problem26 partB A1FCLYRBAB430F    0.0
28      8002 problem26 partB A2IPRDTE6B4TAB    0.0
29      8002 problem26 partB A3G0MO562MHMZ3    0.0
30      8002 problem26 partB  A6SON3OS15XKA    0.0
31      8002 problem27 partA A1FCLYRBAB430F    0.0
32      8002 problem27 partA A25FZQY34C6RVO    0.0
33      8002 problem27 partA A2IPRDTE6B4TAB    0.0
34      8002 problem27 partA A2U9676210WST5    0.0
35      8002 problem27 partA A3G0MO562MHMZ3    0.0
36      8002 problem27 partB A1FCLYRBAB430F    0.0
37      8002 problem27 partB A1V52SSKROBV8E    2.0
38      8002 problem27 partB A25FZQY34C6RVO    2.0
39      8002 problem27 partB A2IPRDTE6B4TAB    0.0
40      8002 problem27 partB A3G0MO562MHMZ3    0.0
>
> #Make a wrapper
> wrapper <- function ( ratingData, weight.func ) {
+   print(weight.func) #prove that the function is being passed
+   ddply(ratingData, c('studentId','problem','part'), summarize,
+           sum.weights = sum ( weight.func(rating)  ))
+ }
> wrapper( sampleData, weight.func=function(x) (x+.001)^-1  )
function(x) (x+.001)^-1
Error in data.frame(sum.weights = sum(weight.func(rating))) :
  could not find function "weight.func"
>
> #'globally' declare weight.func
> weight.func <- function(x) (x+.001)^-1
> wrapper( sampleData, weight.func=NULL  )
NULL
  studentId   problem  part sum.weights
1      8001 problem26 partA 3002.495758
2      8001 problem26 partB    8.983033
3      8001 problem27 partA 4000.499750
4      8001 problem27 partB 4000.999001
5      8002 problem26 partA 2004.491766
6      8002 problem26 partB 4000.499750
7      8002 problem27 partA 5000.000000
8      8002 problem27 partB 3000.999500
</code>```

The second output is the goal. Any help appreciated! (Including a non plyr based way to accomplish the same task.)

The example above is a toy example. It's the simplest case I could get to reproduce the behavior.

答:
An update on this issue in plyr (https://github.com/hadley/plyr/issues/3):

Use the 'here' function in plyr, just replace 'summarize', with 'here(summarize)' to access the environment where ddply was called from.

```<code>wrapper <- function(ratingData, weight.func){
           ddply(ratingData, c('studentId','problem','part'),
                 here(summarize),  # here(summarize)!
                 sum.weights = sum(weight.func(rating))
                 )
            }
</code>```

Body:
I'm trying to pass a function (weight.func) to a different function (wrapper) that calls ddply. I want ddply to use that function (weight.func) as part of its calculations. I get the output I want when weight.func is set 'globally' but not when it is passes as an anonymous function to the wrapper.

Can I get ddply to do what I want? Here is a code example:

> print(sampleData)
   studentId   problem  part       workerId rating
1       8001 problem26 partA A127R5QI5OGBIK    0.0
2       8001 problem26 partA A1FCLYRBAB430F    0.0
3       8001 problem26 partA A25FZQY34C6RVO    0.0
4       8001 problem26 partA A3G0MO562MHMZ3    0.5
5       8001 problem26 partA A3RB9ZOIUC3NWG    2.0
6       8001 problem26 partB A1FCLYRBAB430F    0.5
7       8001 problem26 partB A1XRDZKSJBWY8Q    0.5
8       8001 problem26 partB A22CRWMZUX7FFR    0.5
9       8001 problem26 partB A25FZQY34C6RVO    1.0
10      8001 problem26 partB A3G0MO562MHMZ3    0.5
11      8001 problem27 partA A1ET309DW6M2XA    2.0
12      8001 problem27 partA A1FCLYRBAB430F    0.0
13      8001 problem27 partA A22CRWMZUX7FFR    0.0
14      8001 problem27 partA A25FZQY34C6RVO    0.0
15      8001 problem27 partA A3G0MO562MHMZ3    0.0
16      8001 problem27 partB A1FCLYRBAB430F    1.0
17      8001 problem27 partB A22CRWMZUX7FFR    0.0
18      8001 problem27 partB A25FZQY34C6RVO    0.0
19      8001 problem27 partB A2U9676210WST5    0.0
20      8001 problem27 partB A3G0MO562MHMZ3    0.0
21      8002 problem26 partA A127R5QI5OGBIK    0.0
22      8002 problem26 partA A1FCLYRBAB430F    0.5
23      8002 problem26 partA A22CRWMZUX7FFR    0.0
24      8002 problem26 partA A25FZQY34C6RVO    2.0
25      8002 problem26 partA A3G0MO562MHMZ3    0.5
26      8002 problem26 partB A17EHJZNJGNRAN    2.0
27      8002 problem26 partB A1FCLYRBAB430F    0.0
28      8002 problem26 partB A2IPRDTE6B4TAB    0.0
29      8002 problem26 partB A3G0MO562MHMZ3    0.0
30      8002 problem26 partB  A6SON3OS15XKA    0.0
31      8002 problem27 partA A1FCLYRBAB430F    0.0
32      8002 problem27 partA A25FZQY34C6RVO    0.0
33      8002 problem27 partA A2IPRDTE6B4TAB    0.0
34      8002 problem27 partA A2U9676210WST5    0.0
35      8002 problem27 partA A3G0MO562MHMZ3    0.0
36      8002 problem27 partB A1FCLYRBAB430F    0.0
37      8002 problem27 partB A1V52SSKROBV8E    2.0
38      8002 problem27 partB A25FZQY34C6RVO    2.0
39      8002 problem27 partB A2IPRDTE6B4TAB    0.0
40      8002 problem27 partB A3G0MO562MHMZ3    0.0
>
> #Make a wrapper
> wrapper <- function ( ratingData, weight.func ) {
+   print(weight.func) #prove that the function is being passed
+   ddply(ratingData, c('studentId','problem','part'), summarize,
+           sum.weights = sum ( weight.func(rating)  ))
+ }
> wrapper( sampleData, weight.func=function(x) (x+.001)^-1  )
function(x) (x+.001)^-1
Error in data.frame(sum.weights = sum(weight.func(rating))) :
  could not find function "weight.func"
>
> #'globally' declare weight.func
> weight.func <- function(x) (x+.001)^-1
> wrapper( sampleData, weight.func=NULL  )
NULL
  studentId   problem  part sum.weights
1      8001 problem26 partA 3002.495758
2      8001 problem26 partB    8.983033
3      8001 problem27 partA 4000.499750
4      8001 problem27 partB 4000.999001
5      8002 problem26 partA 2004.491766
6      8002 problem26 partB 4000.499750
7      8002 problem27 partA 5000.000000
8      8002 problem27 partB 3000.999500

The second output is the goal. Any help appreciated! (Including a non plyr based way to accomplish the same task.)

The example above is a toy example. It's the simplest case I could get to reproduce the behavior.

Body:
An update on this issue in plyr (https://github.com/hadley/plyr/issues/3):

Use the 'here' function in plyr, just replace 'summarize', with 'here(summarize)' to access the environment where ddply was called from.

wrapper <- function(ratingData, weight.func){
           ddply(ratingData, c('studentId','problem','part'),
                 here(summarize),  # here(summarize)!
                 sum.weights = sum(weight.func(rating))
                 )
            }


问:
Amazon Polly to S3 Directly
Is there anyway to tell Amazon's Polly service to dump the audio file to S3 directly?

Using the SDK you can get a stream of the response, which I can then upload to S3, but I was hoping to skip the step and do it directly.

I've tried sending Polly S3-presigned post url as the file location but haven't gotten it to work.

答: Update: This became possible since the question was asked. See Amazon Polly Now Supports Input Character Limit of 100K and Stores Output Files in S3.

Title: Amazon Polly to S3 Directly


问:
GWT-Platform Proxies
I am totally new to GWT and I am using GWT-Platform (http://code.google.com/p/gwt-platform/).

My GWT client will communicate with an API which is implemented using Restlet. Restlet comes with the GWT serialization through Proxies.

In GWT-P you also have a proxy interface in the presenter but would this be replaced by the Restlet proxy or are they completely seperate things?

答:
The proxies of the GWT-P framework have nothing to do with the client server communication. Their solely purpose is to listen for events that indicate that their associated presenter and view need to be created. As written on the GWT-P site:

Proxies are the key to a fast MVP web application, they enable code splitting and lazy instantiation of the largest part of your code.

I assume that the Restlet proxies you're referring to deal with the communication between client and server.

So no, they're not a replacement for the GWT-P proxies.

Title: GWT-Platform Proxies


问:
How to get substring out of String in java?
i am getting this String input="One Two Three";
how to get substrings out of it?
I want to get optimized solutions.
help me!</p>

答:
This code will work for your scenario:</p>

```<code> String input = "One Two Three";
 String[] splitWords = input.split(" ");

 for ( String word : splitWords){
       System.out.println(word);
  }
</code>```

Body:
This code will work for your scenario:

 String input = "One Two Three";
 String[] splitWords = input.split(" ");

 for ( String word : splitWords){
       System.out.println(word);
  }