问:
Shift + Return to insert linebreak in python
I'm trying to get the behaviour of typical IM clients that use Return to send a text and Shift + Return to insert a linebreak. Is there a way to achieve that with minimal effort in Python, using e.g. readline and raw_input?

答:
```<code>import readline
# I am using Ctrl+x to insert line break
# (dont know the symbols and bindings for meta-key or shift-key,
# let alone 4 shift+enter)

def startup_hook():
    readline.insert_text('» ') # \033[32m»\033[0m

def prmpt():
try:
    readline.parse_and_bind('tab: complete')
    readline.parse_and_bind('set editing-mode vi')
    readline.parse_and_bind('C-x: "\x16\n"') # \x16 is C-v which writes
    readline.set_startup_hook(startup_hook) # the \n without returning
except Exception as e:                      # thus no need 4 appending
    print (e)                              # '#' 2 write multilines
    return                # simply use ctrl-x or other some other bind
while True:             # instead of shift + enter
    try:
        line = raw_input()
        print '%s' % line
    except EOFError:
        print 'EOF signaled, exiting...'
        break

# It can probably be improved more to use meta+key or maybe even shift enter
# Anyways sry 4 any errors I probably may have made.. first time answering
</code>```


来源: stackexchange

问:
remove image and its container if image is broken
I am just trying to remove image and its title in case if image fails to load or broken using html or JavaScript.what is the best and easiest way to do that?

```<code><?php

   include("../includes/db.php");   // ../ means go to parent directory
  $query='SELECT * FROM `table` WHERE tag NOT IN("news") ORDER BY `id` DESC LIMIT 0,5';
  $run=mysqli_query($conn,$query);
  while($row=mysqli_fetch_array($run)){
         $img=$row['src'];
         $title=$row['title'];
   ?>

       <table class='mobileTable'>
          <tr> <td><img src='<?php echo $img ?>' onerror='imgError(this)' /></td></tr>
          <tr> <td  class='mobMidTitle'><?php echo $title ?></td></tr>//i want to remove this title as well
       </table>
   <?php } ?>

 <script>
 function imgError(image) {
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    document.getElementById('tit').style.display='none';
    return true;
}</script>
</code>```

code above will fetch 5 images from database and with  javascript i can change image to error.jpg but i want to remove both image as well as its title only of failed image.

