问:
Use the result of a function call in next function
I want to combine the result of two asynchronouse function calls. I tried to get that as seperate functions.

```<code>$scope.showPage = function () {
    var base ="";
    var menu= "";
    service.getGUI('menu', function (reply) {
            if (reply.status === 200 && reply.data !== null) {
               menu = reply.data;
            }
        });

    service.getGUI('base', function (reply) {
            if (reply.status === 200 && reply.data !== null) {
               base=reply.data;
        });

console.log("base:"+ base);
console.log("menu:"+ menu);
}
</code>```

But the console output is not updating as expected. How can I execute is one by one and use the result of the first one in second function.

答:
Your calls are both async so there is no consistency for what order the functions will finish in.  You can use the promise reduce pattern to accomplish wait until both are resolved before accessing the data.  While the promise reduce may not seem the best on the surface when you are dealing with 20+ async calls you will appreciate not having to continue nesting.</p>

```<code>$scope.showPage = function () {
  var results = { base: "", menu: "" };

  ['menu', 'base'].reduce(function(acc, current) {
    return acc.then(new Promise(function(resolve, reject) => {
      service.getGUI(current, function (reply) {
        if (reply.status === 200 && reply.data !== null) {
           results[current] = reply.data;
           resolve(results);
        } else {
           reject("error")
        }
      });
    }));
  }, Promise.resolve()).then(function(res) {
    console.log(res.menu, res.base);
  }).catch(function(e) {
    console.log('errors have occured', e);
  });
}
</code>```

Body:
I want to combine the result of two asynchronouse function calls. I tried to get that as seperate functions.

$scope.showPage = function () {
    var base ="";
    var menu= "";
    service.getGUI('menu', function (reply) {
            if (reply.status === 200 && reply.data !== null) {
               menu = reply.data;
            }
        });

    service.getGUI('base', function (reply) {
            if (reply.status === 200 && reply.data !== null) {
               base=reply.data;
        });

console.log("base:"+ base);
console.log("menu:"+ menu);
}

But the console output is not updating as expected. How can I execute is one by one and use the result of the first one in second function.

Body:
Your calls are both async so there is no consistency for what order the functions will finish in.  You can use the promise reduce pattern to accomplish wait until both are resolved before accessing the data.  While the promise reduce may not seem the best on the surface when you are dealing with 20+ async calls you will appreciate not having to continue nesting.

$scope.showPage = function () {
  var results = { base: "", menu: "" };

  ['menu', 'base'].reduce(function(acc, current) {
    return acc.then(new Promise(function(resolve, reject) => {
      service.getGUI(current, function (reply) {
        if (reply.status === 200 && reply.data !== null) {
           results[current] = reply.data;
           resolve(results);
        } else {
           reject("error")
        }
      });
    }));
  }, Promise.resolve()).then(function(res) {
    console.log(res.menu, res.base);
  }).catch(function(e) {
    console.log('errors have occured', e);
  });
}


来源: stackexchange

问:
How can I make a clickable UILabel in Swift 3?
I'm trying to make a clickable UILabel by following this code:

```<code>class ViewNotificationsDetails: UIViewController {
   @IBOutlet weak var back: UILabel!

      override func viewDidLoad() {
          super.viewDidLoad()

          let tap = UITapGestureRecognizer(target: self, action: #selector(ViewNotificationsDetails.tapFunction))
          back.isUserInteractionEnabled = true
          back.addGestureRecognizer(tap)
      }

      @objc func tapFunction(sender:UITapGestureRecognizer) {
          print("tap working")
      }
}
</code>```

But when executing the code, I get the error ->

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
  Optional value on the line "back.isUserInteractionEnabled = true".

What could be the problem?

答:
try this code, is working well with me

```<code>class ViewController: UIViewController {
@IBOutlet weak var cliclableLable: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
    cliclableLable.isUserInteractionEnabled = true
    cliclableLable.addGestureRecognizer(tap)
}

func tapFunction(sender:UITapGestureRecognizer) {
    print("tap working")
}
</code>```

}

also don't forget to link your label with the code

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a clickable UILabel by following this code:

class ViewNotificationsDetails: UIViewController {
   @IBOutlet weak var back: UILabel!

      override func viewDidLoad() {
          super.viewDidLoad()

          let tap = UITapGestureRecognizer(target: self, action: #selector(ViewNotificationsDetails.tapFunction))
          back.isUserInteractionEnabled = true
          back.addGestureRecognizer(tap)
      }

      @objc func tapFunction(sender:UITapGestureRecognizer) {
          print("tap working")
      }
}

But when executing the code, I get the error ->

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
  Optional value on the line "back.isUserInteractionEnabled = true".

What could be the problem?

Body:
try this code, is working well with me

class ViewController: UIViewController {
@IBOutlet weak var cliclableLable: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
    cliclableLable.isUserInteractionEnabled = true
    cliclableLable.addGestureRecognizer(tap)
}

func tapFunction(sender:UITapGestureRecognizer) {
    print("tap working")
}

}

also don't forget to link your label with the code


问:
How can I store the text entered into a html textarea into a javascript variable?
I want to store the text users enter into a textarea in a website into a javascript variable in order to compare it to another variable already defined.

How would you do it? Any hints? Thanks in advance!

答:
using jquery

```<code>var n=$('#textarea_id').val();
</code>```

using javascript

```<code>var n=document.getElementById('textAreaID').value;
</code>```

Body:
using jquery

var n=$('#textarea_id').val();

using javascript

var n=document.getElementById('textAreaID').value;


问:
Identifying Bullets in Ms Word, using Apache POI
I'm trying to make an application which would read a word file (docx) and do some stuff with it. So far, I've done pretty much everything except for to identify bullets.
I can find isBold(), isItalic(), isStrike() but I cannot seem to find isBullet()

can anyone please tell me how to identify bullets?

the application is built in Java

答:
You can use below code for  getting list of all the bullets from the word document. I have used apache poi's  XWPF api.</p>

```<code>public class ListTest {

   public static void main(String[] args) {
    String filename = "file_path";
        List<String> paraList = new ArrayList<String>();
        try {
            // is = new FileInputStream(fileName);
            XWPFDocument doc =
               new XWPFDocument(OPCPackage.open(filename));
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            for(XWPFParagraph para :paragraphList) {
                if((para.getStyle()!=null) && (para.getNumFmt() !=null)) {
                  paraList.add(para.getText());
            }
            for(String bullet :paraList) {
                System.out.println(bullet);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

Body:
You can use below code for  getting list of all the bullets from the word document. I have used apache poi's  XWPF api.

public class ListTest {

   public static void main(String[] args) {
    String filename = "file_path";
        List<String> paraList = new ArrayList<String>();
        try {
            // is = new FileInputStream(fileName);
            XWPFDocument doc =
               new XWPFDocument(OPCPackage.open(filename));
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            for(XWPFParagraph para :paragraphList) {
                if((para.getStyle()!=null) && (para.getNumFmt() !=null)) {
                  paraList.add(para.getText());
            }
            for(String bullet :paraList) {
                System.out.println(bullet);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}


问:
Is this a bash bug? (list directories with ls)
If I want to list all files and directories in the following directory :

```<code>[root@centos2 dir1]# tree
.
+-- dir2
    +-- coucou.txt

1 directory, 1 file
</code>```

Why dir2 is not shown below? Only the file is shown.

```<code>[root@centos2 dir1]# ls -l *
total 0
-rwxr--r-- 1 root root 0 Dec  2 18:20 coucou.txt
</code>```

If I copy the directory and list, they are both shown :

```<code>[root@centos2 dir1]# cp -r dir2/ dir3
[root@centos2 dir1]# tree
.
+-- dir2
¦   +-- coucou.txt
+-- dir3
    +-- coucou.txt

2 directories, 2 files

[root@centos2 dir1]# ls -l *
dir2:
total 0
-rwxr--r-- 1 root root 0 Dec  2 18:20 coucou.txt

dir3:
total 0
-rwxr--r-- 1 root root 0 Dec  5 11:34 coucou.txt
</code>```

答:
No, it's not a bug; it's the expected behaviour of the shell to expand * to match everything. The * is replaced by a list of arguments, one for each matching path, before the command is run.

In your first example, ls -l *, the shell expands * to dir2, so your command is ls -l dir2. ls then just lists the contents of that directory, so you get your file coucou.txt.

In your second example, * is expanded to two arguments, dir2 and dir3. In this case, the behaviour of ls -l is to separately list the contents of each directory.

Body:
If I want to list all files and directories in the following directory :

[root@centos2 dir1]# tree
.
+-- dir2
    +-- coucou.txt

1 directory, 1 file

Why dir2 is not shown below? Only the file is shown.

[root@centos2 dir1]# ls -l *
total 0
-rwxr--r-- 1 root root 0 Dec  2 18:20 coucou.txt

If I copy the directory and list, they are both shown :

[root@centos2 dir1]# cp -r dir2/ dir3
[root@centos2 dir1]# tree
.
+-- dir2
¦   +-- coucou.txt
+-- dir3
    +-- coucou.txt

2 directories, 2 files

[root@centos2 dir1]# ls -l *
dir2:
total 0
-rwxr--r-- 1 root root 0 Dec  2 18:20 coucou.txt

dir3:
total 0
-rwxr--r-- 1 root root 0 Dec  5 11:34 coucou.txt


答:
If you use the command like that ls -l * it's like you are writing the command for every element in your current directory, changing that * with the name of your element. And when you use the command ls and the argument is a directory, it lists the elements inside, not the directory itself.

I think you are looking for a recursive ls option, which is -R:

```<code>[root@centos2 dir1]#ls -lR
.:
total 8
drwxr-xr-x 2 root root 4096 Dec  5 11:41 dir2
drwxr-xr-x 2 root root 4096 Dec  5 11:41 dir3

./dir2:
total 0
-rw-r--r-- 1 root root 0 Dec  5 11:41 cocou.txt

