问:
"global" keyword needed in the top-level declaration
I am keen to know whether there is any need to use the keyword global in the top-level declaration/assignment in Python (such as the one for the 1st line of code below).

Both fn_2() and fn_4() have the same effect to change the corresponding variables in the codes below.

```<code>global factor_1
factor_1 = None

factor_2 = None

def main():

    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_1()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_2()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_3()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_4()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

def fn_1():
    factor_1 = 10

def fn_2():
    global factor_1
    factor_1 = 20

def fn_3():
    factor_2 = 30

def fn_4():
    global factor_2
    factor_2 = 40

if __name__ == '__main__':
    main()
</code>```

答:
global allows you to use a variable that is outside the scope of a function, so it must be used inside of a function:

```<code>def fn_1():
    # this is declaring a local variable factor_1
    factor_1 = 10

def fn_2():
    # this is changing the value of the global variable factor_1
    global factor_1
    factor_1 = 20

def fn_3():
    # this is declaring a local variable factor_2
    factor_2 = 30

def fn_4():
    # this is changing the value of the global variable factor_2
    global factor_2
    factor_2 = 40
</code>```

Body:
I am keen to know whether there is any need to use the keyword global in the top-level declaration/assignment in Python (such as the one for the 1st line of code below).

Both fn_2() and fn_4() have the same effect to change the corresponding variables in the codes below.

global factor_1
factor_1 = None

factor_2 = None

def main():

    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_1()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_2()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_3()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_4()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

def fn_1():
    factor_1 = 10

def fn_2():
    global factor_1
    factor_1 = 20

def fn_3():
    factor_2 = 30

def fn_4():
    global factor_2
    factor_2 = 40

if __name__ == '__main__':
    main()

Body:
global allows you to use a variable that is outside the scope of a function, so it must be used inside of a function:

def fn_1():
    # this is declaring a local variable factor_1
    factor_1 = 10

def fn_2():
    # this is changing the value of the global variable factor_1
    global factor_1
    factor_1 = 20

def fn_3():
    # this is declaring a local variable factor_2
    factor_2 = 30

def fn_4():
    # this is changing the value of the global variable factor_2
    global factor_2
    factor_2 = 40


来源: stackexchange

问:
scala foreach of a 2-D List/Array in chisel with types issue
Can "foreach" can be used for each element of the 2-D List/Array?
I tried the code:

```<code>val n_vec = (0 to 2).map(i=>
              (0 to 2).map(j=>
                Wire(UInt(3.W))
              )
            )
n_vec.foreach((i:Int)=>(
  n_vec(i).foreach((j:Int)=>{
    n_vec(i)(j) := i.U + j.U
  })
))
</code>```

the error message is

```<code>top.scala:24: error: type mismatch;
 found   : Int => Unit
 required: chisel3.core.UInt => ?
      n_vec(i).foreach((j:Int)=>{
                              ^
</code>```

Could you enlight me whether it can be used in such a way, even how?

答:
Yes it can be used this way.

solution:

```<code>var x = 0
var y = 0
n_vec.foreach(i=>{
  i.foreach(j=>{
    j := x.U + y.U
    y = y + 1
  })
  y = 0
  x = x + 1
})
x = 0
y = 0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can "foreach" can be used for each element of the 2-D List/Array?
I tried the code:

val n_vec = (0 to 2).map(i=>
              (0 to 2).map(j=>
                Wire(UInt(3.W))
              )
            )
n_vec.foreach((i:Int)=>(
  n_vec(i).foreach((j:Int)=>{
    n_vec(i)(j) := i.U + j.U
  })
))

the error message is

top.scala:24: error: type mismatch;
 found   : Int => Unit
 required: chisel3.core.UInt => ?
      n_vec(i).foreach((j:Int)=>{
                              ^

Could you enlight me whether it can be used in such a way, even how?

Body:
Yes it can be used this way.

solution:

var x = 0
var y = 0
n_vec.foreach(i=>{
  i.foreach(j=>{
    j := x.U + y.U
    y = y + 1
  })
  y = 0
  x = x + 1
})
x = 0
y = 0


问:
Cygwin C:/Program: No such file or directory
After migrating from Windows 7 to Windows 10, I re-installed Cygwin. When I run from Cygwin I'm getting following error:

/cygdrive/c/Cygwin64/bin/sh: C:/Program: No such file or directory

Any idea what this could be related to ?

答:
This is the result of spaces in windows file or directory names.

To properly diagnose the problem, you will need to quote the exact command you enter, and the value of the cygwin PATH variable, e.g. echo $PATH.

Typically, this problem is fixed by quoting shell commands so the shell does not split path names on the spaces within file paths. You add double or single quotes around literal file paths, e.g. '/cygdrive/c/Program Files/...', and double quotes around variable references, e.g. "$FileName" in shell commands and scripts.

When you install or re-install cygwin, it is very important to not install to a directory with a space in its path name, do not use e.g. C:\Cygwin 64; instead use C:\Cygwin64 or C:\Cygwin_64. If you do install to such a path, your best bet is to delete that installation and reinstall to a path without a space in it.


问:
How kafka partitions behave
Can you explain how kafka partitions works for this scenario

If i produce 9 (1-9) messages round robin with 1 topic & 3 partitions.

Does it means that:

Partition 1 contains: [1,4,7]

Partition 2 contains: [2,5,8]

Partition 3 contains: [3,6,9]

?

Also how many consumers can get all the data 3? why?

Can you explain?

I guess also that consumer group can solve it but not sure why

答:
The distribution of messages in the partitions is correct if and only if you publish messages without keys. In Kafka it is common to publish messages as (Key, Value) pairs and if you produce messages this way then the default partitioner will ensure that all messages of the same key will get put in the same partition. It does this by using a hashing function on each of the keys that maps to one of the available partitions. In the extreme case where all your messages have the same key, then they would all go to the same partition. If your messages all had either a string key "foo" or a key called "bar" then all the messages with key "foo" may go to partition 3 and all the messages with key "bar" may go to partition 1.

In terms of your question about consumers, you can have an unlimited number of consumers. If each consumer has a unique group.id then they are considered independent and they will each get their own full set of the messages from all partitions.

However if you have consumers that share the same group.id then they are said to be in a consumer group and each will get an exclusive and roughly equal subset of the partitions. If you had 3 consumers in the same group they would get 1 partition each. If you added any more than 3 consumers in the same group then the first 3 will get 1 partition each and all the others will be standby consumers than only become active if one of the 3 active consumers leaves the group.

Title: How kafka partitions behave


问:
What is the correct way to instantiate ImageShader?
I need an ImageShader for my custom painter. Constructor requires Image.

I've tried to get AssetImage but I don't see the way to transform it into Image directly.

Now I'm stuck on decodeImageFromList(). How can I transform AssetImage into Uint8List?

答:
Adapted from my answer on a previous question, here is how to turn an AssetImage into a ui.Image.

```<code>  Future<ui.Image> _getImage() {
    Completer<ui.Image> completer = new Completer<ui.Image>();
    new AssetImage('assets/image.png')
      .resolve(new ImageConfiguration())
      .addListener((ImageInfo info, bool _) => completer.complete(info.image));
    return completer.future;
  }
</code>```

Body:
Adapted from my answer on a previous question, here is how to turn an AssetImage into a ui.Image.

  Future<ui.Image> _getImage() {
    Completer<ui.Image> completer = new Completer<ui.Image>();
    new AssetImage('assets/image.png')
      .resolve(new ImageConfiguration())
      .addListener((ImageInfo info, bool _) => completer.complete(info.image));
    return completer.future;
  }


问:
Why can I pass by value here but not by reference (C++)?
I have an interesting predicament here where the code will compile if I pass a variable by value to the function but not if I pass it by reference, and I'm not sure why.  In header.h:

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

void get_name(std::string &name)
{
  getline(std::cin, name);
  return;
}

template <class T, class U>
class readonly
{
  friend U;
  private:
    T data;
    T& operator=(const T& arg) {data = arg; return data;}
  public:
    operator const T&() const {return data;}
};

class myClass
{
  private:
    typedef readonly<std::string, myClass> RO_string;

  public:
    RO_string y;

    void f()
    {
      get_name(y); // compile error
    }
};
</code>```

The main.cpp implementation file simply includes this header file, creates an instance of myClass and then calls f().  When doing so, it won't compile properly.  The problem lies in the fact that I'm passing the variable y by reference to the get_name function.  If I change the function so that I pass by value instead, everything compiles properly and works as expected (except I'm obviously not making changes to y anymore).  However, I don't understand this behavior.  Why does this happen and is there an optimal way to fix it in this situation?

答:
As explained by Nir Friedman, get_name(y); invoques the implicit conversion operator which gives you a const reference.

But, as you wrote friend U;, myClass has access to the private member data of y and allows you to do:

```<code>get_name(y.data);
</code>```

Body:
I have an interesting predicament here where the code will compile if I pass a variable by value to the function but not if I pass it by reference, and I'm not sure why.  In header.h:

#include <iostream>
#include <string>

void get_name(std::string &name)
{
  getline(std::cin, name);
  return;
}

template <class T, class U>
class readonly
{
  friend U;
  private:
    T data;
    T& operator=(const T& arg) {data = arg; return data;}
  public:
    operator const T&() const {return data;}
};

class myClass
{
  private:
    typedef readonly<std::string, myClass> RO_string;

  public:
    RO_string y;

    void f()
    {
      get_name(y); // compile error
    }
};

The main.cpp implementation file simply includes this header file, creates an instance of myClass and then calls f().  When doing so, it won't compile properly.  The problem lies in the fact that I'm passing the variable y by reference to the get_name function.  If I change the function so that I pass by value instead, everything compiles properly and works as expected (except I'm obviously not making changes to y anymore).  However, I don't understand this behavior.  Why does this happen and is there an optimal way to fix it in this situation?

Body:
As explained by Nir Friedman, get_name(y); invoques the implicit conversion operator which gives you a const reference.

But, as you wrote friend U;, myClass has access to the private member data of y and allows you to do:

get_name(y.data);


问:
Null set property with innerHTML
I have been trying to merge the data from openweathermap's api together with google map's api. However, whenever I try to get my data down from the api using innerHTML, it shows that Uncaught TypeError: Cannot set property 'innerHTML' of null.

Javascript

var map;
var weather;
var temp;
var APPID = 'e9e239c6585f081bee7b0d7f6045a53f';

function updateByCity(q) {
  var url = "http://api.openweathermap.org/data/2.5/weather?q={" +
    q +
    "}&APPID=" + APPID;
  sendRequest(url);
}

function sendRequest(url) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var data = JSON.parse(xmlhttp.responseText);
      var weather = {};
      weather.temp = data.main.temp;

      update(weather);
    }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function update(weather) {
  temp.innerHTML = weather.temp;
}

window.onload = function() {
  temp = document.getElementById("temperature");
  var weather = {};
  weather.temp = "35";

  update(weather);
}

function initMap() {
  var KL = {
    lat: 3.1390,
    lng: 101.6869
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {
      lat: 4.444997,
      lng: 106.554199
    }
  });

  var marker = new google.maps.Marker({
    position: KL,
    map: map
  });

  var contentString = '
' +
    '
' +
    '
' +
    '
Kuala Lumpur
' +
    '
' +
    '
Temperature: ' + temp + '
' +
    '
' +
    '
';

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

}```
</div>
</div>
</p>

<p><strong>HTML</strong></p>

<pre class="lang-html prettyprint-override"><code><!doctype>
<html>

<head>
  <script src="mapJS.js"></script>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuhL2_brcvjW12heXCPV8G-lXd7Kmue84&callback=initMap">
  </script>
  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">
  <style>
    #map {
      height: 100%;
    }

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
  <div id="map"></div>
</head>

</html>
</code>```