答:
How about this JQuery javascipt (https://jquery.com) to hide any image that failed to load:

```<code>$("img").error(function() { $(this).hide(); });
</code>```

or, if you want to hide its container you can do this:

```<code>$("img").error(function() { $(this).parent().hide(); });
</code>```

or if you really want to remove the image, or container, use remove() instead of hide().

You could also display your own error image:

```<code>$("img").error(function() { $(this).attr("src","error.png"); });
</code>```

Code has been tested and it works.

You can make it more specific by selecting only those images you want to hide or remove. Change $("img") to $(".hideOnError") and the use the class hideOnError on those images you want to hide or remove. Different actions could be take like replaceOnError. You can also apply this to other loadable elements.

In your specific case you have two elements you want to remove when an image fails. The best way to go about this is to associate the title with the image through attributes:

```<code>   <table class='mobileTable'>
      <tr><td><img id='image1' src='<?php echo $img ?>'></td></tr>
      <tr><td id='image1title' class='mobMidTitle'><?php echo $title ?></td></tr>
   </table>
</code>```

As you can see, the id of the image here is image1 and the table cell containing the title has id image1title. To remove image and title on error, while leaving the table structure intact, you do:

```<code>$("img").error(function() {
  var id = $(this).attr('id');     // get id of image
  $(this).remove();                // remove image
  $("#"+id+"title").empty();       // remove title
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am just trying to remove image and its title in case if image fails to load or broken using html or JavaScript.what is the best and easiest way to do that?

<?php

   include("../includes/db.php");   // ../ means go to parent directory
  $query='SELECT * FROM `table` WHERE tag NOT IN("news") ORDER BY `id` DESC LIMIT 0,5';
  $run=mysqli_query($conn,$query);
  while($row=mysqli_fetch_array($run)){
         $img=$row['src'];
         $title=$row['title'];
   ?>

 <img src='<?php echo $img ?>' onerror='imgError(this)' />

 <?php echo $title ?>
//i want to remove this title as well

   <?php } ?>

code above will fetch 5 images from database and with  javascript i can change image to error.jpg but i want to remove both image as well as its title only of failed image.

Body:
How about this JQuery javascipt (https://jquery.com) to hide any image that failed to load:

$("img").error(function() { $(this).hide(); });

or, if you want to hide its container you can do this:

$("img").error(function() { $(this).parent().hide(); });

or if you really want to remove the image, or container, use remove() instead of hide().

You could also display your own error image:

$("img").error(function() { $(this).attr("src","error.png"); });

Code has been tested and it works.

You can make it more specific by selecting only those images you want to hide or remove. Change $("img") to $(".hideOnError") and the use the class hideOnError on those images you want to hide or remove. Different actions could be take like replaceOnError. You can also apply this to other loadable elements.

In your specific case you have two elements you want to remove when an image fails. The best way to go about this is to associate the title with the image through attributes:

   <table class='mobileTable'>
      <tr><td><img id='image1' src='<?php echo $img ?>'></td></tr>
      <tr><td id='image1title' class='mobMidTitle'><?php echo $title ?></td></tr>
   </table>

As you can see, the id of the image here is image1 and the table cell containing the title has id image1title. To remove image and title on error, while leaving the table structure intact, you do:

$("img").error(function() {
  var id = $(this).attr('id');     // get id of image
  $(this).remove();                // remove image
  $("#"+id+"title").empty();       // remove title
});


答:
You can accomplish this in one of two ways:

Either use the removeChild function (assuming you want to remove the elements and not hide them):

```<code>function imgError(image) {
   // Get image row
   var imageRow = image.parentNode.parentNode;
   // Get image label row
   var imageLabel = imageRow.nextElementSibling;
   // Get table element of that image row and remove imageLabel
   imageRow.parentNode.removeChild(imageLabel);
   // Get table element of that image row and remove img element
   imageRow.parentNode.removeChild(imageRow);
}
</code>```

Or you can instead hide your elements using the .style.visibility property of the image and label elements:

```<code> function imgError(image) {
    // Get image row
    var imageRow = image.parentNode.parentNode;
    // Get image label row
    var imageLabel = imageRow.nextElementSibling;
    // Hide imageLabel
    imageRow.style.visibility = 'hidden';
    // Hide imageRow
    imageLabel.style.visibility = 'hidden';
}
</code>```

Title: remove image and its container if image is broken

Body:
You can accomplish this in one of two ways:

Either use the removeChild function (assuming you want to remove the elements and not hide them):

function imgError(image) {
   // Get image row
   var imageRow = image.parentNode.parentNode;
   // Get image label row
   var imageLabel = imageRow.nextElementSibling;
   // Get table element of that image row and remove imageLabel
   imageRow.parentNode.removeChild(imageLabel);
   // Get table element of that image row and remove img element
   imageRow.parentNode.removeChild(imageRow);
}

Or you can instead hide your elements using the .style.visibility property of the image and label elements:

 function imgError(image) {
    // Get image row
    var imageRow = image.parentNode.parentNode;
    // Get image label row
    var imageLabel = imageRow.nextElementSibling;
    // Hide imageLabel
    imageRow.style.visibility = 'hidden';
    // Hide imageRow
    imageLabel.style.visibility = 'hidden';
}


问:
Unable to send cross-domain request in `Firefox` extension
I am trying to access cross-domain data by using jsonp or XMLHttpRequest with GET method. My Code:

XMLHttpRequest

```<code>var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/ajax.php?code=BSE", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
xhr.send();
</code>```

JsonP

```<code>$.ajax({
     type: 'GET',
     url: "http://example.com/ajax.php?code=BSE",
     dataType: "jsonp",
     jsonpCallback: "jsonp_callback",
     crossDomain: true,
     success: function(res){
         console.log(res);
     }
});
</code>```

Both methods having same behavior. Whenever i am sending request its just keep loading (even i am not sure its sending request or not) and do nothing.

And my php code:

PHP Code:

```<code>header('content-type: application/json; charset=utf-8');
$dts=array('value'=>'123');
echo $_GET['jsonp_callback'] . '('.json_encode($dts).')';
</code>```

答:
The XMLHttpRequest will work just fine, no need for jsonp. In your manifest.json, make sure you request permissions for the domain you are posting to -- Chrome doesn't require permissions for XHR, but Firefox does. This error manifests in Firefox as a http code 404 in the XHR, but no activity in the network panel. If you get a http code 0, you have CORS or mixed content security issues as well.

```<code>{
  "manifest_version": 2,
  "name": "web extension",
  "version": "1",
  "permissions": [
    "http://example.com/"
  ],
  "content_scripts": [
    {
      // ...
    }
  ]
}
</code>```

Body:
I am trying to access cross-domain data by using jsonp or XMLHttpRequest with GET method. My Code:

XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/ajax.php?code=BSE", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
xhr.send();

JsonP

$.ajax({
     type: 'GET',
     url: "http://example.com/ajax.php?code=BSE",
     dataType: "jsonp",
     jsonpCallback: "jsonp_callback",
     crossDomain: true,
     success: function(res){
         console.log(res);
     }
});

Both methods having same behavior. Whenever i am sending request its just keep loading (even i am not sure its sending request or not) and do nothing.

And my php code:

PHP Code:

header('content-type: application/json; charset=utf-8');
$dts=array('value'=>'123');
echo $_GET['jsonp_callback'] . '('.json_encode($dts).')';

Body:
The XMLHttpRequest will work just fine, no need for jsonp. In your manifest.json, make sure you request permissions for the domain you are posting to -- Chrome doesn't require permissions for XHR, but Firefox does. This error manifests in Firefox as a http code 404 in the XHR, but no activity in the network panel. If you get a http code 0, you have CORS or mixed content security issues as well.

{
  "manifest_version": 2,
  "name": "web extension",
  "version": "1",
  "permissions": [
    "http://example.com/"
  ],
  "content_scripts": [
    {
      // ...
    }
  ]
}


问:
Converting the Select Case with To and Is to c# problems
I am convertng vb.net to c# 2010 as my job, and none of the automatic tools I have can succeed completely.   In special example, this case:

```<code>'searchString is a string paramter from a long method
Select Case searchString
   Case "paid"
      'Do something long here
   Case "oaaaaa" To "ozzzzzz", "maaaaaa" To "mzzzzzz"
      'Do other long code
   Case Else
      'other long code
End Select
</code>```

I am mostly java developer before this, so not great with c# and none with vb.net.  I do not understand the "oaaaa to ...." part and this part is not converting.  Can you please point me to right place to find the c# version of this?

答:
There's no direct C# equivalent of the Case "xxx" To "yyy" syntax. I suppose the closest translation will probably be an if/else if/else stack:

```<code>if (seachString == "paid")
{
    // do something long here
}
else if (((searchString.CompareTo("oaaaaaa") >= 0) && (searchString.CompareTo("ozzzzzz") <= 0))
         || ((searchString.CompareTo("maaaaaa") >= 0) && (searchString.CompareTo("mzzzzzz") <= 0)))
{
    // do other long code
}
else
{
    // other long code
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am convertng vb.net to c# 2010 as my job, and none of the automatic tools I have can succeed completely.   In special example, this case:

'searchString is a string paramter from a long method
Select Case searchString
   Case "paid"
      'Do something long here
   Case "oaaaaa" To "ozzzzzz", "maaaaaa" To "mzzzzzz"
      'Do other long code
   Case Else
      'other long code
End Select

I am mostly java developer before this, so not great with c# and none with vb.net.  I do not understand the "oaaaa to ...." part and this part is not converting.  Can you please point me to right place to find the c# version of this?

Body:
There's no direct C# equivalent of the Case "xxx" To "yyy" syntax. I suppose the closest translation will probably be an if/else if/else stack:

if (seachString == "paid")
{
    // do something long here
}
else if (((searchString.CompareTo("oaaaaaa") >= 0) && (searchString.CompareTo("ozzzzzz") <= 0))
         || ((searchString.CompareTo("maaaaaa") >= 0) && (searchString.CompareTo("mzzzzzz") <= 0)))
{
    // do other long code
}
else
{
    // other long code
}


问:
MONGO_QUERY_BLACKLIST doesn't work
I'm using python-eve with default settings where

```<code>'MONGO_QUERY_BLACKLIST': ['$where', '$regex']
</code>```

But it appears that I still can use 'where'-parameter in queries to Eve.

```<code>import requests

params = {'where': '{"username":"Alex"}'}
response = requests.get('http://localhost/users', params)
print response.content
print response.status_code
</code>```

{"_items": [{"username": "Alex", ... }], ...}

200

答:
You are conflating Eve's REST API parameter called where (which translates the given parameters into query criteria for a standard MongoDB  find() query) with MongoDB's  $where  JavaScript operator (whose usage is strongly discouraged and disabled by default in Eve).

This is an unfortunately confusing naming choice in the Eve API. The $where operator (if used) would be part of the query criteria provided to Eve's where.

Modifying your example params to use a $where query (for illustration purposes only, as this is definitely not recommendable or performant):

```<code>params = {'where': '{"$where":"this.username == \'Alex\'"}'}
</code>```

With Eve's default settings (or $where included in MONGO_QUERY_BLACKLIST), the Eve API will return a response similar to the following:

{"_status": "ERR", "_error": {"message": "The browser (or proxy) sent a request that this server could not understand.", "code": 400}}

Removing $where from the blacklist will return matching _items. I tested this against Eve 0.7.2 to confirm the expected behaviour.

Title: MONGO_QUERY_BLACKLIST doesn't work

Body:
I'm using python-eve with default settings where

'MONGO_QUERY_BLACKLIST': ['$where', '$regex']

But it appears that I still can use 'where'-parameter in queries to Eve.

import requests

params = {'where': '{"username":"Alex"}'}
response = requests.get('http://localhost/users', params)
print response.content
print response.status_code

{"_items": [{"username": "Alex", ... }], ...}

200

Body:
You are conflating Eve's REST API parameter called where (which translates the given parameters into query criteria for a standard MongoDB  find() query) with MongoDB's  $where  JavaScript operator (whose usage is strongly discouraged and disabled by default in Eve).

This is an unfortunately confusing naming choice in the Eve API. The $where operator (if used) would be part of the query criteria provided to Eve's where.

Modifying your example params to use a $where query (for illustration purposes only, as this is definitely not recommendable or performant):

params = {'where': '{"$where":"this.username == \'Alex\'"}'}

With Eve's default settings (or $where included in MONGO_QUERY_BLACKLIST), the Eve API will return a response similar to the following:

{"_status": "ERR", "_error": {"message": "The browser (or proxy) sent a request that this server could not understand.", "code": 400}}

Removing $where from the blacklist will return matching _items. I tested this against Eve 0.7.2 to confirm the expected behaviour.


问:
swift 3 - http authentication in WKWebView
I'm trying to build a simple WebView which shows a web page - the page requires http authentication for all pages (for testing purposes).

Here is my code:

```<code>class ViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }

    // #1 variant
    func webView(webView: WKWebView, willSendRequestForAuthenticationChallenge challenge:
        URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let user = "user"
        let password = "pass"
        let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
        challenge.sender?.use(credential, for: challenge)
    }

    // #2 variant
    func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

            let user = "user"
            let password = "pass"
            let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
            challenge.sender?.use(credential, for: challenge)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string: "https://myurl.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }

}
</code>```

I've found willSendRequestForAuthenticationChallenge and didReceiveAuthenticationChallenge, but none of them is called and I've got error from the server that I was not authenticated.

Could somebody help?

Thank you a lot!

David

答:
It works by removing (or comment out) this line.
challenge.sender?.use(credential, for: challenge)
I have checked it also in other iOS versions 9.X, 10.1, 10.2 and 10.3.
It's working fine.

```<code>func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    let user = "user"
    let password = "pass"
    let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
    completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)
</code>```

}

Body:
I'm trying to build a simple WebView which shows a web page - the page requires http authentication for all pages (for testing purposes).

Here is my code:

class ViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }

    // #1 variant
    func webView(webView: WKWebView, willSendRequestForAuthenticationChallenge challenge:
        URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let user = "user"
        let password = "pass"
        let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
        challenge.sender?.use(credential, for: challenge)
    }

    // #2 variant
    func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

            let user = "user"
            let password = "pass"
            let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
            challenge.sender?.use(credential, for: challenge)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string: "https://myurl.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }

}