./dir3:
total 0
-rw-r--r-- 1 root root 0 Dec  5 11:41 cocou.txt
</code>```

Title: Is this a bash bug? (list directories with ls)

Body:
If you use the command like that ls -l * it's like you are writing the command for every element in your current directory, changing that * with the name of your element. And when you use the command ls and the argument is a directory, it lists the elements inside, not the directory itself.

I think you are looking for a recursive ls option, which is -R:

[root@centos2 dir1]#ls -lR
.:
total 8
drwxr-xr-x 2 root root 4096 Dec  5 11:41 dir2
drwxr-xr-x 2 root root 4096 Dec  5 11:41 dir3

./dir2:
total 0
-rw-r--r-- 1 root root 0 Dec  5 11:41 cocou.txt

./dir3:
total 0
-rw-r--r-- 1 root root 0 Dec  5 11:41 cocou.txt


问:
.NET C#: How to handle forms authentication expiration during an AJAX call
For context, I have a forms authentication timeout value set in my web.config, and am using ASP.NET MVC 1. I think it might be easiest to state my problem as 2 use cases -- the first one what happens without an authentication timeout, and the second one what happens with an authentication timeout:

Normal case:

The user logs into the app, and the authentication timer starts ticking. While the authentication period is still valid, the user clicks something on the page that triggers an AJAX call (through jQuery). We hit the server, process the request, and return a partial view to the user (as an ActionResult). The html comes through as a string to the ajax's success method, and I take this html and inject it into a div on the page. This is all expected.

Timed out case:

The user logs into the app, and the authentication timer starts ticking. After x amount of time, the authentication period expires. With the expiration time up, the user clicks something on the page that triggers an AJAX call (using jQuery). We hit the server, but the authentication ticket is expired. .NET automatically redirects to the loginURL value defined in the same web.config element that sets the timeout period. For me, this page is the login page where the user is asked to input username/password to log in. So the Home/Login Controller action runs, and eventually returns a full (not partial) view back as a string of html to the ajax's success method. This causes the page to bomb because I'm trying to take a full page's html (with  tags and all) and inject it into a div on the page.

So therein lies my problem. When the authentication period has expired, and .NET redirects me to the login page, I end up returning a full page's html to an ajax success method. Of course, everything works fine when the server hit isn't an AJAX call -- it redirects fine to the login page. But how can I handle this case? Does anyone have any ideas?

Thanks.

答:
so the Account/Login action get's executed when the ticket expires</p>

```<code>public Action Login()
{
   if(Request.IsAjaxRequest())
   return Content(@"<meta http-equiv="refresh" content="1" />");
   //if it is ajax request the div will be filled with this meta tag which will refresh the page

  return View();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
so the Account/Login action get's executed when the ticket expires

public Action Login()
{
   if(Request.IsAjaxRequest())
   return Content(@"<meta http-equiv="refresh" content="1" />");
   //if it is ajax request the div will be filled with this meta tag which will refresh the page

  return View();
}


问:
PHP payment gateway integration using CCAvenue
I want to pass the value for select payment mode and card type.

My code is :

```<code><form method="post" action="http://www.ccavenue.com/shopzone/cc_details.jsp" name="frmTransaction">
     <input type="hidden" name="Merchant_Id" value="<?php echo $Merchant_Id;?>">
     <input type="hidden" name="Amount" value="<?php echo $Amount;?>">
     <input type="hidden" name="Order_Id" value="<?php echo  $Order_Id;?>">
      <input type="hidden" name="Redirect_Url" value="<?php echo $Redirect_Url;?>">
       <input type="hidden" name="Checksum" value="<?php echo $Checksum; ?>">

<input type="hidden" name="Merchant_Param" value="<?php echo $Order_Id; ?>">
        <input type="hidden" name="pay_type" value="Debit Card" /> //credit card, netbanking
        <input type="hidden" name="nb_bid" value="<?php echo $bank_name;?>" /> //VISA, mastercard
</code>```

Here, How to pass pay_type and bank type and preselect the value in CCAvenue gateway. I cannot get any resource for this. Thanks in advace.

答:
I followed the below steps to integrate ccavenue in PHP

Login to ccavenue dashboard.

On the top menu bar navigate to Settings > Api keys. There you can find

 merchant_id ,access_code,Working key

Navigate to Resources > Web Integration Kit

Under this screen there is an option to select Testing and Production Environment where you can find the testing and production URL.

Testing URL is not enabled by default you need to ask the support to enable it.

On the same screen there is Download Integration Kits . Click on this and find the Download PHP kit and download the code.

Use the downloaded kit according to your requirments.Also you can find the required parameters on Integration Methods menu as i used the iframe method.

Hope this will help in integrating the payment gateway

Body:
I want to pass the value for select payment mode and card type.

My code is :

<form method="post" action="http://www.ccavenue.com/shopzone/cc_details.jsp" name="frmTransaction">
     <input type="hidden" name="Merchant_Id" value="<?php echo $Merchant_Id;?>">
     <input type="hidden" name="Amount" value="<?php echo $Amount;?>">
     <input type="hidden" name="Order_Id" value="<?php echo  $Order_Id;?>">
      <input type="hidden" name="Redirect_Url" value="<?php echo $Redirect_Url;?>">
       <input type="hidden" name="Checksum" value="<?php echo $Checksum; ?>">

<input type="hidden" name="Merchant_Param" value="<?php echo $Order_Id; ?>">
        <input type="hidden" name="pay_type" value="Debit Card" /> //credit card, netbanking
        <input type="hidden" name="nb_bid" value="<?php echo $bank_name;?>" /> //VISA, mastercard

Here, How to pass pay_type and bank type and preselect the value in CCAvenue gateway. I cannot get any resource for this. Thanks in advace.


问:
Building libcurl with SSL support on Windows
I'm using libcurl in a Win32 C++ application.

I have the curllib.vcproj project added to my solution and set my other projects to depend on it.

How do I build it with SSL support enabled?

答:
In my case follow the curl README file was enough.

My configuration is the following:

Visual Studio 2015 (VC14)

Static library

Win64

curl version 7.57.0

OpenSSL 1.0.2

Compilation of libCurl

Download libcurl source there: https://curl.haxx.se/download.html

Uncompress the file and go to the folder curl-7.57.0\projects

Open the README file and follow the instructions, this lead me to do the following:

Downloaded OpenSSL

Extract it and rename it to openssl, put it aside the curl folder, this is important as you'll open the VS project that expect to find openssl there.

Install Perl

Execute the utility build-openssl.bat to perform the compilation of openSSL. With my settings this became the following:

.\build-openssl.bat vc14 x64 release ..\..\openssl\

just runs .\build-openssl.bat -help to know more about the parameters.

After that you can see OpenSSL has been compiled as you got a new folder here: openssl\build\Win64

Open the Visual Studio project curl-7.57.0\projects\Windows\VC14\curl-all.sln

Be sure to set the visual studio project to the build configuration you need (LIB Release - LIB OpenSSL in my case)

Build all

The library is located at curl-7.57.0\build\Win64\VC14\LIB Release - LIB OpenSSL\libcurl.lib

Remarks

Don't forget to define the CURL_STATICLIB preprocessor in your own project

With static library, you will have to links with the dependencies of libcurl, see this answer

You might not want to depend on LDAP, in that case you can disable it by setting the preprocessor CURL_DISABLE_LDAP before you compile libcurl.

OwnerDisplayName: Robert A

LastEditorDisplayName: Robert A


问:
Tkinter quit freezes
I have written a very simple snippet of code just to try tkinter:

```<code>import tkinter as tk

root=tk.Tk()
frame = tk.Frame(root).pack()
button = tk.Button(frame,
                   text="next",
                   command=root.quit).pack()
root.mainloop()
</code>```

The above code causes the window to freeze. Could someone explain to me what is the reason behind this behaviour?

答:
Seperating the pack() from the initialisation lines will fix your issue.

```<code>import tkinter as tk
root=tk.Tk()
frame=tk.Frame(root)
frame.pack()
button = tk.Button(frame,text="next",command=root.quit)
button.pack()
root.mainloop()
</code>```

Title: Tkinter quit freezes

Body:
I have written a very simple snippet of code just to try tkinter:

import tkinter as tk

root=tk.Tk()
frame = tk.Frame(root).pack()
button = tk.Button(frame,
                   text="next",
                   command=root.quit).pack()
root.mainloop()

The above code causes the window to freeze. Could someone explain to me what is the reason behind this behaviour?

Body:
Seperating the pack() from the initialisation lines will fix your issue.

import tkinter as tk
root=tk.Tk()
frame=tk.Frame(root)
frame.pack()
button = tk.Button(frame,text="next",command=root.quit)
button.pack()
root.mainloop()


问:
Rails facebook app returns 422 " the change u wanted was rejected" error
My facebook is just approved today. However,when I clicked on "Go to app", it returns Rail 422 " The change you wanted was rejected. error" I set my Canvas URL to my site url and I am using Omniauth, so I am just wondering what did I miss.</p>

答:
Try removing

```<code>protect_from_forgery
</code>```

In the application_controller, or

```<code># you can disable csrf protection on controller-by-controller basis:
skip_before_filter :verify_authenticity_token
</code>```

Facebook uses signed_request that you can decode and use to verify that the request actually comes from facebook, so protect_from_forgery is unnecessary for applications that are accessible through the facebook canvas only.

More here: Canvas Authentication & ActionController::RequestForgeryProtection

Body:
Try removing

protect_from_forgery

In the application_controller, or

# you can disable csrf protection on controller-by-controller basis:
skip_before_filter :verify_authenticity_token

Facebook uses signed_request that you can decode and use to verify that the request actually comes from facebook, so protect_from_forgery is unnecessary for applications that are accessible through the facebook canvas only.

More here: Canvas Authentication & ActionController::RequestForgeryProtection


问:
NodeJS - infinite call on promise functions
I'm looking for a way to call infinitely a functions with promises.
I tried 2 scenarios, one works the other don't.
The aim of the code that doesn't works is to: get data from an API and then store it into a database.

I'm learning promises, can someone explain me why one is working and the other don't ?
Below my codes

Working code
The function is called only once, I'm looking to get it called infinitly

```<code>const request = require('request') //node to facilitate http request
var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
var db_name  = nano.db.use('bitfinex'); //couchdb database name
var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
var nonce = new Date().toISOString()  //gives a unique id
                      .replace(/T/, ' ')    // replace T with a space
                      .replace(/\..+/, '')     // delete the dot and everything after

let cleanTheRoom = function() {
      return new Promise(function(resolve, reject) {
        resolve('Cleaned the Room, ');
      });
    };

  let removedTheGarbage = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg + 'removed the garbage, ');
    });
  };

  let getIcecream = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg +'got icecream.');
    });
  };

setInterval(function(){
  cleanTheRoom()
    .then(removedTheGarbage)
    .then(getIcecream)
    .then(function(msg) {
    console.log(msg );
  });
}, 2000);
</code>```

Failing code

```<code>const request = require('request') //node to facilitate http request
    var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
    var db_name  = nano.db.use('bitfinex'); //couchdb database name
    var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
    var nonce = new Date().toISOString()  //gives a unique id
                          .replace(/T/, ' ')    // replace T with a space
                          .replace(/\..+/, '')     // delete the dot and everything after

// get current litecoin price from Bitfinex

function getLtcPrice(){
  return new Promise(function(resolve, reject){
    request.get(ltc_url,
        function (error, response, body) {
        var rep = JSON.parse(body);
        var ltc_price = rep.ask;
          resolve (ltc_price)
        if (error){
          reject(ltc_price)
          }
      });
    })
  }

//save current litecoin price to the database

function saveLtcPrice (ltc_price){
      return new Promise(function(resolve, reject){
        resolve(
        db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
           function(err, body) {
             if (!err)
             console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
          })
          )
      });
    }

setInterval(function(){
  getLtcPrice()
    .then(function(ltcPrice){
      saveLtcPrice(ltcPrice);
    });
}, 2000);
</code>```

答:
Adding one more answer:</p>

```<code>// get current litecoin price from Bitfinex
const getLtcPrice = (ltc_url) =>
  new Promise(
    (resolve, reject) =>
      request.get(
        ltc_url,
        (error, response, body) =>
          error
            ? reject(error)
            : resolve(JSON.parse(body).ask)
      )
  );

//save current litecoin price to the database
const saveLtcPrice = (ltc_price) =>
  new Promise(
    (resolve, reject) =>
      db_name.insert(
        { _id: nonce, currency: "Litecoin", price: ltc_price },
        (err, body) =>
          err
            ? reject(err)
            : console.log(" ltc price : " + ltc_price + ", uploaded to the database ")
              || resolve(body)
    )
  );

const keepGettingPrice = () => {
  const rec =
    p =>
      //if previous saves were not finished then wait for it to finish
      p = p.then(
        //!!!!!!!!!!!!! where does ltc_url come from?
        _ => getLtcPrice(ltc_url)
      ).then(
        saveLtcPrice
      ).then(
        undefined,
        //handle the error
        err=>console.warn("failed one:",err,)
      )
      .then(
        x=>new Promise((r)=>setTimeout(r,2000))
      );
  return rec(Promise.resolve());
};
keepGettingPrice();
</code>```

Body:
I'm looking for a way to call infinitely a functions with promises.
I tried 2 scenarios, one works the other don't.
The aim of the code that doesn't works is to: get data from an API and then store it into a database.

I'm learning promises, can someone explain me why one is working and the other don't ?
Below my codes

Working code
The function is called only once, I'm looking to get it called infinitly

const request = require('request') //node to facilitate http request
var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
var db_name  = nano.db.use('bitfinex'); //couchdb database name
var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
var nonce = new Date().toISOString()  //gives a unique id
                      .replace(/T/, ' ')    // replace T with a space
                      .replace(/\..+/, '')     // delete the dot and everything after

let cleanTheRoom = function() {
      return new Promise(function(resolve, reject) {
        resolve('Cleaned the Room, ');
      });
    };

  let removedTheGarbage = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg + 'removed the garbage, ');
    });
  };

  let getIcecream = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg +'got icecream.');
    });
  };

