问:
How to resume audio after interruption in Swift?
I am following instructions here, I've put together this test project to handle interruptions to audio play. Specifically, I'm using the alarm from the default iphone clock app as interruption. It appears that the interruption handler is getting called but is not getting past the let = interruptionType line as "wrong type" showed up twice.

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    let audioPath = NSBundle.mainBundle().pathForResource("rachmaninov-romance-sixhands-alianello", ofType: "mp3")!

    func handleInterruption(notification: NSNotification) {

        guard let interruptionType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType else { print("wrong type"); return }

        switch interruptionType {

        case .Began:
            print("began")
            // player is paused and session is inactive. need to update UI)
            player.pause()
            print("audio paused")

        default:
            print("ended")
            /**/
            if let option = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? AVAudioSessionInterruptionOptions where option == .ShouldResume {
                // ok to resume playing, re activate session and resume playing
                // need to update UI
                player.play()
                print("audio resumed")
            }
            /**/
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        do {
            try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
            player.numberOfLoops = -1 // play indefinitely
            player.prepareToPlay()
            //player.delegate = player

        } catch {
            // process error here
        }

        // enable play in background https://stackoverflow.com/a/30280699/1827488 but this audio still gets interrupted by alerts
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            print("AVAudioSession Category Playback OK")
            do {
                try AVAudioSession.sharedInstance().setActive(true)
                print("AVAudioSession is Active")
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

        // add observer to handle audio interruptions
        // using 'object: nil' does not have a noticeable effect
        let theSession = AVAudioSession.sharedInstance()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.handleInterruption(_:)), name: AVAudioSessionInterruptionNotification, object: theSession)

        // start playing audio
        player.play()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

Furthermore, following an idea here, I have modified the handler to

```<code>func handleInterruption(notification: NSNotification) {

        //guard let interruptionType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType else { print("wrong type"); return }

        if notification.name != AVAudioSessionInterruptionNotification
            || notification.userInfo == nil{
            return
        }

        var info = notification.userInfo!
        var intValue: UInt = 0
        (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
        if let interruptionType = AVAudioSessionInterruptionType(rawValue: intValue) {

            switch interruptionType {

            case .Began:
                print("began")
                // player is paused and session is inactive. need to update UI)
                player.pause()
                print("audio paused")

            default:
                print("ended")
                /** /
                if let option = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? AVAudioSessionInterruptionOptions where option == .ShouldResume {
                    // ok to resume playing, re activate session and resume playing
                    // need to update UI
                    player.play()
                    print("audio resumed")
                }
                / **/
                player.play()
                print("audio resumed")
            }
        }
    }
</code>```

Results are that all of "began", "audio paused", "ended" and "audio resumed" show up in console but audio play is not actually resumed.

Note: I moved the player.play() outside of the commented out where option == .ShouldResume if statement because that if condition is not true when the .Ended interruption occurs.

答:
@rockhammers suggestion worked for me. Here

before class

```<code>let theSession = AVAudioSession.sharedInstance()
</code>```

in viewDidLoad

```<code>    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.handleInterruption(notification:)), name: NSNotification.Name.AVAudioSessionInterruption, object: theSession)
</code>```

And then the Function

```<code>func handleInterruption(notification: NSNotification) {
    print("handleInterruption")
    guard let value = (notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? NSNumber)?.uintValue,
        let interruptionType =  AVAudioSessionInterruptionType(rawValue: value)
        else {
            print("notification.userInfo?[AVAudioSessionInterruptionTypeKey]", notification.userInfo?[AVAudioSessionInterruptionTypeKey])
            return }
    switch interruptionType {
    case .began:
        print("began")
        vox.pause()
        music.pause()
        print("audioPlayer.playing", vox.isPlaying)
        /**/
        do {
            try theSession.setActive(false)
            print("AVAudioSession is inactive")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        pause()
    default :
        print("ended")
        if let optionValue = (notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? NSNumber)?.uintValue, AVAudioSessionInterruptionOptions(rawValue: optionValue) == .shouldResume {
            print("should resume")
            // ok to resume playing, re activate session and resume playing
            /**/
            do {
                try theSession.setActive(true)
                print("AVAudioSession is Active again")
                vox.play()
                music.play()
            } catch let error as NSError {
                print(error.localizedDescription)
            }
            play()
        }
    }
}
</code>```

Body:
I am following instructions here, I've put together this test project to handle interruptions to audio play. Specifically, I'm using the alarm from the default iphone clock app as interruption. It appears that the interruption handler is getting called but is not getting past the let = interruptionType line as "wrong type" showed up twice.

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    let audioPath = NSBundle.mainBundle().pathForResource("rachmaninov-romance-sixhands-alianello", ofType: "mp3")!

    func handleInterruption(notification: NSNotification) {

        guard let interruptionType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType else { print("wrong type"); return }

        switch interruptionType {

        case .Began:
            print("began")
            // player is paused and session is inactive. need to update UI)
            player.pause()
            print("audio paused")

        default:
            print("ended")
            /**/
            if let option = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? AVAudioSessionInterruptionOptions where option == .ShouldResume {
                // ok to resume playing, re activate session and resume playing
                // need to update UI
                player.play()
                print("audio resumed")
            }
            /**/
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        do {
            try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
            player.numberOfLoops = -1 // play indefinitely
            player.prepareToPlay()
            //player.delegate = player

        } catch {
            // process error here
        }

        // enable play in background https://stackoverflow.com/a/30280699/1827488 but this audio still gets interrupted by alerts
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            print("AVAudioSession Category Playback OK")
            do {
                try AVAudioSession.sharedInstance().setActive(true)
                print("AVAudioSession is Active")
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

        // add observer to handle audio interruptions
        // using 'object: nil' does not have a noticeable effect
        let theSession = AVAudioSession.sharedInstance()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.handleInterruption(_:)), name: AVAudioSessionInterruptionNotification, object: theSession)

        // start playing audio
        player.play()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Furthermore, following an idea here, I have modified the handler to

func handleInterruption(notification: NSNotification) {

        //guard let interruptionType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType else { print("wrong type"); return }

        if notification.name != AVAudioSessionInterruptionNotification
            || notification.userInfo == nil{
            return
        }

        var info = notification.userInfo!
        var intValue: UInt = 0
        (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
        if let interruptionType = AVAudioSessionInterruptionType(rawValue: intValue) {

            switch interruptionType {

            case .Began:
                print("began")
                // player is paused and session is inactive. need to update UI)
                player.pause()
                print("audio paused")

            default:
                print("ended")
                /** /
                if let option = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? AVAudioSessionInterruptionOptions where option == .ShouldResume {
                    // ok to resume playing, re activate session and resume playing
                    // need to update UI
                    player.play()
                    print("audio resumed")
                }
                / **/
                player.play()
                print("audio resumed")
            }
        }
    }

Results are that all of "began", "audio paused", "ended" and "audio resumed" show up in console but audio play is not actually resumed.

Note: I moved the player.play() outside of the commented out where option == .ShouldResume if statement because that if condition is not true when the .Ended interruption occurs.

Body:
@rockhammers suggestion worked for me. Here

before class

let theSession = AVAudioSession.sharedInstance()

in viewDidLoad

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.handleInterruption(notification:)), name: NSNotification.Name.AVAudioSessionInterruption, object: theSession)

And then the Function

func handleInterruption(notification: NSNotification) {
    print("handleInterruption")
    guard let value = (notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? NSNumber)?.uintValue,
        let interruptionType =  AVAudioSessionInterruptionType(rawValue: value)
        else {
            print("notification.userInfo?[AVAudioSessionInterruptionTypeKey]", notification.userInfo?[AVAudioSessionInterruptionTypeKey])
            return }
    switch interruptionType {
    case .began:
        print("began")
        vox.pause()
        music.pause()
        print("audioPlayer.playing", vox.isPlaying)
        /**/
        do {
            try theSession.setActive(false)
            print("AVAudioSession is inactive")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        pause()
    default :
        print("ended")
        if let optionValue = (notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? NSNumber)?.uintValue, AVAudioSessionInterruptionOptions(rawValue: optionValue) == .shouldResume {
            print("should resume")
            // ok to resume playing, re activate session and resume playing
            /**/
            do {
                try theSession.setActive(true)
                print("AVAudioSession is Active again")
                vox.play()
                music.play()
            } catch let error as NSError {
                print(error.localizedDescription)
            }
            play()
        }
    }
}


来源: stackexchange

问:
Determine landscape or portrait of HTML resource at runtime on iOS
I have an app that is essentially an eBook reader.  It is able to download a zip file that contains a group of HTML, CSS and JavaScript.  The app unzips the file and then displays the "webapp".

For 99% of the eBooks, I want the app to display in portrait only.  The pages are all formatted with this in mind. So, the app is now set for portrait only.

There is one eBook however that would work best in landscape view.

How can I detect if this eBook is loaded and change at runtime to show the pages only in landscape view?

I can easily put a string in the index.html file
Landscape
 and have this div hidden.  How can I search for this string at runtime and then change the setting in the app so that this resource is only viewed in landscape mode.

Linda

答:
Are you using UIWebView to display that content? If you do, I assume that the HTML/CSS/Javascript do the rest of the job with the eBook.. Have you try some kind of bridge between javascript and objective C? something like this.

Hope this helps

ContentLicense: CC BY-SA 2.5


问:
navbar changes size when adding header
I have a weird problem. Something is going on with my static navbar, I can't quite figure out what that is. Best way is to show it

So as you can see. I'm trying to add a header under navbar like a cover, but navbar always changes, you can see that it makes a small gap between nav bar and header, Here is the code:

header.php

```<code><!DOCTYPE html>
<html>
<head>

  <title><?php echo $pageTitle; ?></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/blog/css/style.css">

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <!-- Font Awesome ikonice jbg ovo koristim -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>
<body>

    <nav class="navbar navbar-default navbar-static-top">
      <div class="container">
        <ul class="nav navbar-nav">
            <li><a href="/blog"><i class="glyphicon glyphicon-home"></i> <?php echo $lang['MENU_HOME']; ?></a></li>

            <?php

            if(!logged_in())
            {
              echo '
                    <li><a href="#"><i class="fa fa-users"></i>  ', $lang['MENU_ABOUT'],'</a></li>';
            }
            else
            {
              echo '
                    <li><a href="#"><i class="glyphicon glyphicon-inbox"></i>  ', $lang['MENU_MESSAGES'],'</a></li>
                    <li><a href="#"><i class="glyphicon glyphicon-heart"></i>  ', $lang['MENU_NOTIFICATIONS'],'</a></li>';
            }

            ?>
        </ul>
        <ul class="nav navbar-nav navbar-right">

        <?php
          if(!logged_in())
          {
            echo
            '
              <li class="dropdown">
              <a class="dropdown-toggle" data-toggle="dropdown" href="#">Language:
              <span class="caret"></span></a>
              <ul class="dropdown-menu">
              <li><a href="chlng.php?lang=english">English (US)</a></li>
              <li><a href="chlng.php?lang=serbian">Srpski</a></li>
              <li><a href="chlng.php?lang=croatian">Hrvatski</a></li>
              <li><a href="chlng.php?lang=german">Deutsch</a></li>
              </ul>
              </li>
              ';
              }
              else
              {
              echo
              '
              <li class="dropdown">
              <img data-toggle="dropdown" class="circle" height="40" width="40" src="/blog/uploads/',$_SESSION['avatar'],'">

              <ul class="dropdown-menu">
              <li><a href="/blog/', $_SESSION['username'] ,'">', $lang['MENU_ACCOUNT'] ,'</a></li>
              <li><a href="/blog/settings">', $lang['MENU_SETTINGS'] ,'</a></li>
              <li><a href="/blog/logout">', $lang['MENU_LOGOUT'] ,'</a></li>
              </ul>
              </li>

            ';
          }
        ?>

          </ul>
      </div>
    </nav>
</code>```

view_profile.php

```<code><?php

echo '

<div class="header-profile">
dfdsfsd
</div>

';

?>
</code>```

header-profile

```<code>.header-profile
{
    display: block;
    content: "";
    position: absolute;
    height: 22%;
    width: 100%;
    box-shadow: inset 0 0 1px 1px rgba(0,0,0,0.2);
    background-color: #1DA1F2 !important
}
</code>```

答:
Bootstrap navbar has a bottom margin of 20px by default.

Set

```<code>nav {
    margin-bottom: 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: navbar changes size when adding header

Body:
I have a weird problem. Something is going on with my static navbar, I can't quite figure out what that is. Best way is to show it

So as you can see. I'm trying to add a header under navbar like a cover, but navbar always changes, you can see that it makes a small gap between nav bar and header, Here is the code:

header.php

<!DOCTYPE html>

  <title><?php echo $pageTitle; ?></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/blog/css/style.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

 <?php echo $lang['MENU_HOME']; ?>

            <?php

            if(!logged_in())
            {
              echo '

  ', $lang['MENU_ABOUT'],'
';
            }
            else
            {
              echo '

  ', $lang['MENU_MESSAGES'],'

  ', $lang['MENU_NOTIFICATIONS'],'
';
            }

            ?>

        <?php
          if(!logged_in())
          {
            echo
            '

              Language:

English (US)

Srpski

Hrvatski

Deutsch

              ';
              }
              else
              {
              echo
              '

', $lang['MENU_ACCOUNT'] ,'

', $lang['MENU_SETTINGS'] ,'

', $lang['MENU_LOGOUT'] ,'

            ';
          }
        ?>

view_profile.php

<?php

echo '

dfdsfsd

';

?>

header-profile

.header-profile
{
    display: block;
    content: "";
    position: absolute;
    height: 22%;
    width: 100%;
    box-shadow: inset 0 0 1px 1px rgba(0,0,0,0.2);
    background-color: #1DA1F2 !important
}

Body:
Bootstrap navbar has a bottom margin of 20px by default.

Set

nav {
    margin-bottom: 0;
}


问:
Java JNA - Base Address Finding
I am currently attempting to read/write to memory through the use of JNA for Java. For the past week I have tried a multitude of solutions, mostly from [similar projects][1] I have found online, but nothing has resolved my problem.

I know I am receiving the correct process ID of the program, then I create a Pointer using the openProcess method. Then I call getBaseAddress using the newly created Pointer. The problem I believe lies within the EnumProcessModules/Psapi method/class.

Truthfully I am slightly in over my head but this is one of the last issues I am having with this program. My overall goal is to find the base address of the program, use various offsets to access the information I am trying to modify, and then modify it appropriately. The program is 32-bit, which I have seen other people say you need to use a EnumProcessModulesEx method for? but truthfully I am unsure of how/where to implement that.

Any help would be appreciated!

答:
You're getting an Access Denied error because Windows requires you to enable Debug privilege on your current process before accessing the memory of another process.  So you will need to both run your program as Administrator, and before you call your OpenProcess code, enable debug privilege.

Here's the JNA code in my application that does this. It's a static method as I only call it once for the entire application:

/**
 * Enables debug privileges for this process, required for OpenProcess() to get
 * processes other than the current user
 *
 * @return {@code true} if debug privileges were successfully enabled.
 */
private static boolean enableDebugPrivilege() {
    HANDLEByReference hToken = new HANDLEByReference();
    boolean success = Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(),
            WinNT.TOKEN_QUERY | WinNT.TOKEN_ADJUST_PRIVILEGES, hToken);
    if (!success) {
        LOG.error("OpenProcessToken failed. Error: {}", Native.getLastError());
        return false;
    }
    try {
        WinNT.LUID luid = new WinNT.LUID();
        success = Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid);
        if (!success) {
            LOG.error("LookupPrivilegeValue failed. Error: {}", Native.getLastError());
            return false;
        }
        WinNT.TOKEN_PRIVILEGES tkp = new WinNT.TOKEN_PRIVILEGES(1);
        tkp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED));
        success = Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tkp, 0, null, null);
        int err = Native.getLastError();
        if (!success) {
            LOG.error("AdjustTokenPrivileges failed. Error: {}", err);
            return false;
        } else if (err == WinError.ERROR_NOT_ALL_ASSIGNED) {
            LOG.debug("Debug privileges not enabled.");
            return false;
        }
    } finally {
        Kernel32.INSTANCE.CloseHandle(hToken.getValue());
    }
    return true;
}
```
<p>I'm not sure from looking at your code whether you also have the right permissions for <code>OpenProcess</code>.  Be sure you have the <code>VM_READ</code> permission.   Here's what I use, your mileage may vary (I assume you'll need writing permissions as well).</p>
```final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(
    WinNT.PROCESS_QUERY_INFORMATION | WinNT.PROCESS_VM_READ,
    false, processID);
```

ContentLicense: CC BY-SA 4.0

Title: Java JNA - Base Address Finding

Body:
You're getting an Access Denied error because Windows requires you to enable Debug privilege on your current process before accessing the memory of another process.  So you will need to both run your program as Administrator, and before you call your OpenProcess code, enable debug privilege.

Here's the JNA code in my application that does this. It's a static method as I only call it once for the entire application:

/**
 * Enables debug privileges for this process, required for OpenProcess() to get
 * processes other than the current user
 *
 * @return {@code true} if debug privileges were successfully enabled.
 */
private static boolean enableDebugPrivilege() {
    HANDLEByReference hToken = new HANDLEByReference();
    boolean success = Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(),
            WinNT.TOKEN_QUERY | WinNT.TOKEN_ADJUST_PRIVILEGES, hToken);
    if (!success) {
        LOG.error("OpenProcessToken failed. Error: {}", Native.getLastError());
        return false;
    }
    try {
        WinNT.LUID luid = new WinNT.LUID();
        success = Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid);
        if (!success) {
            LOG.error("LookupPrivilegeValue failed. Error: {}", Native.getLastError());
            return false;
        }
        WinNT.TOKEN_PRIVILEGES tkp = new WinNT.TOKEN_PRIVILEGES(1);
        tkp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED));
        success = Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tkp, 0, null, null);
        int err = Native.getLastError();
        if (!success) {
            LOG.error("AdjustTokenPrivileges failed. Error: {}", err);
            return false;
        } else if (err == WinError.ERROR_NOT_ALL_ASSIGNED) {
            LOG.debug("Debug privileges not enabled.");
            return false;
        }
    } finally {
        Kernel32.INSTANCE.CloseHandle(hToken.getValue());
    }
    return true;
}