I've found willSendRequestForAuthenticationChallenge and didReceiveAuthenticationChallenge, but none of them is called and I've got error from the server that I was not authenticated.

Could somebody help?

Thank you a lot!

David

Body:
It works by removing (or comment out) this line.
challenge.sender?.use(credential, for: challenge)
I have checked it also in other iOS versions 9.X, 10.1, 10.2 and 10.3.
It's working fine.

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    let user = "user"
    let password = "pass"
    let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
    completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)

}


问:
Restart Kubernetes pod when change happens on another
Two pods app and postgres are successfully created and are able to communicate through each other's services in a node. In the current process, the two pods get created at the same time, but that can be changed to have them be created/started in a sequence.

Initially, the database container in the postgres pod is empty and needs to be seeded. The seed process goes through the app pod and so, it needs to be up and running too. Once postgres is seeded, app still is not aware of this new data, and needs to be restarted. This is a flaw in app itself, that I have low control over.

Right now, the process is:

```<code>kubectl create -f pods.yaml       # creates `app` and `postgres` pods
kubectl exec app -- bash -c "<seed command>"
kubectl delete pod app
sleep 45                          # takes a while for `app` to terminate
kubectl create -f pods.yaml       # Ignore the "postgres pod and service already exist" error
</code>```

Is there a better way of automatically co-ordinating a restart of app once postgres reaches a seeded state?

Perhaps there is some aspect/feature set of Kubernetes that I'm missing entirely which helps with such a circumstance....

答:
You can use a "readiness probe" on the postgresql pod that will not report the container as ready before the data is imported (e.g. query the DB or Table you import). You app container can query the readiness status of the db pod in order to restart automatically once it reports ready.
The readiness probe can be a script performing the import. Here is an example (you need to replace the "SHOW DATABASES" command with whatever applies in your case):

```<code>spec:
  containers:
  - name: mysql
    image: mysql:latest
    ports:
    - containerPort: 3306
      name: mysql
    readinessProbe:
      exec:
        command:
        - /path-in-container/readiness-probe.sh
      initialDelaySeconds: 15
      timeoutSeconds: 5
</code>```

readiness-probe.sh:

```<code>#!/bin/bash

MYSQL_USER="readinessProbe"
MYSQL_PASS="readinessProbe"
MYSQL_HOST="127.0.0.1"

mysql -u${MYSQL_USER} -p${MYSQL_PASS} -h${MYSQL_HOST} -e"SHOW DATABASES;"

if [ $? -ne 0 ]; then
  exit 1
else
  exit 0
fi
</code>```

To read more on the topic refer to k8s docs:

readiness probes

health checking

Body:
Two pods app and postgres are successfully created and are able to communicate through each other's services in a node. In the current process, the two pods get created at the same time, but that can be changed to have them be created/started in a sequence.

Initially, the database container in the postgres pod is empty and needs to be seeded. The seed process goes through the app pod and so, it needs to be up and running too. Once postgres is seeded, app still is not aware of this new data, and needs to be restarted. This is a flaw in app itself, that I have low control over.

Right now, the process is:

kubectl create -f pods.yaml       # creates `app` and `postgres` pods
kubectl exec app -- bash -c "<seed command>"
kubectl delete pod app
sleep 45                          # takes a while for `app` to terminate
kubectl create -f pods.yaml       # Ignore the "postgres pod and service already exist" error

Is there a better way of automatically co-ordinating a restart of app once postgres reaches a seeded state?

Perhaps there is some aspect/feature set of Kubernetes that I'm missing entirely which helps with such a circumstance....

Body:
You can use a "readiness probe" on the postgresql pod that will not report the container as ready before the data is imported (e.g. query the DB or Table you import). You app container can query the readiness status of the db pod in order to restart automatically once it reports ready.
The readiness probe can be a script performing the import. Here is an example (you need to replace the "SHOW DATABASES" command with whatever applies in your case):

spec:
  containers:
  - name: mysql
    image: mysql:latest
    ports:
    - containerPort: 3306
      name: mysql
    readinessProbe:
      exec:
        command:
        - /path-in-container/readiness-probe.sh
      initialDelaySeconds: 15
      timeoutSeconds: 5

readiness-probe.sh:

#!/bin/bash

MYSQL_USER="readinessProbe"
MYSQL_PASS="readinessProbe"
MYSQL_HOST="127.0.0.1"

mysql -u${MYSQL_USER} -p${MYSQL_PASS} -h${MYSQL_HOST} -e"SHOW DATABASES;"

if [ $? -ne 0 ]; then
  exit 1
else
  exit 0
fi

To read more on the topic refer to k8s docs:

readiness probes

health checking


问:
Python - Use values from 1D array as column indices for 2D array
Little tricky to explain it with few words (and google it), so:

I have this 2D np array:

```<code>import numpy as np

x = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15,16,17]])
</code>```

and this 1D np array:

```<code>y = np.array([0,2,1,0,2,0])
</code>```

what I would like to do is to return the column values from x using y as a (column) index, so it will return something like this:

```<code>[0, 5, 7, 9, 14, 15]
</code>```

in ugly-code it would be solved like this:

```<code>for row,col in zip(x,y):
    print(row[col])
</code>```

and in a not-so-ugly code:

```<code>[row[col] for row,col in zip(x,y)]
</code>```