setInterval(function(){
  cleanTheRoom()
    .then(removedTheGarbage)
    .then(getIcecream)
    .then(function(msg) {
    console.log(msg );
  });
}, 2000);

Failing code

const request = require('request') //node to facilitate http request
    var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
    var db_name  = nano.db.use('bitfinex'); //couchdb database name
    var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
    var nonce = new Date().toISOString()  //gives a unique id
                          .replace(/T/, ' ')    // replace T with a space
                          .replace(/\..+/, '')     // delete the dot and everything after

// get current litecoin price from Bitfinex

function getLtcPrice(){
  return new Promise(function(resolve, reject){
    request.get(ltc_url,
        function (error, response, body) {
        var rep = JSON.parse(body);
        var ltc_price = rep.ask;
          resolve (ltc_price)
        if (error){
          reject(ltc_price)
          }
      });
    })
  }

//save current litecoin price to the database

function saveLtcPrice (ltc_price){
      return new Promise(function(resolve, reject){
        resolve(
        db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
           function(err, body) {
             if (!err)
             console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
          })
          )
      });
    }

setInterval(function(){
  getLtcPrice()
    .then(function(ltcPrice){
      saveLtcPrice(ltcPrice);
    });
}, 2000);

Body:
Adding one more answer:

// get current litecoin price from Bitfinex
const getLtcPrice = (ltc_url) =>
  new Promise(
    (resolve, reject) =>
      request.get(
        ltc_url,
        (error, response, body) =>
          error
            ? reject(error)
            : resolve(JSON.parse(body).ask)
      )
  );

//save current litecoin price to the database
const saveLtcPrice = (ltc_price) =>
  new Promise(
    (resolve, reject) =>
      db_name.insert(
        { _id: nonce, currency: "Litecoin", price: ltc_price },
        (err, body) =>
          err
            ? reject(err)
            : console.log(" ltc price : " + ltc_price + ", uploaded to the database ")
              || resolve(body)
    )
  );

const keepGettingPrice = () => {
  const rec =
    p =>
      //if previous saves were not finished then wait for it to finish
      p = p.then(
        //!!!!!!!!!!!!! where does ltc_url come from?
        _ => getLtcPrice(ltc_url)
      ).then(
        saveLtcPrice
      ).then(
        undefined,
        //handle the error
        err=>console.warn("failed one:",err,)
      )
      .then(
        x=>new Promise((r)=>setTimeout(r,2000))
      );
  return rec(Promise.resolve());
};
keepGettingPrice();


问:
jQuery fieldselection replaceSelection doesn't works for me
hi this is the simple jquery fieldselection plugin.

```<code>   /*
 * jQuery plugin: fieldSelection - v0.1.1 - last change: 2006-12-16
 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
 */

(function() {

    var fieldSelection = {

        getSelection: function() {

            var e = (this.jquery) ? this[0] : this;

            return (

                /* mozilla / dom 3.0 */
                ('selectionStart' in e && function() {
                    var l = e.selectionEnd - e.selectionStart;
                    return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
                }) ||

                /* exploder */
                (document.selection && function() {

                    e.focus();

                    var r = document.selection.createRange();
                    if (r === null) {
                        return { start: 0, end: e.value.length, length: 0 }
                    }

                    var re = e.createTextRange();
                    var rc = re.duplicate();
                    re.moveToBookmark(r.getBookmark());
                    rc.setEndPoint('EndToStart', re);

                    return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
                }) ||

                /* browser not supported */
                function() { return null; }

            )();

        },

        replaceSelection: function() {

            var e = (typeof this.id == 'function') ? this.get(0) : this;
            var text = arguments[0] || '';

            return (

                /* mozilla / dom 3.0 */
                ('selectionStart' in e && function() {
                    e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
                    return this;
                }) ||

                /* exploder */
                (document.selection && function() {
                    e.focus();
                    document.selection.createRange().text = text;
                    return this;
                }) ||

                /* browser not supported */
                function() {
                    e.value += text;
                    return jQuery(e);
                }

            )();

        }

    };

    jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });

})();
</code>```

i can't understand why doing this the selected text in textarea element is not replaced.

```<code>$('.wysiwyg-editor-italic').live('click',function(){
   var _selection = $('.wysiwyg textarea').getSelection().text;
   var wcode = "";

   if(_selection){
       $('.wysiwyg textarea').replaceSelection("{italic}"+_selection+"{/italic}");
       console.log(_selection);
    }
    else{
        wcode = "{italic} italic {/italic}";
    }
    var wysiwyg_val = $('.wysiwyg textarea').val();

    $('.wysiwyg textarea').val("").val(wysiwyg_val+wcode);
     $('.wysiwyg-preview').html(wysiwyg_val);
    $('.wysiwyg textarea').focus();

    refresh_preview()
});
</code>```

in console i can see _selection which is ok but after that is not replaced ... maybe i'm missing up somenthing?

答:
Please can you make a fiddle to show the problem? try the new version of library: https://github.com/nikolasmagno/jquery-fieldselection/

I'm sure it'll work

Body:
hi this is the simple jquery fieldselection plugin.

   /*
 * jQuery plugin: fieldSelection - v0.1.1 - last change: 2006-12-16
 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
 */

(function() {

    var fieldSelection = {

        getSelection: function() {

            var e = (this.jquery) ? this[0] : this;

            return (

                /* mozilla / dom 3.0 */
                ('selectionStart' in e && function() {
                    var l = e.selectionEnd - e.selectionStart;
                    return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
                }) ||

                /* exploder */
                (document.selection && function() {

                    e.focus();

                    var r = document.selection.createRange();
                    if (r === null) {
                        return { start: 0, end: e.value.length, length: 0 }
                    }

                    var re = e.createTextRange();
                    var rc = re.duplicate();
                    re.moveToBookmark(r.getBookmark());
                    rc.setEndPoint('EndToStart', re);

                    return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
                }) ||

                /* browser not supported */
                function() { return null; }

            )();

        },

        replaceSelection: function() {

            var e = (typeof this.id == 'function') ? this.get(0) : this;
            var text = arguments[0] || '';

            return (

                /* mozilla / dom 3.0 */
                ('selectionStart' in e && function() {
                    e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
                    return this;
                }) ||

                /* exploder */
                (document.selection && function() {
                    e.focus();
                    document.selection.createRange().text = text;
                    return this;
                }) ||

                /* browser not supported */
                function() {
                    e.value += text;
                    return jQuery(e);
                }

            )();

        }

    };

    jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });

})();