I'm not sure from looking at your code whether you also have the right permissions for OpenProcess.  Be sure you have the VM_READ permission.   Here's what I use, your mileage may vary (I assume you'll need writing permissions as well).

final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(
    WinNT.PROCESS_QUERY_INFORMATION | WinNT.PROCESS_VM_READ,
    false, processID);


问:
How to parse JSON file for a specific key and value?
Currently, have multiple JSON files to parse. In each file, I would look for “ID”: “1”:

```<code>{“TYPE”: “fire”, “ID”: “1”, “COLOR”: “black”}
</code>```

and if it is, copy and paste the whole JSON content (which is just 1 line), and paste it onto the result file.

In Python, what would be the right approach to look for a specific key/value in a JSON file to copy to a new file?

答:
Step 1 : Load your JSON as a dict

```<code>import json
my_json_dict = json.loads(json_string)
</code>```

The json library parses your JSON string to a Python dictionary.

Step 2 : Access the value using key

```<code>value1 = my_json_dict['ID']
value1 = my_json_dict.get('ID', default_value) # Preferred.
</code>```

The first statement will throw an exception if KEY1 is not available in the JSON string.
The second statement is safer, as a fallback value can be given.

Step 3 : Apply your business logic

```<code>if id == 1:
    # do your operations.
</code>```

If you must use the first line, or if dealing with unknowns that could throw errors anyway, test for the error you are getting and add exception handling around in it as in:

```<code>try:
   <your code solution here>
except NameOfError as ee:
   <what to do if error occurs>
   print(type(ee)); print(ee)    # if you want to see the error
</code>```

You can add as many except statements as there are error types you are attempting to process.  A generic "Exception" can be used in place of NameOfError as a catch-all for unknown errors, but best practice is to handle the true Exceptions first by type.  A little testing as code breaks initially can reveal what should go in place of "NameOfError".

Body:
Currently, have multiple JSON files to parse. In each file, I would look for “ID”: “1”:

{“TYPE”: “fire”, “ID”: “1”, “COLOR”: “black”}

and if it is, copy and paste the whole JSON content (which is just 1 line), and paste it onto the result file.

In Python, what would be the right approach to look for a specific key/value in a JSON file to copy to a new file?

Body:
Step 1 : Load your JSON as a dict

import json
my_json_dict = json.loads(json_string)

The json library parses your JSON string to a Python dictionary.

Step 2 : Access the value using key

value1 = my_json_dict['ID']
value1 = my_json_dict.get('ID', default_value) # Preferred.

The first statement will throw an exception if KEY1 is not available in the JSON string.
The second statement is safer, as a fallback value can be given.

Step 3 : Apply your business logic

if id == 1:
    # do your operations.

If you must use the first line, or if dealing with unknowns that could throw errors anyway, test for the error you are getting and add exception handling around in it as in:

try:
   <your code solution here>
except NameOfError as ee:
   <what to do if error occurs>
   print(type(ee)); print(ee)    # if you want to see the error

You can add as many except statements as there are error types you are attempting to process.  A generic "Exception" can be used in place of NameOfError as a catch-all for unknown errors, but best practice is to handle the true Exceptions first by type.  A little testing as code breaks initially can reveal what should go in place of "NameOfError".


问:
angular2 cannot find name require
I want to use a new component named ng2-material-select in my application.
Added it into systemjs.config.js

```<code>var map = {
 'Ng2Select': '/node_modules/ng2-material-select',
 "angular2-jwt": "/node_modules/angular2-jwt/angular2-jwt"
};

var packages = {
    'Ng2Select': { main: 'index.js', defaultExtension: 'js' },
};
</code>```

But when I start the application, I face following error:

Error loading http://192.168.0.46:3002/ng2-material-select as "ng2-material-select" from http://192.168.0.46:3002/app/module.js

also there is following error in node_modules/ng2-material-select/index.ts,which I think it may causes problem in loading:

cannot find name require :

```<code>const components = require('./ng2-select.bundle.js');
</code>```

I updated angularjs   and typescript ,but still problem does not solve.

Please help me.

答:
I believe your systemjs.config.js mappings are wrong.

This ..

```<code>'Ng2Select': '/node_modules/ng2-material-select'
</code>```

points to a TS file, I believe you need to point to a JS file. I believe you want ..

```<code>'Ng2Select': '/node_modules/ng2-material-select/dist/ng2-select.bundle.js'
</code>```

poke around in the /node_modules/ng2-material-select folder and make sure you are pointing to the right file.

(I believe the JS file is the file that the TS file is trying to require).

Title: angular2 cannot find name require

Body:
I want to use a new component named ng2-material-select in my application.
Added it into systemjs.config.js

var map = {
 'Ng2Select': '/node_modules/ng2-material-select',
 "angular2-jwt": "/node_modules/angular2-jwt/angular2-jwt"
};

var packages = {
    'Ng2Select': { main: 'index.js', defaultExtension: 'js' },
};

But when I start the application, I face following error:

Error loading http://192.168.0.46:3002/ng2-material-select as "ng2-material-select" from http://192.168.0.46:3002/app/module.js

also there is following error in node_modules/ng2-material-select/index.ts,which I think it may causes problem in loading:

cannot find name require :

const components = require('./ng2-select.bundle.js');

I updated angularjs   and typescript ,but still problem does not solve.

Please help me.

Body:
I believe your systemjs.config.js mappings are wrong.

This ..

'Ng2Select': '/node_modules/ng2-material-select'

points to a TS file, I believe you need to point to a JS file. I believe you want ..

'Ng2Select': '/node_modules/ng2-material-select/dist/ng2-select.bundle.js'

poke around in the /node_modules/ng2-material-select folder and make sure you are pointing to the right file.

(I believe the JS file is the file that the TS file is trying to require).


问:
AES256-CBC Ciphertext from BouncyCastle decrypts in BC, but PHP openssl_decrypt fails w/same inputs
I encrypted a String with 256-bit AES (CBC mode) using BouncyCastle (technically, SpongyCastle) under Android and logged the base64-encoded values of the ciphertext, key, and iv.

I then wrote a test program (as an instrumented Android Unit Test) that hardcodes all three values as base64-encoded Strings. It decrypts successfully when I run the code below under Android.

The exact same base64-encoded ciphertext, key, and iv fail under PHP (5.6.30). I'm struggling to understand why. In both cases, the ciphertext, key, and iv all start out as hardcoded base64-encoded Strings with the exact same values.

Among other things, it's complaining that the key length (32 bytes) is invalid (the last time I checked, 32 * 8 == 256).

Android (SpongyCastle) code:

```<code>@Test
    public void crossplatformTest() {
        String ciphertext64 = "gfcC6t1BarndpzMuvYj2JFpWHqlWSJMhTtxPN7QjyEg=";
        String key64 = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
        String iv64="AAECAwQFBgcICQoLDA0ODw==";

        byte[] ciphertext = Base64.decode(ciphertext64, Base64.DEFAULT);
        byte[] key = Base64.decode(key64, Base64.DEFAULT);
        byte[] iv = Base64.decode(iv64, Base64.DEFAULT);

        byte[] decrypted = Crypto.decryptWithAesCBC(ciphertext, key, iv);
        // the following assertion succeeds.
        assertEquals("Ugh! Endless grief!", new String(decrypted, StandardCharsets.UTF_8));
    }
</code>```

PHP (OpenSSL) code:

```<code><?php
    $ciphertext64 = "gfcC6t1BarndpzMuvYj2JFpWHqlWSJMhTtxPN7QjyEg=";
    $key64 = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
    $iv64="AAECAwQFBgcICQoLDA0ODw==";

    // UPDATE: THE LINE BELOW IS THE PROBLEM. SEE ANSWER FOR SOLUTION.
    $decrypted = openssl_decrypt($ciphertext64, 'aes-256-cbc', $key64, 0, $iv64);
    if ($decrypted == false) {
        while ($msg = openssl_error_string())
            echo "<p>$msg</p>\n";
        echo("key length=" . strlen(base64_decode($key64, true))."<BR>\n");
        echo("iv length=" . strlen(base64_decode($iv64, true))."<BR>\n");
    }
</code>```

PHP's output:

```<code>error:0607A082:digital envelope routines:EVP_CIPHER_CTX_set_key_length:invalid key length
error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

key length=32
iv length=16
</code>```

According to what little documentation for openssl_decrypt seems to exist at php.net (http://php.net/manual/en/function.openssl-decrypt.php), openssl_decrypt wants base64-encoded strings for ciphertext, key, and iv.

For what it's worth, here's the code I used to encrypt the original String, and the code I'm using on Android to decrypt it:

```<code>public static byte[] decryptWithAesCBC(byte[] ciphertext, byte[] key, byte[] iv) {
        try {
            PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
            CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
            aes.init(false, ivAndKey);
            return cipherData(aes, ciphertext);
        }
        catch (InvalidCipherTextException e) {
            throw new RuntimeException(e);
        }
    }

private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) throws InvalidCipherTextException {
        int minSize = cipher.getOutputSize(data.length);
        byte[] outBuf = new byte[minSize];
        int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
        int length2 = cipher.doFinal(outBuf, length1);
        int actualLength = length1 + length2;
        byte[] ciphertext = new byte[actualLength];
        for (int x=0; x < actualLength; x++) {
            ciphertext[x] = outBuf[x];
        }
        return ciphertext;
    }

public static byte[] encryptWithAesCBC(byte[] plaintext, byte[] key, byte[] iv) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC");

            PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
            CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
            aes.init(true, ivAndKey);
            return cipherData(aes, plaintext);
        }
        catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidCipherTextException e) {
            throw new RuntimeException(e);
        }
    }
</code>```

答:
OK, found the definitive answer & confirmed that it works.

The official documentation for openssl_decrypt at php.net is bad, and the first few comments taken in isolation are somewhere between "incomplete" and "misleading".

According to the most authoritative documentation for openssl_decrypt (ext/openssl/openssl.c in the source code for PHP 5.6.30 itself):

$data is presumed to be base64-encoded unless OPENSSL_RAW_DATA is explicitly specified as an option. The source code itself makes this clear:

```<code>if (!(options & OPENSSL_RAW_DATA)) {
    base64_str = (char*)php_base64_decode((unsigned char*)data, data_len, &base64_str_len);
    if (!base64_str) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to base64 decode the input");
        RETURN_FALSE;
    }
    data_len = base64_str_len;
    data = base64_str;
}
</code>```

HOWEVER, the values of $password and $iv are cast DIRECTLY to (unsigned char *).

Thus, the correct usage is:

```<code>$ciphertext64 = "gfcC6t1BarndpzMuvYj2JFpWHqlWSJMhTtxPN7QjyEg=";
$key64 = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
$iv64="AAECAwQFBgcICQoLDA0ODw==";

$key = base64_decode($key64, true);
$iv = base64_decode($iv64, true);

$decrypted = openssl_decrypt($ciphertext64, 'aes-256-cbc', $key, 0, $iv);
</code>```

... which outputs the value of the String I originally encrypted using BouncyCastle (SpongyCastle) on Android -- "Ugh! Endless grief!"

As to why the official documentation is so bad, PHP's developers have apparently decided to quietly deprecate the openssl functions, with the expectation that once PHP 7.2 becomes mainstream, everyone will use libsodium going forward. The addition of libsodium to default installations of PHP 7.2 onward is awesome, but unfortunately, it won't do anybody with a shared web hosting account (who lacks admin, let alone root, shell access to the server and can't install their own extensions) much good until at least early 2018.

In other words, if you found this post via Google sometime after late 2017 while attempting to solve some problem you're having with openssl and PHP, check to see whether your web server has PHP 7.2 available.

If it doesn't, and neither upgrading to PHP 7.2+ nor getting libsodium installed on the server is a viable option, proceed with my solution.

If it does, forget that the openssl_* functions ever existed, and go straight to libsodium (which by design makes it a lot harder to accidentally screw up)

Body:
I encrypted a String with 256-bit AES (CBC mode) using BouncyCastle (technically, SpongyCastle) under Android and logged the base64-encoded values of the ciphertext, key, and iv.

I then wrote a test program (as an instrumented Android Unit Test) that hardcodes all three values as base64-encoded Strings. It decrypts successfully when I run the code below under Android.

The exact same base64-encoded ciphertext, key, and iv fail under PHP (5.6.30). I'm struggling to understand why. In both cases, the ciphertext, key, and iv all start out as hardcoded base64-encoded Strings with the exact same values.

Among other things, it's complaining that the key length (32 bytes) is invalid (the last time I checked, 32 * 8 == 256).

Android (SpongyCastle) code:

@Test
    public void crossplatformTest() {
        String ciphertext64 = "gfcC6t1BarndpzMuvYj2JFpWHqlWSJMhTtxPN7QjyEg=";
        String key64 = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
        String iv64="AAECAwQFBgcICQoLDA0ODw==";

        byte[] ciphertext = Base64.decode(ciphertext64, Base64.DEFAULT);
        byte[] key = Base64.decode(key64, Base64.DEFAULT);
        byte[] iv = Base64.decode(iv64, Base64.DEFAULT);

        byte[] decrypted = Crypto.decryptWithAesCBC(ciphertext, key, iv);
        // the following assertion succeeds.
        assertEquals("Ugh! Endless grief!", new String(decrypted, StandardCharsets.UTF_8));
    }

PHP (OpenSSL) code:

<?php
    $ciphertext64 = "gfcC6t1BarndpzMuvYj2JFpWHqlWSJMhTtxPN7QjyEg=";
    $key64 = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
    $iv64="AAECAwQFBgcICQoLDA0ODw==";

    // UPDATE: THE LINE BELOW IS THE PROBLEM. SEE ANSWER FOR SOLUTION.
    $decrypted = openssl_decrypt($ciphertext64, 'aes-256-cbc', $key64, 0, $iv64);
    if ($decrypted == false) {
        while ($msg = openssl_error_string())
            echo "
$msg
\n";
        echo("key length=" . strlen(base64_decode($key64, true))."
\n");
        echo("iv length=" . strlen(base64_decode($iv64, true))."
\n");
    }

PHP's output:

error:0607A082:digital envelope routines:EVP_CIPHER_CTX_set_key_length:invalid key length
error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

key length=32
iv length=16

According to what little documentation for openssl_decrypt seems to exist at php.net (http://php.net/manual/en/function.openssl-decrypt.php), openssl_decrypt wants base64-encoded strings for ciphertext, key, and iv.

For what it's worth, here's the code I used to encrypt the original String, and the code I'm using on Android to decrypt it:

public static byte[] decryptWithAesCBC(byte[] ciphertext, byte[] key, byte[] iv) {
        try {
            PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
            CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
            aes.init(false, ivAndKey);
            return cipherData(aes, ciphertext);
        }
        catch (InvalidCipherTextException e) {
            throw new RuntimeException(e);
        }
    }

private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) throws InvalidCipherTextException {
        int minSize = cipher.getOutputSize(data.length);
        byte[] outBuf = new byte[minSize];
        int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
        int length2 = cipher.doFinal(outBuf, length1);
        int actualLength = length1 + length2;
        byte[] ciphertext = new byte[actualLength];
        for (int x=0; x < actualLength; x++) {
            ciphertext[x] = outBuf[x];
        }
        return ciphertext;
    }

public static byte[] encryptWithAesCBC(byte[] plaintext, byte[] key, byte[] iv) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC");

            PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
            CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
            aes.init(true, ivAndKey);
            return cipherData(aes, plaintext);
        }
        catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidCipherTextException e) {
            throw new RuntimeException(e);
        }
    }

Body:
OK, found the definitive answer & confirmed that it works.

The official documentation for openssl_decrypt at php.net is bad, and the first few comments taken in isolation are somewhere between "incomplete" and "misleading".

According to the most authoritative documentation for openssl_decrypt (ext/openssl/openssl.c in the source code for PHP 5.6.30 itself):

$data is presumed to be base64-encoded unless OPENSSL_RAW_DATA is explicitly specified as an option. The source code itself makes this clear:

if (!(options & OPENSSL_RAW_DATA)) {
    base64_str = (char*)php_base64_decode((unsigned char*)data, data_len, &base64_str_len);
    if (!base64_str) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to base64 decode the input");
        RETURN_FALSE;
    }
    data_len = base64_str_len;
    data = base64_str;
}

HOWEVER, the values of $password and $iv are cast DIRECTLY to (unsigned char *).

Thus, the correct usage is:

$ciphertext64 = "gfcC6t1BarndpzMuvYj2JFpWHqlWSJMhTtxPN7QjyEg=";
$key64 = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
$iv64="AAECAwQFBgcICQoLDA0ODw==";

$key = base64_decode($key64, true);
$iv = base64_decode($iv64, true);

$decrypted = openssl_decrypt($ciphertext64, 'aes-256-cbc', $key, 0, $iv);

... which outputs the value of the String I originally encrypted using BouncyCastle (SpongyCastle) on Android -- "Ugh! Endless grief!"

As to why the official documentation is so bad, PHP's developers have apparently decided to quietly deprecate the openssl functions, with the expectation that once PHP 7.2 becomes mainstream, everyone will use libsodium going forward. The addition of libsodium to default installations of PHP 7.2 onward is awesome, but unfortunately, it won't do anybody with a shared web hosting account (who lacks admin, let alone root, shell access to the server and can't install their own extensions) much good until at least early 2018.

In other words, if you found this post via Google sometime after late 2017 while attempting to solve some problem you're having with openssl and PHP, check to see whether your web server has PHP 7.2 available.

If it doesn't, and neither upgrading to PHP 7.2+ nor getting libsodium installed on the server is a viable option, proceed with my solution.

If it does, forget that the openssl_* functions ever existed, and go straight to libsodium (which by design makes it a lot harder to accidentally screw up)


问:
PHP - How do I get a parameter value from $_SERVER['HTTP_REFERER']?
In a PHP application, $_SERVER['HTTP_REFERER'] has the following value:

```
http://www.google.com/aclk?sa=l&ai=CPWNSJV30TK{snip}&num=2&sig=AGiWqtxY{snip}
&adurl=http://www.jumpfly.com&rct=j&q=adwords&cad=rja
```

My question is what is the proper way to extract the value of q?

Should I search for the position of q, then the position of the next &, and then take the substring between them?  That seems a bit unprofessional since what if someday q is the final parameter in that query string and then there is no & afterwards.

Thank you.

答: You can use parse_url() for that.  From there, split the query on &.

Body:
In a PHP application, $_SERVER['HTTP_REFERER'] has the following value:

http://www.google.com/aclk?sa=l&ai=CPWNSJV30TK{snip}&num=2&sig=AGiWqtxY{snip}
&adurl=http://www.jumpfly.com&rct=j&q=adwords&cad=rja

My question is what is the proper way to extract the value of q?

Should I search for the position of q, then the position of the next &, and then take the substring between them?  That seems a bit unprofessional since what if someday q is the final parameter in that query string and then there is no & afterwards.

Thank you.


问:
Weird casting related issue in java
consider the following code:

```<code>public class ListDemo {

    List<Inner> inners;

    public ListDemo() {
        this.inners = new ArrayList<>();
    }

    private void load(){
        SomeClzz.load(inners);
    }

    private class Inner implements TestInterface {

        @Override
        public void bla() {
            System.out.println("Bla");
        }

    }
}
</code>```

with the interface:

```<code>public interface TestInterface {
    public void bla();
}
</code>```

and the class:

```<code>public class SomeClzz {
    public static void load(List<TestInterface> test){
        for (TestInterface testInterface : test) {
            testInterface.bla();
        }
    }
}
</code>```

I created this fake code based on a real world example, because I wanted to see if I could isolate the issue and found the that the load method had an error.

Why is it that SomeClzz.load(inners); gives an error that inners can't be cast from a List<Inner> to a List<TestInterface>?

答:
Simple change will make it work:

```<code>public static void load(List<? extends TestInterface> test){
    for (TestInterface testInterface : test) {
        testInterface.bla();
    }
}
</code>```

UPDATE:
You can find the answer here.

In short.

List<Inner> is not a subtype of List<TestInterface>.

This is a common misunderstanding when it comes to programming with generics, but you need to understand this, as generics are very important frequently used.

Title: Weird casting related issue in java

Body:
consider the following code:

public class ListDemo {

    List<Inner> inners;

    public ListDemo() {
        this.inners = new ArrayList<>();
    }

    private void load(){
        SomeClzz.load(inners);
    }

    private class Inner implements TestInterface {

        @Override
        public void bla() {
            System.out.println("Bla");
        }

    }
}

with the interface:

public interface TestInterface {
    public void bla();
}

and the class:

public class SomeClzz {
    public static void load(List<TestInterface> test){
        for (TestInterface testInterface : test) {
            testInterface.bla();
        }
    }
}

I created this fake code based on a real world example, because I wanted to see if I could isolate the issue and found the that the load method had an error.

Why is it that SomeClzz.load(inners); gives an error that inners can't be cast from a List<Inner> to a List<TestInterface>?

Body:
Simple change will make it work:

public static void load(List<? extends TestInterface> test){
    for (TestInterface testInterface : test) {
        testInterface.bla();
    }
}

UPDATE:
You can find the answer here.

In short.

List<Inner> is not a subtype of List<TestInterface>.

This is a common misunderstanding when it comes to programming with generics, but you need to understand this, as generics are very important frequently used.


问:
Run a function on each item in parallel every 5 seconds with Python
I am processing a video and want to check multiple regions of interest in parallel, every 5 seconds. I would like to know if the function I currently have is accomplishing this in the correct manner.

```<code>def checkFrames():
    timer = threading.Timer(5.0, checkFrames)
    timer.daemon = True
    timer.start()
    if(started):
        index = 0
        for region in regions:
            threading.Thread(target=processRegion, args=(frame, region, index)).start()
            index += 1
</code>```

Right now I can't really tell if all of the regions are being processed in parallel (although I know that they are all being processed). The program runs pretty slow here compared to when I'm purposely checking the regions right after the other. The processing for all the regions don't have to start at the same time.

答: Yes, this code appears to launch N threads in parallel every 5 seconds, however, it may perform no faster than a single thread that examines N regions, due to Python's global interpreter lock.  </p>

Body:
I am processing a video and want to check multiple regions of interest in parallel, every 5 seconds. I would like to know if the function I currently have is accomplishing this in the correct manner.

def checkFrames():
    timer = threading.Timer(5.0, checkFrames)
    timer.daemon = True
    timer.start()
    if(started):
        index = 0
        for region in regions:
            threading.Thread(target=processRegion, args=(frame, region, index)).start()
            index += 1

Right now I can't really tell if all of the regions are being processed in parallel (although I know that they are all being processed). The program runs pretty slow here compared to when I'm purposely checking the regions right after the other. The processing for all the regions don't have to start at the same time.


问:
Return certain record based on criteria
Take this list of results

```<code>  Date     | YESorNO
---------------------
01/01/2001 | NO
01/01/2002 | NO
01/01/2003 | YES
01/01/2004 | NO
01/01/2005 | NO
01/01/2006 | NO
01/01/2007 | YES
01/01/2008 | YES
01/01/2009 | YES
</code>```

The list is ordered and I cannot sort this is any other way other than descending / ascending.

I want to be able to return the first 'YES' after all 'NO's have been accounted for.

In the above example, row 7 is the record I want returned (on 01/01/2007)

My code is as follows

```<code>var query =
(
    from m in db.MyTable
    where m.Criteria == XYZ
    select new
    {
      Date = m.Date,
      YESorNO = m.YESorNO
    }
).OrderBy(x => x.Date);
</code>```

Using .FirstOrDefault(x => x.YesOrNO == "YES") returns the 3rd record.

Thanks for any help.

答:
```<code>var query = db.MyTable
    .Where(m.Criteria == XYZ)
    .Select(e => new { Date = e.Date, YESorNO = e.YESorNO })
    .OrderBy(e => x.Date);

var latestNODate = query.Where(ee => ee.YESorNO == "NO").Last().Date;
var element = query.Where(e => e.Date > latestNODate && e.YESorNO == "YES").FirstOrDefault();
</code>```

Title: Return certain record based on criteria

Body:
Take this list of results

  Date     | YESorNO
---------------------
01/01/2001 | NO
01/01/2002 | NO
01/01/2003 | YES
01/01/2004 | NO
01/01/2005 | NO
01/01/2006 | NO
01/01/2007 | YES
01/01/2008 | YES
01/01/2009 | YES

The list is ordered and I cannot sort this is any other way other than descending / ascending.

I want to be able to return the first 'YES' after all 'NO's have been accounted for.

In the above example, row 7 is the record I want returned (on 01/01/2007)

My code is as follows

var query =
(
    from m in db.MyTable
    where m.Criteria == XYZ
    select new
    {
      Date = m.Date,
      YESorNO = m.YESorNO
    }
).OrderBy(x => x.Date);

Using .FirstOrDefault(x => x.YesOrNO == "YES") returns the 3rd record.

Thanks for any help.


问:
awk split column into multiple columns in staggered manner
I have a text file containing a single column of data as below :

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

I want to split this into multiple columns using awk or sed command as follows:

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

How can I do this? Thanks in advance

答:
This should work because echo is a default command for xargs

```<code>xargs -n 3 file
</code>```

Body:
I have a text file containing a single column of data as below :

1
2
3
4
5
6

I want to split this into multiple columns using awk or sed command as follows:

1 2 3
4 5 6

How can I do this? Thanks in advance

Body:
This should work because echo is a default command for xargs

xargs -n 3 file


答:
```<code>parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $queries);
echo $queries['q'];
</code>```

References:

http://php.net/parse_url

http://php.net/parse_str

Title: PHP - How do I get a parameter value from $_SERVER['HTTP_REFERER']?

Body:
parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $queries);
echo $queries['q'];

References:

http://php.net/parse_url

http://php.net/parse_str


问:
Using a timer in java Error
```<code> public void setTimerCount(View view){
        int value5;
        final double timerCountSeconds = 0;

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                timerCountSeconds ++ 0.1;
                timerCount.setText("" + (timerCountSeconds));

            }
        };
</code>```

I think this is right but i get this error on the call of the variable in the run function "Not a Statement

答:
final double timerCountSeconds = 0;

You are trying to change the value of a final variable...

timerCountSeconds ++ 0.1;

You probably meant to use timerCountSeconds += 0.1;

Try this code:

```<code>public void setTimerCount(View view) {
    int value5;
    final double[] timerCountSeconds = {0};

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            timerCountSeconds[0] += timerCountSeconds[0] + 0.1;
            timerCount.setText("" + (timerCountSeconds[0]));

        }
    };
}
</code>```

Title: Using a timer in java Error

Body:
 public void setTimerCount(View view){
        int value5;
        final double timerCountSeconds = 0;

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                timerCountSeconds ++ 0.1;
                timerCount.setText("" + (timerCountSeconds));

            }
        };