Is there another way solve this? I would like something like:

```<code>x[y]
</code>```

or a numpy specific function.

答:
Yes it is better to do it with numpy because it is several times faster than doing it with for loop. What I suggest is to slice your array using np.ix_() function and take diagonal of the result to get by value from each row:

np.diag(x[np.ix_(range(0, np.shape(x)[0]), y)])

Body:
Little tricky to explain it with few words (and google it), so:

I have this 2D np array:

import numpy as np

x = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15,16,17]])

and this 1D np array:

y = np.array([0,2,1,0,2,0])

what I would like to do is to return the column values from x using y as a (column) index, so it will return something like this:

[0, 5, 7, 9, 14, 15]

in ugly-code it would be solved like this:

for row,col in zip(x,y):
    print(row[col])

and in a not-so-ugly code:

[row[col] for row,col in zip(x,y)]

Is there another way solve this? I would like something like:

x[y]

or a numpy specific function.


问:
Download Files using C# from https Website
I'm trying to download a pdf file from https website, but it doesn't work. I'm new to C#, so did some research and found a simple code. Worse, the exception I get is quite generic. Help please.

```<code>    static void Main(string[] args)
    {

        string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
        string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

        WebClient wc_ = new WebClient();
        wc_.DownloadFile(file_, path_);
    }
</code>```

The exception:
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (403) Forbidden.

答:
The server is checking to see if you're a real user by using your user agent header. It also requires that you specify the mime type you want. This isn't a general C# thing, it's just the host you're connecting to (nseindia.com).

This works for me.

```<code>static void Main(string[] args)
{

    string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
    string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

    WebClient wc_ = new WebClient();
    wc_.Headers.Add(HttpRequestHeader.UserAgent, "Other");
    wc_.Headers.Add(HttpRequestHeader.Accept, "application/pdf");
    wc_.DownloadFile(file_, path_);
}
</code>```

Body:
I'm trying to download a pdf file from https website, but it doesn't work. I'm new to C#, so did some research and found a simple code. Worse, the exception I get is quite generic. Help please.

    static void Main(string[] args)
    {

        string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
        string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

        WebClient wc_ = new WebClient();
        wc_.DownloadFile(file_, path_);
    }

The exception:
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (403) Forbidden.

Body:
The server is checking to see if you're a real user by using your user agent header. It also requires that you specify the mime type you want. This isn't a general C# thing, it's just the host you're connecting to (nseindia.com).

This works for me.

static void Main(string[] args)
{

    string file_ = "https://www.nseindia.com/content/circulars/CMPT34469.pdf";
    string path_ = @"E:\RSR\Office\EEP\FileDownloader\output\Hello_World.pdf";

    WebClient wc_ = new WebClient();
    wc_.Headers.Add(HttpRequestHeader.UserAgent, "Other");
    wc_.Headers.Add(HttpRequestHeader.Accept, "application/pdf");
    wc_.DownloadFile(file_, path_);
}


问:
Transition on box-shadow on-off?
http://lucasdebelder.be/googledoodle/
Here is a live version.

So as you can see on the portals there's a glow around it which is the box-shadow; I want to have it going on and off so it kinda feels more real, I've added  transition: box-shadow ease-in-out; but it only does it at the start, after the page is loaded, and then just keeps glowing on.

Here's the relevant code. (portaal_links means portal left, and rechts means right, it's dutch)

HTML:

```<code><div class="portaal portaal_links"></div>
<div class="portaal portaal_rechts"></div>
</code>```

CSS:

```<code>/*portaal general*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}

/*portaal left*/
.portaal_links {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    transition: box-shadow ease-in-out;
    transition-delay: 1s;
    transition-duration: 1s;
    box-shadow: 0 0 55px #57B6FF;
    opacity: 0.75;
    left: 50px;
}

.portaal_rechts {
    background: radial-gradient(ellipse at center, rgba(243,197,189,1) 0%,rgba(232,108,87,1) 50%,rgba(234,40,3,1) 51%,rgba(255,102,0,1) 75%,rgba(199,34,0,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    box-shadow: 0 0 55px #FF6600;
    opacity: 0.55;
    left: 750px;
}
</code>```

答:
You could create a animation like below on box-shadow,

/*portaal general*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 60px;
}

/*portaal left*/
.portaal_links {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    transition: box-shadow ease-in-out;
    transition-delay: 1s;
    transition-duration: 1s;
    box-shadow: 0 0 55px #57B6FF;
    opacity: 0.75;
    left: 50px;
    animation:mvv 2s infinite;
}
@keyframes mvv{
   0%{
         box-shadow: 0 0 55px #57B6FF;
   }
   50%{
         box-shadow: 0 0 0px #57B6FF;
   }
}