i can't understand why doing this the selected text in textarea element is not replaced.

$('.wysiwyg-editor-italic').live('click',function(){
   var _selection = $('.wysiwyg textarea').getSelection().text;
   var wcode = "";

   if(_selection){
       $('.wysiwyg textarea').replaceSelection("{italic}"+_selection+"{/italic}");
       console.log(_selection);
    }
    else{
        wcode = "{italic} italic {/italic}";
    }
    var wysiwyg_val = $('.wysiwyg textarea').val();

    $('.wysiwyg textarea').val("").val(wysiwyg_val+wcode);
     $('.wysiwyg-preview').html(wysiwyg_val);
    $('.wysiwyg textarea').focus();

    refresh_preview()
});

in console i can see _selection which is ok but after that is not replaced ... maybe i'm missing up somenthing?


问:
How nested FETCH JOIN works on Hibernate using JpaRepository and @Query annotation?
I have the following problem (pseudo-java-code):

Let me a class A,B,C with the following relationships:

```<code>@Entity
@Table(name = "A")
public class A {

  @OneToMany(mappedBy = "a")
  private B b;

}

@Entity
@Table(name = "B")
public class B {

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "a_id")
  private A a;

  @OneToOne(mappedBy = "b", fetch = FetchType.LAZY)
  private C c;

}

@Entity
@Table(name = "C")
public class C {

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "b_id")
  private B b;

}
</code>```

I'm using JpaRepository with @Query annotation and I implemented the following query:

```<code>@Query("SELECT DISTINCT(a) FROM A a "
        + "LEFT JOIN FETCH a.b as b"
        + "WHERE a.id = :id ")
A findById(@Param("id") Integer id);
</code>```

I want retrieve the informations about class A and B, but not C.
Somehow (I don't know why) the query try to retrive also the relation between B and C.
And then, with hibernate, start the lazy invocation for retrieving C.

Naturally, if I fetch also the relation between B and C (adding LEFT JOIN FETCH b.c as c) that's not happen.

My question is, why? Why I'm forced to fetch all nested relations and not only the ones which I need?

thank you.
Carmelo

答: Shot in the dark, but there are some issues with lazy-loading @OneToOne-relationships. At least in older versions of Hibernate. I think (but can't seem to find any documentation) that this was fixed in one of the newer versions, so if you are not using a new version of Hibernate, try upgrading.

Body:
I have the following problem (pseudo-java-code):

Let me a class A,B,C with the following relationships:

@Entity
@Table(name = "A")
public class A {

  @OneToMany(mappedBy = "a")
  private B b;

}

@Entity
@Table(name = "B")
public class B {

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "a_id")
  private A a;

  @OneToOne(mappedBy = "b", fetch = FetchType.LAZY)
  private C c;

}

@Entity
@Table(name = "C")
public class C {

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "b_id")
  private B b;

}

I'm using JpaRepository with @Query annotation and I implemented the following query:

@Query("SELECT DISTINCT(a) FROM A a "
        + "LEFT JOIN FETCH a.b as b"
        + "WHERE a.id = :id ")
A findById(@Param("id") Integer id);