I think this is right but i get this error on the call of the variable in the run function "Not a Statement

Body:
final double timerCountSeconds = 0;

You are trying to change the value of a final variable...

timerCountSeconds ++ 0.1;

You probably meant to use timerCountSeconds += 0.1;

Try this code:

public void setTimerCount(View view) {
    int value5;
    final double[] timerCountSeconds = {0};

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            timerCountSeconds[0] += timerCountSeconds[0] + 0.1;
            timerCount.setText("" + (timerCountSeconds[0]));

        }
    };
}


答:
Try these:

parse_url(): http://php.net/manual/en/function.parse-url.php.

parse_str(): http://www.php.net/manual/en/function.parse-str.php


问:
Powershell with Dataloop/Outlyer
I'm not sure if this is the correct page for this question but I'm having a hard time getting Dataloop to properly display a widget based on my Powershell script's exit code.

I've just began playing with Dataloop monitoring so I may be going about this all wrong, but as far as I can tell from their documentation, they use the same error code system as Nagios and that those error codes map to a .status metric within Dataloop which you can use for displaying widgets.

As a test, I created the following Powershell script:

```<code>if (Test-path c:\scripts02) {
    Write-Host "I found the directory!"
    exit 0
}
else {
    Write-Host "I could not find the directory!"
    exit 2
}
</code>```