.portaal_rechts {
    background: radial-gradient(ellipse at center, rgba(243,197,189,1) 0%,rgba(232,108,87,1) 50%,rgba(234,40,3,1) 51%,rgba(255,102,0,1) 75%,rgba(199,34,0,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    box-shadow: 0 0 55px #FF6600;
    opacity: 0.55;
    left: 750px;
    animation:mv 2s infinite;
}
@keyframes mv{
   0%{
         box-shadow: 0 0 55px #FF6600;
   }
   50%{
         box-shadow: 0 0 0px #FF6600;
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="portaal portaal_links"></div>
<div class="portaal portaal_rechts"></div></code>```

Title: Transition on box-shadow on-off?

Body:
http://lucasdebelder.be/googledoodle/
Here is a live version.

So as you can see on the portals there's a glow around it which is the box-shadow; I want to have it going on and off so it kinda feels more real, I've added  transition: box-shadow ease-in-out; but it only does it at the start, after the page is loaded, and then just keeps glowing on.

Here's the relevant code. (portaal_links means portal left, and rechts means right, it's dutch)

HTML:

CSS:

/*portaal general*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}

/*portaal left*/
.portaal_links {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    transition: box-shadow ease-in-out;
    transition-delay: 1s;
    transition-duration: 1s;
    box-shadow: 0 0 55px #57B6FF;
    opacity: 0.75;
    left: 50px;
}

.portaal_rechts {
    background: radial-gradient(ellipse at center, rgba(243,197,189,1) 0%,rgba(232,108,87,1) 50%,rgba(234,40,3,1) 51%,rgba(255,102,0,1) 75%,rgba(199,34,0,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    box-shadow: 0 0 55px #FF6600;
    opacity: 0.55;
    left: 750px;
}

Body:
You could create a animation like below on box-shadow,

/*portaal general*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 60px;
}

/*portaal left*/
.portaal_links {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    transition: box-shadow ease-in-out;
    transition-delay: 1s;
    transition-duration: 1s;
    box-shadow: 0 0 55px #57B6FF;
    opacity: 0.75;
    left: 50px;
    animation:mvv 2s infinite;
}
@keyframes mvv{
   0%{
         box-shadow: 0 0 55px #57B6FF;
   }
   50%{
         box-shadow: 0 0 0px #57B6FF;
   }
}

.portaal_rechts {
    background: radial-gradient(ellipse at center, rgba(243,197,189,1) 0%,rgba(232,108,87,1) 50%,rgba(234,40,3,1) 51%,rgba(255,102,0,1) 75%,rgba(199,34,0,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    box-shadow: 0 0 55px #FF6600;
    opacity: 0.55;
    left: 750px;
    animation:mv 2s infinite;
}
@keyframes mv{
   0%{
         box-shadow: 0 0 55px #FF6600;
   }
   50%{
         box-shadow: 0 0 0px #FF6600;
   }
}

<div class="portaal portaal_links"></div>
<div class="portaal portaal_rechts"></div>


问:
Vertical Centering a DIV within an unknown height DIV
I currently have this HTML:

```<code><div id:root>
  <div id:contents>
    <h3>I am the one that need to be vertical centered.</h3>
    <p>Lorem300..............</p>
  </div>
  <img scr:"somewhere.jpg"></img>
</div>
</code>```

And the current SASS:

```<code>img
  width: 100%
  height: inherit
</code>```

The problem I want to solve is I want the 'root' DIV to have the exactly same size as the img. In this case the img width is set to 100%, which means it always take 100% width of the viewport. Is there a way that I can vertically center the 'contents' DIV to the 'root' DIV? Thank you very much. I spent the whole day and still nothing found. Even when I use:

```<code>#contents
  top: 50%
  transform: translateY(-50%)
</code>```

The 'contents' div take the height of the body, not the 'root' div. :(

Is there a way that I can solve this? Thank you!

答:
.center_block{
   position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center_block">
  <div>
    <h3>I am the one that need to be vertical centered.</h3>
    <p>Lorem300..............</p>
  </div>
  <img scr="somewhere.jpg" class="img-responsive" />
</div></code>```

Body:
I currently have this HTML:

I am the one that need to be vertical centered.

Lorem300..............

And the current SASS:

img
  width: 100%
  height: inherit

The problem I want to solve is I want the 'root' DIV to have the exactly same size as the img. In this case the img width is set to 100%, which means it always take 100% width of the viewport. Is there a way that I can vertically center the 'contents' DIV to the 'root' DIV? Thank you very much. I spent the whole day and still nothing found. Even when I use:

#contents
  top: 50%
  transform: translateY(-50%)

The 'contents' div take the height of the body, not the 'root' div. :(

Is there a way that I can solve this? Thank you!

Body:
.center_block{
   position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

<div class="center_block">
  <div>
    <h3>I am the one that need to be vertical centered.</h3>
    <p>Lorem300..............</p>
  </div>
  <img scr="somewhere.jpg" class="img-responsive" />
</div>


问:
Is it reasonable to assume my visitors have javascript enabled?
I understand that server-side validation is an absolute must to prevent malicious users (or simply users who choose to disable javascript) from bypassing client-side validation.  But that's mainly to protect your application, not to provide value for those who are running browsers with javascript disabled.  Is it reasonable to assume visitors have javascript enabled and simply have an unusable site for those who don't?</p>

答:
Not that everyone else hasn't chimed in, but I disagree with the "look at your audience" position to some extent.

It really should be "look at your app" if you are just displaying some information, and your js is for bell/whistle purposes, then certainly look at nice degradation, if you want to.

However, if you're building something like Google Docs, it's really asinine that someone would think they could use your site without js, so perhaps let them know that via a nice sarcastic message inside  tags.

From a purely philosophical point of view, if users want to access your site, they will flip the js switch, or upgrade to a decent browser, etc.  And you should force them to do this, because evolution is important for the survival of the species.

OwnerDisplayName: Kevin Pang

Body:
Not that everyone else hasn't chimed in, but I disagree with the "look at your audience" position to some extent.

It really should be "look at your app" if you are just displaying some information, and your js is for bell/whistle purposes, then certainly look at nice degradation, if you want to.

However, if you're building something like Google Docs, it's really asinine that someone would think they could use your site without js, so perhaps let them know that via a nice sarcastic message inside <noscript> tags.

From a purely philosophical point of view, if users want to access your site, they will flip the js switch, or upgrade to a decent browser, etc.  And you should force them to do this, because evolution is important for the survival of the species.


问:
Get Image by Class and Click using Selenium Python
I'm trying to get all images from the image class profile_view_img_5087188 but there are multiple classes "profile_view_img_xxxxxx" in the page source and fewer from them containing the same url of an image let says that classes containing image

```<code>http://i.imgur.com/oraB49H.png
</code>```

and I want to click if the above image url found

```<code><head><style type="text/css">.profile_view_img_5087188 { background-image: url('http://i.imgur.com/oraB49H.png'); }</style></head>

<a class="cursor earn_pages_button profile_view_img_5087188" onclick="startlink52efa('newlookskincenter','follow','99218',16837);imageWin('http://instagram.com/newlookskincenter','Instagram','99218','newlookskincenter','qFVnV5xlY2OJaW4','1015','500','follow',16837)"></a>
</code>```

here is my code but doesn't work

```<code>            like_button = browser.find_elements_by_css_selector("div > span > a")
            for links in like_button:
                    if "http://i.imgur.com/oraB49H.png" in link.get_attribute('href'):
                            links.click()
</code>```

答:
First you need to get all the  tags which have classname profile_view_img_5087188  the number is different. So get all tag using  below xpath :

```<code>like_button = browser.find_elements_by_xpath("//a[contains(@class,'profile_view_img')]")
</code>```

Then loop through in all links and find your image url in

```<code>for links in like_button:
if "http://instagram.com/newlookskincenter" in link.get_attribute('onclick'):
  links.click()
</code>```

Note : Please make sure you are using correct string comparison as I'm not much aware with python syntax

Body:
I'm trying to get all images from the image class profile_view_img_5087188 but there are multiple classes "profile_view_img_xxxxxx" in the page source and fewer from them containing the same url of an image let says that classes containing image

http://i.imgur.com/oraB49H.png

and I want to click if the above image url found

here is my code but doesn't work

            like_button = browser.find_elements_by_css_selector("div > span > a")
            for links in like_button:
                    if "http://i.imgur.com/oraB49H.png" in link.get_attribute('href'):
                            links.click()

Body:
First you need to get all the <a> tags which have classname profile_view_img_5087188  the number is different. So get all tag using  below xpath :

like_button = browser.find_elements_by_xpath("//a[contains(@class,'profile_view_img')]")

Then loop through in all links and find your image url in

for links in like_button:
if "http://instagram.com/newlookskincenter" in link.get_attribute('onclick'):
  links.click()

Note : Please make sure you are using correct string comparison as I'm not much aware with python syntax


问:
socket.io get rooms which socket is currently in
Is it possible to get rooms which socket is currently in, without calling

```<code>io.sockets.clients(roomName)
</code>```

for every room name and looking for this socket in results

答:
Version 1.7.3, socket.rooms contains socket.id, so remove it and get the list of rooms:

```<code>Object.keys(socket.rooms).filter(item => item!=socket.id);
</code>```

In other version, you can print the socket and find the rooms.

Body:
Is it possible to get rooms which socket is currently in, without calling

io.sockets.clients(roomName)

for every room name and looking for this socket in results

Body:
Version 1.7.3, socket.rooms contains socket.id, so remove it and get the list of rooms:

Object.keys(socket.rooms).filter(item => item!=socket.id);

In other version, you can print the socket and find the rooms.


问:
bootstrap disabling collapse/toggleable on navbar
How can I make my navbar not collapse/toggle when the window is resized? I tried adding

```<code>.collapse{
   display: inline-block;
 }
</code>```

to my css. With this, when the window is resized, the nav bar elements end up stacking. I'm also using bootstrap 4 alpha 6

here's my code for the navbar: http://www.bootply.com/mHeWTUSxAM

答:
updated Bootply

Just use navbar-toggleable-xl in place of navbar-toggleable-md.

Working snippet

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

        Menu

        logged in as

          Logout
          My Movements

```

Body:
How can I make my navbar not collapse/toggle when the window is resized? I tried adding

.collapse{
   display: inline-block;
 }

to my css. With this, when the window is resized, the nav bar elements end up stacking. I'm also using bootstrap 4 alpha 6

here's my code for the navbar: http://www.bootply.com/mHeWTUSxAM

Body:
updated Bootply

Just use navbar-toggleable-xl in place of navbar-toggleable-md.

Working snippet

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<nav class="navbar navbar-toggleable-xl navbar-inverse bg-inverse">

  <div class="navbar-collapse collapse" id="collapsingNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a href="#menu-toggle" class="nav-link" id="menu-toggle">Menu</a>
      </li>
    </ul>
    <ul class="navbar-nav dropdown dropdown-menu-right ml-auto">
      <li class="nav-item ">
        <a class="nav-link dropdown-toggle" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">logged in as</a>

        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdown01">
          <a class="dropdown-item" href="#">Logout</a>
          <a class="dropdown-item" href="#">My Movements</a>
        </div>
      </li>
    </ul>
  </div>

</nav>


问:
How to avoid a "java.util.NoSuchElementException" crashing my program
TL;DR-- how to get a java.util.NoSuchElementException to return a null instead of error and crash the program.

I was writing a program that is supposed to read a series of ints from a text file. In the program the amount of ints will vary each time I run it. I have written a piece of code that will read ints and I want to know how to make the java.util.NoSuchElementException not crash my program and instead return a null.

 The code I have writen is as follows

```<code>    public static void main(String[] args)  throws IOException{
    Scanner Input = new Scanner(new File("newestcode.txt"));
    Integer[] digits = new Integer[100];
    int h = 0;
    while(true){
        digits[h] = Input.nextInt();
        h++;
        System.out.println(digits[h]);
    }
}
</code>```

in case you are curious, the program I am to be writing is a sort of decryption engine for a bad encryption engine I wrote the other day

答:
You should use the input.hasNext() method to check whether the input has any more 'int' before using it.
In order to support any length of int elements, you cannot set the array to a fixed length of 100, you need to use an ArrayList to add elements dynamically.

```<code>Scanner input = new Scanner(new File("./newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while (input.hasNext()) {
    digits.add(h, input.nextInt());
    System.out.println(digits.get(h));
    h++;
}
</code>```

Note: You need to print digits[h] before increasing the h.

Body:
TL;DR-- how to get a java.util.NoSuchElementException to return a null instead of error and crash the program.

I was writing a program that is supposed to read a series of ints from a text file. In the program the amount of ints will vary each time I run it. I have written a piece of code that will read ints and I want to know how to make the java.util.NoSuchElementException not crash my program and instead return a null.

 The code I have writen is as follows

    public static void main(String[] args)  throws IOException{
    Scanner Input = new Scanner(new File("newestcode.txt"));
    Integer[] digits = new Integer[100];
    int h = 0;
    while(true){
        digits[h] = Input.nextInt();
        h++;
        System.out.println(digits[h]);
    }
}

in case you are curious, the program I am to be writing is a sort of decryption engine for a bad encryption engine I wrote the other day

Body:
You should use the input.hasNext() method to check whether the input has any more 'int' before using it.
In order to support any length of int elements, you cannot set the array to a fixed length of 100, you need to use an ArrayList to add elements dynamically.

Scanner input = new Scanner(new File("./newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while (input.hasNext()) {
    digits.add(h, input.nextInt());
    System.out.println(digits.get(h));
    h++;
}

Note: You need to print digits[h] before increasing the h.


问:
Python Twill: follow link and grab data
I finally arrived to open a page and make the request I want.

```<code>#!/usr/bin/env python
from twill.commands import *

go("http://www.website.com/")
code(200) # assert page loaded fine
showforms()
# Make a search
searchStr = '%s' % n
formvalue(1, 'q', searchStr)
submit('Factorize!')
links = showlinks()
</code>```

I now see all the links listed and I would like to click on the number 11 and 12 and when I'm there grab 1 value per page.

How to use follow() and what's the command used for grabbing a value?

答:
The solution was:

```<code>data = urllib2.urlopen(follow(str(3)))
</code>```

where '3' is is the number of the link listed by links = showlinks()

Title: Python Twill: follow link and grab data

Body:
I finally arrived to open a page and make the request I want.

#!/usr/bin/env python
from twill.commands import *

go("http://www.website.com/")
code(200) # assert page loaded fine
showforms()
# Make a search
searchStr = '%s' % n
formvalue(1, 'q', searchStr)
submit('Factorize!')
links = showlinks()

I now see all the links listed and I would like to click on the number 11 and 12 and when I'm there grab 1 value per page.

How to use follow() and what's the command used for grabbing a value?

Body:
The solution was:

data = urllib2.urlopen(follow(str(3)))

where '3' is is the number of the link listed by links = showlinks()


问:
UITableView leaking?
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}
</code>```

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?

答:
Looks like you have an array or dictionary thats leaking, not the tableview.

What is the array that you are using to fill your tableview?

Also, you wont want to [self.tableVIew initWithFrame,
try [self.tableView setFrameCGRectMake(x,y,w,h)];

Title: UITableView leaking?

Body:
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?


问:
Adding mleader to AutoCAD
Currently my program has a leader with mtext in it and I wanted to convert it to a multi-leader so the text is infused and it's easier and nicer to move around. So for leader it's easier.. I just add .addleader(pointsarray, annotation, leadertype)

But for mleader it's : .addmleader(pointsarray, leaderlineindex as long)

So my question is... what's leader line index? And where does my leader text go?
Thank you in advance

答:
what's leader line index?

an MLeader object is an "object composed of an arrowhead attached to multiple splines or straight line segments"

so it can have multiple lines (i.e. leader lines), each one identified through its own index (i.e. leader line index)

when you create a Mleader object through its AddLeader() method, you're setting its first leader line, that you have to identify through its index (normally zero, but you can specify any positive integer)

you may very well use a literal integer:

```<code>Set oML = ThisDrawing.ModelSpace.AddMLeader(pointsArray, 0) '<--| set newly created leader line index to zero (or 1, or whatever positive integer)
</code>```

but it's convenient to store it in some (Long) variable so it can be subsequently used by such other object methods as, for example, AddLeaderLine() or SetLeaderLineVertices()

And where does my leader text go?

you just set MLeader TextString property to wanted text

for instance:

```<code>    Dim oML As AcadMLeader
    Dim points(0 To 14) As Double

    ' Define the leader points
    points(0) = 1: points(1) = 1: points(2) = 0
    points(3) = 1: points(4) = 2: points(5) = 0
    points(6) = 2: points(7) = 2: points(8) = 0
    points(9) = 3: points(10) = 2: points(11) = 0
    points(12) = 4: points(13) = 4: points(14) = 0

    Set oML = ThisDrawing.ModelSpace.AddMLeader(points, 0) '<--| set the MLeader object (and assign it a leader line index of zero)

    oML.TextString = "This is Mleader Text" '<--| set its text
</code>```

a thorough reading of this AutoCAD Help page can possibly help you better understanding the issue

Title: Adding mleader to AutoCAD

Body:
what's leader line index?

an MLeader object is an "object composed of an arrowhead attached to multiple splines or straight line segments"

so it can have multiple lines (i.e. leader lines), each one identified through its own index (i.e. leader line index)

when you create a Mleader object through its AddLeader() method, you're setting its first leader line, that you have to identify through its index (normally zero, but you can specify any positive integer)

you may very well use a literal integer:

Set oML = ThisDrawing.ModelSpace.AddMLeader(pointsArray, 0) '<--| set newly created leader line index to zero (or 1, or whatever positive integer)

but it's convenient to store it in some (Long) variable so it can be subsequently used by such other object methods as, for example, AddLeaderLine() or SetLeaderLineVertices()

And where does my leader text go?

you just set MLeader TextString property to wanted text

for instance:

    Dim oML As AcadMLeader
    Dim points(0 To 14) As Double

    ' Define the leader points
    points(0) = 1: points(1) = 1: points(2) = 0
    points(3) = 1: points(4) = 2: points(5) = 0
    points(6) = 2: points(7) = 2: points(8) = 0
    points(9) = 3: points(10) = 2: points(11) = 0
    points(12) = 4: points(13) = 4: points(14) = 0

    Set oML = ThisDrawing.ModelSpace.AddMLeader(points, 0) '<--| set the MLeader object (and assign it a leader line index of zero)

    oML.TextString = "This is Mleader Text" '<--| set its text

a thorough reading of this AutoCAD Help page can possibly help you better understanding the issue


问:
How to setup ViewController in Playgrounds?
In swift playgrounds how do you setup a viewcontroller and use it? I've done it with a UIView before but the UI gets cut when in a difference orientation so I want to try use a viewcontroller.
I've got let view = UIViewController() but after that how do I set it up to add a background and stuff on it?

答:
To create a view controller in a Swift playground you need this code:</p>
```<code>import UIKit
import PlaygroundSupport

class ViewController: UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        // do setup here
    }
}

let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

Body:
To create a view controller in a Swift playground you need this code:

import UIKit
import PlaygroundSupport

class ViewController: UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        // do setup here
    }
}

let viewController = ViewController()
PlaygroundPage.current.liveView = viewController
PlaygroundPage.current.needsIndefiniteExecution = true

ContentLicense: CC BY-SA 4.0


问:
remove image and its container if image is broken
I am just trying to remove image and its title in case if image fails to load or broken using html or JavaScript.what is the best and easiest way to do that?

```<code><?php

   include("../includes/db.php");   // ../ means go to parent directory
  $query='SELECT * FROM `table` WHERE tag NOT IN("news") ORDER BY `id` DESC LIMIT 0,5';
  $run=mysqli_query($conn,$query);
  while($row=mysqli_fetch_array($run)){
         $img=$row['src'];
         $title=$row['title'];
   ?>

       <table class='mobileTable'>
          <tr> <td><img src='<?php echo $img ?>' onerror='imgError(this)' /></td></tr>
          <tr> <td  class='mobMidTitle'><?php echo $title ?></td></tr>//i want to remove this title as well
       </table>
   <?php } ?>

 <script>
 function imgError(image) {
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    document.getElementById('tit').style.display='none';
    return true;
}</script>
</code>```

code above will fetch 5 images from database and with  javascript i can change image to error.jpg but i want to remove both image as well as its title only of failed image.

答:
well, there are multiple approaches to do this :

here, I'm assuming that you want to use Pure javescript -no jquery- and keeping the original DOM document hierarchy.

```<code><table class='mobileTable'>
    <tr> <td><img src='path/to/broken/image.jpg' onerror='imgError(this)' /></td></tr>
    <tr> <td  class='mobMidTitle'>some title</td></tr>
</table>

<script>
function imgError(image) {
    // this will step up to get the parent of the image's parent
    var imgParent = image.parentElement.parentElement;
    // this will get the next sibling of the image grandpa
    var nextSib = imgParent.nextElementSibling;
    // reset it's html to empty
    nextSib.innerHTML = '';
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    return true;
}
</script>
</code>```

another easier approach is by adding new ID to your title TD and then remove it using javascript as follows :

```<code>/* here we've added id='mobMidTitle' */
<td  class='mobMidTitle' id='mobMidTitle' >some title</td>

<script>
function imgError(image) {
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    document.getElementById('mobMidTitle').style.display = 'none';
    //                       ^^^^^^^^^^^
    return true;
}
</script>
</code>```

Body:
I am just trying to remove image and its title in case if image fails to load or broken using html or JavaScript.what is the best and easiest way to do that?

<?php

   include("../includes/db.php");   // ../ means go to parent directory
  $query='SELECT * FROM `table` WHERE tag NOT IN("news") ORDER BY `id` DESC LIMIT 0,5';
  $run=mysqli_query($conn,$query);
  while($row=mysqli_fetch_array($run)){
         $img=$row['src'];
         $title=$row['title'];
   ?>

 <img src='<?php echo $img ?>' onerror='imgError(this)' />

 <?php echo $title ?>
//i want to remove this title as well

   <?php } ?>

code above will fetch 5 images from database and with  javascript i can change image to error.jpg but i want to remove both image as well as its title only of failed image.

Body:
well, there are multiple approaches to do this :

here, I'm assuming that you want to use Pure javescript -no jquery- and keeping the original DOM document hierarchy.

<table class='mobileTable'>
    <tr> <td><img src='path/to/broken/image.jpg' onerror='imgError(this)' /></td></tr>
    <tr> <td  class='mobMidTitle'>some title</td></tr>
</table>

<script>
function imgError(image) {
    // this will step up to get the parent of the image's parent
    var imgParent = image.parentElement.parentElement;
    // this will get the next sibling of the image grandpa
    var nextSib = imgParent.nextElementSibling;
    // reset it's html to empty
    nextSib.innerHTML = '';
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    return true;
}
</script>

another easier approach is by adding new ID to your title TD and then remove it using javascript as follows :

/* here we've added id='mobMidTitle' */
<td  class='mobMidTitle' id='mobMidTitle' >some title</td>

<script>
function imgError(image) {
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    document.getElementById('mobMidTitle').style.display = 'none';
    //                       ^^^^^^^^^^^
    return true;
}
</script>


问:
How to edit mail appearance in PHP?
I wonder how that can change the appearance of e-mail that comes to me via PHP?

This is a PHP code:

```<code><?php
$Ime = $_POST["Ime"];
$Prezime = $_POST["Prezime"];
$NaslovOglasa = $_POST["NaslovOglasa"];
$Email = $_POST["Email"];
$SadrzajOglasa = $_POST["SadrzajOglasa"];
$Kontakt = $_POST["Kontakt"];

if (isset($_POST['Istaknut_Oglas'])) {
$IstaknutOglas = "Da";
} else {
$IstaknutOglas = "Ne";
}

if (isset($_POST['Standardni_Paket'])) {
$StandardniPaket = "Da";
} else {
$StandardniPaket = "Ne";
}

$Za = "bratunac.info@gmail.com";
$Od  = "Od: " . $Email . "\r\n";
$Info .= "|NOVI OGLAS|" . "\r\n";
$Info .= "Ime: " . $Ime . "\r\n";
$Info .= "Prezime: " . $Prezime . "\r\n";
$Info .= "Naslov oglasa: " . $NaslovOglasa . "\r\n";
$Info .= "Sadrzaj oglasa: " . $SadrzajOglasa . "\r\n";
$Info .= "Kontakt informacije: " . $Kontakt . "\r\n";
$Info .= "Istaknut oglas: " . $IstaknutOglas . "\r\n";
$Info .= "Standardni paket: " . $StandardniPaket . "\r\n";
$Info .= "" . "\r\n";

if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 1; $i < count($tmp_name_array); $i++){
    if(move_uploaded_file($tmp_name_array[$i], "adsuploads/".$name_array[$i])){
        $Info .= "Fotografija ".$i.": ".$name_array[$i]. "\r\n";
    }
}
mail($Za, $Od, $Info);
header("Location: http://bratunacinfo.000webhostapp.com/pages/postavi_oglas-3");
}
?>
</code>```

I wonder if this can be done via php me or I need some framework

答:
You need to do following:

Prepare your mail contents in html format.

//write your stuff

Provide absolute path of your image instead of relative path. So, just providing image name is not sufficient. You need to provide exact path where that image resides in your server. So that, it will load it from there.

Title: How to edit mail appearance in PHP?

Body:
I wonder how that can change the appearance of e-mail that comes to me via PHP?

This is a PHP code:

<?php
$Ime = $_POST["Ime"];
$Prezime = $_POST["Prezime"];
$NaslovOglasa = $_POST["NaslovOglasa"];
$Email = $_POST["Email"];
$SadrzajOglasa = $_POST["SadrzajOglasa"];
$Kontakt = $_POST["Kontakt"];

if (isset($_POST['Istaknut_Oglas'])) {
$IstaknutOglas = "Da";
} else {
$IstaknutOglas = "Ne";
}

if (isset($_POST['Standardni_Paket'])) {
$StandardniPaket = "Da";
} else {
$StandardniPaket = "Ne";
}

$Za = "bratunac.info@gmail.com";
$Od  = "Od: " . $Email . "\r\n";
$Info .= "|NOVI OGLAS|" . "\r\n";
$Info .= "Ime: " . $Ime . "\r\n";
$Info .= "Prezime: " . $Prezime . "\r\n";
$Info .= "Naslov oglasa: " . $NaslovOglasa . "\r\n";
$Info .= "Sadrzaj oglasa: " . $SadrzajOglasa . "\r\n";
$Info .= "Kontakt informacije: " . $Kontakt . "\r\n";
$Info .= "Istaknut oglas: " . $IstaknutOglas . "\r\n";
$Info .= "Standardni paket: " . $StandardniPaket . "\r\n";
$Info .= "" . "\r\n";

if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 1; $i < count($tmp_name_array); $i++){
    if(move_uploaded_file($tmp_name_array[$i], "adsuploads/".$name_array[$i])){
        $Info .= "Fotografija ".$i.": ".$name_array[$i]. "\r\n";
    }
}
mail($Za, $Od, $Info);
header("Location: http://bratunacinfo.000webhostapp.com/pages/postavi_oglas-3");
}
?>

I wonder if this can be done via php me or I need some framework

Body:
You need to do following:

Prepare your mail contents in html format.

<html>
<body>
//write your stuff
</body>
</html>

Provide absolute path of your image instead of relative path. So, just providing image name is not sufficient. You need to provide exact path where that image resides in your server. So that, it will load it from there.


问:
How to get eNB id of LTE on Android Studio (TelephonyManager)
Good day,

May I ask how to get the eNB id of CellIdentityLte?

Is there any way of getting it?

Thanks!

答:
I got it!

```<code>                    final CellIdentityLte identityLte = ((CellInfoLte) info).getCellIdentity();
                    int longCid = identityLte.getCi();

                    String cellidHex = DecToHex(longCid);
                    String eNBHex = cellidHex.substring(0, cellidHex.length()-2);

                    int eNB = HexToDec(eNBHex);

                    return checkValidString(Integer.toString(eNB));
</code>```

by using this method...

```<code>// Decimal -> hexadecimal
public String DecToHex(int dec){
    return String.format("%x", dec);
}

// hex -> decimal
public int HexToDec(String hex){
    return Integer.parseInt(hex, 16);
}
</code>```

Body:
I got it!

                    final CellIdentityLte identityLte = ((CellInfoLte) info).getCellIdentity();
                    int longCid = identityLte.getCi();

                    String cellidHex = DecToHex(longCid);
                    String eNBHex = cellidHex.substring(0, cellidHex.length()-2);

                    int eNB = HexToDec(eNBHex);

                    return checkValidString(Integer.toString(eNB));

by using this method...

// Decimal -> hexadecimal
public String DecToHex(int dec){
    return String.format("%x", dec);
}

// hex -> decimal
public int HexToDec(String hex){
    return Integer.parseInt(hex, 16);
}


问:
How to separate a picture to color groups?
Let's say I have an image of a ball like this one:

I want to separate the colors of the ball to the color groups. In this case I should have 2 main color groups - "brown" and "white". The "brown" group will have all the brown pixels and the "white" group will have all the white pixels.
I'm using matlab for this task. The way that I thought to do is:

to look at the RGB channels. I used scatter to look if I could clearly see some groups, but I didn't.

to look at the bayer vales. But couldn't see any groups either.

to run an edge detector. Then, in each enclosed area I'll find the mean of the pixels. The areas that will have similar mean values (within a certain threshold) will belong to the same group. It seemed to sort of to work but in many case it didn't

Any other ideas?

答:
This task is called segmentation, in your case each color is a segment and segments are not always continuous.

Searching segmentation examples for Matlab should yield a lot of code examples and theorems.

Note one thing, there is no ground truth solution, you can't say how many segments there are for each image since it is subjective question. In a general case you can run clustering algorithm on the color values which will break the image to color segments, there are algorithms which will find the number of groups automatically - this can be a good start for the number of color groups in your image.

quick search yielded these works, they can get you started with ideas:

Image segmentation with matlab

Using EM for image segmentation


问:
How to reinject the packet in the Iptables?
I have a packet inside a packet a.k.a tunneling. So it's of the form [IP HEADER 1][IP HEADER 2][PAYLOAD]. After reading the first header(done by a library) I will get the packet with [ IP HEADER 2] at the INPUT chain of the iptables. I want to re-inject the packet to the starting of the iptables i.e. in the PREROUTING chain. Ultimate aim is to forward the packet to a remote host (that's why I want the packet to be in the PREROUTING chain). I have read something about the libipq but I am not really sure that it is the best way to do it. </p>

答:
Although there may be some add-on target to do this. My gut feeling is that you would use the MARK target to mark this packet then use iproute2 to set up the routing of where you want it to go.

Something like:

```<code>iptables -t mangle -A INPUT -s 192.168.1.2 -j MARK --set-mark 0xAA
</code>```

ip rule add fwmark 0xAA table Reroute_Tunnel

Then it's up to you to add and decide what the Reroute_Tunnel table does

Body:
Although there may be some add-on target to do this. My gut feeling is that you would use the MARK target to mark this packet then use iproute2 to set up the routing of where you want it to go.

Something like:

iptables -t mangle -A INPUT -s 192.168.1.2 -j MARK --set-mark 0xAA

ip rule add fwmark 0xAA table Reroute_Tunnel

Then it's up to you to add and decide what the Reroute_Tunnel table does