答:
This should fix your null set property issue. Main reason is you have missed to create an element to set your temperature readings. Therefore i have created a new
 and it fixed the issue.

var map;
var weather;
var temp;
var APPID = 'e9e239c6585f081bee7b0d7f6045a53f';

function updateByCity(q) {
  var url = "http://api.openweathermap.org/data/2.5/weather?q={" +
    q +
    "}&APPID=" + APPID;
  sendRequest(url);
}

function sendRequest(url) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var data = JSON.parse(xmlhttp.responseText);
      var weather = {};
      weather.temp = data.main.temp;

      update(weather);
    }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function update(weather) {
  temp.innerHTML = weather.temp;
}

window.onload = function() {
  temp = document.getElementById("temperature");
  var weather = {};
  weather.temp = "35";

  update(weather);
}

function initMap() {
  var KL = {
    lat: 3.1390,
    lng: 101.6869
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {
      lat: 4.444997,
      lng: 106.554199
    }
  });

  var marker = new google.maps.Marker({
    position: KL,
    map: map
  });

  var contentString = '
' +
    '
' +
    '
' +
    '
Kuala Lumpur
' +
    '
' +
    '
Temperature: ' + temp + '
' +
    '
' +
    '
';

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

}

////////////////////////////////////////////////////```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype>
<html>

<head>
  <script src="mapJS.js"></script>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuhL2_brcvjW12heXCPV8G-lXd7Kmue84&callback=initMap">
  </script>
  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">
  <style>
    #map {
      height: 100%;
    }

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>

  <br>
  <div id="temperature"></div><br>
  <div id="map"></div>
</head>

</html></code>```

Title: Null set property with innerHTML

Body:
I have been trying to merge the data from openweathermap's api together with google map's api. However, whenever I try to get my data down from the api using innerHTML, it shows that Uncaught TypeError: Cannot set property 'innerHTML' of null.

Javascript

var map;
var weather;
var temp;
var APPID = 'e9e239c6585f081bee7b0d7f6045a53f';

function updateByCity(q) {
  var url = "http://api.openweathermap.org/data/2.5/weather?q={" +
    q +
    "}&APPID=" + APPID;
  sendRequest(url);
}

function sendRequest(url) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var data = JSON.parse(xmlhttp.responseText);
      var weather = {};
      weather.temp = data.main.temp;

      update(weather);
    }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function update(weather) {
  temp.innerHTML = weather.temp;
}

window.onload = function() {
  temp = document.getElementById("temperature");
  var weather = {};
  weather.temp = "35";

  update(weather);
}

function initMap() {
  var KL = {
    lat: 3.1390,
    lng: 101.6869
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {
      lat: 4.444997,
      lng: 106.554199
    }
  });

  var marker = new google.maps.Marker({
    position: KL,
    map: map
  });

  var contentString = '
' +
    '
' +
    '
' +
    '
Kuala Lumpur
' +
    '
' +
    '
Temperature: ' + temp + '
' +
    '
' +
    '
';

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

}

HTML

<!doctype>

  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">

Body:
This should fix your null set property issue. Main reason is you have missed to create an element to set your temperature readings. Therefore i have created a new <div id="temperature"> and it fixed the issue.

var map;
var weather;
var temp;
var APPID = 'e9e239c6585f081bee7b0d7f6045a53f';

function updateByCity(q) {
  var url = "http://api.openweathermap.org/data/2.5/weather?q={" +
    q +
    "}&APPID=" + APPID;
  sendRequest(url);
}

function sendRequest(url) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var data = JSON.parse(xmlhttp.responseText);
      var weather = {};
      weather.temp = data.main.temp;

      update(weather);
    }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function update(weather) {
  temp.innerHTML = weather.temp;
}

window.onload = function() {
  temp = document.getElementById("temperature");
  var weather = {};
  weather.temp = "35";

  update(weather);
}

function initMap() {
  var KL = {
    lat: 3.1390,
    lng: 101.6869
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {
      lat: 4.444997,
      lng: 106.554199
    }
  });

  var marker = new google.maps.Marker({
    position: KL,
    map: map
  });

  var contentString = '<div id="content">' +
    '<div id="siteNotice">' +
    '</div>' +
    '<h1 id="firstHeading" class="firstHeading">Kuala Lumpur</h1>' +
    '<div id="bodyContent">' +
    '<p>Temperature: ' + temp + '</p>' +
    '</div>' +
    '</div>';

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

}

////////////////////////////////////////////////////

<!doctype>
<html>

<head>
  <script src="mapJS.js"></script>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuhL2_brcvjW12heXCPV8G-lXd7Kmue84&callback=initMap">
  </script>
  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">
  <style>
    #map {
      height: 100%;
    }

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>

  <br>
  <div id="temperature"></div><br>
  <div id="map"></div>
</head>

</html>


问:
Xcode unable to dequeue a cell with identifier
my work is about `UITableView. Each time I run my project, this error appears :

```<code>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell1 - must register a nib or a class for the identifier or connect a prototype cell in a storyboard
</code>```

I checked a hundred times my cell identifier in my storyboard and in my code are the same.
Code (defaut code from UITableViewController) :

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *CellIdentifier = @"Cell1";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    return cell;
}
</code>```

Picture of Table View Cell properties :

I created and implemented a subclass of UITableViewCell for my cell.

Any idea why this is not working ?

Any way (line of code) to know what is the identifier of a cell ?

Thanks

Edit : Screenshot of my interface builder.

Edit 2 : Text of customCell.h

```<code>#import <UIKit/UIKit.h>

@interface customCell : UITableViewCell

@end
</code>```

New error appears when I run the project :

```<code>[<choixActiviteViewController 0x7591ac0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Cell1.
</code>```

choixActiviteViewController is a subclass of UITableViewController and is the custom class of Choix Activite View Controller.

答:
I was facing this issue when presenting the UITableViewController having a custom cell from another viewcontroller. As a workaround I instantiated it from the storyboard and that solved the issue. </p>

```<code>let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "YourTableViewController")
self.present(controller, animated: true, completion: nil)
</code>```

Body:
my work is about `UITableView. Each time I run my project, this error appears :

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell1 - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

I checked a hundred times my cell identifier in my storyboard and in my code are the same.
Code (defaut code from UITableViewController) :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *CellIdentifier = @"Cell1";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    return cell;
}

Picture of Table View Cell properties :

I created and implemented a subclass of UITableViewCell for my cell.

Any idea why this is not working ?

Any way (line of code) to know what is the identifier of a cell ?

Thanks

Edit : Screenshot of my interface builder.

Edit 2 : Text of customCell.h

#import <UIKit/UIKit.h>

@interface customCell : UITableViewCell

@end

New error appears when I run the project :

[<choixActiviteViewController 0x7591ac0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Cell1.

choixActiviteViewController is a subclass of UITableViewController and is the custom class of Choix Activite View Controller.

Body:
I was facing this issue when presenting the UITableViewController having a custom cell from another viewcontroller. As a workaround I instantiated it from the storyboard and that solved the issue.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "YourTableViewController")
self.present(controller, animated: true, completion: nil)


问:
Armadillo: convert cube subview (tube) to vector
I get compilation error when I try to get a vector/double from armadillo cube (using tube or slice). How to get from cube to (row)vec? I can not find an elegant cast/transform armadillo function.</p>

```<code>#include <RcppArmadillo.h>
//#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void testarma() {
  arma::mat B;

  B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << arma::endr
    << 0.108929 << 0.830123 << 0.891726 << 0.895283 << arma::endr
    << 0.948014 << 0.973234 << 0.216504 << 0.883152 << arma::endr
    << 0.023787 << 0.675382 << 0.231751 << 0.450332 << arma::endr;

  B.print("B:");

  // cubes ("3D matrices")
  arma::cube Q(B.n_rows, B.n_cols, 4);

  Q.slice(0) = B;
  Q.slice(1) = 2.0 * B;
  Q.slice(2) = 3.0 * B;
  Q.slice(3) = 4.0 * B;

  Q.print("Q:");

  Rcpp::Rcout << "Q.tube(0, 1): " << std::endl << Q.tube(0, 1) << std::endl;

  arma::rowvec whatIwant = arma::rowvec(4).fill(0.0);

  for (int i = 0; i < 4; i++) {
    // This gives an error. cannot convert 'arma::subview_col<double>' to 'double' in assignment
    //whatIwant[i] = Q.slice(i).row(0).col(1);
    Rcpp::Rcout << "At slice i=" << i << " value=" << Q.slice(i).row(0).col(1) << std::endl;
  }

  // But I don't want to write for loop. I am sure there exists
  // an "armadillo" way (function) that does exactly this
  // How to convert output of tube to rowvec?
}
</code>```