I want retrieve the informations about class A and B, but not C.
Somehow (I don't know why) the query try to retrive also the relation between B and C.
And then, with hibernate, start the lazy invocation for retrieving C.

Naturally, if I fetch also the relation between B and C (adding LEFT JOIN FETCH b.c as c) that's not happen.

My question is, why? Why I'm forced to fetch all nested relations and not only the ones which I need?

thank you.
Carmelo


问:
Ruby on rails undefined method `firstname'
I am working on the final project "stories" on code academy and my signup page is throwing this error code

```<code>undefined method 'firstname' for #<Signup id: nil, created_at: nil, updated_at: nil>
</code>```

Any help to fix this error would be greatly appreciated.

Here is my html

```<code>    <div class="contact-main">
  <img alt="Open" class="icon-menu" src="/assets/open.svg" width="24px" />
  <div class="content container">
    <h1>Get the latest updates from Stories</h1>
    <div class="row">
      <div class="col-md-4 col-md-4-offset"></div>
      <div class="col-md-4">
        <%= form_for(@signup) do |f| %>
          <div class="form-group">
            <%= f.label "First Name" %>
            #<%= f.text_field :firstname, { :class => "form-control" } %>
          </div>
          <div class="form-group">
            <%= f.label "Email" %>
           # <%= f.text_field :email, { :class => "form-control" } %>
          </div>
        #  <%= f.submit "Join", { :class => "btn btn-default" } %>
        <% end %>
      </div>
      <div class="col-md-4 col-md-4-offset"></div>
    </div>
  </div>
</div>
</code>```

Controller_

```<code>class SignupsController < ApplicationController
    def new
        @signup = Signup.new
    end
    def create
        @signup = Signup.new(signup_params)
        if @signup.save
            redirect_to "/thanks"
        else
            render "/new"
        end
    end
    def thanks
    end
    private
    def signup_params
        params.require(:signup).permit(:firstname).permit(:email)
    end
end
</code>```

And finally my migration

```<code>class CreateSignups < ActiveRecord::Migration
  def change
    create_table :signups do |t|
      t.string :firstname
      t.string :email
      t.timestamps null: false
    end
  end
end
</code>```

答:
Hey when you permit your params, you can do that

```<code>params.require(:signup).permit(:firstname, :email)
</code>```

Instead of that:

```<code>params.require(:signup).permit(:firstname).permit(:email)
</code>```

Body:
I am working on the final project "stories" on code academy and my signup page is throwing this error code

undefined method 'firstname' for #<Signup id: nil, created_at: nil, updated_at: nil>

Any help to fix this error would be greatly appreciated.

Here is my html

Get the latest updates from Stories

        <%= form_for(@signup) do |f| %>

            <%= f.label "First Name" %>
            #<%= f.text_field :firstname, { :class => "form-control" } %>

            <%= f.label "Email" %>
           # <%= f.text_field :email, { :class => "form-control" } %>

        #  <%= f.submit "Join", { :class => "btn btn-default" } %>
        <% end %>

Controller_

class SignupsController < ApplicationController
    def new
        @signup = Signup.new
    end
    def create
        @signup = Signup.new(signup_params)
        if @signup.save
            redirect_to "/thanks"
        else
            render "/new"
        end
    end
    def thanks
    end
    private
    def signup_params
        params.require(:signup).permit(:firstname).permit(:email)
    end
end

And finally my migration

class CreateSignups < ActiveRecord::Migration
  def change
    create_table :signups do |t|
      t.string :firstname
      t.string :email
      t.timestamps null: false
    end
  end
end

Body:
Hey when you permit your params, you can do that

params.require(:signup).permit(:firstname, :email)

Instead of that:

params.require(:signup).permit(:firstname).permit(:email)


答:
You can use group by for unique record like below :-

```<code>SELECT * from TABLENAME
    group by TABLE_COLOUM_NAME
</code>```

This query give you only unique value from your Table.

Title: Select Except the duplicate Records from the table in SQL Server

Body:
I have a SQL Server table that has duplicate entries in one of the columns  e.g.:

  +----+-----------+------------+
  | id | object_id | status_val |
  +----+-----------+------------+
  |  1 |         1 |          0 |
  |  2 |         1 |          0 |
  |  3 |         1 |          0 |
  |  4 |         2 |          0 |
  |  5 |         3 |          0 |
  |  6 |         4 |          0 |
  |  7 |         4 |          0 |
  +----+-----------+------------+

I need the output to be like this:

  +----+-----------+------------+
  | id | object_id | status_val |
  +----+-----------+------------+
  |  4 |         2 |          0 |
  |  5 |         3 |          0 |
  +----+-----------+------------+

How to resolve this?

Body:
You can use group by for unique record like below :-

SELECT * from TABLENAME
    group by TABLE_COLOUM_NAME

This query give you only unique value from your Table.


问:
How can I reset the Android studio layout?
My Android Studio Layout

I'm so sad because my android sutios's layout is something strange.
In above screenshot, as you can see, the blue circled position is located at very right side of studio. I want to move it like the position that the arrow points but I don't know how to move it..

Any help will be appreciated.
Thanks!

答:
to move the toolbar back to the left side check 'toolbar' in the View menu.

On AS3.0 unchecking toolbar in the View menu moves it to the right of the screen. Deleting the settings didn't restore it to the correct position for me


问:
Future and asynchronism
I use a extern api (ESRI API for Android) where I have a loop for which me return a class Future

```<code>...
for (Layer layer : layers) {

// ListenableFuture extends Future<V>
final ListenableFuture<FeatureQueryResult> future= gdbFeatureTable.queryFeaturesAsync(query);

future.addDoneListener(() -> {
                try {
                    FeatureQueryResult result = future.get();
...
}
</code>```

OR

```<code>try {
                FeatureQueryResult result = future.get();

    }
    ...
</code>```

Is it possible to launch all queryFeaturesAsync and obtain the global result (result1 + result2 + etc..) with asynchronously after the loop for ?
What's the best way ? promises? ThreadPoolExecutor ?

Thanks for your help

答:
I think method queryFeaturesAsync() inside already uses ThreadPoolService, and using ThreadPoolService to retreive result from another ThreadPoolService is overkill, IMHO.

I would recomend you to use AsyncTask becuse it is native Android SDK tool and very simple to use:

```<code>AsyncTask<ListenableFuture<FeatureQueryResult>, Integer, List<FeatureQueryResult>> task =
        new AsyncTask<ListenableFuture<FeatureQueryResult>, Integer, List<FeatureQueryResult>>() {
    @Override
    protected List<FeatureQueryResult> doInBackground(ListenableFuture<FeatureQueryResult>[] futures) {
        int counter = 0;
        List<FeatureQueryResult> results = new ArrayList<>();
        for (ListenableFuture<FeatureQueryResult> future : futures) {
            try {
                results.add(future.get());
                publishProgress(++counter); // Optional feature
            } catch (ExecutionException | InterruptedException e) {
                Log.w("Huh?", "Interrupted!");
            }
        }
        return results;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        notifyMainThreadAboutProgress(values[0]); // Optional feature
    }

    @Override
    protected void onPostExecute(List<FeatureQueryResult> featureQueryResults) {
        doSomethingWithResultsInMainThread(featureQueryResults);
    }
};

ListenableFuture<FeatureQueryResult> future1 = gdbFeatureTable.queryFeaturesAsync(query);
ListenableFuture<FeatureQueryResult> future2 = gdbFeatureTable.queryFeaturesAsync(another_query);
ListenableFuture<FeatureQueryResult> future3 = gdbFeatureTable.queryFeaturesAsync(yet_another_query);

task.execute(future1, future2, future3);
</code>```

I made AsyncTask as an anonymous class for shortening of example. On production it must be static class.

Title: Future and asynchronism

Body:
I use a extern api (ESRI API for Android) where I have a loop for which me return a class Future

...
for (Layer layer : layers) {

// ListenableFuture extends Future<V>
final ListenableFuture<FeatureQueryResult> future= gdbFeatureTable.queryFeaturesAsync(query);

future.addDoneListener(() -> {
                try {
                    FeatureQueryResult result = future.get();
...
}

OR

try {
                FeatureQueryResult result = future.get();

    }
    ...

Is it possible to launch all queryFeaturesAsync and obtain the global result (result1 + result2 + etc..) with asynchronously after the loop for ?
What's the best way ? promises? ThreadPoolExecutor ?

Thanks for your help

Body:
I think method queryFeaturesAsync() inside already uses ThreadPoolService, and using ThreadPoolService to retreive result from another ThreadPoolService is overkill, IMHO.

I would recomend you to use AsyncTask becuse it is native Android SDK tool and very simple to use:

AsyncTask<ListenableFuture<FeatureQueryResult>, Integer, List<FeatureQueryResult>> task =
        new AsyncTask<ListenableFuture<FeatureQueryResult>, Integer, List<FeatureQueryResult>>() {
    @Override
    protected List<FeatureQueryResult> doInBackground(ListenableFuture<FeatureQueryResult>[] futures) {
        int counter = 0;
        List<FeatureQueryResult> results = new ArrayList<>();
        for (ListenableFuture<FeatureQueryResult> future : futures) {
            try {
                results.add(future.get());
                publishProgress(++counter); // Optional feature
            } catch (ExecutionException | InterruptedException e) {
                Log.w("Huh?", "Interrupted!");
            }
        }
        return results;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        notifyMainThreadAboutProgress(values[0]); // Optional feature
    }

    @Override
    protected void onPostExecute(List<FeatureQueryResult> featureQueryResults) {
        doSomethingWithResultsInMainThread(featureQueryResults);
    }
};

ListenableFuture<FeatureQueryResult> future1 = gdbFeatureTable.queryFeaturesAsync(query);
ListenableFuture<FeatureQueryResult> future2 = gdbFeatureTable.queryFeaturesAsync(another_query);
ListenableFuture<FeatureQueryResult> future3 = gdbFeatureTable.queryFeaturesAsync(yet_another_query);

task.execute(future1, future2, future3);

I made AsyncTask as an anonymous class for shortening of example. On production it must be static class.


问:
How can I access a list that is created in a static object that is part of another class?
What I would like to do is to have a list that is in an object counts that is defined in the App class as a static when my application starts:

Here's the object:

```<code>public class Counts
{
    public Counts()
    {
       public static List<CntQty> CardClicks2m;
    }
}
</code>```

In my application I declare this

am using the following code:

```<code>public partial class App : Application
{
    public static Counts counts = new Counts();

    public App()
    {
    }
}
</code>```

Now I try to use load some data into the list but it gives me the error below. Note that this function is in another class.

```<code>public void GetClickHistory()
{
   App.counts.CardClicks2m = db2.Query<CntQty>(sql);
</code>```

The last line of the code is giving me an error saying

counts.CardClicks2m cannot be accessed with an instance reference;
  qualify it with a type name instead.

I have tried a few different ways to make this work. One by removing the static and creating the object in the app constructor. This also didn't seem to work so I am hoping someone can point me in the right direction or at least suggest something.

答:
The error is pretty self explanatory, you cannot access a static property using an instance variable. all you need to do is use the typename. So this:

```<code>App.Counts.CardClicks2m
</code>```

Becomes this:

```<code>Counts.CardClicks2m
</code>```

You may need to specify the full namespace of the Counts class:

```<code>Some.Namespace.Counts.CardClicks2m
</code>```

Body:
What I would like to do is to have a list that is in an object counts that is defined in the App class as a static when my application starts:

Here's the object:

public class Counts
{
    public Counts()
    {
       public static List<CntQty> CardClicks2m;
    }
}

In my application I declare this

am using the following code:

public partial class App : Application
{
    public static Counts counts = new Counts();

    public App()
    {
    }
}

Now I try to use load some data into the list but it gives me the error below. Note that this function is in another class.

public void GetClickHistory()
{
   App.counts.CardClicks2m = db2.Query<CntQty>(sql);

The last line of the code is giving me an error saying

counts.CardClicks2m cannot be accessed with an instance reference;
  qualify it with a type name instead.

I have tried a few different ways to make this work. One by removing the static and creating the object in the app constructor. This also didn't seem to work so I am hoping someone can point me in the right direction or at least suggest something.

Body:
The error is pretty self explanatory, you cannot access a static property using an instance variable. all you need to do is use the typename. So this:

App.Counts.CardClicks2m

Becomes this:

Counts.CardClicks2m

You may need to specify the full namespace of the Counts class:

Some.Namespace.Counts.CardClicks2m


问:
Filtering data-frame on multiple criteria
I have a dataframe df which has a head that looks like:

```<code>               Shop       Opening date
0            London                NaT
22         Brighton         01/03/2016
27       Manchester         01/31/2017
54          Bristol         03/31/2017
69          Glasgow         04/09/2017
</code>```

I also have a variable startPeriod which is set to 1/04/2017 date and endPeriod variable that has a value of 30/06/17

I am trying to create a new dataframe based on df that filters out any rows that do not have a date (so removing any rows with an Opening date of NaT) and also filter out any rows with an opening date between the startPeriod and endPeriod.  So in the above example I would be left with the following new dataframe:

```<code>                 Shop       Opening date
22           Brighton         01/03/2016
69            Glasgow         04/09/2017
</code>```

I have tried to filter out the 'NaT' using the following:

```<code>df1 = df['Opening date '] != 'NaT'
</code>```

but am unsure how to also filter out any Opening date that are inside the startPeriod/endPeriod range.

答:
First of all, be careful with the space after date in df['Opening date ']

try this solution:

```<code>df1 = df[df['Opening date'] != 'NaT']
</code>```

it would be much better if you create a copy of the subset you're making

```<code>df1 = df[df['Opening date'] != 'NaT'].copy()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe df which has a head that looks like:

               Shop       Opening date
0            London                NaT
22         Brighton         01/03/2016
27       Manchester         01/31/2017
54          Bristol         03/31/2017
69          Glasgow         04/09/2017

I also have a variable startPeriod which is set to 1/04/2017 date and endPeriod variable that has a value of 30/06/17

I am trying to create a new dataframe based on df that filters out any rows that do not have a date (so removing any rows with an Opening date of NaT) and also filter out any rows with an opening date between the startPeriod and endPeriod.  So in the above example I would be left with the following new dataframe:

                 Shop       Opening date
22           Brighton         01/03/2016
69            Glasgow         04/09/2017

I have tried to filter out the 'NaT' using the following:

df1 = df['Opening date '] != 'NaT'

but am unsure how to also filter out any Opening date that are inside the startPeriod/endPeriod range.

Body:
First of all, be careful with the space after date in df['Opening date ']

try this solution:

df1 = df[df['Opening date'] != 'NaT']

it would be much better if you create a copy of the subset you're making

df1 = df[df['Opening date'] != 'NaT'].copy()


问:
Loop through column A and copy values in matching sheet on different workbook
I have 2 workbooks, where workbook 1 has a list of names in column A and each name has a row of values.
Workbook 2 has worksheets labeled with names as well. Some of these name are the same as the list of names in column A of workbook 1.

What I am trying to achieve is to check if the name in column A matches the worksheet name. If yes, I want to copy the values in that row and paste them into specific cells in the sheet on workbook 2.
The code I have below works fine if every name in column A has a corresponding sheet in workbook 2 in the same order. However, I want it to be able to skip blank spaces or skip names that do not have a sheet in workbook 2. So I have added an if statement to see if that solves the problem, but that did not work. I'm getting the error: 'Application-defined or object-defined error', highlighting the if statement.

The original working code didn't have the IF statement. It worked as long as there were no spaces in the column A and every single name had a matching sheet in the same order.

I have also tried adding the error resume next lines but that just stopped triggering the error code. It copy/pasted the first row into the correct cells, but then nothing for the rest.

```<code>Sub Measures()

Dim wb1 As Workbook
Dim Sht As Worksheet
Dim Rng, Rng2 As Range
Dim wb2 As Workbook
Dim cell As Range
Dim ws As Worksheet

Set wb1 = ThisWorkbook
Set wb2 = Workbooks("November Stream 1 v2.xlsm")
Set Sht = wb1.Worksheets("Summary")
Set Rng = Sht.Range("A7:A" & Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row)

For Each cell In Rng
Set ws = wb2.Sheets(cell.Text)

If wb1.Sheets("Summary").Range("A" & i) = wb2.Sheet.Name Then

   Select Case ws.Range("A4").Value
        Case "green"  '
        ws.Range("B29").Value = cell.Offset(0, 1).Value
        ws.Range("B33").Value = cell.Offset(0, 2).Value
        ws.Range("B37").Value = cell.Offset(0, 3).Value
        ws.Range("B40").Value = cell.Offset(0, 4).Value
        ws.Range("B44").Value = cell.Offset(0, 5).Value

        Case "red"
        ws.Range("B47").Value = cell.Offset(0, 6).Value
        ws.Range("B51").Value = cell.Offset(0, 7).Value
        ws.Range("B54").Value = cell.Offset(0, 8).Value
        ws.Range("B60").Value = cell.Offset(0, 9).Value
        ws.Range("B65").Value = cell.Offset(0, 11).Value

        Case "blue"
        ws.Range("B68").Value = cell.Offset(0, 12).Value
        ws.Range("B74").Value = cell.Offset(0, 14).Value
        ws.Range("B76").Value = cell.Offset(0, 15).Value
      End Select
        End If

    Next cell

End Sub
</code>```

答:
Try looping through each worksheet in wb2 and compare their names to the current cell in wb1

As psuedo (this is a rough idea, I don't have time to type it in full at current, sorry)

```<code>for each cell. wb1.range("your range)
    wb2.activate
    for each worksheet in wb2
        if activesheet.name = cell.value then
            'do stuff
        else
            'do nothing
        end if
    next worksheet
next cell
</code>```

Body:
I have 2 workbooks, where workbook 1 has a list of names in column A and each name has a row of values.
Workbook 2 has worksheets labeled with names as well. Some of these name are the same as the list of names in column A of workbook 1.

What I am trying to achieve is to check if the name in column A matches the worksheet name. If yes, I want to copy the values in that row and paste them into specific cells in the sheet on workbook 2.
The code I have below works fine if every name in column A has a corresponding sheet in workbook 2 in the same order. However, I want it to be able to skip blank spaces or skip names that do not have a sheet in workbook 2. So I have added an if statement to see if that solves the problem, but that did not work. I'm getting the error: 'Application-defined or object-defined error', highlighting the if statement.

The original working code didn't have the IF statement. It worked as long as there were no spaces in the column A and every single name had a matching sheet in the same order.

I have also tried adding the error resume next lines but that just stopped triggering the error code. It copy/pasted the first row into the correct cells, but then nothing for the rest.

Sub Measures()

Dim wb1 As Workbook
Dim Sht As Worksheet
Dim Rng, Rng2 As Range
Dim wb2 As Workbook
Dim cell As Range
Dim ws As Worksheet

Set wb1 = ThisWorkbook
Set wb2 = Workbooks("November Stream 1 v2.xlsm")
Set Sht = wb1.Worksheets("Summary")
Set Rng = Sht.Range("A7:A" & Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row)

For Each cell In Rng
Set ws = wb2.Sheets(cell.Text)

If wb1.Sheets("Summary").Range("A" & i) = wb2.Sheet.Name Then

   Select Case ws.Range("A4").Value
        Case "green"  '
        ws.Range("B29").Value = cell.Offset(0, 1).Value
        ws.Range("B33").Value = cell.Offset(0, 2).Value
        ws.Range("B37").Value = cell.Offset(0, 3).Value
        ws.Range("B40").Value = cell.Offset(0, 4).Value
        ws.Range("B44").Value = cell.Offset(0, 5).Value

        Case "red"
        ws.Range("B47").Value = cell.Offset(0, 6).Value
        ws.Range("B51").Value = cell.Offset(0, 7).Value
        ws.Range("B54").Value = cell.Offset(0, 8).Value
        ws.Range("B60").Value = cell.Offset(0, 9).Value
        ws.Range("B65").Value = cell.Offset(0, 11).Value

        Case "blue"
        ws.Range("B68").Value = cell.Offset(0, 12).Value
        ws.Range("B74").Value = cell.Offset(0, 14).Value
        ws.Range("B76").Value = cell.Offset(0, 15).Value
      End Select
        End If

    Next cell

End Sub

Body:
Try looping through each worksheet in wb2 and compare their names to the current cell in wb1

As psuedo (this is a rough idea, I don't have time to type it in full at current, sorry)

for each cell. wb1.range("your range)
    wb2.activate
    for each worksheet in wb2
        if activesheet.name = cell.value then
            'do stuff
        else
            'do nothing
        end if
    next worksheet
next cell


问:
Naming conventions in C# compared to Java
The standard naming convention in the Java world is to name packages, classes and methods  according to:

```<code>com.domainname.productname (package)
com.domainname.productname.ClassName (class)
com.domainname.productname.ClassName.isUpperCase(String str) (method)
</code>```

What is the C#/.NET standard naming convention for the above cases?

答:
It is rare to see "com." in C# or .NET:

```<code>DomainName.ProductName (namespace)
DomainName.ProductName.ClassName (class)
DomainName.ProductName.ClassName.IsUpperCase(String str) (method)
</code>```

See the .NET Library Design Guidelines from Microsoft for the full scoop (this is really a .NET question more than a C# question).

Body:
The standard naming convention in the Java world is to name packages, classes and methods  according to:

com.domainname.productname (package)
com.domainname.productname.ClassName (class)
com.domainname.productname.ClassName.isUpperCase(String str) (method)

What is the C#/.NET standard naming convention for the above cases?

Body:
It is rare to see "com." in C# or .NET:

DomainName.ProductName (namespace)
DomainName.ProductName.ClassName (class)
DomainName.ProductName.ClassName.IsUpperCase(String str) (method)

See the .NET Library Design Guidelines from Microsoft for the full scoop (this is really a .NET question more than a C# question).

OwnerDisplayName: Joe Erickson


问:
How do you render OpenGL-ES to an external screen using the VGA out adapter?
I've been developing a 3D program for the iPad and iPhone and would like to be able to render it to an external screen. According to my understanding, you have to do something similar to the below code to implement it, (found at: Sunsetlakesoftware.com):

```<code>if ([[UIScreen screens] count] > 1)
{
    // External screen attached
}
else
{
    // Only local screen present
}

CGRect externalBounds = [externalScreen bounds];
externalWindow = [[UIWindow alloc] initWithFrame:externalBounds];

UIView *backgroundView = [[UIView alloc]  initWithFrame:externalBounds];
backgroundView.backgroundColor = [UIColor whiteColor];

[externalWindow addSubview:backgroundView];

[backgroundView release];

externalWindow.screen = externalScreen;
[externalWindow makeKeyAndVisible];
</code>```

However, I'm not sure what to change to do this to an OpenGL project. Does anyone know what you would do to implement this into the defualt openGL project for iPad or iPhone in XCode?

答:
All you need to do to render OpenGL ES content on the external display is to either create a UIView that is backed by a CAEAGLLayer and add it as a subview of the backgroundView above, or take such a view and move it to be a subview of backgroundView.

In fact, you can remove the backgroundView if you want and just place your OpenGL-hosting view directly on the externalWindow UIWindow instance.  That window is attached to the UIScreen instance that represents the external display, so anything placed on it will show on that display.  This includes OpenGL ES content.

There does appear to be an issue with particular types of OpenGL ES content, as you can see in the experimental support I've tried to add to my Molecules application.  If you look in the source code there, I attempt to migrate my rendering view to an external display, but it never appears.  I have done the same with other OpenGL ES applications and had their content render fine, so I believe there might be an issue with the depth buffer on the external display.  I'm still working to track that down.

Body:
I've been developing a 3D program for the iPad and iPhone and would like to be able to render it to an external screen. According to my understanding, you have to do something similar to the below code to implement it, (found at: Sunsetlakesoftware.com):

if ([[UIScreen screens] count] > 1)
{
    // External screen attached
}
else
{
    // Only local screen present
}

CGRect externalBounds = [externalScreen bounds];
externalWindow = [[UIWindow alloc] initWithFrame:externalBounds];

UIView *backgroundView = [[UIView alloc]  initWithFrame:externalBounds];
backgroundView.backgroundColor = [UIColor whiteColor];

[externalWindow addSubview:backgroundView];

[backgroundView release];

externalWindow.screen = externalScreen;
[externalWindow makeKeyAndVisible];

However, I'm not sure what to change to do this to an OpenGL project. Does anyone know what you would do to implement this into the defualt openGL project for iPad or iPhone in XCode?


问:
Show countdown timer after button click
I have a table with many lines (about 50 - 100 at the end) and each lines have a different timeout. I want when i click on the first button (link) the countdown of the first line start, if on the second line, the second countdown start.

After, when the countdown is finish, any word will display instead of the timer.

Here are two exmeple of lines:

```<code><tr>
      <td><form action="http://www.google.fr"><input type="submit" formtarget="_blank" value="Google 3 seconds"></form>
      </td>
      <td>00:00:03</td>
</tr>
<tr>
      <td><form action="http://www.google.fr"><input type="submit" formtarget="_blank" value="Google 2h30mins"></form>
      </td>
      <td>02:30:00</td>
</tr>
</code>```

For js i found this here: http://jsfiddle.net/6nDYd/10/

Anyone can help me to create the js script with the link i provide ?

答:
How to continue timer after browser is refreshed and closed?

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}

function startTimer() {
  var nextElem = $(this).parents('td').next();
  var duration = nextElem.text();
  var a = duration.split(':');
  var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
  setInterval(function() {
    seconds--;
    if (seconds >= 0) {
      nextElem.html(toTimeString(seconds));
    }
    if (seconds === 0) {
      alert('sorry, out of time');
      clearInterval(seconds);
    }
  }, 1000);
}
$('.btn').on('click', startTimer);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <form action="http://www.google.fr">
        <input class="btn" type="button" formtarget="_blank" value="Google 3 seconds">
      </form>
    </td>
    <td>00:00:03</td>
  </tr>
  <tr>
    <td>
      <form action="http://www.google.fr">
        <input class="btn" type="button" formtarget="_blank" value="Google 2h30mins">
      </form>
    </td>
    <td>02:30:00</td>
  </tr>
</table></code>```

Title: Show countdown timer after button click

Body:
I have a table with many lines (about 50 - 100 at the end) and each lines have a different timeout. I want when i click on the first button (link) the countdown of the first line start, if on the second line, the second countdown start.

After, when the countdown is finish, any word will display instead of the timer.

Here are two exmeple of lines:

      <form action="http://www.google.fr"><input type="submit" formtarget="_blank" value="Google 3 seconds"></form>

      00:00:03

      <form action="http://www.google.fr"><input type="submit" formtarget="_blank" value="Google 2h30mins"></form>

      02:30:00

For js i found this here: http://jsfiddle.net/6nDYd/10/

Anyone can help me to create the js script with the link i provide ?

Body:
How to continue timer after browser is refreshed and closed?

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}

function startTimer() {
  var nextElem = $(this).parents('td').next();
  var duration = nextElem.text();
  var a = duration.split(':');
  var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
  setInterval(function() {
    seconds--;
    if (seconds >= 0) {
      nextElem.html(toTimeString(seconds));
    }
    if (seconds === 0) {
      alert('sorry, out of time');
      clearInterval(seconds);
    }
  }, 1000);
}
$('.btn').on('click', startTimer);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <form action="http://www.google.fr">
        <input class="btn" type="button" formtarget="_blank" value="Google 3 seconds">
      </form>
    </td>
    <td>00:00:03</td>
  </tr>
  <tr>
    <td>
      <form action="http://www.google.fr">
        <input class="btn" type="button" formtarget="_blank" value="Google 2h30mins">
      </form>
    </td>
    <td>02:30:00</td>
  </tr>
</table>


问:
Having array of values for ionic range
I'm having trouble using ionic range, I want it to have non linear value such as:
 0 - 10 - 20 - 30 - 40 etc...
But more like:
50 - 100 - 200 - 300 - 400 - 500 - 1000 - 1500 etc...
Like a specific array of values.
Is it possible or how can I call a .ts method at each movement to dynamically change the steps while moving the the knob(s)?
many thanks

答:
There's no way to custom your steps, but there's a workaround you can use. Let's say you have the following array [50, 100, 200, 300, 400, 500, 1000, 1500], you can use a function on your range change to select a value in this array based in the value you have in your range:

```<code><!-- -->
<ion-badge>{{customSteps}}</ion-badge>
  <ion-item>
    <!-- YOUR max WILL'BE YOUR ARRAY LENGTH - 1 TO GET THE LAST VALUE POSITION -->
    <ion-range min="0" [max]="rangeArray.length - 1" [(ngModel)]="range" (ionChange)="watchRange()" color="secondary">
    <ion-label range-left>50</ion-label>
    <ion-label range-right>1500</ion-label>
  </ion-range>
</ion-item>
</code>```

In your .ts:

```<code>range: number = 0;
customSteps: any;
rangeArray: any[] = [50, 100, 200, 300, 400, 500, 1000, 1500];

constructor(){
  // INITIALIZE YOUR RANGE VALUE
  this.watchRange();
}

watchRange(){
  // IN THIS METHOD YOU'LL CHANGE YOUR customSteps VALUE USING THE RANGE VALUE TO GET
  //A VALUE IN YOUR ARRAY POSITION. customSteps WILL BE USED FOR PRESENTATION AND IN YOUR OTHER METHODS
  this.customSteps = this.rangeArray[this.range];
}
</code>```

Hope this helps.

Title: Having array of values for ionic range

Body:
There's no way to custom your steps, but there's a workaround you can use. Let's say you have the following array [50, 100, 200, 300, 400, 500, 1000, 1500], you can use a function on your range change to select a value in this array based in the value you have in your range:

<!-- -->
<ion-badge>{{customSteps}}</ion-badge>
  <ion-item>
    <!-- YOUR max WILL'BE YOUR ARRAY LENGTH - 1 TO GET THE LAST VALUE POSITION -->
    <ion-range min="0" [max]="rangeArray.length - 1" [(ngModel)]="range" (ionChange)="watchRange()" color="secondary">
    <ion-label range-left>50</ion-label>
    <ion-label range-right>1500</ion-label>
  </ion-range>
</ion-item>

In your .ts:

range: number = 0;
customSteps: any;
rangeArray: any[] = [50, 100, 200, 300, 400, 500, 1000, 1500];

constructor(){
  // INITIALIZE YOUR RANGE VALUE
  this.watchRange();
}

watchRange(){
  // IN THIS METHOD YOU'LL CHANGE YOUR customSteps VALUE USING THE RANGE VALUE TO GET
  //A VALUE IN YOUR ARRAY POSITION. customSteps WILL BE USED FOR PRESENTATION AND IN YOUR OTHER METHODS
  this.customSteps = this.rangeArray[this.range];
}

Hope this helps.


问:
How to get Selected Value from DevExpress RepositoryItemLookUpEdit
I have 1 DevExpress.XtraBars.Bar control in the form. I have Added 1 RepositoryItemLookUpEdit on that menu Bar  now I want to get selected value on 1 button Click event

```<code> private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        if(lkpReportName.EditValue!=null)
        {

        }
    }
</code>```

It gives error

Error 42  'DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit' does not contain a definition for 'EditValue' and no extension method 'EditValue' accepting a first argument of type 'DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit' could be found (are you missing a using directive or an assembly reference?)

答: RepositoryItemLookUpEdit itself doesn't have this property. However, you can access the selected value via EditValue property of BarEditValue - which is the container for your RepositoryItemLookUpEdit.

Body:
I have 1 DevExpress.XtraBars.Bar control in the form. I have Added 1 RepositoryItemLookUpEdit on that menu Bar  now I want to get selected value on 1 button Click event

 private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        if(lkpReportName.EditValue!=null)
        {

        }
    }

It gives error

Error 42  'DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit' does not contain a definition for 'EditValue' and no extension method 'EditValue' accepting a first argument of type 'DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit' could be found (are you missing a using directive or an assembly reference?)


问:
Autoreload of modules in IPython
Is there a way to have IPython automatically reload all changed code? Either before each line is executed in the shell or failing that when it is specifically requested to. I'm doing a lot of exploratory programming using IPython and SciPy and it's quite a pain to have to manually reload each module whenever I change it.</p>

答:
REVISED - please see Andrew_1510's answer below, as IPython has been updated.

...

It was a bit hard figure out how to get there from a dusty bug report, but:

It ships with IPython now!

```<code>import ipy_autoreload
%autoreload 2
%aimport your_mod

# %autoreload? for help
</code>```

... then every time you call your_mod.dwim(), it'll pick up the latest version.

Title: Autoreload of modules in IPython

Body:
REVISED - please see Andrew_1510's answer below, as IPython has been updated.

...

It was a bit hard figure out how to get there from a dusty bug report, but:

It ships with IPython now!

import ipy_autoreload
%autoreload 2
%aimport your_mod

# %autoreload? for help

... then every time you call your_mod.dwim(), it'll pick up the latest version.


问:
Retain parent instance if using SelectMany on nested collection
I have a collection of my model Person:

```<code>class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string Company {get; set;}
    public IEnumerable<string> Tags {get; set;}
}
</code>```

and would transform this one by LINQ into another collection grouped by tags. How can I do that?

My approach so far:

```<code>var result = PersonCollection
    .SelectMany(m => m.Tags)
    .GroupBy(b => b);
</code>```

But this throws all informations about the person away.

答:
When you use GroupBy() You are essentially making another collection of objects using only those properties. You need to either include all of the information that you want in the grouping. Or you can use a meaningful "key" in your grouping and use another query to find the rest of the information from your original collection. Something like.

```<code>    var fullObject = collection.ElementAt(GroupingIndex);
</code>```

or

```<code>    var fullObject = collection.Where(search => search.prop1 = "foo" && search.prop2 = "bar");
</code>```

The constraints here are that you need an index or some hard coded value to search the collection.

Because you have grouped by b => b, a better solution would be to move this anonymous object into a POCO. Then you have an object you can address directly in a separate search.

```<code>    .GroupBy(b => b)
    .Select(grouped => new GroupedObj { B = grouped.Key.b});
</code>```

Then you can use that collection of grouped results in some form or loop or index etc and get what you want from there. Then use that to get what you want from the original collection (where the more information is).

Badly written answer i know.

Body:
I have a collection of my model Person:

class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string Company {get; set;}
    public IEnumerable<string> Tags {get; set;}
}

and would transform this one by LINQ into another collection grouped by tags. How can I do that?

My approach so far:

var result = PersonCollection
    .SelectMany(m => m.Tags)
    .GroupBy(b => b);

But this throws all informations about the person away.

Body:
When you use GroupBy() You are essentially making another collection of objects using only those properties. You need to either include all of the information that you want in the grouping. Or you can use a meaningful "key" in your grouping and use another query to find the rest of the information from your original collection. Something like.

    var fullObject = collection.ElementAt(GroupingIndex);

or

    var fullObject = collection.Where(search => search.prop1 = "foo" && search.prop2 = "bar");

The constraints here are that you need an index or some hard coded value to search the collection.

Because you have grouped by b => b, a better solution would be to move this anonymous object into a POCO. Then you have an object you can address directly in a separate search.

    .GroupBy(b => b)
    .Select(grouped => new GroupedObj { B = grouped.Key.b});

Then you can use that collection of grouped results in some form or loop or index etc and get what you want from there. Then use that to get what you want from the original collection (where the more information is).

Badly written answer i know.


问:
Using conditionalPanels with nested tabPanel in Shiny
I'm working on building a R Shiny web app to help with data exploration. I have a main page with a row of tabs, and then a row of sub tabs:

I want to have a panel appear that provides different inputs for users to select in order to create different charts (for example, when Bar Chart tab is selected, I'd like to have a dropdown list for the dataset columns, and when Histogram is selected, I'd like to have a slider for number of bins.

I can do this fine with the first level of tabs. For example, this following line of code in my ui.R allows me to easily render a panel whenever Correlation is selected:

```<code>conditionalPanel(
    condition = "input.tabs == 'correlation'",

    actionButton("generate_correlation", "Generate Heat Map")
  )
</code>```

server.R:

```<code>      tabsetPanel(
        id = "tabs",

        tabPanel("Correlation", value = "correlation",
                 plotOutput("correlation"))

... code for other tabs...
</code>```

However, I can't figure out how to access the value returned by the nested tabPanel (for example, Bar Chart or Histogram). I attempted to use this code:

```<code>tabPanel(
  "Visualize",
  value = "visualize",

  tabsetPanel(
    id = "vis_tabs",
    tabPanel("Bar Chart", value = "bar_tab",# <-- want a conditionalPanel to appear when this tab is selected

             plotOutput("bar_chart")),
    tabPanel("Histogram", value = "histogram_tab",
             plotOutput("histogram"))
  )
),
</code>```

with the following conditionalPanel:

```<code>  conditionalPanel(
    condition = "input.vis_tabs" == "bar_tab",
    #CODE HERE FOR INPUT STUFF TO APPEAR WHEN BAR CHART TAB IS SELECTED
  ),
</code>```

But right now, the above conditionalPanel is always evaluating to true. This SO post is the closest I could find to an answer, and it really didn't help much since it was focused on display output.

My guess is that since the second-level tab is defined within the scope of the first level tab, the value it returns isn't available in the "global" ui.R or server.R scope. But if that's the case, I'd expect the conditionalPanel to always evaluate to false, while it's currently evaluating to always be true!

I also know that the condition being evaluated is in JavaScript, so would the nested tab condition be something like

```<code>input.tabs.vis_tabs == "bar_tab"
</code>```

? I'm assuming that input is an instance of some Input JS object with tabs being a string property that is dynamically set as the user selects different tabs.

答:
Here is complete example for non HTML expert (like me :D) based on @Yu Chen answer:</p>

```<code>runApp(list(
  ui = shinyUI( fluidPage(

sidebarLayout(
  sidebarPanel(
    conditionalPanel(condition="input.conditioned == 0",helpText("This is navnarMenu 0")),
    conditionalPanel(condition="input.conditioned == 1",helpText("This is navnarMenu 1")),
    conditionalPanel(condition= "input.Guidelines == 2.1 && input.conditioned == 2",helpText("This is navnarMenu 2")),
    conditionalPanel(condition= "input.Guidelines == 2.2 && input.conditioned == 2",helpText("This is navnarMenu 3"))),

  mainPanel(tabsetPanel(id='conditioned',

                        tabPanel("About", value=0),

                        tabPanel("Tab 1",value=1,tabsetPanel(
                          tabPanel("Tab 1.1"),
                          tabPanel("Tab 1.2", tabsetPanel(
                            tabPanel("Tab 1.2.1"),
                            tabPanel("Tab 1.2.2"))))),

tabPanel("Guidelines",value = 2, tabsetPanel( id = "Guidelines",
                   navbarMenu("Tab 2.1",
                                   tabPanel("Tab 2.1.1",value=2.1),
                                   tabPanel("Tab 2.1.2",value=2.1)),

                 navbarMenu("Tab 2.2",
                                   tabPanel("Tab 2.2.1",value=2.2),
                                   tabPanel("Tab 2.2.2",value=2.2))))

  ))))),

server = function(input, output, session) {}

))
</code>```

Body:
I'm working on building a R Shiny web app to help with data exploration. I have a main page with a row of tabs, and then a row of sub tabs:

I want to have a panel appear that provides different inputs for users to select in order to create different charts (for example, when Bar Chart tab is selected, I'd like to have a dropdown list for the dataset columns, and when Histogram is selected, I'd like to have a slider for number of bins.

I can do this fine with the first level of tabs. For example, this following line of code in my ui.R allows me to easily render a panel whenever Correlation is selected:

conditionalPanel(
    condition = "input.tabs == 'correlation'",

    actionButton("generate_correlation", "Generate Heat Map")
  )

server.R:

      tabsetPanel(
        id = "tabs",

        tabPanel("Correlation", value = "correlation",
                 plotOutput("correlation"))

... code for other tabs...

However, I can't figure out how to access the value returned by the nested tabPanel (for example, Bar Chart or Histogram). I attempted to use this code:

tabPanel(
  "Visualize",
  value = "visualize",

  tabsetPanel(
    id = "vis_tabs",
    tabPanel("Bar Chart", value = "bar_tab",# <-- want a conditionalPanel to appear when this tab is selected

             plotOutput("bar_chart")),
    tabPanel("Histogram", value = "histogram_tab",
             plotOutput("histogram"))
  )
),

with the following conditionalPanel:

  conditionalPanel(
    condition = "input.vis_tabs" == "bar_tab",
    #CODE HERE FOR INPUT STUFF TO APPEAR WHEN BAR CHART TAB IS SELECTED
  ),

But right now, the above conditionalPanel is always evaluating to true. This SO post is the closest I could find to an answer, and it really didn't help much since it was focused on display output.

My guess is that since the second-level tab is defined within the scope of the first level tab, the value it returns isn't available in the "global" ui.R or server.R scope. But if that's the case, I'd expect the conditionalPanel to always evaluate to false, while it's currently evaluating to always be true!

I also know that the condition being evaluated is in JavaScript, so would the nested tab condition be something like

input.tabs.vis_tabs == "bar_tab"

? I'm assuming that input is an instance of some Input JS object with tabs being a string property that is dynamically set as the user selects different tabs.

Body:
Here is complete example for non HTML expert (like me :D) based on @Yu Chen answer:

runApp(list(
  ui = shinyUI( fluidPage(

sidebarLayout(
  sidebarPanel(
    conditionalPanel(condition="input.conditioned == 0",helpText("This is navnarMenu 0")),
    conditionalPanel(condition="input.conditioned == 1",helpText("This is navnarMenu 1")),
    conditionalPanel(condition= "input.Guidelines == 2.1 && input.conditioned == 2",helpText("This is navnarMenu 2")),
    conditionalPanel(condition= "input.Guidelines == 2.2 && input.conditioned == 2",helpText("This is navnarMenu 3"))),

  mainPanel(tabsetPanel(id='conditioned',

                        tabPanel("About", value=0),

                        tabPanel("Tab 1",value=1,tabsetPanel(
                          tabPanel("Tab 1.1"),
                          tabPanel("Tab 1.2", tabsetPanel(
                            tabPanel("Tab 1.2.1"),
                            tabPanel("Tab 1.2.2"))))),

tabPanel("Guidelines",value = 2, tabsetPanel( id = "Guidelines",
                   navbarMenu("Tab 2.1",
                                   tabPanel("Tab 2.1.1",value=2.1),
                                   tabPanel("Tab 2.1.2",value=2.1)),

                 navbarMenu("Tab 2.2",
                                   tabPanel("Tab 2.2.1",value=2.2),
                                   tabPanel("Tab 2.2.2",value=2.2))))

  ))))),

server = function(input, output, session) {}

))


问:
Postgres - Manual Locking Clashing with Auto Vacumn
I'm working an part of a system where tables need to be locked in "IN SHARE ROW EXCLUSIVE MODE NOWAIT" mode.

The problem is that the Autovacumn daemon (autovacuum: ANALYZE) kicks in immediately on a table after it has been worked on - stopping the next process from taking a "IN SHARE ROW EXCLUSIVE MODE NOWAIT".

The tables are large so the vacuum takes a while. I could check for this before the transaction that is trying to lock starts and use pg_cancel_backend to stop the autovacuum daemon. Are there any consequences to this? The other option is to manually schedule vacuuming but everywhere you read it's best to avoid this. Are there any parameters which I have missed that could tweak the autovacuum to stop it from behaving like this?

Thanks

答:
If you keep autovacuum from working, you will incur table bloat and eventually risk downtime when PostgreSQL shuts down to avoid data loss due to transaction ID wraparound.

Disabling autovacuum for this table (ALTER TABLE ... SET (autovacuum_enabled = off)) and regularly scheduling a manual VACUUM is an option.

But it would be best to change your procedure so that you don't have to lock tables explicitly all the time.


问:
Embed Excel Sheet into form
OK, I need to embed an Excel template document into a winform (retaining all the formatting), change some values, printpreview it, then print it to either PDF or a printer. And I need to do it without spending any of the boss's cash.

I tried embedding the standard Excel COM stuff, but the IDE (C# Express 2010) didn't like it and crashed (the Office control didn't seem to do much and accessing an XLS in a webbrowser only worked occasionally)

So I'm guessing that I'm looking at a third party open source Excel control?

In fact theoretically it could be any grid-type format as long as I can do similar formatting to Excel and make it look all pretty for the client.

Any ideas?

Cheers

答:
You could get the functionality you want with the DSOFramer control. This was a small control that Microsoft provided long, long time ago, and has since decomissioned from their site. It still works perfectly well, though. You can download the control from here:

http://download.cnet.com/Microsoft-Developer-Support-Office-Framer-Control-Sample-KB-311765/3000-2206_4-10732960.html

Title: Embed Excel Sheet into form


问:
draw prism dynamically based on distance
I would like to draw an octagonal prism which also could be oblique and its face shape and height depends on variable and edge lengths.  Where do I start?

Could I use some function for calculating the base B coordinates considering base A is fixed:

.

PS: Base A and base B are equals.

答:
Depends on what type of geometry you use. For simplicity, there's an example with a usual geometry (THREE.CylinderGeometry()):

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 2, 10);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.GridHelper(10, 10));

var prismGeom = new THREE.CylinderGeometry(1, 1, 4, 8, 1);
for(let i=0; i< 8;i++){// upper base
  prismGeom.vertices[i].y = 1 + THREE.Math.randFloat(-1, 1);
}
prismGeom.vertices[prismGeom.vertices.length - 2].y = 1 + THREE.Math.randFloat(-1, 1);// center of the upper base
prismGeom.translate(0, 2, 0);

var prism = new THREE.Mesh(prismGeom, new THREE.MeshBasicMaterial({color: "yellow", wireframe: true}));
scene.add(prism);

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: hidden;
  margin: 0;
}</code>```

```

If you want to use a buffer geometry, then you can access its coordinates of vertices with methods of THREE.BufferAttibute(), like .setX, .setY, .setZ and so on.

Body:
Depends on what type of geometry you use. For simplicity, there's an example with a usual geometry (THREE.CylinderGeometry()):

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 2, 10);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.GridHelper(10, 10));

var prismGeom = new THREE.CylinderGeometry(1, 1, 4, 8, 1);
for(let i=0; i< 8;i++){// upper base
  prismGeom.vertices[i].y = 1 + THREE.Math.randFloat(-1, 1);
}
prismGeom.vertices[prismGeom.vertices.length - 2].y = 1 + THREE.Math.randFloat(-1, 1);// center of the upper base
prismGeom.translate(0, 2, 0);

var prism = new THREE.Mesh(prismGeom, new THREE.MeshBasicMaterial({color: "yellow", wireframe: true}));
scene.add(prism);

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

body {
  overflow: hidden;
  margin: 0;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

If you want to use a buffer geometry, then you can access its coordinates of vertices with methods of THREE.BufferAttibute(), like .setX, .setY, .setZ and so on.