When I run the plugin test through the Dataloop site, this prints out the "I could not find the directory!" message along with the correct exit code of 2. When I change the path it's testing to an existing directory, it does exit with 0 and the correct output message. Everything seems to work as expected before until I move to the next part.

Inside Dataloop, I'd attempt to add a widget, set the source to one of my agents, select the "status" metric for my test plugin (the powershell script). The widget just appears with a gray screen when it should be green since the directory path does exist...

Has anyone had success with this? I checked out their documentation and tried the steps outlined there but have had no success.

答:
For anyone who's interested, this is actually a bug in the dataloop agent v1.1. Updated to v1.3 and code executes properly and reports the correct exit code.

On a side note, I had to use the function below to get dataloop to report properly as well instead of the "exit [int]" in my original code above:

```<code>function ExitWithCode {
    param($exitcode)

    $host.SetShouldExit($exitcode)
    exit
}
</code>```

Title: Powershell with Dataloop/Outlyer

Body:
I'm not sure if this is the correct page for this question but I'm having a hard time getting Dataloop to properly display a widget based on my Powershell script's exit code.

I've just began playing with Dataloop monitoring so I may be going about this all wrong, but as far as I can tell from their documentation, they use the same error code system as Nagios and that those error codes map to a .status metric within Dataloop which you can use for displaying widgets.