答:
There are three ways I see to do it:

Using a loop with as_scalar() to convert the final subset to a double.

Subset to cube then use a shared memory pointer

Direct subset to a rowvec

The last option is most likely what you want as it can be done inline.

In your case, the operation would be:

```<code>arma::rowvec A = Q(arma::span(0), arma::span(1), arma::span::all);
</code>```

This is taken from the subcube subset section of the documentation.

The implementation of each of the above cases is shown below.

```<code>#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
void cube_subset_to_rowvec() {
    // Sample data
    arma::mat B;

    B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << arma::endr
      << 0.108929 << 0.830123 << 0.891726 << 0.895283 << arma::endr
      << 0.948014 << 0.973234 << 0.216504 << 0.883152 << arma::endr
      << 0.023787 << 0.675382 << 0.231751 << 0.450332 << arma::endr;

    // cubes ("3D matrices")
    arma::cube Q(B.n_rows, B.n_cols, 4);

    Q.slice(0) = B;
    Q.slice(1) = 2.0 * B;
    Q.slice(2) = 3.0 * B;
    Q.slice(3) = 4.0 * B;

    // Objective
    Rcpp::Rcout << "Q.tube(0, 1): " << std::endl << Q.tube(0, 1) << std::endl;

    // Individually loading elements
    arma::rowvec individual_elements(4);
    for (int i = 0; i < 4; i++) {
        individual_elements[i] = arma::as_scalar(Q.slice(i).row(0).col(1));
        Rcpp::Rcout << "At slice i=" << i << " value=" << individual_elements[i] << std::endl;
    }

    // Subset to cube then use a shared memory pointer
    arma::cube mem_ex = Q.tube(0,1);
    arma::rowvec cub_subset = arma::rowvec(mem_ex.memptr(), mem_ex.n_elem, 1, false);
    Rcpp::Rcout << cub_subset << std::endl;

    // Direct subset to a rowvec
    arma::rowvec direct_subset = Q(arma::span(0), arma::span(1), arma::span::all);
    Rcpp::Rcout << direct_subset << std::endl;

}
</code>```

Run:

```<code>cube_subset_to_rowvec()
</code>```

Output:

```<code>Q.tube(0, 1):
[cube slice 0]
   0.2747

[cube slice 1]
   0.5494

[cube slice 2]
   0.8241

[cube slice 3]
   1.0988

At slice i=0 value=0.27469
At slice i=1 value=0.54938
At slice i=2 value=0.82407
At slice i=3 value=1.09876
   0.2747   0.5494   0.8241   1.0988

   0.2747   0.5494   0.8241   1.0988
</code>```

Body:
I get compilation error when I try to get a vector/double from armadillo cube (using tube or slice). How to get from cube to (row)vec? I can not find an elegant cast/transform armadillo function.

#include <RcppArmadillo.h>
//#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void testarma() {
  arma::mat B;

  B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << arma::endr
    << 0.108929 << 0.830123 << 0.891726 << 0.895283 << arma::endr
    << 0.948014 << 0.973234 << 0.216504 << 0.883152 << arma::endr
    << 0.023787 << 0.675382 << 0.231751 << 0.450332 << arma::endr;

  B.print("B:");

  // cubes ("3D matrices")
  arma::cube Q(B.n_rows, B.n_cols, 4);

  Q.slice(0) = B;
  Q.slice(1) = 2.0 * B;
  Q.slice(2) = 3.0 * B;
  Q.slice(3) = 4.0 * B;

  Q.print("Q:");

  Rcpp::Rcout << "Q.tube(0, 1): " << std::endl << Q.tube(0, 1) << std::endl;

  arma::rowvec whatIwant = arma::rowvec(4).fill(0.0);

  for (int i = 0; i < 4; i++) {
    // This gives an error. cannot convert 'arma::subview_col<double>' to 'double' in assignment
    //whatIwant[i] = Q.slice(i).row(0).col(1);
    Rcpp::Rcout << "At slice i=" << i << " value=" << Q.slice(i).row(0).col(1) << std::endl;
  }

  // But I don't want to write for loop. I am sure there exists
  // an "armadillo" way (function) that does exactly this
  // How to convert output of tube to rowvec?
}

Body:
There are three ways I see to do it:

Using a loop with as_scalar() to convert the final subset to a double.

Subset to cube then use a shared memory pointer

Direct subset to a rowvec

The last option is most likely what you want as it can be done inline.

In your case, the operation would be:

arma::rowvec A = Q(arma::span(0), arma::span(1), arma::span::all);

This is taken from the subcube subset section of the documentation.

The implementation of each of the above cases is shown below.

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
void cube_subset_to_rowvec() {
    // Sample data
    arma::mat B;

    B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << arma::endr
      << 0.108929 << 0.830123 << 0.891726 << 0.895283 << arma::endr
      << 0.948014 << 0.973234 << 0.216504 << 0.883152 << arma::endr
      << 0.023787 << 0.675382 << 0.231751 << 0.450332 << arma::endr;

    // cubes ("3D matrices")
    arma::cube Q(B.n_rows, B.n_cols, 4);

    Q.slice(0) = B;
    Q.slice(1) = 2.0 * B;
    Q.slice(2) = 3.0 * B;
    Q.slice(3) = 4.0 * B;

    // Objective
    Rcpp::Rcout << "Q.tube(0, 1): " << std::endl << Q.tube(0, 1) << std::endl;

    // Individually loading elements
    arma::rowvec individual_elements(4);
    for (int i = 0; i < 4; i++) {
        individual_elements[i] = arma::as_scalar(Q.slice(i).row(0).col(1));
        Rcpp::Rcout << "At slice i=" << i << " value=" << individual_elements[i] << std::endl;
    }

    // Subset to cube then use a shared memory pointer
    arma::cube mem_ex = Q.tube(0,1);
    arma::rowvec cub_subset = arma::rowvec(mem_ex.memptr(), mem_ex.n_elem, 1, false);
    Rcpp::Rcout << cub_subset << std::endl;

    // Direct subset to a rowvec
    arma::rowvec direct_subset = Q(arma::span(0), arma::span(1), arma::span::all);
    Rcpp::Rcout << direct_subset << std::endl;

}

Run:

cube_subset_to_rowvec()

Output:

Q.tube(0, 1):
[cube slice 0]
   0.2747

[cube slice 1]
   0.5494

[cube slice 2]
   0.8241

[cube slice 3]
   1.0988

At slice i=0 value=0.27469
At slice i=1 value=0.54938
At slice i=2 value=0.82407
At slice i=3 value=1.09876
   0.2747   0.5494   0.8241   1.0988

   0.2747   0.5494   0.8241   1.0988


问:
Python: save attachments from .msg files
So I have a folder with a ton of .msg files. I want to be able to save one of the attachments. My idea was automating clicking the files, then somehow extracting the file with a certain file name but I have yet to find any solutions to this.

How do I go about doing this? Or a better way?

Thanks!

Update:
I've got an idea to use os.startfile to open the file I want it to open...
How do I not open it in another window? But act like it did? If that makes any sense :/

答:
This should work:

```<code>import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem(filename)        #filename including path
att=msg.Attachments
for i in att:
    i.SaveAsFile(os.path.join(Pathname, i.FileName))#Saves the file with the attachment name
</code>```

Since you say you have a folder, this will automate the whole folder:

```<code>import win32com.client
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for file in files:
    if file.endswith(".msg"):
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        msg = outlook.OpenSharedItem(file)
        att=msg.Attachments
        for i in att:
            i.SaveAsFile(os.path.join(Pathname, i.FileName))#Saves the file with the attachment name
</code>```

Body:
This should work:

import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem(filename)        #filename including path
att=msg.Attachments
for i in att:
    i.SaveAsFile(os.path.join(Pathname, i.FileName))#Saves the file with the attachment name

Since you say you have a folder, this will automate the whole folder:

import win32com.client
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for file in files:
    if file.endswith(".msg"):
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        msg = outlook.OpenSharedItem(file)
        att=msg.Attachments
        for i in att:
            i.SaveAsFile(os.path.join(Pathname, i.FileName))#Saves the file with the attachment name