As a test, I created the following Powershell script:

if (Test-path c:\scripts02) {
    Write-Host "I found the directory!"
    exit 0
}
else {
    Write-Host "I could not find the directory!"
    exit 2
}

When I run the plugin test through the Dataloop site, this prints out the "I could not find the directory!" message along with the correct exit code of 2. When I change the path it's testing to an existing directory, it does exit with 0 and the correct output message. Everything seems to work as expected before until I move to the next part.

Inside Dataloop, I'd attempt to add a widget, set the source to one of my agents, select the "status" metric for my test plugin (the powershell script). The widget just appears with a gray screen when it should be green since the directory path does exist...

Has anyone had success with this? I checked out their documentation and tried the steps outlined there but have had no success.

Body:
For anyone who's interested, this is actually a bug in the dataloop agent v1.1. Updated to v1.3 and code executes properly and reports the correct exit code.

On a side note, I had to use the function below to get dataloop to report properly as well instead of the "exit [int]" in my original code above:

function ExitWithCode {
    param($exitcode)

    $host.SetShouldExit($exitcode)
    exit
}


问:
extended class doesnt accept extended class type
In WolfStateController.Start() im trying to set State TrueState to WolfIdleState that inherits from State. </p>

<p>But WolfStateController extends StateController. Still its not accepted. Look at the Start method ive written the error message. Is this supposed to be possible? Either im missing something regarding polymorphism or my syntax is wrong. </p>

```<code>    // STATECONTROLLER

public class StateController : MonoBehaviour

{
    public State<StateController> CurrentState;
}

public class WolfStateController : StateController
{
    void Start()
    {
        var idleState = new WolfIdleState();
        var keyPressDecision = new KeyPressedDecision(KeyCode.Space);

        // FOLLOWING GIVES ERROR:
        // Cannot implicity convert WolfIdleState to State<StateController>
        keyPressDecision.TrueState = idleState;
    }
}

// STATE

    public abstract class State<SC>  where SC : StateController
    {
    }

   public abstract class WolfState : State<WolfStateController>
   {
   }

  public class WolfIdleState : WolfState
   {
   }

    // DECISIONS

public abstract class StateDecision<SC> where SC : StateController
{

    public State<SC> TrueState;
}

public class KeyPressedDecision : StateDecision<StateController>
{

}
</code>```

答:
The error is correct. I think you need to check out the following article on covariance and contravariance.

https://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx

You could probably achieve what you want by using an interface.

Body:
In WolfStateController.Start() im trying to set State TrueState to WolfIdleState that inherits from State.

But WolfStateController extends StateController. Still its not accepted. Look at the Start method ive written the error message. Is this supposed to be possible? Either im missing something regarding polymorphism or my syntax is wrong.

    // STATECONTROLLER

public class StateController : MonoBehaviour

{
    public State<StateController> CurrentState;
}

public class WolfStateController : StateController
{
    void Start()
    {
        var idleState = new WolfIdleState();
        var keyPressDecision = new KeyPressedDecision(KeyCode.Space);

        // FOLLOWING GIVES ERROR:
        // Cannot implicity convert WolfIdleState to State<StateController>
        keyPressDecision.TrueState = idleState;
    }
}

// STATE

    public abstract class State<SC>  where SC : StateController
    {
    }

   public abstract class WolfState : State<WolfStateController>
   {
   }

  public class WolfIdleState : WolfState
   {
   }

    // DECISIONS

public abstract class StateDecision<SC> where SC : StateController
{

    public State<SC> TrueState;
}

public class KeyPressedDecision : StateDecision<StateController>
{

}


问:
wireshark 802.11 wlan_radio.duration wlan_radio.preamble
I am using wireshark in linux to capture 802.11 packet. When I see the resolution result, I see the durationt, preamble, then I find it is actually wlan_radio.duration, wlan_radio.preamble. wlan_radio.preamble is matched with the 802.11 protocol, and its meaning is obvious. But what does wlan_radio.duration mean? When I use (frame length - radiotaoheader length)*8/data rate, then plus preamble time, it is not equal to duration?

So, what does wlan_radio.duration mean in wireshark? How/where can I find its definition?

答:
wlan_radio.preamble is duration of the PLCP or preamble in microseconds, calculated from PHY data.

wlan_radio.duration is total duration of the frame in microseconds, including any preamble or PLCP header
and it calculated from the frame length, modulation and other PHY data.

This info you can find in packet-ieee80211-radio.c


问:
Combining ifelse and any to create new column - R 3.3.2 Windows 7
I have a data.table and I'm trying to create a new column by checking to see if a row has particular values in any of a given set of columns.

```<code>head(d1)

   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA
</code>```

What I want to happen is if any of the "drug" columns == "Macrolides" AND any of the same columns == "Cephalosporins" then my new column, "correct" == 1 otherwise "correct" == 0 (or it could be logical), like so:

```<code>head(d1)
   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12 correct
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA   1
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA   0
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA   1
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA   0
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
</code>```

I've tried both of these (but am still learning how to decipher warning messages so those don't help much, especially as I am new to data.table):

```<code>> d1$correct<-ifelse(d1[,c(3:14)]=="Macrolides" | d1[,c(3:14)]=="Cephalosporins", 1, 0)
Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
  12 column matrix RHS of := will be treated as one vector
2: In `[<-.data.table`(x, j = name, value = value) :
  Supplied 56868 items to be assigned to 4739 items of column 'correct' (52129 unused)
>
>
> selected_cols<-c("drug1", "drug2", "drug3", "drug4", "drug5", "drug6", "drug7", "drug8", "drug9", "drug10", "drug11", "drug12")
> d1$correct<-ifelse(d1 %in% selected_cols=="Macrolides" | d1 %in% selected_cols=="Cephalosporins", 1, 0)
Warning message:
In `[<-.data.table`(x, j = name, value = value) :
  Supplied 16 items to be assigned to 4739 items of column 'correct' (recycled leaving remainder of 3 items).
</code>```

The closest I've gotten is this:

```<code>d1$correct<-apply(d1, 1, function(r) any(r %in% c("Macrolides", "Cephalosporins")))
</code>```

Which will give TRUE if either of those is true across columns, but I can't figure out how to do it if both of those is true across columns. I'd prefer to not have to use a stunningly massive ifelse statement, since I have 12 columns and more combinations I'll need to make, and the NA's throw it off anyway.

I'd love a dplyr or data.table solution since those are so elegant, but at this point I'm desperate.

答:
Okay I built an example and tried it out. Not a dplyr/tidyr method though.

```<code>d1 <- data.table::data.table(x_key = c(-101,-102,-103), y_key = c(669,668,667),
                            drug1 = c("Macrolides",NA,"Macrolides"),
                            drug2 = c(NA, "Cephalosporins", "Cephalosporins"))

   x_key y_key      drug1          drug2
1:  -101   669 Macrolides             NA
2:  -102   668         NA Cephalosporins
3:  -103   667 Macrolides Cephalosporins

d1$correct <- rowSums(apply(d1, 2, function(r) (r %in% c("Macrolides", "Cephalosporins")))[,-c(1:2)]*1)>=2
d1
   x_key y_key      drug1          drug2  correct
1:  -101   669 Macrolides             NA    FALSE
2:  -102   668         NA Cephalosporins    FALSE
3:  -103   667 Macrolides Cephalosporins     TRUE
</code>```

The problem you were having is you were doing your apply with an index of 1, while you really wanted an index of 2. This checks if there are at least 2 TRUEs which will only work the way you want it to if you don't repeat the same drug (e.g., 2 Macrolides means 2 TRUES and thus, correct == TRUE).

Body:
I have a data.table and I'm trying to create a new column by checking to see if a row has particular values in any of a given set of columns.

head(d1)

   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA

What I want to happen is if any of the "drug" columns == "Macrolides" AND any of the same columns == "Cephalosporins" then my new column, "correct" == 1 otherwise "correct" == 0 (or it could be logical), like so:

head(d1)
   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12 correct
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA   1
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA   0
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA   1
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA   0
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA   0

I've tried both of these (but am still learning how to decipher warning messages so those don't help much, especially as I am new to data.table):

> d1$correct<-ifelse(d1[,c(3:14)]=="Macrolides" | d1[,c(3:14)]=="Cephalosporins", 1, 0)
Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
  12 column matrix RHS of := will be treated as one vector
2: In `[<-.data.table`(x, j = name, value = value) :
  Supplied 56868 items to be assigned to 4739 items of column 'correct' (52129 unused)
>
>
> selected_cols<-c("drug1", "drug2", "drug3", "drug4", "drug5", "drug6", "drug7", "drug8", "drug9", "drug10", "drug11", "drug12")
> d1$correct<-ifelse(d1 %in% selected_cols=="Macrolides" | d1 %in% selected_cols=="Cephalosporins", 1, 0)
Warning message:
In `[<-.data.table`(x, j = name, value = value) :
  Supplied 16 items to be assigned to 4739 items of column 'correct' (recycled leaving remainder of 3 items).

The closest I've gotten is this:

d1$correct<-apply(d1, 1, function(r) any(r %in% c("Macrolides", "Cephalosporins")))

Which will give TRUE if either of those is true across columns, but I can't figure out how to do it if both of those is true across columns. I'd prefer to not have to use a stunningly massive ifelse statement, since I have 12 columns and more combinations I'll need to make, and the NA's throw it off anyway.

I'd love a dplyr or data.table solution since those are so elegant, but at this point I'm desperate.

Body:
Okay I built an example and tried it out. Not a dplyr/tidyr method though.

d1 <- data.table::data.table(x_key = c(-101,-102,-103), y_key = c(669,668,667),
                            drug1 = c("Macrolides",NA,"Macrolides"),
                            drug2 = c(NA, "Cephalosporins", "Cephalosporins"))

   x_key y_key      drug1          drug2
1:  -101   669 Macrolides             NA
2:  -102   668         NA Cephalosporins
3:  -103   667 Macrolides Cephalosporins

d1$correct <- rowSums(apply(d1, 2, function(r) (r %in% c("Macrolides", "Cephalosporins")))[,-c(1:2)]*1)>=2
d1
   x_key y_key      drug1          drug2  correct
1:  -101   669 Macrolides             NA    FALSE
2:  -102   668         NA Cephalosporins    FALSE
3:  -103   667 Macrolides Cephalosporins     TRUE

The problem you were having is you were doing your apply with an index of 1, while you really wanted an index of 2. This checks if there are at least 2 TRUEs which will only work the way you want it to if you don't repeat the same drug (e.g., 2 Macrolides means 2 TRUES and thus, correct == TRUE).


问:
Java enhanced enhanced for loop
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

```<code>int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}
</code>```

答: There isn't way right now unless you keep a counter! I know this is ugly, but java 7 will be better. I don't know why other people are saying we don't need it. Sometimes we need to know what is last member, or odd member, etc.</p>

Title: Java enhanced enhanced for loop

Body:
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}