问:
Displaying Tumblr Posts in a Specified Order
What I would like to accomplish is a Tumblr blog whose main page ('home/index') displays posts in an order specified by the blog owner (in this case, myself; I do not want it to display the most recent first, nor do I want it to display in chronological order.

The ideal would be to tag or otherwise specify a post with a number (e.g. '1', '2') and regardless of which was posted first, 2 is displayed after 1 if I designate it as so (except a bit more complex than that, because I was hoping to use dates).

Is this possible? And if so, how would I go about doing it?

edit: (To more clearly illustrate the purpose for this, I'm hoping to display posts containing content that is supposed to be in 'chronological order'. However, the posts themselves cannot be displayed chronologically because the content I'm putting in the posts is not all known; if I discover new content, I need to insert it into a pre-existing timeline).

Thank you!

答:
A possible solution would be to post your post and then edit the date to be in between the two posts you want it to be.

Another solution would be to use tumbr's API v1 with JSON. You would make a function that first calls something like http://yoururl.tumblr.com/api/read/json?tagged=1 where 1 is actually a variable and from there, if it returns a post, then you increment your variable and call the function again and it will repeat for as many number tags as you have.


问:
getchar() is not called when the program is executed via nvim in C
I am a novice C programmer currently designing simple programs based on books to get more knowledge.
Right now, I am studying "The C Programming Language" (Brian Kernighan, Dennis Ritchie) and I'm hitting the section discussing about input/output programming.

Here is the code I am trying to run (almost exact copy from K&R):

```<code>#include <stdlib.h>
#include <stdio.h>

int main (int argc, char** argv)
{
    int c;

    printf("Input character:\n");

    while ((c = getchar()) != EOF){
        putchar(c);
    }

    printf("End of code\n");

    return 0;

}
</code>```

I use nvim as my IDE. I set my nvim shortcuts as follow for the compilation:

```<code>nnoremap <leader>cc :!gcc -Wall % -o %:r && ./%:r<CR>
</code>```

Now back to the code. When I compile this one using the shortcut showed above, it works just fine. the code compiles. However, my program ends without asking me for any input (as the call to getchar() should do):

```<code>:!gcc -Wall inputoutput.c -o inputoutput && ./inputoutput

Input character:
End of code
</code>```

Typing the command directly in nvim, without any subsitution:

```<code>:gcc -Wall inputoutput.c -o inputoutput && ./inputoutput
</code>```

Gives me the same output as before.

However, when I execute the compiled program outside nvim, I get the expected behavior:

```<code>nxr: ~/scratch/c - ./inputouput
Input character:
a
a
** <CTRL-d> **
End of code

nxr: ~/scratch/c -
</code>```

My questions are:

Why the behavior within nvim and outside is different when I try running the code?

What should I change in my C code or my nvim macro in order to obtain the expected behavior when running the program within nvim?

答:
Neovim bang character introduces a EOF, as explained here.

Change the ! in the macro by "te".

Body:
I am a novice C programmer currently designing simple programs based on books to get more knowledge.
Right now, I am studying "The C Programming Language" (Brian Kernighan, Dennis Ritchie) and I'm hitting the section discussing about input/output programming.

Here is the code I am trying to run (almost exact copy from K&R):

#include <stdlib.h>
#include <stdio.h>

int main (int argc, char** argv)
{
    int c;

    printf("Input character:\n");

    while ((c = getchar()) != EOF){
        putchar(c);
    }

    printf("End of code\n");

    return 0;

}

I use nvim as my IDE. I set my nvim shortcuts as follow for the compilation:

nnoremap <leader>cc :!gcc -Wall % -o %:r && ./%:r<CR>

Now back to the code. When I compile this one using the shortcut showed above, it works just fine. the code compiles. However, my program ends without asking me for any input (as the call to getchar() should do):

:!gcc -Wall inputoutput.c -o inputoutput && ./inputoutput

Input character:
End of code

Typing the command directly in nvim, without any subsitution:

:gcc -Wall inputoutput.c -o inputoutput && ./inputoutput

Gives me the same output as before.

However, when I execute the compiled program outside nvim, I get the expected behavior:

nxr: ~/scratch/c - ./inputouput
Input character:
a
a
** <CTRL-d> **
End of code

nxr: ~/scratch/c -

My questions are:

Why the behavior within nvim and outside is different when I try running the code?

What should I change in my C code or my nvim macro in order to obtain the expected behavior when running the program within nvim?


问:
CSS color sections dived diagonally
Is it possible to accomplish a diagonal line stroke, with a bit of an off-set in any side. I've seen a variation of this accomplished with css linear-gradient, but I need something slightly different. I don't know how to describe what I need exactly in words. I'll use pictures.

I've tried playing with gradients:

.diagonal{
  background-color: #34ADFF;
  background-image: linear-gradient(to right top, whitesmoke 50%, #34ADFF 50%);
  height: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="diagonal">
</div></code>```

That's how far I've gone. I'm thinking of playing around with child divs, but I'm not sure yet.

Any ideas ?

I don't want to use images, I want to use just CSS.

答:
Ok so here's the thing. This must stay responsive and able to evolve over time so I searched for a better solution and here's what I found. To simplify it a little bit, here's a snippet :

.se-container {
  display: block;
  width: 100%;
  overflow: hidden;
  padding-top: 100px;
}

.se-slope {
  margin: 0 -50px;
  transform-origin: left center;
}

.se-slope:nth-child(odd) {
  background: url(http://lorempixel.com/400/200/);
  background-size: cover;
  transform: rotate(5deg);
  margin-top: -200px;
  box-shadow: 0px -1px 3px rgba(0, 0, 0, 0.4);
}

.se-slope:nth-child(even) {
  background: linear-gradient(to right, purple 0%, red 100%);
  transform: rotate(-5deg);
  box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.4) inset;
}

.se-content {
  margin: 0 auto;
}

.se-content p {
  width: 75%;
  max-width: 500px;
  margin: 0 auto;
  font-size: 18px;
  line-height: 24px;
}

.se-slope:nth-child(odd) .se-content {
  transform: rotate(-5deg);
  padding: 130px 100px 250px 100px;
}

.se-slope:nth-child(even) .se-content {
  transform: rotate(5deg);
  padding: 150px 100px 250px 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="se-container">
  <div class="se-slope">
    <article class="se-content">
      <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam id dolor id nibh ultricies vehicula ut id elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</p>
    </article>
  </div>
  <div class="se-slope">
    <article class="se-content">
      <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam id dolor id nibh ultricies vehicula ut id elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</p>
    </article>
  </div>
  <div class="se-slope">
    <article class="se-content">
      <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam id dolor id nibh ultricies vehicula ut id elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</p>
    </article>
  </div>
</section></code>```

Title: CSS color sections dived diagonally

Body:
Is it possible to accomplish a diagonal line stroke, with a bit of an off-set in any side. I've seen a variation of this accomplished with css linear-gradient, but I need something slightly different. I don't know how to describe what I need exactly in words. I'll use pictures.

I've tried playing with gradients:

.diagonal{
  background-color: #34ADFF;
  background-image: linear-gradient(to right top, whitesmoke 50%, #34ADFF 50%);
  height: 300px;
}

That's how far I've gone. I'm thinking of playing around with child divs, but I'm not sure yet.

Any ideas ?

I don't want to use images, I want to use just CSS.

Body:
Ok so here's the thing. This must stay responsive and able to evolve over time so I searched for a better solution and here's what I found. To simplify it a little bit, here's a snippet :

.se-container {
  display: block;
  width: 100%;
  overflow: hidden;
  padding-top: 100px;
}

.se-slope {
  margin: 0 -50px;
  transform-origin: left center;
}

.se-slope:nth-child(odd) {
  background: url(http://lorempixel.com/400/200/);
  background-size: cover;
  transform: rotate(5deg);
  margin-top: -200px;
  box-shadow: 0px -1px 3px rgba(0, 0, 0, 0.4);
}

.se-slope:nth-child(even) {
  background: linear-gradient(to right, purple 0%, red 100%);
  transform: rotate(-5deg);
  box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.4) inset;
}

.se-content {
  margin: 0 auto;
}

.se-content p {
  width: 75%;
  max-width: 500px;
  margin: 0 auto;
  font-size: 18px;
  line-height: 24px;
}

.se-slope:nth-child(odd) .se-content {
  transform: rotate(-5deg);
  padding: 130px 100px 250px 100px;
}

.se-slope:nth-child(even) .se-content {
  transform: rotate(5deg);
  padding: 150px 100px 250px 100px;
}

<section class="se-container">
  <div class="se-slope">
    <article class="se-content">
      <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam id dolor id nibh ultricies vehicula ut id elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</p>
    </article>
  </div>
  <div class="se-slope">
    <article class="se-content">
      <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam id dolor id nibh ultricies vehicula ut id elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</p>
    </article>
  </div>
  <div class="se-slope">
    <article class="se-content">
      <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam id dolor id nibh ultricies vehicula ut id elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</p>
    </article>
  </div>
</section>


问:
Horizontal Recycler View inside ViewPager not scrolling

The Problem

I have a horizontal RecyclerView inside a NestedScrollView which is inside a ViewPager. Now when I try to scroll the RecyclerView, sometimes it scrolls, but sometimes only the ViewPager scrolls.

The Code

That's how my RecyclerView XML looks like:

```<code><android.support.v7.widget.RecyclerView
            android:id="@+id/sidescroll"
            android:layout_below="@+id/movie_more_movies2"
            android:layout_marginTop="@dimen/material_layout_keylines_horizontal_margin"
            android:layout_marginBottom="@dimen/material_layout_keylines_horizontal_margin"
            android:layout_width="match_parent"
            android:orientation="horizontal"
            app:layoutManager="android.support.v7.widget.LinearLayoutManager"
            android:layout_height="wrap_content"/>
</code>```

That's how the Nested Scroll, in which the RecyclerView is, looks like:

```<code><android.support.v4.widget.NestedScrollView
    android:id="@+id/detail_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:descendantFocusability="blocksDescendants"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >
</code>```

And this is the viewpager xml:

```<code><com.mt.moviesiwanttowatch.ui.ViewPagerWithHorizontalRecyclerView
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipChildren="false"
            android:clipToPadding="false"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code>```

I am using this Custom ViewPager:

```<code>public class ViewPagerWithHorizontalRecyclerView extends ViewPager {

    public ViewPagerWithHorizontalRecyclerView(Context context) {
        super(context);
    }

    public ViewPagerWithHorizontalRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
        if(v instanceof RecyclerView){
            Log.e("PAGER", "IS");
            return false;
        } else {
            Log.e("PAGER", "IS NOT " + v.toString());
        }

        return super.canScroll(v, checkV, dx, x, y);
    }
}
</code>```

My Approach

What I tried so far, as you can see I wrote a custom ViewPager. I tried to tell the ViewPager that it can not scroll if the scroll comes from an RecyclerView. However this doesn't work.

The Logs:

This is a log when the ViewPager scrolls instead of the RecyclerView

```<code>>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT
> com.mt.moviesiwanttowatch.ui.ViewPagerWithHorizontalRecyclerView{c506165
> VFED..... ........ 0,341-1080,1794 #7f090287 app:id/viewpager}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT android.support.v4.widget.NestedScrollView{d21952 VFED.....
> ........ 0,0-1080,1453 #7f0900b9 app:id/detail_holder}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT android.widget.RelativeLayout{6ddeec0 V.E...... ........
> 0,0-1080,2860 #7f090199 app:id/movie_overview_holder}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS
</code>```

答:
try to set onTouchListener for recycleView:

```<code>recycleView.setOnTouchListener(new OnTouchListener() {
        private float mLastX = 0, mLastY = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    float deltaX = event.getX() - mLastX;
                    float deltaY = event.getY() - mLastY;
                    if (Math.abs(deltaX) > 20 && Math.abs(deltaX) > Math.abs(deltaY)) {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                    mLastX = event.getX();
                    mLastY = event.getY();
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    getParent().requestDisallowInterceptTouchEvent(false);
                    break;
            }
            return onTouchEvent(event);
        }
    });
</code>```

Body:
The Problem

I have a horizontal RecyclerView inside a NestedScrollView which is inside a ViewPager. Now when I try to scroll the RecyclerView, sometimes it scrolls, but sometimes only the ViewPager scrolls.

The Code

That's how my RecyclerView XML looks like:

<android.support.v7.widget.RecyclerView
            android:id="@+id/sidescroll"
            android:layout_below="@+id/movie_more_movies2"
            android:layout_marginTop="@dimen/material_layout_keylines_horizontal_margin"
            android:layout_marginBottom="@dimen/material_layout_keylines_horizontal_margin"
            android:layout_width="match_parent"
            android:orientation="horizontal"
            app:layoutManager="android.support.v7.widget.LinearLayoutManager"
            android:layout_height="wrap_content"/>

That's how the Nested Scroll, in which the RecyclerView is, looks like:

<android.support.v4.widget.NestedScrollView
    android:id="@+id/detail_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:descendantFocusability="blocksDescendants"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >

And this is the viewpager xml:

<com.mt.moviesiwanttowatch.ui.ViewPagerWithHorizontalRecyclerView
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipChildren="false"
            android:clipToPadding="false"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

I am using this Custom ViewPager:

public class ViewPagerWithHorizontalRecyclerView extends ViewPager {

    public ViewPagerWithHorizontalRecyclerView(Context context) {
        super(context);
    }

    public ViewPagerWithHorizontalRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
        if(v instanceof RecyclerView){
            Log.e("PAGER", "IS");
            return false;
        } else {
            Log.e("PAGER", "IS NOT " + v.toString());
        }

        return super.canScroll(v, checkV, dx, x, y);
    }
}

My Approach

What I tried so far, as you can see I wrote a custom ViewPager. I tried to tell the ViewPager that it can not scroll if the scroll comes from an RecyclerView. However this doesn't work.

The Logs:

This is a log when the ViewPager scrolls instead of the RecyclerView

>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT
> com.mt.moviesiwanttowatch.ui.ViewPagerWithHorizontalRecyclerView{c506165
> VFED..... ........ 0,341-1080,1794 #7f090287 app:id/viewpager}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT android.support.v4.widget.NestedScrollView{d21952 VFED.....
> ........ 0,0-1080,1453 #7f0900b9 app:id/detail_holder}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT android.widget.RelativeLayout{6ddeec0 V.E...... ........
> 0,0-1080,2860 #7f090199 app:id/movie_overview_holder}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS

Body:
try to set onTouchListener for recycleView:

recycleView.setOnTouchListener(new OnTouchListener() {
        private float mLastX = 0, mLastY = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    float deltaX = event.getX() - mLastX;
                    float deltaY = event.getY() - mLastY;
                    if (Math.abs(deltaX) > 20 && Math.abs(deltaX) > Math.abs(deltaY)) {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                    mLastX = event.getX();
                    mLastY = event.getY();
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    getParent().requestDisallowInterceptTouchEvent(false);
                    break;
            }
            return onTouchEvent(event);
        }
    });


问:
jquery this child selector?
hey,
quick question, i couldn't find anything on the web. I have a parent div and a child div inside of it. to select it with css you would say:

```<code>#parent .child {}
</code>```

In jquery I have a var for my parent element, however how can i select the child with this?
I know it's easy to create a new var, i'm just curious if it's possible?

```<code>var Parent = $('#parent');

Parent.click(function() {
$(this > '.child').hide();
</code>```

thank you

答:
U can find children of your parent elements and apply css.

Sample code is below.

```<code>var Parent = $('#parent');

Parent.click(function() {
$(this).find('.child').hide();});
</code>```

ContentLicense: CC BY-SA 2.5

Title: jquery this child selector?

Body:
hey,
quick question, i couldn't find anything on the web. I have a parent div and a child div inside of it. to select it with css you would say:

#parent .child {}

In jquery I have a var for my parent element, however how can i select the child with this?
I know it's easy to create a new var, i'm just curious if it's possible?

var Parent = $('#parent');

Parent.click(function() {
$(this > '.child').hide();

thank you

Body:
U can find children of your parent elements and apply css.

Sample code is below.

var Parent = $('#parent');

Parent.click(function() {
$(this).find('.child').hide();});


问:
SQL - Table waiting for Commit/Rollback after closing session
I have a large table without any indexes on it, about 27.5m rows.
I tried to delete about half of those using using BEGIN TRAN.
I then tried canceling the querie, but because it was taking long I decided to just close the Management Studio.

Now when I try to look into that table, it does not return anything, just keeps running.

When I run SELECT TOP 10 * FROM Tbl it just executes without returning anything.

But when I run SELECT TOP 10 * FROM Tbl(NOLOCK) it return 10 rows.

This tells me that it is waiting on a Rollback/Commit from my BEGIN TRAN.

I thought it would rollback automatically after closing the session and Management Studio.

 How do I fix this issue?

Thanks.

答:
Execute SP: SP_LOCK

In Results you will get SPID, DBID, OBJID, INDID, TYPE, RESOURCE,
  MODE, STATUS

   Now check the status column, if it is showing wait then

kill that SPID.   To kill a particular SPID Execute SP: Kill 65 (Where
  65 is SPID)

MSDN Forum


问:
How to add favicon.ico on beego?
my routers/default.go, I'm trying to use the original Go solution, but failed, this code can't compiled. I don't know how to replace the router with faviconHandler:</p>

```<code>func faviconHandler(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "static/img/favicon.ico")
}
func init() {
        beego.Router("/", &controllers.MainController{})
        beego.Router("/favicon.ico", faviconHandler)  // this doesn't work
}
</code>```

答:
I found there is at least one method: embedded into index.tpl.

```<code>bee new newapp
cd $GOPATH/src/newapp
bee run  # you will see the favicon of a bee.
</code>```

Modify the embedded text in $GOPATH/src/view/index.tpl to yours, here is a linux script

```<code>cd views
# assume you have put the favicon.ico in this directory
base64 -w0 favicon.ico > favicon.b64
cp index.tpl index.tpl.old
sed 's/base64,.*"/base64,\n"/' index.tpl.old | sed '7r favicon.b64' > index.tpl
# rm favicon.ico favicon.b64  index.tpl.old # remove the temp file
</code>```

Title: How to add favicon.ico on beego?

Body:
my routers/default.go, I'm trying to use the original Go solution, but failed, this code can't compiled. I don't know how to replace the router with faviconHandler:

func faviconHandler(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "static/img/favicon.ico")
}
func init() {
        beego.Router("/", &controllers.MainController{})
        beego.Router("/favicon.ico", faviconHandler)  // this doesn't work
}

Body:
I found there is at least one method: embedded into index.tpl.

bee new newapp
cd $GOPATH/src/newapp
bee run  # you will see the favicon of a bee.

Modify the embedded text in $GOPATH/src/view/index.tpl to yours, here is a linux script

cd views
# assume you have put the favicon.ico in this directory
base64 -w0 favicon.ico > favicon.b64
cp index.tpl index.tpl.old
sed 's/base64,.*"/base64,\n"/' index.tpl.old | sed '7r favicon.b64' > index.tpl
# rm favicon.ico favicon.b64  index.tpl.old # remove the temp file


问:
Select appropriate function from enum
Let's say I have small library that I want to wrap in order to improve usability. I only want to wrapper them; I don't want to touch the existing code.

For example:

```<code>template <typename T>
class vector_type_A {
    //...
};
template <typename T>
class vector_type_B {
    //...
};
template <typename T>
class vector_type_C {
    //...
};
</code>```

I can do this to wrap a class:

```<code>enum type_e {
    Type_A, Type_B, Type_C
};

template <type_e type, typename T>
class vector_selector;

template <typename T>
class vector_selector <Type_A, T> {
public:
    using vector = vector_type_A<T>;
};
template <typename T>
class vector_selector <Type_B, T> {
public:
    using vector = vector_type_B<T>;
};
template <typename T>
class vector_selector <Type_C, T> {
public:
    using vector = vector_type_C<T>;
};

template <type_e type, typename T>
using vector = typename vector_selector<type,T>::vector;
</code>```

But this doesn't wrap functions, only classes.

How can I write similar selector for functions?

答:
This would be easy if we could partially specialize function templates, but we can't, so we need to use a class to do this.

Given your functions (as an example):

```<code>template<typename T>
int fn_type_A(vector_type_A<T> const&) {
    return 0;
}

template<typename T>
int fn_type_B(vector_type_B<T> const&) {
    return 1;
}

template<typename T>
int fn_type_C(vector_type_C<T> const&) {
    return 2;
}
</code>```

You can write this:

```<code>template<type_e type>
struct fn_selector;

template<>
struct fn_selector<Type_A>
{
    template<typename T>
    static int fn(vector_type_A<T> const& vec) {
        return fn_type_A(vec);
    }
};

template<>
struct fn_selector<Type_B>
{
    template<typename T>
    static int fn(vector_type_B<T> const& vec) {
        return fn_type_B(vec);
    }
};

template<>
struct fn_selector<Type_C>
{
    template<typename T>
    static int fn(vector_type_C<T> const& vec) {
        return fn_type_C(vec);
    }
};

template<type_e type, typename T>
int fn(vector<type, T> const& vec) {
    return fn_selector<type>::fn(vec);
}
</code>```

If you find that you are writing many of these, you should probably combine them into a single selector:

```<code>template<type_e>
struct vector_selector;

template<>
struct vector_selector<Type_A>
{
    template<typename T>
    using type = vector_type_A<T>;

    template<typename T>
    static int fn(vector_type_A<T> const& vec) {
        return fn_type_A(vec);
    }
};

template<>
struct vector_selector<Type_B>
{
    template<typename T>
    using type = vector_type_B<T>;

    template<typename T>
    static int fn(vector_type_B<T> const& vec) {
        return fn_type_B(vec);
    }
};

template<>
struct vector_selector<Type_C>
{
    template<typename T>
    using type = vector_type_C<T>;

    template<typename T>
    static int fn(vector_type_C<T> const& vec) {
        return fn_type_C(vec);
    }
};

template <type_e type, typename T>
using vector = typename vector_selector<type>::template type<T>;

template<type_e type, typename T>
int fn(vector<type, T> const& vec) {
    return vector_selector<type>::fn(vec);
}
</code>```

With C++17, you could simplify the function selection to:

```<code>template<type_e type, typename T>
int fn(vector<type, T> const& vec) {
    if constexpr (type == Type_A) {
        return fn_type_A(vec);
    } else if (type == Type_B) {
        return fn_type_B(vec);
    } else {
        static_assert(type == Type_C, "Unknown type");
        return fn_type_C(vec);
    }
}
</code>```

Title: Select appropriate function from enum

Body:
Let's say I have small library that I want to wrap in order to improve usability. I only want to wrapper them; I don't want to touch the existing code.

For example:

template <typename T>
class vector_type_A {
    //...
};
template <typename T>
class vector_type_B {
    //...
};
template <typename T>
class vector_type_C {
    //...
};

I can do this to wrap a class:

enum type_e {
    Type_A, Type_B, Type_C
};

template <type_e type, typename T>
class vector_selector;

template <typename T>
class vector_selector <Type_A, T> {
public:
    using vector = vector_type_A<T>;
};
template <typename T>
class vector_selector <Type_B, T> {
public:
    using vector = vector_type_B<T>;
};
template <typename T>
class vector_selector <Type_C, T> {
public:
    using vector = vector_type_C<T>;
};

template <type_e type, typename T>
using vector = typename vector_selector<type,T>::vector;

But this doesn't wrap functions, only classes.

How can I write similar selector for functions?

Body:
This would be easy if we could partially specialize function templates, but we can't, so we need to use a class to do this.

Given your functions (as an example):

template<typename T>
int fn_type_A(vector_type_A<T> const&) {
    return 0;
}

template<typename T>
int fn_type_B(vector_type_B<T> const&) {
    return 1;
}

template<typename T>
int fn_type_C(vector_type_C<T> const&) {
    return 2;
}

You can write this:

template<type_e type>
struct fn_selector;

template<>
struct fn_selector<Type_A>
{
    template<typename T>
    static int fn(vector_type_A<T> const& vec) {
        return fn_type_A(vec);
    }
};

template<>
struct fn_selector<Type_B>
{
    template<typename T>
    static int fn(vector_type_B<T> const& vec) {
        return fn_type_B(vec);
    }
};

template<>
struct fn_selector<Type_C>
{
    template<typename T>
    static int fn(vector_type_C<T> const& vec) {
        return fn_type_C(vec);
    }
};

template<type_e type, typename T>
int fn(vector<type, T> const& vec) {
    return fn_selector<type>::fn(vec);
}

If you find that you are writing many of these, you should probably combine them into a single selector:

template<type_e>
struct vector_selector;

template<>
struct vector_selector<Type_A>
{
    template<typename T>
    using type = vector_type_A<T>;

    template<typename T>
    static int fn(vector_type_A<T> const& vec) {
        return fn_type_A(vec);
    }
};

template<>
struct vector_selector<Type_B>
{
    template<typename T>
    using type = vector_type_B<T>;

    template<typename T>
    static int fn(vector_type_B<T> const& vec) {
        return fn_type_B(vec);
    }
};

template<>
struct vector_selector<Type_C>
{
    template<typename T>
    using type = vector_type_C<T>;

    template<typename T>
    static int fn(vector_type_C<T> const& vec) {
        return fn_type_C(vec);
    }
};

template <type_e type, typename T>
using vector = typename vector_selector<type>::template type<T>;

template<type_e type, typename T>
int fn(vector<type, T> const& vec) {
    return vector_selector<type>::fn(vec);
}

With C++17, you could simplify the function selection to:

template<type_e type, typename T>
int fn(vector<type, T> const& vec) {
    if constexpr (type == Type_A) {
        return fn_type_A(vec);
    } else if (type == Type_B) {
        return fn_type_B(vec);
    } else {
        static_assert(type == Type_C, "Unknown type");
        return fn_type_C(vec);
    }
}


问:
changing the url into dash instead of underscore using Codeigniter
Hi im using codeigniter framework because its really cool when it comes to MVC thing. I have a question regarding in the url thing. Usually when saving a controller, lets say in the about us page it has to do something like this About_us extends CI_Controller. When that comes to the url thing it goes like this test.com/about_us. I want that my url is not underscore. I want to be dashed something like this test.com/about-us. How will i able to use the dash instead of using underscore???

any help is greatly appreciated
thanks!

答:
Code Ignitor 3 has this built-in option. In your routes.php:

```<code>$route['translate_uri_dashes'] = FALSE;
</code>```

Just change this to "TRUE" and you can use either _ or - in URL

Here is a detailed article how to fix it.

Body:
Code Ignitor 3 has this built-in option. In your routes.php:

$route['translate_uri_dashes'] = FALSE;

Just change this to "TRUE" and you can use either _ or - in URL

Here is a detailed article how to fix it.


问:
App works in Simulator but not on Device - NSMutableArray
I have a problem with my app, which run well on the simulator but when I launch on my iDevice I got an error:

```<code>     Terminating app due to uncaught exception 'NSInvalidArgumentException',
         reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'

    0   CoreFoundation                      0x3513cfd3 __exceptionPreprocess + 114
    1   libobjc.A.dylib                     0x303928a5 objc_exception_throw + 24
    2   CoreFoundation                      0x350bff99 -[__NSArrayM insertObject:atIndex:] + 472
    3   CoreFoundation                      0x350bfda7 -[__NSArrayM addObject:] + 34
    ....
    Program received signal:  “SIGABRT”.
</code>```

In the debugger I can see where is the problem. The error comes from there, at the addObject:

```<code>for (int i = 0; i < [arrayValues count]; i++) {
    f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    myNumber =[f numberFromString:[arrayValues objectAtIndex:i]];

    [arrayValues2 addObject:myNumber];
    [f release];    }
</code>```

Here I convert objects of arrayValues (NSString) in NSNumbers in arrayValues2.

In the Simulator there is no problem, the arrays are not empties.
I don't know where to look for.

I also checked the other posts of stackoverflow, they are not really like my error

答:
Just working with the information you've given, it's not possible to pinpoint the problem (where is the data coming from?), but what we can say is that the exception gives a big clue:

You can't insert nil values into an array (use NSNull if you really need to).

Why is there a nil value? Well, when you try convert your string into a number it finds something it doesn't recognise. When that happens it returns a nil.

So you need to either sanitise your data (to make sure that everything is a number) or put error handling in your loop so that it doesn't try to put invalid values into the array.

(Also, I agree with Thomas about your implementation. His version will be easier to debug and use less memory.)

Body:
I have a problem with my app, which run well on the simulator but when I launch on my iDevice I got an error:

     Terminating app due to uncaught exception 'NSInvalidArgumentException',
         reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'

    0   CoreFoundation                      0x3513cfd3 __exceptionPreprocess + 114
    1   libobjc.A.dylib                     0x303928a5 objc_exception_throw + 24
    2   CoreFoundation                      0x350bff99 -[__NSArrayM insertObject:atIndex:] + 472
    3   CoreFoundation                      0x350bfda7 -[__NSArrayM addObject:] + 34
    ....
    Program received signal:  “SIGABRT”.

In the debugger I can see where is the problem. The error comes from there, at the addObject:

for (int i = 0; i < [arrayValues count]; i++) {
    f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    myNumber =[f numberFromString:[arrayValues objectAtIndex:i]];

    [arrayValues2 addObject:myNumber];
    [f release];    }

Here I convert objects of arrayValues (NSString) in NSNumbers in arrayValues2.

In the Simulator there is no problem, the arrays are not empties.
I don't know where to look for.

I also checked the other posts of stackoverflow, they are not really like my error


问:
What does "family" mean in the context of the asset pipeline?
In the Rails guides for the asset pipeline, there's a reference to "family":

Directives are processed top to bottom, but the order in which files
  are included by require_tree is unspecified. You should not rely on
  any particular order among those. If you need to ensure some
  particular JavaScript ends up above some other in the concatenated
  file, require the prerequisite file first in the manifest. Note that
  the family of require directives prevents files from being
  included twice in the output.

What does "family" mean in this context?

答:
Family refers to the group of require directives that include :

require

require_self

require_tree

require_directory


问:
Matplotlib & Jupyter - Same command returns different results in different cells
First Jupyter cell:

```<code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
%matplotlib notebook

plt.figure()
plt.plot((1,2,3))

labels = [item.get_text() for item in plt.gca().get_xticklabels()]
print("Labels are: {}".format(labels))
</code>```

The ouput is (besides the chart):

Labels are: ['', '', '', '', '', '', '', '', '', '', '']

Now, in another cell, if I run the same code:

```<code>labels = [item.get_text() for item in plt.gca().get_xticklabels()]
print("Labels are: {}".format(labels))
</code>```

The ouput is:

Labels are: ['', '0.00', '0.25', '0.50', '0.75', '1.00', '1.25', '1.50', '1.75', '2.00', '']

Why the same code, referencing the same Axes, returns different results?

答:
It's an interesting problem, as far as I can tell it seems to be that while you are referencing the same object in both lots of code the actual plotting that jupyter is doing isn't side-effect free.

The plot itself is generated when the code in the cell has finished running (at least with the notebook back-end), and during the generation the details such as the xtick-labels are populated. Naïvely I assume that this is because you can add additional things to the plots that will change the x and y limits of the figure and it's more efficient to only do that once when we need to see it.

Note that you can manually set the xtick-labels prior to the generation of the plot if you know what they are going to be (or what you want them to be) ahead of time:

```<code>plt.gca().set_xticklabels(list_of_labels)
</code>```

However, if you do actually need the label values prior to the plot being generated you can always use

```<code>plt.gca().get_xticks()
</code>```

This will return a list of the locations of the ticks and from there it's pretty easy to make the labels from that

```<code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
%matplotlib notebook

# generate the figure and axes objects
plt.figure()
plt.plot((1, 2, 3))  # plot the data

# now we can look at the xtick positions, and infer the labels
labels = ["{:.2f}".format(item) for item in plt.gca().get_xticks()]
print("Labels are: {}".format(labels))
</code>```

Body:
First Jupyter cell:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
%matplotlib notebook

plt.figure()
plt.plot((1,2,3))

labels = [item.get_text() for item in plt.gca().get_xticklabels()]
print("Labels are: {}".format(labels))

The ouput is (besides the chart):

Labels are: ['', '', '', '', '', '', '', '', '', '', '']

Now, in another cell, if I run the same code:

labels = [item.get_text() for item in plt.gca().get_xticklabels()]
print("Labels are: {}".format(labels))

The ouput is:

Labels are: ['', '0.00', '0.25', '0.50', '0.75', '1.00', '1.25', '1.50', '1.75', '2.00', '']

Why the same code, referencing the same Axes, returns different results?

Body:
It's an interesting problem, as far as I can tell it seems to be that while you are referencing the same object in both lots of code the actual plotting that jupyter is doing isn't side-effect free.

The plot itself is generated when the code in the cell has finished running (at least with the notebook back-end), and during the generation the details such as the xtick-labels are populated. Naïvely I assume that this is because you can add additional things to the plots that will change the x and y limits of the figure and it's more efficient to only do that once when we need to see it.

Note that you can manually set the xtick-labels prior to the generation of the plot if you know what they are going to be (or what you want them to be) ahead of time:

plt.gca().set_xticklabels(list_of_labels)

However, if you do actually need the label values prior to the plot being generated you can always use

plt.gca().get_xticks()

This will return a list of the locations of the ticks and from there it's pretty easy to make the labels from that

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
%matplotlib notebook

# generate the figure and axes objects
plt.figure()
plt.plot((1, 2, 3))  # plot the data

# now we can look at the xtick positions, and infer the labels
labels = ["{:.2f}".format(item) for item in plt.gca().get_xticks()]
print("Labels are: {}".format(labels))


问:
iOS native alert
Currently automating iOS Web app using selenium appium stack in iOS10.3, native app alert "This site is attempting to open popup window". Not able to switch the alert as we need to access the native layer from web layer. do looking forward for solution</p>

答:
Try changing Appium context by:</p>

```<code>driver.context("NATIVE_APP");
</code>```

Title: iOS native alert

Body:
Try changing Appium context by:

driver.context("NATIVE_APP");


问:
SQL - defining date for observations based on three different tables
I have three tables: Table_A, Table_B, and Table_C.

Each table contains three variables - ID, Problem, and Date. The date may or may not be missing in the tables.

I need to create a new table such that all observations have a date. Rule for achieving this: For all ID/Problem pairs in Table_A, Date from Table_A will be used as the date when Date exists. Otherwise, the minimum Date from Table_B and Table_C will be used. If Date is missing in all the tables then drop the observation.

SELECT ID, Problem, MIN(Date) as Date
FROM
(   SELECT ID, Problem, Date
    FROM Table_A
    UNION ALL
    SELECT ID, Problem, Date
    FROM Table_B
    UNION ALL
    SELECT ID, Problem, Date
    FROM Table_C
) as subQuery
Delete From table Where Date IS NULL

答:
If I understand correctly, this may get you started:</p>

```<code>select id, problem, `date` from table_a where `date` is not null
union

select id, problem, min(`date`)
from (
    select id, problem, date from table_b where `date` is not null
    union all
    select id, problem, date from table_c where `date` is not null
    ) d
group by id, problem
</code>```

Body:
If I understand correctly, this may get you started:

select id, problem, `date` from table_a where `date` is not null
union

select id, problem, min(`date`)
from (
    select id, problem, date from table_b where `date` is not null
    union all
    select id, problem, date from table_c where `date` is not null
    ) d
group by id, problem


问:
Log4j 1 and 2 - Custom appenders from two Log4J versions writing to the same file simultaneously
I want to migrate from Log4J 1.x to Log4J 2 but at the same time I want to keep Log4J to support any external features (jars) that use Log4J. There are custom appenders written in Log4J and so the appenders will be re-written according to Log4J2 using plugins. So two configuration files needs to be there to support each version and the logs from both versions need to be written to the same file with the same format as defined in the custom appenders.

I found that simultaneous writing of multiple appenders to the same file is possible within a version but is it possible for the appenders coming from two Log4J versions to write to the same file simultaneously? If yes is it a recommended practice and please suggest an alternative if it is not recommended.

答:
It would be an unusual setup to use both Log4j2 and Log4j 1.2 (not the adapter but the actual implementation) to do logging for an application at the same time.

Configuring both logging libraries to write to the same file adds even more risk. It might work, it might not. It is certainly not what these libraries were designed for.

I would not recommend such a setup.

The safest thing to do would be to postpone your Log4j2 migration until your log4j 1.2 custom appenders have been ported to Log4j2. Then use the Log4j2 implementation and the log4j-1.2-api-2.x adapter module for the external libraries that use the Log4j 1.2 API.


答:
You should use NonSwipeableViewPager following way. your pager will not work</p>

```<code>import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;

public class NonSwipeableViewPager extends ViewPager {

    public NonSwipeableViewPager(Context context) {
        super(context);
        setMyScroller();
    }

    public NonSwipeableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        setMyScroller();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    //down one is added for smooth scrolling

    private void setMyScroller() {
        try {
            Class<?> viewpager = ViewPager.class;
            Field scroller = viewpager.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            scroller.set(this, new MyScroller(getContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class MyScroller extends Scroller {
        public MyScroller(Context context) {
            super(context, new DecelerateInterpolator());
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
        }
    }
}
</code>```

Title: Horizontal Recycler View inside ViewPager not scrolling

Body:
You should use NonSwipeableViewPager following way. your pager will not work

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;

public class NonSwipeableViewPager extends ViewPager {

    public NonSwipeableViewPager(Context context) {
        super(context);
        setMyScroller();
    }

    public NonSwipeableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        setMyScroller();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    //down one is added for smooth scrolling

    private void setMyScroller() {
        try {
            Class<?> viewpager = ViewPager.class;
            Field scroller = viewpager.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            scroller.set(this, new MyScroller(getContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class MyScroller extends Scroller {
        public MyScroller(Context context) {
            super(context, new DecelerateInterpolator());
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
        }
    }
}


问:
How do I parse specific parts of a page using JQuery's AJAX method?
I'm trying to work out how to parse specific parts of a page using JQuery's AJAX method. What I'd like to do is something like this:

```<code>$.ajax({
    url: "page-to-load.htm",
    dataType: "html",
    success: function (response) {
            var html= $(response);
            var content = html.find("#main");
            var title = html.find("title");
            var nav = html.find("ul.nav");
    }
});
</code>```

I know that I can load specific page parts using [container].load() but this will (as far as I understand it) create a request for each page part I want to load.

In my sample code, the html object seems to be an array of HTML elements but each of the objects returned by find() are null. The elements searched for do exist in the target page.

Am I missing something obvious or is this just not something that JQuery can handle?

答:
You could do a split, and then some string replaces before you add it to a jquery object.

```<code>$.ajax({
url: "file.html",
dataType: "html",
success: function (response) {
    var resp = response.split('<body>');
    resp = resp[1].split('</body>');
    resp = resp[0].toString();
    var html = $('<div>'+resp+'</div>');
    var div = html.find('div');
    var ul = html.find('ul');
    var foot = html.find('footer');
    console.log(resp, html, div, ul, foot);
    ul.appendTo('body');
 }});
</code>```

Works with given HTML:

```<code><!DOCTYPE html>
 <html>
<head>
    <title></title>
</head>
<body>
<div>Something that we're gonna get</div>
<ul>

  <li>List item</li>
</ul>
<footer>Good foot</footer>
</body>
</html>
</code>```

Body:
I'm trying to work out how to parse specific parts of a page using JQuery's AJAX method. What I'd like to do is something like this:

$.ajax({
    url: "page-to-load.htm",
    dataType: "html",
    success: function (response) {
            var html= $(response);
            var content = html.find("#main");
            var title = html.find("title");
            var nav = html.find("ul.nav");
    }
});

I know that I can load specific page parts using [container].load() but this will (as far as I understand it) create a request for each page part I want to load.

In my sample code, the html object seems to be an array of HTML elements but each of the objects returned by find() are null. The elements searched for do exist in the target page.

Am I missing something obvious or is this just not something that JQuery can handle?

Body:
You could do a split, and then some string replaces before you add it to a jquery object.

$.ajax({
url: "file.html",
dataType: "html",
success: function (response) {
    var resp = response.split('<body>');
    resp = resp[1].split('</body>');
    resp = resp[0].toString();
    var html = $('<div>'+resp+'</div>');
    var div = html.find('div');
    var ul = html.find('ul');
    var foot = html.find('footer');
    console.log(resp, html, div, ul, foot);
    ul.appendTo('body');
 }});

Works with given HTML:

<!DOCTYPE html>
 <html>
<head>
    <title></title>
</head>
<body>
<div>Something that we're gonna get</div>
<ul>

  <li>List item</li>
</ul>
<footer>Good foot</footer>
</body>
</html>


问:
Linking external javascript and css files into Vue component?
I created a functional chess board using javascript and CSS. I want to use it in a Vue app but I can't figure out how to link the javascript and CSS files to the component. Is there a way to load them in webpack, or what is the correct way of going about this?</p>

答:
this should help</p>

```<code><style scoped>
    @import '../assets/css/custom.css';
</style>
</code>```

Body:
this should help

<style scoped>
    @import '../assets/css/custom.css';
</style>


问:
Python - apply_async doesn't execute function
Hi I'm trying to use multiprocessing to speed up my code. However, the apply_async doesn't work for me. I tried to do a simple example like:

```<code>from multiprocessing.pool import Pool
t = [0, 1, 2, 3, 4, 5]
def cube(x):
    t[x] = x**3
pool = Pool(processes=4)
for i in range(6):
    pool.apply_async(cube, args=(i, ))
for x in t:
    print(x)
</code>```

It does not really change t as I would expect.

My real code is like:

```<code>from multiprocessing.pool import Pool
def func(a, b, c, d):
    #some calculations
    #save result to files
    #no return value
lt = #list of possible value of a
#set values to b, c, d
p = Pool()
for i in lt:
    p.apply_async(func, args=(i, b, c, d, ))
</code>```

Where are the problems here?

Thank you!

Update: Thanks to the comments and answers, now I understand why my simple example won't work. However, I'm still in trouble with my real code. I have checked that my func does not rely on any global variable, so it seems not to be the same problem as my example code.

As suggested, I added a return value to my func, now my code is:

```<code>f = Flux("reactor")
d = Detector("Ge")
mv = arange(-6, 1.5, 0.5)
p = Pool()
lt = ["uee", "dee"]
for i in lt:
    re = p.apply_async(res, args=(i, d, f, mv, ))
    print(re.get())
p.close()
p.join()
</code>```

Now I get the following error:

```<code>Traceback (most recent call last):
  File "/Users/Shu/Documents/Programming/Python/Research/debug.py", line 35, in <module>
print(re.get())
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 608, in get
raise self._value
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 385, in _handle_tasks
put(task)
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'Flux.__init__.<locals>.<lambda>'
</code>```

答:
Function quits too soon, try add at the end of your script this code:</p>

```<code>import time
time.sleep(3)
</code>```

Body:
Hi I'm trying to use multiprocessing to speed up my code. However, the apply_async doesn't work for me. I tried to do a simple example like:

from multiprocessing.pool import Pool
t = [0, 1, 2, 3, 4, 5]
def cube(x):
    t[x] = x**3
pool = Pool(processes=4)
for i in range(6):
    pool.apply_async(cube, args=(i, ))
for x in t:
    print(x)

It does not really change t as I would expect.

My real code is like:

from multiprocessing.pool import Pool
def func(a, b, c, d):
    #some calculations
    #save result to files
    #no return value
lt = #list of possible value of a
#set values to b, c, d
p = Pool()
for i in lt:
    p.apply_async(func, args=(i, b, c, d, ))

Where are the problems here?

Thank you!

Update: Thanks to the comments and answers, now I understand why my simple example won't work. However, I'm still in trouble with my real code. I have checked that my func does not rely on any global variable, so it seems not to be the same problem as my example code.

As suggested, I added a return value to my func, now my code is:

f = Flux("reactor")
d = Detector("Ge")
mv = arange(-6, 1.5, 0.5)
p = Pool()
lt = ["uee", "dee"]
for i in lt:
    re = p.apply_async(res, args=(i, d, f, mv, ))
    print(re.get())
p.close()
p.join()

Now I get the following error:

Traceback (most recent call last):
  File "/Users/Shu/Documents/Programming/Python/Research/debug.py", line 35, in <module>
print(re.get())
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 608, in get
raise self._value
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 385, in _handle_tasks
put(task)
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'Flux.__init__.<locals>.<lambda>'

Body:
Function quits too soon, try add at the end of your script this code:

import time
time.sleep(3)


问:
How can I detect browser and OS of user and use this to dynamically modify my MySQL database query from a PHP page
I need to be able to run a mysql query and omit certain results if the user is using a certain browser on a certain OS. My database query takes place from an AMFPHP service and I have a javascript browserDetect script that I can use to get user browser and OS.

Ideally I want to run the browserDetect script when the user arrives at my page and then store this in the PHP session variables but I cannot see how to pass the javascript vars to the PHP session. This would allow my database query script to look up the session and modify the query accordingly. I also tried to include the browser detect script in the AMFPHP script but this did not work - I realise that this a serverside vs client side problem.

What other solutions would work for me?

thanks

答:
Why not accomplish that with PHP only? PHP is also capable of fetching browser and os...

$_SERVER['HTTP_USER_AGENT'] contains browser and os...


问:
Python: any way to perform this "hybrid" split() on multi-lingual (e.g. Chinese & English) strings?
I have strings that are multi-lingual consist of both languages that use whitespace as word separator (English, French, etc) and languages that don't (Chinese, Japanese, Korean).

Given such a string, I want to separate the English/French/etc part into words using whitespace as separator, and to separate the Chinese/Japanese/Korean part into individual characters.

And I want to put of all those separated components into a list.

Some examples would probably make this clear:

Case 1: English-only string. This case is easy:

```<code>>>> "I love Python".split()
['I', 'love', 'Python']
</code>```

Case 2: Chinese-only string:

```<code>>>> list(u"我爱蟒蛇")
[u'\u6211', u'\u7231', u'\u87d2', u'\u86c7']
</code>```

In this case I can turn the string into a list of Chinese characters. But within the list I'm getting unicode representations:

```<code>[u'\u6211', u'\u7231', u'\u87d2', u'\u86c7']
</code>```

How do I get it to display the actual characters instead of the unicode? Something like:

```<code>['我', '爱', '蟒', '蛇']
</code>```

??

Case 3: A mix of English & Chinese:

I want to turn an input string such as

```<code>"我爱Python"
</code>```

and turns it into a list like this:

```<code>['我', '爱', 'Python']
</code>```

Is it possible to do something like that?

答:
In Python 3, it also splits the number if you needed.

```<code>def spliteKeyWord(str):
    regex = r"[\u4e00-\ufaff]|[0-9]+|[a-zA-Z]+\'*[a-z]*"
    matches = re.findall(regex, str, re.UNICODE)
    return matches

print(spliteKeyWord("Testing English text我爱Python123"))
</code>```

=> ['Testing', 'English', 'text', '我', '爱', 'Python', '123']

Body:
I have strings that are multi-lingual consist of both languages that use whitespace as word separator (English, French, etc) and languages that don't (Chinese, Japanese, Korean).

Given such a string, I want to separate the English/French/etc part into words using whitespace as separator, and to separate the Chinese/Japanese/Korean part into individual characters.

And I want to put of all those separated components into a list.

Some examples would probably make this clear:

Case 1: English-only string. This case is easy:

>>> "I love Python".split()
['I', 'love', 'Python']

Case 2: Chinese-only string:

>>> list(u"我爱蟒蛇")
[u'\u6211', u'\u7231', u'\u87d2', u'\u86c7']

In this case I can turn the string into a list of Chinese characters. But within the list I'm getting unicode representations:

[u'\u6211', u'\u7231', u'\u87d2', u'\u86c7']

How do I get it to display the actual characters instead of the unicode? Something like:

['我', '爱', '蟒', '蛇']

??

Case 3: A mix of English & Chinese:

I want to turn an input string such as

"我爱Python"

and turns it into a list like this:

['我', '爱', 'Python']

Is it possible to do something like that?

Body:
In Python 3, it also splits the number if you needed.

def spliteKeyWord(str):
    regex = r"[\u4e00-\ufaff]|[0-9]+|[a-zA-Z]+\'*[a-z]*"
    matches = re.findall(regex, str, re.UNICODE)
    return matches

print(spliteKeyWord("Testing English text我爱Python123"))

=> ['Testing', 'English', 'text', '我', '爱', 'Python', '123']


问:
Specify generic type parameter in Scala
I'm new to Scala and have generic method written in Java:

```<code>public interface Context{
    <T> Optional<T> get(String parameterName);
}
</code>```

and Scala class:

```<code>class Mcls(ctx: Context){
    val str = ctx.[Optional[String]]get("str").get //error
}
</code>```

Is there a way to specify generic type parameter shorted then asInstanceOf[Optional[String]] in Scala?

答:
I think you can use type alias to short this, and it's unnecessary to cast the type.

```<code>  type MY_TYPE = Optional[String]
  val str: MY_TYPE = ctx.get("str") //it's unnecessary get in here, since the `get` method already return `MY_TYPE`, and specify type after variable, the compiler will auto infer the generic type for this.
  println(str)
</code>```

Title: Specify generic type parameter in Scala

Body:
I'm new to Scala and have generic method written in Java:

public interface Context{
    <T> Optional<T> get(String parameterName);
}

and Scala class:

class Mcls(ctx: Context){
    val str = ctx.[Optional[String]]get("str").get //error
}

Is there a way to specify generic type parameter shorted then asInstanceOf[Optional[String]] in Scala?

Body:
I think you can use type alias to short this, and it's unnecessary to cast the type.

  type MY_TYPE = Optional[String]
  val str: MY_TYPE = ctx.get("str") //it's unnecessary get in here, since the `get` method already return `MY_TYPE`, and specify type after variable, the compiler will auto infer the generic type for this.
  println(str)


问:
chmod(): No such file or directory
this might be a duplicate but dont know the reason why i got this error.. this code is fine when im using another laptop which the php version is 5.6 but when im using a laptop with php version 5.4 i got an error..
here is the code that im using..

```<code>        public function uploadImg($file, $newname){

            $path = "../valenciamd/captured_images/";
            $fileparts = pathinfo($file["name"]);
            $name =  $newname . $fileparts["extension"];

            if( is_dir($path) === false ){
                mkdir($path);
            }

            $i = 0;
            $parts = pathinfo($name);
            // while (file_exists($path . $name)) {
            //     $i++;
            //     $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
            // }
            $name = $parts["filename"]. "." . $parts["extension"];
            $success = move_uploaded_file($file["tmp_name"],
                $path . $name);

            chmod($path . $name, 0777);

            return $path . $name;
        }
</code>```

$img = $reg->uploadImg( $_FILES['image'], $patientID.'.');

答:
try to use the recursive directory creation

read the mkdir manual http://php.net/manual/en/function.mkdir.php

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive =
  false [, resource $context ]]] )

Title: chmod(): No such file or directory

Body:
this might be a duplicate but dont know the reason why i got this error.. this code is fine when im using another laptop which the php version is 5.6 but when im using a laptop with php version 5.4 i got an error..
here is the code that im using..

        public function uploadImg($file, $newname){

            $path = "../valenciamd/captured_images/";
            $fileparts = pathinfo($file["name"]);
            $name =  $newname . $fileparts["extension"];

            if( is_dir($path) === false ){
                mkdir($path);
            }

            $i = 0;
            $parts = pathinfo($name);
            // while (file_exists($path . $name)) {
            //     $i++;
            //     $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
            // }
            $name = $parts["filename"]. "." . $parts["extension"];
            $success = move_uploaded_file($file["tmp_name"],
                $path . $name);

            chmod($path . $name, 0777);

            return $path . $name;
        }

$img = $reg->uploadImg( $_FILES['image'], $patientID.'.');