问:
Launch App1 from App2,then press home button to the home screen,and open App1 again by press icon,why onCreate get called?
I launched App1 from App2, and here are the methods in App2:

```<code>Intent resolveIntent = getPackageManager()
    .getLaunchIntentForPackage("com.example.weijunhao.launchmode");
startActivity(resolveIntent);
</code>```

Then I press the home button to go to the home screen and I open App2 by pressing the launch icon.

Why does the onCreate method get called and not the onRestart method?

答:
When an Activity is no longer visible (like when you press the home button) it goes to the stopped state. From that state it may need to go through the onCreate() method if the system has killed the process to release memory for apps in the foreground (or system processes, I suppose).

There's a nice life-cycle diagram in Android documentation.

Body:
I launched App1 from App2, and here are the methods in App2:

Intent resolveIntent = getPackageManager()
    .getLaunchIntentForPackage("com.example.weijunhao.launchmode");
startActivity(resolveIntent);

Then I press the home button to go to the home screen and I open App2 by pressing the launch icon.

Why does the onCreate method get called and not the onRestart method?


问:
Using match in R, but keeping subsequent instances
I have a data frame:

```<code>df <- data.frame(name = c('a', 'b', 'c', 'd', 'a', 'b', 'a'), value = c(rep(TRUE, 4), rep(FALSE, 3)))
</code>```

and a target:

```<code>target <- c('b', 'a', 'd', 'c')
</code>```

I know that if I run the following,

```<code>new_df <- df[match(target, df$name), ]
</code>```

it will return df in the order of the target, BUT only the first instance. In the sample data, I have subsequent instances of 'a' and 'b' in df$name. How can I preserve those? I do not care where they occur, only that they remain. The first instance of any name should be in the order of target (so 'a' must appear before 'd' or 'c'), but after that I don't care.

答:
How about this?

```<code>df <- data.frame(name = c('a', 'b', 'c', 'd', 'a', 'b', 'a'),
   value = c(rep(TRUE, 4), rep(FALSE, 3)))

target <- c('b', 'a', 'd', 'c')

> df[unlist(sapply(target, function(e) which(df$name == e))),]
</code>```

Result:

```<code>  name value
2    b  TRUE
6    b FALSE
1    a  TRUE
5    a FALSE
7    a FALSE
4    d  TRUE
3    c  TRUE
</code>```

Body:
I have a data frame:

df <- data.frame(name = c('a', 'b', 'c', 'd', 'a', 'b', 'a'), value = c(rep(TRUE, 4), rep(FALSE, 3)))

and a target:

target <- c('b', 'a', 'd', 'c')

I know that if I run the following,

new_df <- df[match(target, df$name), ]

it will return df in the order of the target, BUT only the first instance. In the sample data, I have subsequent instances of 'a' and 'b' in df$name. How can I preserve those? I do not care where they occur, only that they remain. The first instance of any name should be in the order of target (so 'a' must appear before 'd' or 'c'), but after that I don't care.

Body:
How about this?

df <- data.frame(name = c('a', 'b', 'c', 'd', 'a', 'b', 'a'),
   value = c(rep(TRUE, 4), rep(FALSE, 3)))

target <- c('b', 'a', 'd', 'c')

> df[unlist(sapply(target, function(e) which(df$name == e))),]

Result:

  name value
2    b  TRUE
6    b FALSE
1    a  TRUE
5    a FALSE
7    a FALSE
4    d  TRUE
3    c  TRUE


问:
Is there any replacement for push notification in Ionic 2?
For some reasons I can not use push notification but I had to have such this ability in my application that send a notification from back-end (Oracle Apex) to special available user's application. One possible way I think is using SMS but I don't know is there any better way?

答:
You can push notifications to users when certain actions are triggered with Toast,
http://ionicframework.com/docs/v2/api/components/toast/ToastController/

The API docs give some background on them, I'd suggest starting from there


问:
Why my select with an expression in 'where' clause doesn't work?
I am trying to do something like </p>

```<code>SELECT *
FROM bucket bck
WHERE bck.type = 'Beer'
    and ARRAY_LENGTH(bck.path.to.array) > 1
</code>```

<p>Unfortunately, this select returns nothing. </p>

答:
The predicate might be evaluated to false. Check by running this and see what values it returns
SELECT ARRAY_LENGTH(bck.path.to.array) FROM  \bucket bck WHERE bck.type = 'Beer';</p>

Body:
I am trying to do something like

SELECT *
FROM bucket bck
WHERE bck.type = 'Beer'
    and ARRAY_LENGTH(bck.path.to.array) > 1

Unfortunately, this select returns nothing.


问:
jQuery detect mousedown inside an element and then mouseup outside the element
I have something similar to a drawing canvas, and I capture it's state on mouseup for undo purposes. The canvas isn't full screen, so you can draw with a brush and release outside the canvas. Something like this:

```<code>$("#element").mousedown(function(){
  $(document).mouseup(function(){
    //do something
  });
});
</code>```

But this doesn't work of course. A plain $(document).mouseup doesn't work either, because I have many other UI elements and it saves the state each time you click on a UI element.

Any ideas?

答:
Hopefully you find this little solution to be helpful. You can see it in action here:
http://jsfiddle.net/neopreneur/PR2yE/</p>

```<code>$(document).ready(function(){
    var startMouseDownElement = null;

    $('#element').mousedown(function(){
        // do whatever
        //...

        // set mousedown start element
        startMouseDownElement = $(this);
    });

    // handle bad mouseup
    // $('#container, #container *').mouseup would be more efficient in a busy DOM
    $('body *').mouseup(function(event){
        event.stopPropagation(); // stop bubbling
        if($(this).attr('id') != $(startMouseDownElement).attr('id')){
            //oops, bad mouseup
            alert('bad mouseup :(');
        }
    });
});
</code>```

Body:
I have something similar to a drawing canvas, and I capture it's state on mouseup for undo purposes. The canvas isn't full screen, so you can draw with a brush and release outside the canvas. Something like this:

$("#element").mousedown(function(){
  $(document).mouseup(function(){
    //do something
  });
});

But this doesn't work of course. A plain $(document).mouseup doesn't work either, because I have many other UI elements and it saves the state each time you click on a UI element.

Any ideas?

Body:
Hopefully you find this little solution to be helpful. You can see it in action here:
http://jsfiddle.net/neopreneur/PR2yE/

$(document).ready(function(){
    var startMouseDownElement = null;

    $('#element').mousedown(function(){
        // do whatever
        //...

        // set mousedown start element
        startMouseDownElement = $(this);
    });

    // handle bad mouseup
    // $('#container, #container *').mouseup would be more efficient in a busy DOM
    $('body *').mouseup(function(event){
        event.stopPropagation(); // stop bubbling
        if($(this).attr('id') != $(startMouseDownElement).attr('id')){
            //oops, bad mouseup
            alert('bad mouseup :(');
        }
    });
});


问:
Using RubyMine, how do I fix "Get available generators script executes with errors" warning?
In RubyMine 2017.1 (and maybe earlier), the "Messages" Tool Window, opens with the title "Messages  Get available generators list" and displays

```<code>Warning:Get available generators script executes with errors:
Warning:Expected string default value for '--serializer'; got true (boolean)
</code>```

This happens each time I open the project, but also after certain events.

答:
I do not know of a fix at this time, but a work-around is to downgrade the thor gem from 0.19.4 to 0.19.1.

```<code>gem 'thor', '0.19.4'
</code>```

and

```<code>bundle update thor
</code>```

This appears to be expected behavior in thor > 0.19.1, and the gems that are using thor are expected to fix the problems with invalid parameters.  See https://github.com/erikhuda/thor/issues/538

Body:
In RubyMine 2017.1 (and maybe earlier), the "Messages" Tool Window, opens with the title "Messages  Get available generators list" and displays

Warning:Get available generators script executes with errors:
Warning:Expected string default value for '--serializer'; got true (boolean)

This happens each time I open the project, but also after certain events.

Body:
I do not know of a fix at this time, but a work-around is to downgrade the thor gem from 0.19.4 to 0.19.1.

gem 'thor', '0.19.4'

and

bundle update thor

This appears to be expected behavior in thor > 0.19.1, and the gems that are using thor are expected to fix the problems with invalid parameters.  See https://github.com/erikhuda/thor/issues/538


问:
OpenCart custom page not accessible
I have a custom page in the backend (admin) of my OpenCart site. It is an exact copy of admin/view/template/sale/order_info.tpl but with a few minor cosmetic changes. It is located at admin/view/template/sale/order_preview.tpl. I have also created a copy of admin/controller/sale/order.php, and called it admin/controller/sale/order_preview.php, and modified the first line so that it reads:

```<code>class ControllerSaleOrderPreview extends Controller {
</code>```

but when I try to access the page at the url "http://www.example.com/admin/index.php?route=sale/order/preview&token=BtkiB5js5u3hkXBYrFlGgz39dWtrQ4Ww&order_id=2" I get "Page Not Found!" every time.

What else do I need in order to be able to access this page? This is in OpenCart 2.3.0.2.

答:
Your url is wrong based on how you created the page.

route=sale/order/preview

This will call the function preview in your sale/order controller.  Since you created a new controller for your changes, the route is going to be different. Change the route to match the new controller.

route=sale/order_preview

The thing to keep in mind is the route parameter is all about pointing you at a controller, so it is the controller filename you want to pay attention to.  Opencart uses the convention of route=folder/controllerFilename/methodToCall If you omit the third part  route=folder/controllerFilename, index is the default method called.

Title: OpenCart custom page not accessible

Body:
I have a custom page in the backend (admin) of my OpenCart site. It is an exact copy of admin/view/template/sale/order_info.tpl but with a few minor cosmetic changes. It is located at admin/view/template/sale/order_preview.tpl. I have also created a copy of admin/controller/sale/order.php, and called it admin/controller/sale/order_preview.php, and modified the first line so that it reads:

class ControllerSaleOrderPreview extends Controller {

but when I try to access the page at the url "http://www.example.com/admin/index.php?route=sale/order/preview&token=BtkiB5js5u3hkXBYrFlGgz39dWtrQ4Ww&order_id=2" I get "Page Not Found!" every time.

What else do I need in order to be able to access this page? This is in OpenCart 2.3.0.2.


问:
How can I order this struct using qsort()?
I have these structs,

```<code> typedef struct
{
  int votos; //Votes
  float classifica; //Rating
  char* titulo; //Title
  int ano;     //Year
} vg_elemento;

/**
* this register has a vetorg of elements a counter for the size and a counter for the capacity
*/
typedef struct
{
  /** numero de elementos do vetorg */
  int tamanho;       //size

  /** capacidade do vetorg */
  int capacidade; //capacity

  /** array of stored elements */
  vg_elemento* elementos;

} vetorg;
</code>```

I heard that there is a qsort() function that allows me to sort an array, I tried checking the internet but all examples either use int, float or strings. How can I use the qsort() function using the structures above?

I have some comparing functions, already given:

```<code> typedef int (*comp)(const vg_elemento a, const vg_elemento b);

int comp_ano_asc(const vg_elemento a, const vg_elemento b){ //sorts bt year
    if(b.ano > a.ano)
        return -1;
    if(a.ano > b.ano)
        return 1;
    return 0;
}

int comp_votos_asc(const vg_elemento a, const vg_elemento b) //sorts by votes
{
    if(b.votos > a.votos)
        return -1;
    if(a.votos > b.votos)
        return 1;
    return 0;
}

int comp_classifica_asc(const vg_elemento a, const vg_elemento b) //sorts by rating
{
    if(b.classifica > a.classifica)
        return -1;
    if(a.classifica > b.classifica)
        return 1;
    return 0;
}

int comp_titulo_asc(const vg_elemento a, const vg_elemento b) //sorts by title (alphabetically)
{
    if(strcmp(b.titulo,a.titulo)>0)
        return -1;
    if(strcmp(a.titulo,b.titulo)>0)
        return 1;
    return 0;
}
</code>```

I want to sort the array using a function, calling qsort() in that function. Eg:

```<code>    int vetorg_ordena(vetorg* vec, comp ordem){

    //sorts the array according to ordem in an ascending order. returns 0, if successful
}
</code>```

Here's an example of a sample array of size 3:

```<code>Votes Rating Year Title
319656 8.8 2010 Inception
511125 8.8 2008 The Dark Knight
227431 8.3 1983 Star Wars: Episode VI - Return of the Jedi
</code>```

答:
If you read e.g. this qsort reference you will see that the comparison function gets passed pointers. The pointers it gets passes are pointers to elements in the array being sorted.

So if you have an array of vg_elemento like

```<code>vg_elemento videos[SOME_SIZE];
</code>```

Then the comparison function is basically called like

```<code>comp(&videos[i], &videos[j]);
</code>```

That in turns means your functions should look like

```<code>int comp_ano_asc(const void *a, const void *b){ //sorts bt year
    const vg_elemento *va = (vg_elemento *) a;
    const vg_elemento *vb = (vg_elemento *) b;

    if(vb->ano > va->ano)
        return -1;
    if(ba->ano > vb->ano)
        return 1;
    return 0;
}
</code>```

Body:
I have these structs,

 typedef struct
{
  int votos; //Votes
  float classifica; //Rating
  char* titulo; //Title
  int ano;     //Year
} vg_elemento;

/**
* this register has a vetorg of elements a counter for the size and a counter for the capacity
*/
typedef struct
{
  /** numero de elementos do vetorg */
  int tamanho;       //size

  /** capacidade do vetorg */
  int capacidade; //capacity

  /** array of stored elements */
  vg_elemento* elementos;

} vetorg;

I heard that there is a qsort() function that allows me to sort an array, I tried checking the internet but all examples either use int, float or strings. How can I use the qsort() function using the structures above?

I have some comparing functions, already given:

 typedef int (*comp)(const vg_elemento a, const vg_elemento b);

int comp_ano_asc(const vg_elemento a, const vg_elemento b){ //sorts bt year
    if(b.ano > a.ano)
        return -1;
    if(a.ano > b.ano)
        return 1;
    return 0;
}

int comp_votos_asc(const vg_elemento a, const vg_elemento b) //sorts by votes
{
    if(b.votos > a.votos)
        return -1;
    if(a.votos > b.votos)
        return 1;
    return 0;
}

int comp_classifica_asc(const vg_elemento a, const vg_elemento b) //sorts by rating
{
    if(b.classifica > a.classifica)
        return -1;
    if(a.classifica > b.classifica)
        return 1;
    return 0;
}

int comp_titulo_asc(const vg_elemento a, const vg_elemento b) //sorts by title (alphabetically)
{
    if(strcmp(b.titulo,a.titulo)>0)
        return -1;
    if(strcmp(a.titulo,b.titulo)>0)
        return 1;
    return 0;
}

I want to sort the array using a function, calling qsort() in that function. Eg:

    int vetorg_ordena(vetorg* vec, comp ordem){

    //sorts the array according to ordem in an ascending order. returns 0, if successful
}

Here's an example of a sample array of size 3:

Votes Rating Year Title
319656 8.8 2010 Inception
511125 8.8 2008 The Dark Knight
227431 8.3 1983 Star Wars: Episode VI - Return of the Jedi

Body:
If you read e.g. this qsort reference you will see that the comparison function gets passed pointers. The pointers it gets passes are pointers to elements in the array being sorted.

So if you have an array of vg_elemento like

vg_elemento videos[SOME_SIZE];

Then the comparison function is basically called like

comp(&videos[i], &videos[j]);

That in turns means your functions should look like

int comp_ano_asc(const void *a, const void *b){ //sorts bt year
    const vg_elemento *va = (vg_elemento *) a;
    const vg_elemento *vb = (vg_elemento *) b;

    if(vb->ano > va->ano)
        return -1;
    if(ba->ano > vb->ano)
        return 1;
    return 0;
}


问:
retrieving json data from mysql and php into jquery
I am trying to bring mysql data into jquery by using php, I get the data into a JSON format like this.

```<code>{"uid":"33","title":"Apple, Peach, Grapefruit","ing1":"apple","qty1":"1","meas1":"whole","ing2":"peaches \/ halved and","qty2":"2","meas2":"each","ing3":"grapefruit \/ peeled","qty3":"2","meas3":"each","ing4":"","qty4":"0","meas4":"each","ing5":"","qty5":"0","meas5":"each","ing6":"","qty6":"0","meas6":"each","ing7":"","qty7":"0","meas7":"each","ing8":"","qty8":"0","meas8":"each","ing9":"","qty9":"0","meas9":"each","ing10":"","qty10":"0","meas10":"each","servings":"2","benefits":""}
</code>```

using this following code:

```<code>require_once'connect.php';
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);

$num_rows = mysqli_affected_rows($conn);
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo $data;
}
</code>```

I am using jquery .get to pull it into the web page with this code.

```<code>$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(data);
});
});
</code>```

It displays the json data as above.  I would like to be able to access the different elements individually, how do I do that?

答:
Retrieve the json data to use json response jquery parse function. json data using this function
jQuery.parseJSON()

http://api.jquery.com/jquery.parsejson/

Body:
I am trying to bring mysql data into jquery by using php, I get the data into a JSON format like this.

{"uid":"33","title":"Apple, Peach, Grapefruit","ing1":"apple","qty1":"1","meas1":"whole","ing2":"peaches \/ halved and","qty2":"2","meas2":"each","ing3":"grapefruit \/ peeled","qty3":"2","meas3":"each","ing4":"","qty4":"0","meas4":"each","ing5":"","qty5":"0","meas5":"each","ing6":"","qty6":"0","meas6":"each","ing7":"","qty7":"0","meas7":"each","ing8":"","qty8":"0","meas8":"each","ing9":"","qty9":"0","meas9":"each","ing10":"","qty10":"0","meas10":"each","servings":"2","benefits":""}

using this following code:

require_once'connect.php';
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);

$num_rows = mysqli_affected_rows($conn);
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo $data;
}

I am using jquery .get to pull it into the web page with this code.

$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(data);
});
});

It displays the json data as above.  I would like to be able to access the different elements individually, how do I do that?


问:
Is it possible to echo a specific cell from mysql?
I have a table with a column 'k1'. In the table there's a lot of rows all attached to the id of the user who submitted them. How can I echo them on my site in a specific place?
I called

SELECT * FROM table

but if I echo rows ['k1'] I can't control which row it echoes? Make sense?
Can you help me?

答:
```<code>$result = @mysql_query("SELECT * FROM table");

$k1 = Array();

//Fetch the query
while($row = mysql_fetch_assoc($result))

{

//Column from the databases

$k1[] = $row['k1'];

}
</code>```

You now have all of the K1 rows in an array to grab which one you want by an index number

or.....

```<code>$result = @mysql_query("SELECT * FROM table WHERE id = ?");
</code>```

if an ID Exists

Body:
$result = @mysql_query("SELECT * FROM table");

$k1 = Array();

//Fetch the query
while($row = mysql_fetch_assoc($result))

{

//Column from the databases

$k1[] = $row['k1'];

}

You now have all of the K1 rows in an array to grab which one you want by an index number

or.....

$result = @mysql_query("SELECT * FROM table WHERE id = ?");

if an ID Exists