问:
Python: My program could print, but return None?
I have some problems when calling a function.

```<code>import random
board = []
solution=[]

def isConflict(x, y):

    for (i, j) in board:
        if x == i:
            return True
        if y == j:
            return True
        if abs(x - i) == abs(y - j):
            return True
    else:
        return False

def solve(x,y):
    for y in range(1, 9):
        if isConflict(x, y)==False:
            board.append((x, y))
            solve(x + 1,y)
            board.remove((x,y))
    if x > 8:
        solution.append(list(board))
        if len(solution)==92:
                return solution[random.randint(1,91)]

a=solve(1,1)
print(a)
</code>```

This will give a None. However if I change the last part into:

```<code>    if x > 8:
        solution.append(list(board))
        if len(solution)==92:
                print(solution[random.randint(1,91)])

solve(1,1)
</code>```

I could get the answer.
Therefore I couldn't do anything with the function because it always turns out to be a Nonetype and I want to use it in other functions. What shall I do? Many thanks!!

答:
solve will only ever return anything if x > 8. In Python, if your function ends because it hits the end of its execution (rather than from a return), then it will return None.

If you want to return something when x <= 8, you should add an else and put your return there.

Body:
I have some problems when calling a function.

import random
board = []
solution=[]

def isConflict(x, y):

    for (i, j) in board:
        if x == i:
            return True
        if y == j:
            return True
        if abs(x - i) == abs(y - j):
            return True
    else:
        return False

def solve(x,y):
    for y in range(1, 9):
        if isConflict(x, y)==False:
            board.append((x, y))
            solve(x + 1,y)
            board.remove((x,y))
    if x > 8:
        solution.append(list(board))
        if len(solution)==92:
                return solution[random.randint(1,91)]

a=solve(1,1)
print(a)

This will give a None. However if I change the last part into:

    if x > 8:
        solution.append(list(board))
        if len(solution)==92:
                print(solution[random.randint(1,91)])

solve(1,1)

I could get the answer.
Therefore I couldn't do anything with the function because it always turns out to be a Nonetype and I want to use it in other functions. What shall I do? Many thanks!!


来源: stackexchange

问:
How can I detect named entities that have more than 1 word using CoreNLP's RegexNER?
I am using the RegexNER annotator in CoreNLP and some of my named entities consist of multiple words. Excerpt from my mapping file:

RAF inhibitor       DRUG_CLASS

Gilbert's syndrome   DISEASE

The first one gets detected but each word gets the annotation DRUG_CLASS and there seems to be no way to link the words, like an NER id which both words would have.

The second case does not get detected at all and that's probably because the tokenizer treats the apostrophe after Gilbert as a separate token. Since RegexNER has the tokenization as a dependency, I can't really get around it.

Any suggestions to resolve these cases?

答:
If you use the entitymentions annotator that will create entity mentions out of consecutive tokens with the same ner tags.  There is the downside that if two entities of the same type are side by side they will be joined together.  We are working on improving the ner system so we may include a new model that finds the boundaries of distinct mentions in these cases, hopefully this will go into Stanford CoreNLP 3.8.0.

Here is some sample code for accessing the entity mentions:

```<code>package edu.stanford.nlp.examples;

import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.util.*;

import java.util.*;

public class EntityMentionsExample {

  public static void main(String[] args) {
    Annotation document =
        new Annotation("John Smith visted Los Angeles on Tuesday.");
    Properties props = new Properties();
    props.setProperty("annotators", "tokenize,ssplit,pos,lemma,ner,entitymentions");
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
    pipeline.annotate(document);

    for (CoreMap entityMention : document.get(CoreAnnotations.MentionsAnnotation.class)) {
      System.out.println(entityMention);
      System.out.println(entityMention.get(CoreAnnotations.TextAnnotation.class));
    }
  }
}
</code>```

If you just have your rules tokenized the same way as the tokenizer it will work fine, so for instance the rule should be Gilbert 's syndrome.

So you could just run the tokenizer on all your text patterns and this problem will go away.

ContentLicense: CC BY-SA 3.0

Body:
If you use the entitymentions annotator that will create entity mentions out of consecutive tokens with the same ner tags.  There is the downside that if two entities of the same type are side by side they will be joined together.  We are working on improving the ner system so we may include a new model that finds the boundaries of distinct mentions in these cases, hopefully this will go into Stanford CoreNLP 3.8.0.

Here is some sample code for accessing the entity mentions:

package edu.stanford.nlp.examples;

import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.util.*;

import java.util.*;

public class EntityMentionsExample {

  public static void main(String[] args) {
    Annotation document =
        new Annotation("John Smith visted Los Angeles on Tuesday.");
    Properties props = new Properties();
    props.setProperty("annotators", "tokenize,ssplit,pos,lemma,ner,entitymentions");
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
    pipeline.annotate(document);

    for (CoreMap entityMention : document.get(CoreAnnotations.MentionsAnnotation.class)) {
      System.out.println(entityMention);
      System.out.println(entityMention.get(CoreAnnotations.TextAnnotation.class));
    }
  }
}

If you just have your rules tokenized the same way as the tokenizer it will work fine, so for instance the rule should be Gilbert 's syndrome.

So you could just run the tokenizer on all your text patterns and this problem will go away.


问:
How to clean up a string excluding certain characters
I want to clean up the below string but only get rid of the \n, \r and extra spaces but not the apostrophe(') and other characters like dash(-) and colon(:).

Right now I am using this code but it gets rid of all special characters.

```<code>string = "\n\n\r\n            Scott Hibb's Amazing Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
rx = re.compile('\W+')
string = rx.sub(' ', string).strip()
print(string)
</code>```

How can i do this?

答:
The accepted answer is great but if you would like a slightly more general solution that allows you to specify the explicit set of characters that you still want to remove, add a lambda function to the filter, something like this.

```<code>>>> y = "\n\n\r\n       Scott Hibb's       Amazing    Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
>>> ' '.join(filter(lambda x: x not in ['\n', '\r'], y).strip().split())
"Scott Hibb's Amazing Whisky Grilled Baby Back Ribs"
</code>```

Please note that for your example, explicitly specifying the \n and \r in the lambda is overkill because strip() treats \n and \r as whitespace but if you wanted to remove other characters, then this a reasonable approach. For example this is how you would strip extra white space characters, remove the \n and \r, and remove all standard vowels (a, e, i, o, u).

```<code>>>> y = "\n\n\r\n       Scott Hibb's       Amazing    Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
>>> ' '.join(filter(lambda x: x.lower() not in ['a', 'e', 'i', 'o', 'u', '\r'], y).strip().split())
"Sctt Hbb's mzng Whsky Grlld Bby Bck Rbs"
</code>```

Body:
I want to clean up the below string but only get rid of the \n, \r and extra spaces but not the apostrophe(') and other characters like dash(-) and colon(:).

Right now I am using this code but it gets rid of all special characters.

string = "\n\n\r\n            Scott Hibb's Amazing Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
rx = re.compile('\W+')
string = rx.sub(' ', string).strip()
print(string)

How can i do this?

Body:
The accepted answer is great but if you would like a slightly more general solution that allows you to specify the explicit set of characters that you still want to remove, add a lambda function to the filter, something like this.

>>> y = "\n\n\r\n       Scott Hibb's       Amazing    Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
>>> ' '.join(filter(lambda x: x not in ['\n', '\r'], y).strip().split())
"Scott Hibb's Amazing Whisky Grilled Baby Back Ribs"

Please note that for your example, explicitly specifying the \n and \r in the lambda is overkill because strip() treats \n and \r as whitespace but if you wanted to remove other characters, then this a reasonable approach. For example this is how you would strip extra white space characters, remove the \n and \r, and remove all standard vowels (a, e, i, o, u).

>>> y = "\n\n\r\n       Scott Hibb's       Amazing    Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
>>> ' '.join(filter(lambda x: x.lower() not in ['a', 'e', 'i', 'o', 'u', '\r'], y).strip().split())
"Sctt Hbb's mzng Whsky Grlld Bby Bck Rbs"


问:
Simple delete query based on variable
I want to delete the record when the id column is equal to $id. Would this work?

```<code>$query = "DELETE FROM $TableName WHERE id=$id";
</code>```

As a side i also want to set the number of rows that can be deleted to a
limit of 1.  I know i have to use limit but i am unsure on its parameters

答:
You could do

```<code>mysqli_query = ($con, "DELETE FROM `$TableName` WHERE id='$id' LIMIT 1");
</code>```

That should do it exactly my friend

Title: Simple delete query based on variable

Body:
I want to delete the record when the id column is equal to $id. Would this work?

$query = "DELETE FROM $TableName WHERE id=$id";

As a side i also want to set the number of rows that can be deleted to a
limit of 1.  I know i have to use limit but i am unsure on its parameters

Body:
You could do

mysqli_query = ($con, "DELETE FROM `$TableName` WHERE id='$id' LIMIT 1");

That should do it exactly my friend


问:
I Want my Label to Vertically Align With my Input Field
Here is what my work is so far:

http://jsfiddle.net/2RCBQ/

```<code><div id="main">
<form>
    <label>First Name:<input type="text" id="firstname"></label><br/>
    <label>Last Name:<input type="text" id="lastname"></label><br>
    <label>E-Mail:<input type="text" id="email"></label><br/>
    <label>Phone:<input type="text" id="phone"></label><br/>
</form>
</div>
</code>```

CSS

#main {
    width:300px;

}

#main input {
    float:right;
    display:inline;
}

#main label {
    color: #2D2D2D;
    font-size: 15px;
    width:250px;
    display: block;
}
```

Currently, the label (on the left) is kind of towards to top of the input field (on the right). I want to vertically align them so the label since in the middle of the input field.

I've tried vertical-align and it does not work. Please help me try to figure out the problem. Thanks.

答:
I think that the following is the only method that works for all input types.

label { display: flex; align-items: center; }
input { margin: 0; padding: 0; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label><input type="checkbox">  HTML</label>
<label><input type="radio">  JS</label>
<label>CSS  <input type="text"></label>
<label>Framework
  <select><option selected>none</option></select>
</label></code>```

I put   because it seems to be the simplest way to align different input types; however, margins work just fine.

Body:
Here is what my work is so far:

http://jsfiddle.net/2RCBQ/

<form>
    First Name:<input type="text" id="firstname">

    Last Name:<input type="text" id="lastname">

    E-Mail:<input type="text" id="email">

    Phone:<input type="text" id="phone">

</form>

CSS

#main {
    width:300px;

}

#main input {
    float:right;
    display:inline;
}

#main label {
    color: #2D2D2D;
    font-size: 15px;
    width:250px;
    display: block;
}

Currently, the label (on the left) is kind of towards to top of the input field (on the right). I want to vertically align them so the label since in the middle of the input field.

I've tried vertical-align and it does not work. Please help me try to figure out the problem. Thanks.

Body:
I think that the following is the only method that works for all input types.

label { display: flex; align-items: center; }
input { margin: 0; padding: 0; }

<label><input type="checkbox">&nbsp; HTML</label>
<label><input type="radio">&nbsp; JS</label>
<label>CSS &nbsp;<input type="text"></label>
<label>Framework &nbsp;
  <select><option selected>none</option></select>
</label>

I put &nbsp; because it seems to be the simplest way to align different input types; however, margins work just fine.


问:
How can i show alphabets on the top of product table
```<code>public class Producttable {

public static void main(String[] args) {

    int tableSize = 4;

    printMultiplicationTable(tableSize);
}

public static void printMultiplicationTable(int tableSize) {

    // first print the top header row
    System.out.format("      ");

    for(int i = 1; i<=tableSize;i++ ) {

        System.out.format("%4d",i);
    }
    System.out.println();

    System.out.println("__________________________");

    for(int i = 1 ;i<=tableSize;i++) {
        // print left most column first

        System.out.format("%4d |",i);

        for(int j=1;j<=tableSize;j++) {
            System.out.format("%4d",i*j);
        }
        System.out.println();
    }
}
</code>```

Teacher gave us task to make a product table This is the product table that i am getting with this code
Everything is good here but instead of numbers on the top head of the table i want alphabets like (A B C D). can anybody help me please?

答:
A computer only knows how to work with numbers. When you work with letters, underneath, the computer is working with numbers. So it stands to reason that you can work with numbers and transform them into letters with the appropriate code.

Refresh your knowledge of the ASCII table, this is what the computer uses to convert numbers into characters.

You could write a loop that started at 65 and stopped at 90, and for each number you could print the character that it corresponds to in the ASCII table. See how I use the "%c" format for printf to format an integer as a character.

```<code>for(int i = 65; i <= 90; i++) {
    System.out.printf("%c", i);
}
</code>```

Output:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

Body:
public class Producttable {

public static void main(String[] args) {

    int tableSize = 4;

    printMultiplicationTable(tableSize);
}

public static void printMultiplicationTable(int tableSize) {

    // first print the top header row
    System.out.format("      ");

    for(int i = 1; i<=tableSize;i++ ) {

        System.out.format("%4d",i);
    }
    System.out.println();

    System.out.println("__________________________");

    for(int i = 1 ;i<=tableSize;i++) {
        // print left most column first

        System.out.format("%4d |",i);

        for(int j=1;j<=tableSize;j++) {
            System.out.format("%4d",i*j);
        }
        System.out.println();
    }
}

Teacher gave us task to make a product table This is the product table that i am getting with this code
Everything is good here but instead of numbers on the top head of the table i want alphabets like (A B C D). can anybody help me please?

Body:
A computer only knows how to work with numbers. When you work with letters, underneath, the computer is working with numbers. So it stands to reason that you can work with numbers and transform them into letters with the appropriate code.

Refresh your knowledge of the ASCII table, this is what the computer uses to convert numbers into characters.

You could write a loop that started at 65 and stopped at 90, and for each number you could print the character that it corresponds to in the ASCII table. See how I use the "%c" format for printf to format an integer as a character.

for(int i = 65; i <= 90; i++) {
    System.out.printf("%c", i);
}

Output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ


答:
Replace

System.out.format("%4d",i);

With

System.out.format("%4c", i + 'A' - 1);

Title: How can i show alphabets on the top of product table


问:
Wrapping container for containers providing diffrent interfaces
I want to create universal "wrapper" for stl containers, something like:

```<code>template<template <typename, typename...> class Container = std::vector >
class ContainerWrapper{
  add();
  size();
  find();
  resize();
  sort();
  /**/
}
</code>```

+iterators.
I would want member functions to have different implementations, depending on Container provided methods. Is C++ template system enough to create this? Is this even possible, using only standard (no boost, no messing with preprocessor)?

I know how to do it the hard way - write template specialization for each stl container. But I would want it to work with other containers too, and also i'm looking for more universal way to do it.

Also, what is better here? Inheriting from Container or having Container as component?

答:
Some time ago I've developed something similar for a project of mine.

I've extracted a full working example (the original code is more complex) to show how to use a method addVal() (that call push_back(), push(), insert() or push_front()) to add a value to the wrapped container.

This code works (if I remember correctly) for std::vector, std::set, std::multiset, std::unordered_set, std::unordered_multiset, std::deque, std::queue, std::priority_queue, std::forward_list and std::stack.

Other containers (as std::array, by example) may requires different specializations for cntWrp.

I don't want explaint every single line of code but, if you have questions, I can try to respond (or, if you prefer, I can give you the link of my github project).

The example

```<code>#include <set>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <type_traits>

class emptyClass
 { };

template <typename ... Ts>
struct funcType;

template <typename T, typename ... Ts>
struct funcType<T, Ts...>
 { using type
      = typename std::conditional<T::result,
         typename T::type, typename funcType<Ts...>::type>::type; };

template <>
struct funcType<>
 { using type = emptyClass; };

#define methodCheck_1(meth)                            \
                                                       \
   class helpMeth_1_##meth {};                         \
                                                       \
   template <typename T, typename A>                   \
   struct isWithMethod_1_##meth                        \
    {                                                  \
      template<typename U>                             \
      static decltype(U().meth(A())) func (U*);        \
                                                       \
      template<typename U>                             \
      static emptyClass func (...);                    \
                                                       \
      static const bool result                         \
         = ! std::is_same<emptyClass,                  \
                decltype(func<T>(nullptr))>::value;    \
                                                       \
      using  type = helpMeth_1_##meth;                 \
    }

methodCheck_1(insert);
methodCheck_1(push);
methodCheck_1(push_back);
methodCheck_1(push_front);

template <typename>
class cntWrp;

template <template <typename ...> class C, typename X, typename ... Xs>
class cntWrp< C<X, Xs...> >
 {
   private:

      using addModeType = typename funcType<
         isWithMethod_1_push_back<C<X, Xs...>, X>,
         isWithMethod_1_insert<C<X, Xs...>, X>,
         isWithMethod_1_push<C<X, Xs...>, X>,
         isWithMethod_1_push_front<C<X, Xs...>, X>>::type;

      static constexpr addModeType  addMode {};

      void addVal (X const & x, helpMeth_1_push_back const)
       { val.push_back(x); }

      void addVal (X const & x, helpMeth_1_push const)
       { val.push(x); }

      void addVal (X const & x, helpMeth_1_insert const)
       { val.insert(x); }

      void addVal (X const & x, helpMeth_1_push_front const)
       { val.push_front(x); }

      void addVal (X const & x, emptyClass const)
       { throw std::runtime_error("cntWr<>::addVal without mode"); }

   public:

      C<X, Xs...> val {};

      cntWrp ()
       { }

      cntWrp (C<X, Xs...> const & v0) : val { v0 }
       { }

      void addVal (X const & x)
       { addVal(x, addMode); }
 };

int main ()
 {
   cntWrp<std::set<int>>  csi;

   csi.addVal(2);
   csi.addVal(7);
   csi.addVal(5);

   std::cout << "set:" << std::endl;

   for ( auto const elem : csi.val )
      std::cout << elem << std::endl;

   cntWrp<std::vector<int>> cvi;

   cvi.addVal(2);
   cvi.addVal(7);
   cvi.addVal(5);

   std::cout << "vector:" << std::endl;

   for ( auto const elem : cvi.val )
      std::cout << elem << std::endl;
 }
</code>```

Body:
I want to create universal "wrapper" for stl containers, something like:

template<template <typename, typename...> class Container = std::vector >
class ContainerWrapper{
  add();
  size();
  find();
  resize();
  sort();
  /**/
}

+iterators.
I would want member functions to have different implementations, depending on Container provided methods. Is C++ template system enough to create this? Is this even possible, using only standard (no boost, no messing with preprocessor)?

I know how to do it the hard way - write template specialization for each stl container. But I would want it to work with other containers too, and also i'm looking for more universal way to do it.

Also, what is better here? Inheriting from Container or having Container as component?

Body:
Some time ago I've developed something similar for a project of mine.

I've extracted a full working example (the original code is more complex) to show how to use a method addVal() (that call push_back(), push(), insert() or push_front()) to add a value to the wrapped container.

This code works (if I remember correctly) for std::vector, std::set, std::multiset, std::unordered_set, std::unordered_multiset, std::deque, std::queue, std::priority_queue, std::forward_list and std::stack.

Other containers (as std::array, by example) may requires different specializations for cntWrp.

I don't want explaint every single line of code but, if you have questions, I can try to respond (or, if you prefer, I can give you the link of my github project).

The example

#include <set>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <type_traits>

class emptyClass
 { };

template <typename ... Ts>
struct funcType;

template <typename T, typename ... Ts>
struct funcType<T, Ts...>
 { using type
      = typename std::conditional<T::result,
         typename T::type, typename funcType<Ts...>::type>::type; };

template <>
struct funcType<>
 { using type = emptyClass; };

#define methodCheck_1(meth)                            \
                                                       \
   class helpMeth_1_##meth {};                         \
                                                       \
   template <typename T, typename A>                   \
   struct isWithMethod_1_##meth                        \
    {                                                  \
      template<typename U>                             \
      static decltype(U().meth(A())) func (U*);        \
                                                       \
      template<typename U>                             \
      static emptyClass func (...);                    \
                                                       \
      static const bool result                         \
         = ! std::is_same<emptyClass,                  \
                decltype(func<T>(nullptr))>::value;    \
                                                       \
      using  type = helpMeth_1_##meth;                 \
    }

methodCheck_1(insert);
methodCheck_1(push);
methodCheck_1(push_back);
methodCheck_1(push_front);

template <typename>
class cntWrp;

template <template <typename ...> class C, typename X, typename ... Xs>
class cntWrp< C<X, Xs...> >
 {
   private:

      using addModeType = typename funcType<
         isWithMethod_1_push_back<C<X, Xs...>, X>,
         isWithMethod_1_insert<C<X, Xs...>, X>,
         isWithMethod_1_push<C<X, Xs...>, X>,
         isWithMethod_1_push_front<C<X, Xs...>, X>>::type;

      static constexpr addModeType  addMode {};

      void addVal (X const & x, helpMeth_1_push_back const)
       { val.push_back(x); }

      void addVal (X const & x, helpMeth_1_push const)
       { val.push(x); }

      void addVal (X const & x, helpMeth_1_insert const)
       { val.insert(x); }

      void addVal (X const & x, helpMeth_1_push_front const)
       { val.push_front(x); }

      void addVal (X const & x, emptyClass const)
       { throw std::runtime_error("cntWr<>::addVal without mode"); }

   public:

      C<X, Xs...> val {};

      cntWrp ()
       { }

      cntWrp (C<X, Xs...> const & v0) : val { v0 }
       { }

      void addVal (X const & x)
       { addVal(x, addMode); }
 };

int main ()
 {
   cntWrp<std::set<int>>  csi;

   csi.addVal(2);
   csi.addVal(7);
   csi.addVal(5);

   std::cout << "set:" << std::endl;

   for ( auto const elem : csi.val )
      std::cout << elem << std::endl;

   cntWrp<std::vector<int>> cvi;

   cvi.addVal(2);
   cvi.addVal(7);
   cvi.addVal(5);

   std::cout << "vector:" << std::endl;

   for ( auto const elem : cvi.val )
      std::cout << elem << std::endl;
 }


问:
Angular, broadcast not working
my aim is to send some data from an angular controller to another.

Here is the controller who has to send the datas :

```<code>myApp.controller('MapCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.loadData = function () {
        $http.get('/map/GetListDB').success(function (data, status, headers, config) {

            //Logic here is working fine, it creates a table named "ExcelCols" which is a table of strings

            $scope.$broadcast("SET_EXCEL_TITLES", $scope.ExcelCols);
        })
    }

}]);
</code>```

Here is the second controller

```<code>myApp.controller('ExcelViewCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.$on("SET_EXCEL_TITLES", function (event, excelCols) {

        //this event is never fired

        $scope.ExcelCols = excelCols;
    });
}]);
</code>```

My view is designed that way :

```<code> <body ng-app="myApp">
    <div ng-controller="MapCtrl">
         //everything OK here
    </div>

    <div ng-controller="ExcelViewCtrl">
      <table>
        <thead>
            <tr>
                <th ng-repeat="col in ExcelCols">{{col}}</th>
            </tr>
        </thead>
       </table>
    </div>

 </body>
</code>```

答:
Another option is to use $rootScope to list to event and local $scope to emit it. I have created this plnkr to test it http://plnkr.co/edit/LJECQZ?p=info

var app = angular.module('plunker', []);

app.controller('Ctl1', function($scope, $rootScope) {
  $scope.name = 'World';
  $rootScope.$on('changeValueInCtl1', function(event, value) {
    $scope.name = 'New Value from Ctl2 is: ' + value;
  });
});

app.controller('Ctl2', function($scope) {
  $scope.changeValue = function() {
    $scope.$emit('changeValueInCtl1', 'Control 2 value');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body>
  <div ng-controller="Ctl1">
    <p>Hello {{name}}!</p>
  </div>

  <div ng-controller="Ctl2">
    <button ng-click="changeValue()">Change Value</button>
  </div>

</body>

</html></code>```

The only downside is the $rootScope will be listening and one has to explicitly call $destroy to it.

Title: Angular, broadcast not working

Body:
my aim is to send some data from an angular controller to another.

Here is the controller who has to send the datas :

myApp.controller('MapCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.loadData = function () {
        $http.get('/map/GetListDB').success(function (data, status, headers, config) {

            //Logic here is working fine, it creates a table named "ExcelCols" which is a table of strings

            $scope.$broadcast("SET_EXCEL_TITLES", $scope.ExcelCols);
        })
    }

}]);

Here is the second controller

myApp.controller('ExcelViewCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.$on("SET_EXCEL_TITLES", function (event, excelCols) {

        //this event is never fired

        $scope.ExcelCols = excelCols;
    });
}]);

My view is designed that way :

         //everything OK here

                {{col}}

Body:
Another option is to use $rootScope to list to event and local $scope to emit it. I have created this plnkr to test it http://plnkr.co/edit/LJECQZ?p=info

var app = angular.module('plunker', []);

app.controller('Ctl1', function($scope, $rootScope) {
  $scope.name = 'World';
  $rootScope.$on('changeValueInCtl1', function(event, value) {
    $scope.name = 'New Value from Ctl2 is: ' + value;
  });
});

app.controller('Ctl2', function($scope) {
  $scope.changeValue = function() {
    $scope.$emit('changeValueInCtl1', 'Control 2 value');
  }
});

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body>
  <div ng-controller="Ctl1">
    <p>Hello {{name}}!</p>
  </div>

  <div ng-controller="Ctl2">
    <button ng-click="changeValue()">Change Value</button>
  </div>

</body>

</html>

The only downside is the $rootScope will be listening and one has to explicitly call $destroy to it.


问:
CPU ordering in Linux (with hyper threading)
I'm curious what the CPU ordering is in Linux.  Say I bind a thread to cpu0 and another to cpu1 on a hyperthreaded system, are they both going to be on the same physical core.  Given a Core i7 920 with 4 cores and hyperthreading, the output of /proc/cpuinfo has me thinking that cpu0 and cpu1 are different physical cores, and cpu0 and cpu4 are on the same physical core.

Thanks.

答: You can use likwid-topology -g to get graphical topology of the cpu. It shows each cpu primary cores along with the sibling core.

ContentLicense: CC BY-SA 2.5


问:
How to convert hexstring to (hex)byte
I got a hexstring like "0xFF" and would like to convert the string to byte 0xFF, because an other function needs the value as hexbyte. So something like this:

```<code>         String hexstring="0xFF";
         //convert to byte
         byte hexbyte = (byte) 0xFF;
</code>```

Thanks for helping

答: (byte) (Integer.parseInt("ef",16) & 0xff);will work for you

Title: How to convert hexstring to (hex)byte

Body:
I got a hexstring like "0xFF" and would like to convert the string to byte 0xFF, because an other function needs the value as hexbyte. So something like this:

         String hexstring="0xFF";
         //convert to byte
         byte hexbyte = (byte) 0xFF;

Thanks for helping


问:
Confused, Why c++ global variable was not declared in this scope
I am new to C++. I am trying to modify a very complex video codec code as part of my final year school project. I have already asked it on another thread but got no help. This is my code:

This is the header file in which I have declared three extern variables:

yuv.h

```<code>#include <vector>
namespace X265_NS
{
extern int frameNumber;
extern int frameSize;
extern std::vector<int>numbers;

class YUVInput : public InputFile, public Thread
{
protected:

// some more variables

public:

// more variables and function declarations

};
}
</code>```

This is the first file that uses these extern variables:

yuv.cpp

```<code>#include "yuv.h"
//more includes
#include <vector>

namespace X265_NS {
    int frameNumber;
    int frameSize;
    std::vector<int>numbers;
}

using namespace X265_NS;

// some stuff and function calls
// here I use my extern variables in a function

frameNumber = readCount.get();
frameSize = ceil((double)height / 32) * ceil((double)width / 32);

//more stuff

bool YUVInput::populateFrameQueue()
{
   if(read<1)
             {
                  ifstream file("/home/abu-bakr/bin/test.txt");
                  int number;
                  while (file >> number)
                           numbers.push_back(number);
             }
}

// more stuff
</code>```

This is the second class where I am using these extern variables:

analysis.cpp

```<code>#include "yuv.h"
#include <vector>
....
using namespace X265_NS;

// some stuff

// its in a function and only place where I am using these variables
int qp_ctu = numbers.at((ctu.m_cuAddr + 1) + (frameSize*(frameNumber - 1)));

// more stuff
</code>```

This is the error I am getting that is making me really confused:

```<code>analysis.cpp
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(170): warning C4244: '=' : conversion from 'int' to 'int8_t', possible loss of data
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'numbers' : undeclared identifier
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2228: left of '.at' must have class/struct/union
1>          type is ''unknown-type''
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'frameSize' : undeclared identifier
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'frameNumber' : undeclared identifier

yuv.cpp
2>C:\x265_2.2\x265_2.2\source\input\yuv.cpp(219): warning C4244: '=' : conversion from 'double' to 'int', possible loss of data
2>x265-static.lib(analysis.obj) : error LNK2005: "int x265::frameNumber" (?frameNumber@x265@@3HA) already defined in yuv.cpp.obj
2>x265-static.lib(analysis.obj) : error LNK2005: "int x265::frameSize" (?frameSize@x265@@3HA) already defined in yuv.cpp.obj
2>     Creating library C:/x265_2.2/x265_2.2/build/vc10-x86/Debug/x265.lib and object C:/x265_2.2/x265_2.2/build/vc10-x86/Debug/x265.exp
2>C:\x265_2.2\x265_2.2\build\vc10-x86\Debug\x265.exe : fatal error LNK1169: one or more multiply defined symbols found
</code>```

答: You might be including a wrong file. Most likely there's another yuv.h file in some library source code which gets included in analysis.cpp instead of the one you need. You can quickly check this by adding some erroneous code into your yuv.h and trying to compile analysis.cpp.

Body:
I am new to C++. I am trying to modify a very complex video codec code as part of my final year school project. I have already asked it on another thread but got no help. This is my code:

This is the header file in which I have declared three extern variables:

yuv.h

#include <vector>
namespace X265_NS
{
extern int frameNumber;
extern int frameSize;
extern std::vector<int>numbers;

class YUVInput : public InputFile, public Thread
{
protected:

// some more variables

public:

// more variables and function declarations

};
}

This is the first file that uses these extern variables:

yuv.cpp

#include "yuv.h"
//more includes
#include <vector>

namespace X265_NS {
    int frameNumber;
    int frameSize;
    std::vector<int>numbers;
}

using namespace X265_NS;

// some stuff and function calls
// here I use my extern variables in a function

frameNumber = readCount.get();
frameSize = ceil((double)height / 32) * ceil((double)width / 32);

//more stuff

bool YUVInput::populateFrameQueue()
{
   if(read<1)
             {
                  ifstream file("/home/abu-bakr/bin/test.txt");
                  int number;
                  while (file >> number)
                           numbers.push_back(number);
             }
}

// more stuff

This is the second class where I am using these extern variables:

analysis.cpp

#include "yuv.h"
#include <vector>
....
using namespace X265_NS;

// some stuff

// its in a function and only place where I am using these variables
int qp_ctu = numbers.at((ctu.m_cuAddr + 1) + (frameSize*(frameNumber - 1)));

// more stuff

This is the error I am getting that is making me really confused:

analysis.cpp
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(170): warning C4244: '=' : conversion from 'int' to 'int8_t', possible loss of data
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'numbers' : undeclared identifier
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2228: left of '.at' must have class/struct/union
1>          type is ''unknown-type''
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'frameSize' : undeclared identifier
1>C:\x265_2.2\x265_2.2\source\encoder\analysis.cpp(2814): error C2065: 'frameNumber' : undeclared identifier

yuv.cpp
2>C:\x265_2.2\x265_2.2\source\input\yuv.cpp(219): warning C4244: '=' : conversion from 'double' to 'int', possible loss of data
2>x265-static.lib(analysis.obj) : error LNK2005: "int x265::frameNumber" (?frameNumber@x265@@3HA) already defined in yuv.cpp.obj
2>x265-static.lib(analysis.obj) : error LNK2005: "int x265::frameSize" (?frameSize@x265@@3HA) already defined in yuv.cpp.obj
2>     Creating library C:/x265_2.2/x265_2.2/build/vc10-x86/Debug/x265.lib and object C:/x265_2.2/x265_2.2/build/vc10-x86/Debug/x265.exp
2>C:\x265_2.2\x265_2.2\build\vc10-x86\Debug\x265.exe : fatal error LNK1169: one or more multiply defined symbols found


问:
Make div width vary with jQuery
I have a div in which I generate content every half a second via the following function:

```<code>function ClockAndCalendar() {
  var da = new Date();
  var hours = da.getHours();
  var minutes = da.getMinutes();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var actualTime = hours + ':' + minutes + ampm;
  var wd = weekday[da.getDay()];
  var month = mon[da.getMonth()];
  var curDate = da.getDate();
  var suffix = ending[da.getDate() - 1];
  var timeAndDate = (actualTime + " " + wd + ", " + month + " " + curDate + suffix + ", " + y);
  var newDiv = $('#date-and-time').text(timeAndDate);

  return newDiv;
}
var getTimeDateCalendar = setInterval(ClockAndCalendar, 500);
</code>```

The div #date-and-time is nested in the following div like so:

10:06PM Wednesday, March 29th, 2017

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

<p>with <code>#calDateTimeBox</code> and <code>#clock-link</code> having CSS:</p>

```#calDateTimeBox {
  position: absolute;
  top: 40px;
  margin-left: -357px;
  width: 340px;
  height: auto;
  font-family: 'Many Secrets';
  font-size: 20px;
  letter-spacing: 1px;
  line-height: 1.2;
  color: #FFF;
  background: rgba(0, 0, 0, 0.75);
  text-shadow: 4px 4px 1px #000;
  border-radius: 5px;
  text-align: center;
  padding: 10px 20px;
  pointer-events: none;
  opacity: 0;
}

#clock-link {
  font-family:'FontAwesome';
  float: left;
  margin-right: 10px;
  margin-left: 5px;
}
```

When the times and dates are on the longer side, the div looks like so:

But I want it to look like this:

Is it possible, using jQuery, to get the div to adjust when the content overflows to a second line? If so, how would I achieve that effect?

答:
Change

```<code>#calDateTimeBox {
   width: 340px;
}
</code>```

to:

```<code>#calDateTimeBox {
   min-width: 340px;
}
</code>```

And problem seems solved. This would still make the date go to the other line if the parent container isn't wide enough to accommodate it.

You can also add:

```<code>#date-and-time {
   white-space: nowrap;
}
</code>```

But I wouldn't recommend that because your text will be cut off / show outside of the div container.

Title: Make div width vary with jQuery

Body:
I have a div in which I generate content every half a second via the following function:

function ClockAndCalendar() {
  var da = new Date();
  var hours = da.getHours();
  var minutes = da.getMinutes();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var actualTime = hours + ':' + minutes + ampm;
  var wd = weekday[da.getDay()];
  var month = mon[da.getMonth()];
  var curDate = da.getDate();
  var suffix = ending[da.getDate() - 1];
  var timeAndDate = (actualTime + " " + wd + ", " + month + " " + curDate + suffix + ", " + y);
  var newDiv = $('#date-and-time').text(timeAndDate);

  return newDiv;
}
var getTimeDateCalendar = setInterval(ClockAndCalendar, 500);

The div #date-and-time is nested in the following div like so:

10:06PM Wednesday, March 29th, 2017

with #calDateTimeBox and #clock-link having CSS:

#calDateTimeBox {
  position: absolute;
  top: 40px;
  margin-left: -357px;
  width: 340px;
  height: auto;
  font-family: 'Many Secrets';
  font-size: 20px;
  letter-spacing: 1px;
  line-height: 1.2;
  color: #FFF;
  background: rgba(0, 0, 0, 0.75);
  text-shadow: 4px 4px 1px #000;
  border-radius: 5px;
  text-align: center;
  padding: 10px 20px;
  pointer-events: none;
  opacity: 0;
}

#clock-link {
  font-family:'FontAwesome';
  float: left;
  margin-right: 10px;
  margin-left: 5px;
}

When the times and dates are on the longer side, the div looks like so:

But I want it to look like this:

Is it possible, using jQuery, to get the div to adjust when the content overflows to a second line? If so, how would I achieve that effect?

Body:
Change

#calDateTimeBox {
   width: 340px;
}

to:

#calDateTimeBox {
   min-width: 340px;
}

And problem seems solved. This would still make the date go to the other line if the parent container isn't wide enough to accommodate it.

You can also add:

#date-and-time {
   white-space: nowrap;
}

But I wouldn't recommend that because your text will be cut off / show outside of the div container.


问:
Is there a more concise way to combine many comparisons in Ruby?
I currently have this if statement:

```<code>if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0
</code>```

Is there a more concise way to do this?

答:
The standard Ruby Time library is pretty spare, so I would simply add my own method to make this easier:

```<code>class Time
  def beginning_of_month
    Time.local(self.year, self.month, 1)
  end

  def beginning_of_month?
    self == beginning_of_month
  end
end
</code>```

so you could then write:

```<code>if Time.now.beginning_of_month?
</code>```

Body:
I currently have this if statement:

if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0

Is there a more concise way to do this?

Body:
The standard Ruby Time library is pretty spare, so I would simply add my own method to make this easier:

class Time
  def beginning_of_month
    Time.local(self.year, self.month, 1)
  end

  def beginning_of_month?
    self == beginning_of_month
  end
end

so you could then write:

if Time.now.beginning_of_month?


问:
how can i capture image gallery's without a range
i have already this code

but for this it makes a pattern like image[1-10].jpg
but what i want is to fetch the gallley like this above but also like domain.com/gallery/
what do i get to chance to get this working.

hope someone can tel me the tric.

```<code>$parts = preg_split("/\[\d+-\d+\]/", $url, -1, PREG_SPLIT_DELIM_CAPTURE);
preg_match_all("/\[\d+-\d+\]/", $url, $matches, PREG_PATTERN_ORDER);
$parts_number = count($parts);
$matches_number = count($matches[0]);
// JYM
if ($parts_number==1) {

    $image_alt_url=$url;
    $url = str_replace("[", '', $url);
    $url = str_replace("]", '', $url);

    $alto = str_replace("/", '_', $image_alt_url);
    $alto = str_replace("www", '', $alto);
    $alto = str_replace("http", '', $alto);
    $alto = str_replace("https", '', $alto);
    $alto = str_replace("jpg", '', $alto);
    $alto = str_replace("com", '', $alto);
    $alto = str_replace("net", '', $alto);
    $alto = str_replace("info", '', $alto);
    $alto = str_replace(".com.np", '', $alto);
    $alto = str_replace("org", '', $alto);
    $alto = str_replace(".", '', $alto);
    $alto = str_replace(":_", '', $alto);
    $alto = str_replace("-", '_', $alto);
    $alto = preg_replace("/[^a-z-_]/",'',$alto);
    $alto = str_replace("__", '_', $alto);
    $alto = str_replace("___", '_', $alto);
    $alto = str_replace("_", '-', $alto);
    $alto=substr($alto, 1, -1);

    $ary_header = get_headers($url, 1);
    $filesize = $ary_header['Content-Length'];
</code>```

答:
Since your question doesn't provide any sample inputs, and no expected result, I am forced to make several assumptions:

```<code>$url="https://www.example.com/gallery/image3.jpg, example.com/gallery/image9.jpg, http://example.com/gallery/image14.JPG";
if(!preg_match_all("/([^, ]*\/)([^,]*?(\d+).jpg)/i",$url,$matches,PREG_SET_ORDER)){
    echo "No Matches Found";
}
foreach($matches as $match){
    list($fullstring,$path,$filename,$id)=$match;
    echo "<div>fullstring=$fullstring</div>";
    echo "<div>path=$path</div>";
    echo "<div>filename=$filename</div>";
    echo "<div>id=$id</div><br>";

    // ...now do any necessary substring processing.
}
</code>```

output:

```<code>fullstring=https://www.example.com/gallery/image3.jpg
path=https://www.example.com/gallery/
filename=image3.jpg
id=3

fullstring=example.com/gallery/image9.jpg
path=example.com/gallery/
filename=image9.jpg
id=9

fullstring=http://example.com/gallery/image14.JPG
path=http://example.com/gallery/
filename=image14.JPG
id=14
</code>```

By isolating the parts of the string that you wish to keep, you can reduce the str_replace()/preg_replace workload.

Body:
i have already this code

but for this it makes a pattern like image[1-10].jpg
but what i want is to fetch the gallley like this above but also like domain.com/gallery/
what do i get to chance to get this working.

hope someone can tel me the tric.

$parts = preg_split("/\[\d+-\d+\]/", $url, -1, PREG_SPLIT_DELIM_CAPTURE);
preg_match_all("/\[\d+-\d+\]/", $url, $matches, PREG_PATTERN_ORDER);
$parts_number = count($parts);
$matches_number = count($matches[0]);
// JYM
if ($parts_number==1) {

    $image_alt_url=$url;
    $url = str_replace("[", '', $url);
    $url = str_replace("]", '', $url);

    $alto = str_replace("/", '_', $image_alt_url);
    $alto = str_replace("www", '', $alto);
    $alto = str_replace("http", '', $alto);
    $alto = str_replace("https", '', $alto);
    $alto = str_replace("jpg", '', $alto);
    $alto = str_replace("com", '', $alto);
    $alto = str_replace("net", '', $alto);
    $alto = str_replace("info", '', $alto);
    $alto = str_replace(".com.np", '', $alto);
    $alto = str_replace("org", '', $alto);
    $alto = str_replace(".", '', $alto);
    $alto = str_replace(":_", '', $alto);
    $alto = str_replace("-", '_', $alto);
    $alto = preg_replace("/[^a-z-_]/",'',$alto);
    $alto = str_replace("__", '_', $alto);
    $alto = str_replace("___", '_', $alto);
    $alto = str_replace("_", '-', $alto);
    $alto=substr($alto, 1, -1);

    $ary_header = get_headers($url, 1);
    $filesize = $ary_header['Content-Length'];

Body:
Since your question doesn't provide any sample inputs, and no expected result, I am forced to make several assumptions:

$url="https://www.example.com/gallery/image3.jpg, example.com/gallery/image9.jpg, http://example.com/gallery/image14.JPG";
if(!preg_match_all("/([^, ]*\/)([^,]*?(\d+).jpg)/i",$url,$matches,PREG_SET_ORDER)){
    echo "No Matches Found";
}
foreach($matches as $match){
    list($fullstring,$path,$filename,$id)=$match;
    echo "<div>fullstring=$fullstring</div>";
    echo "<div>path=$path</div>";
    echo "<div>filename=$filename</div>";
    echo "<div>id=$id</div><br>";

    // ...now do any necessary substring processing.
}

output:

fullstring=https://www.example.com/gallery/image3.jpg
path=https://www.example.com/gallery/
filename=image3.jpg
id=3

fullstring=example.com/gallery/image9.jpg
path=example.com/gallery/
filename=image9.jpg
id=9

fullstring=http://example.com/gallery/image14.JPG
path=http://example.com/gallery/
filename=image14.JPG
id=14

By isolating the parts of the string that you wish to keep, you can reduce the str_replace()/preg_replace workload.


问:
How to get the right date with SUtime?
I have a Strings like this one for example:
" I will meet you on Jun 12 and give you your 1500 "

The result i got is 2 dates BUT I ONLY NEED THE JUN 12:

JUN 12 [from char offset 14 to 20] --> 2017-06-12

1500 [from char offset 40 to 44] --> 1500-XX-XX

Also if there wasn't a space between Jun and 12 (Jun12), SUtime doesn't get the date
How can i proceed?

答: Unfortunately you have found some of the errors that SUTime will produce.  I'll note both of these issues, but I am not sure there is a quick fix to address them.</p>

Title: How to get the right date with SUtime?


问:
How to maintain state of a control inside a gridview which has paging enabled?
I have a gridview of 4 columns including a column as Approve. Approve is having a checkbox which will repeat for all the rows of the dataset after binding. I have made allowpaging = true & pageindexsize to be 10. Now, suppose i check checkbox of row 2 and 5, and move to page 2, and come back to page 1, the checkboxes that i checked(of row 2 and 5) on page 1 is getting reset to unchecked state. I know the reason, that it is due to the binding of the gridview that we do on onpageindexchanging event. But is there any way to maintain the state of  checkbox even if we move from 1 page to another.

Thanks

答:
I tried the PreRender techniques from @Chuck, but it didn't work for me (VS2005, ASP.net2, SQLsrv2005). Maybe too old technology, but it's what the client has.

So I tried the simple myaspsnippets technique, and with some modifications it works perfectly!

My Gridview

```<code>                <asp:GridView ID="gvFTUNSENT" runat="server"
                    AutoGenerateColumns="False" CellPadding="4" ForeColor="Black" AllowSorting="False" CssClass="gvCSS" Width="100%"
                    DataKeyNames="StudentID,StudentUnitID" DataSourceID="sdsFTUNSENT"
                    GridLines="None" AllowPaging="True" PageSize="10" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
                    OnPageIndexChanged="GridView_PageIndexChanged"
                    OnPageIndexChanging="GridView_PageIndexChanging">
                    <RowStyle Wrap="True" Height="48px" />
                    <Columns>
...etc...
                    </Columns>
                    <FooterStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Height="100%" />
                    <PagerStyle CssClass="cssPager" BackColor="#6B696B" ForeColor="White" HorizontalAlign="Left" Height="100%" />
                    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
                </asp:GridView>
</code>```

The Pageing methods I used are:

```<code>protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView gv = (GridView)sender;

    //saves a "copy" of the page before it's changed over to the next one
    SavePageState(gv);

    gv.PageIndex = e.NewPageIndex;
    gv.DataBind();
}
</code>```

and

```<code>    protected void GridView_PageIndexChanged(object sender, EventArgs e)
    {
...your code to handle anything after the page has changed

                    gv.DataSource = dt;
                    gv.DataSourceID = null;
                    gv.DataBind();

                    //reload any checkboxes that were session saved in the page
                    LoadPageState(gv);
                }
            }
        }
    }
</code>```

So the SAVE and LOAD methods are as follows:

```<code>private void SavePageState(GridView gv)
{
    ArrayList categoryIDList = new ArrayList();
    Int32 index = -1;
    foreach (GridViewRow row in gv.Rows)
    {
        HiddenField hfStudentUnitID = (HiddenField)row.FindControl("hfStudentUnitID");
        if (hfStudentUnitID != null)
        {
            if (hfStudentUnitID.Value.Length > 0)
            {
                index = Convert.ToInt32(hfStudentUnitID.Value.ToString()); //gv.DataKeys[row.RowIndex]["StudentUnitID"];
                bool result = ((CheckBox)row.FindControl("cbSEND")).Checked;

                // Check in the Session
                if (Session["CHECKED_ITEMS"] != null)
                    categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
                if (result)
                {
                    if (!categoryIDList.Contains(index))
                        categoryIDList.Add(index);
                }
                else
                    categoryIDList.Remove(index);
            }
        }
    }
    if (categoryIDList != null && categoryIDList.Count > 0)
        Session["CHECKED_ITEMS"] = categoryIDList;
}
</code>```

AND

```<code>private void LoadPageState(GridView gv)
{
    ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
    if (categoryIDList != null && categoryIDList.Count > 0)
    {
        foreach (GridViewRow row in gv.Rows)
        {
            HiddenField hfStudentUnitID = (HiddenField)row.FindControl("hfStudentUnitID");
            if (hfStudentUnitID != null)
            {
                if (hfStudentUnitID.Value.Length > 0)
                {
                    Int32 index = Convert.ToInt32(hfStudentUnitID.Value.ToString()); //gv.DataKeys[row.RowIndex]["StudentUnitID"];
                    if (categoryIDList.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)row.FindControl("cbSEND");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }
    }
}
</code>```

To make this work for you, you'll need to place the Paging method calls into your GridView, change the CheckBox ID from cbSEND to what ever you're using, and point the HiddenFields to some other control or value that has a unique identifier for your rows. Don't use RowIndex, as that is not unique throughout the length of the data in your GridView.

Works like a charm!

Body:
I tried the PreRender techniques from @Chuck, but it didn't work for me (VS2005, ASP.net2, SQLsrv2005). Maybe too old technology, but it's what the client has.

So I tried the simple myaspsnippets technique, and with some modifications it works perfectly!

My Gridview

                <asp:GridView ID="gvFTUNSENT" runat="server"
                    AutoGenerateColumns="False" CellPadding="4" ForeColor="Black" AllowSorting="False" CssClass="gvCSS" Width="100%"
                    DataKeyNames="StudentID,StudentUnitID" DataSourceID="sdsFTUNSENT"
                    GridLines="None" AllowPaging="True" PageSize="10" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
                    OnPageIndexChanged="GridView_PageIndexChanged"
                    OnPageIndexChanging="GridView_PageIndexChanging">
                    <RowStyle Wrap="True" Height="48px" />
                    <Columns>
...etc...
                    </Columns>
                    <FooterStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Height="100%" />
                    <PagerStyle CssClass="cssPager" BackColor="#6B696B" ForeColor="White" HorizontalAlign="Left" Height="100%" />
                    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
                </asp:GridView>

The Pageing methods I used are:

protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView gv = (GridView)sender;

    //saves a "copy" of the page before it's changed over to the next one
    SavePageState(gv);

    gv.PageIndex = e.NewPageIndex;
    gv.DataBind();
}

and

    protected void GridView_PageIndexChanged(object sender, EventArgs e)
    {
...your code to handle anything after the page has changed

                    gv.DataSource = dt;
                    gv.DataSourceID = null;
                    gv.DataBind();

                    //reload any checkboxes that were session saved in the page
                    LoadPageState(gv);
                }
            }
        }
    }

So the SAVE and LOAD methods are as follows:

private void SavePageState(GridView gv)
{
    ArrayList categoryIDList = new ArrayList();
    Int32 index = -1;
    foreach (GridViewRow row in gv.Rows)
    {
        HiddenField hfStudentUnitID = (HiddenField)row.FindControl("hfStudentUnitID");
        if (hfStudentUnitID != null)
        {
            if (hfStudentUnitID.Value.Length > 0)
            {
                index = Convert.ToInt32(hfStudentUnitID.Value.ToString()); //gv.DataKeys[row.RowIndex]["StudentUnitID"];
                bool result = ((CheckBox)row.FindControl("cbSEND")).Checked;

                // Check in the Session
                if (Session["CHECKED_ITEMS"] != null)
                    categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
                if (result)
                {
                    if (!categoryIDList.Contains(index))
                        categoryIDList.Add(index);
                }
                else
                    categoryIDList.Remove(index);
            }
        }
    }
    if (categoryIDList != null && categoryIDList.Count > 0)
        Session["CHECKED_ITEMS"] = categoryIDList;
}

AND

private void LoadPageState(GridView gv)
{
    ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
    if (categoryIDList != null && categoryIDList.Count > 0)
    {
        foreach (GridViewRow row in gv.Rows)
        {
            HiddenField hfStudentUnitID = (HiddenField)row.FindControl("hfStudentUnitID");
            if (hfStudentUnitID != null)
            {
                if (hfStudentUnitID.Value.Length > 0)
                {
                    Int32 index = Convert.ToInt32(hfStudentUnitID.Value.ToString()); //gv.DataKeys[row.RowIndex]["StudentUnitID"];
                    if (categoryIDList.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)row.FindControl("cbSEND");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }
    }
}

To make this work for you, you'll need to place the Paging method calls into your GridView, change the CheckBox ID from cbSEND to what ever you're using, and point the HiddenFields to some other control or value that has a unique identifier for your rows. Don't use RowIndex, as that is not unique throughout the length of the data in your GridView.

Works like a charm!


问:
Get-Aduser -Filter will not accept a variable
I'd like to check if a user account already exists in the system.

```<code>$SamAc = Read-Host 'What is your username?'
$User = Get-ADUser -Filter {sAMAccountName -eq "$SamAc"}
</code>```

I'm not sure why, but $User will always return null even if {sAMAccountName -eq "$SamAc"} is supposed to be true.

What am I missing here?

Edit:

This is what was missing:

```<code>$User = Get-ADUser -Filter "sAMAccountName -eq '$SamAc'"
</code>```

Editor's note: The script block ({ ... }) was replaced with a string.

答:
Okay, I got mine to finally work using the following syntax and using the following example from up above:

Previously:

```<code>$User = Get-ADUser -Filter "sAMAccountName -eq '$SamAc'"
</code>```

Working Version:

```<code>$user = Get-aduser -Filter "sAMAccountName -eq '$($SamAc)'"
</code>```

I had to add $($ ) to $SamAc before PowerShell could access the variable string value.

Body:
I'd like to check if a user account already exists in the system.

$SamAc = Read-Host 'What is your username?'
$User = Get-ADUser -Filter {sAMAccountName -eq "$SamAc"}

I'm not sure why, but $User will always return null even if {sAMAccountName -eq "$SamAc"} is supposed to be true.

What am I missing here?

Edit:

This is what was missing:

$User = Get-ADUser -Filter "sAMAccountName -eq '$SamAc'"

Editor's note: The script block ({ ... }) was replaced with a string.

Body:
Okay, I got mine to finally work using the following syntax and using the following example from up above:

Previously:

$User = Get-ADUser -Filter "sAMAccountName -eq '$SamAc'"

Working Version:

$user = Get-aduser -Filter "sAMAccountName -eq '$($SamAc)'"

I had to add $($ ) to $SamAc before PowerShell could access the variable string value.

ContentLicense: CC BY-SA 4.0


问:
Pydev Showing Errors for @staticmethod Reimplementation
I have wanted to create a python decorator that performs a particular task, but also does what @staticmethod does.  I have accomplished this, but using PyDev, it tells me that the usage is incorrect, because the method does not have the self parameter.

My simplified implementation is below:

```<code>class Service(object):

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f
</code>```

and the usage is:

```<code>class Environment:

    @Service
    def getConfig(input):
        return 50
</code>```

When I run this python program, everything runs well, but PyDev thinks it's an error.  Is there some easy way to disable checking for this type of error in pydev, while keeping the rest of its functionality present?

答:
As usual, found it before anybody could answer.

But if anybody in the future wants to know:

Window > Preferences > Pydev > Editor > Code Analysis > Others

This window is self-explanatory.

Body:
I have wanted to create a python decorator that performs a particular task, but also does what @staticmethod does.  I have accomplished this, but using PyDev, it tells me that the usage is incorrect, because the method does not have the self parameter.

My simplified implementation is below:

class Service(object):

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f

and the usage is:

class Environment:

    @Service
    def getConfig(input):
        return 50

When I run this python program, everything runs well, but PyDev thinks it's an error.  Is there some easy way to disable checking for this type of error in pydev, while keeping the rest of its functionality present?


问:
Unix strip EOF (not EOL/whitespace) from stream in pipe
I have a program which takes input and standard input until eof is given (CTRL-D on linux). I want to run this program with a lot of default input, then continue entering things until I manually hit CTRL-D to stop it. Is there any way to remove the EOF that a bash pipeline puts in?

IE: cat somedata.dat | <insert answer here> | ./myprogram such that myprogram never receives EOF on stdin.

答:
Bash doesn't actually add an "end-of-file" character; there isn't such a thing. Rather, the problem is that ./myprogram reaches the end of its standard input (which is hooked up to the pipe), so the next time it tries to read a character, it gets end-of-file instead. There's no way to have it suddenly switch over to "stealing" the standard input from the terminal, because it's not hooked up to that input at all.

Instead, to feed more input to ./myprogram than just what's in somedata.dat, you can ask cat to start reading (and forwarding) its own standard input after it's finished reading somedata.dat:

```<code>cat somedata.dat - | ./myprogram
</code>```

or

```<code>cat somedata.dat /dev/stdin | ./myprogram
</code>```

Edited to add (per further question in the comments): If you have a more complicated pipeline feeding into ./myprogram, rather than just a file, then you can run your main command and then cat, piping the whole thing to ./myprogram:

```<code>{
  reallyConfusingTransform < somedata.dat
  cat
} | ./myprogram
</code>```

or in one line:

```<code>{ reallyConfusingTransform < somedata.dat ; cat ; } | ./myprogram
</code>```

(Note that I've also eliminated a "useless use of cat" (UUOC), but if you really prefer to use cat that way, you can still write cat somedata.dat | reallyConfusingTransform instead of reallyConfusingTransform < somedata.dat.)

Body:
Bash doesn't actually add an "end-of-file" character; there isn't such a thing. Rather, the problem is that ./myprogram reaches the end of its standard input (which is hooked up to the pipe), so the next time it tries to read a character, it gets end-of-file instead. There's no way to have it suddenly switch over to "stealing" the standard input from the terminal, because it's not hooked up to that input at all.

Instead, to feed more input to ./myprogram than just what's in somedata.dat, you can ask cat to start reading (and forwarding) its own standard input after it's finished reading somedata.dat:

cat somedata.dat - | ./myprogram

or

cat somedata.dat /dev/stdin | ./myprogram

Edited to add (per further question in the comments): If you have a more complicated pipeline feeding into ./myprogram, rather than just a file, then you can run your main command and then cat, piping the whole thing to ./myprogram:

{
  reallyConfusingTransform < somedata.dat
  cat
} | ./myprogram

or in one line:

{ reallyConfusingTransform < somedata.dat ; cat ; } | ./myprogram

(Note that I've also eliminated a "useless use of cat" (UUOC), but if you really prefer to use cat that way, you can still write cat somedata.dat | reallyConfusingTransform instead of reallyConfusingTransform < somedata.dat.)


问:
Omitting arguments causes promisified functions to fail for ES2015 classes
I'm having trouble getting the Bluebird library's promisifyAll function to work with an ES2015 class's object instance methods when arguments are omitted. I'm using Node 7.8.0. Here's some sample code:

```<code>// dog.js
class Dog {
  constructor(opts) {
    this.name = opts.name || 'Fido';
  }

  fetchBone(bone, callback) {
    console.log('fetching the bone');
    callback(null, 'got it');
  }
}

exports = module.exports = Dog;
</code>```

Let's say the bone is an optional argument for fetchBone. When I pass it, everything's fine.

```<code>> var Dog = require('./dog');
> Promise = require('bluebird');
> Promise.promisifyAll(Dog); // omitting this line doesn't help
> Promise.promisifyAll(Dog.prototype);
> var puppy = new Dog();
> puppy.fetchBoneAsync('juicy bone')
       .then(result => console.log('from promise:', result))
       .catch(err => console.error('failure:', err));
fetching the bone
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
> from promise: got it
</code>```

It fails when I don't pass in the bone.

```<code>> puppy.fetchBoneAsync()
       .then(result => console.log('from promise:', result))
       .catch(err => console.error('failure:', err));
fetching the bone
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
> failure: TypeError: callback is not a function
    at Dog.fetchBone (dog.js:8:5)
    at Dog.tryCatcher (node_modules/bluebird/js/release/util.js:16:23)
    at Dog.ret [as fetchBoneAsync] (eval at makeNodePromisifiedEval (node_modules/bluebird/js/release/promisify.js:184:12), <anonymous>:14:23)
    at repl:1:7
    at ContextifyScript.Script.runInThisContext (vm.js:23:33)
    at REPLServer.defaultEval (repl.js:339:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.onLine (repl.js:536:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:191:7)
    at REPLServer.Interface._onLine (readline.js:241:10)
    at REPLServer.Interface._line (readline.js:590:8)
    at REPLServer.Interface._ttyWrite (readline.js:869:14)
    at REPLServer.self._ttyWrite (repl.js:609:7)
    at ReadStream.onkeypress (readline.js:120:10)
</code>```

Strangely, it works if I pass in undefined for the bone.

```<code>> puppy.fetchBoneAsync(undefined)
       .then(result => console.log('from promise:', result))
       .catch(err => console.error('failure:', err));
fetching the bone
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
> from promise: got it
</code>```

Anybody know what's going on here?

答:
Yep, that is correct behavior.  The promises are mapped to the original functions.  So fetchBone() is receiving two arguments in the first call and one in the second example.

This means that in the second example, when fetchBone() is called callback is undefined and the bone itself is the callback function created by the promisification to handle the promise itself.

Body:
I'm having trouble getting the Bluebird library's promisifyAll function to work with an ES2015 class's object instance methods when arguments are omitted. I'm using Node 7.8.0. Here's some sample code:

// dog.js
class Dog {
  constructor(opts) {
    this.name = opts.name || 'Fido';
  }

  fetchBone(bone, callback) {
    console.log('fetching the bone');
    callback(null, 'got it');
  }
}

exports = module.exports = Dog;

Let's say the bone is an optional argument for fetchBone. When I pass it, everything's fine.

> var Dog = require('./dog');
> Promise = require('bluebird');
> Promise.promisifyAll(Dog); // omitting this line doesn't help
> Promise.promisifyAll(Dog.prototype);
> var puppy = new Dog();
> puppy.fetchBoneAsync('juicy bone')
       .then(result => console.log('from promise:', result))
       .catch(err => console.error('failure:', err));
fetching the bone
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
> from promise: got it

It fails when I don't pass in the bone.

> puppy.fetchBoneAsync()
       .then(result => console.log('from promise:', result))
       .catch(err => console.error('failure:', err));
fetching the bone
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
> failure: TypeError: callback is not a function
    at Dog.fetchBone (dog.js:8:5)
    at Dog.tryCatcher (node_modules/bluebird/js/release/util.js:16:23)
    at Dog.ret [as fetchBoneAsync] (eval at makeNodePromisifiedEval (node_modules/bluebird/js/release/promisify.js:184:12), <anonymous>:14:23)
    at repl:1:7
    at ContextifyScript.Script.runInThisContext (vm.js:23:33)
    at REPLServer.defaultEval (repl.js:339:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.onLine (repl.js:536:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:191:7)
    at REPLServer.Interface._onLine (readline.js:241:10)
    at REPLServer.Interface._line (readline.js:590:8)
    at REPLServer.Interface._ttyWrite (readline.js:869:14)
    at REPLServer.self._ttyWrite (repl.js:609:7)
    at ReadStream.onkeypress (readline.js:120:10)

Strangely, it works if I pass in undefined for the bone.

> puppy.fetchBoneAsync(undefined)
       .then(result => console.log('from promise:', result))
       .catch(err => console.error('failure:', err));
fetching the bone
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
> from promise: got it

Anybody know what's going on here?


问:
Draw arrow with text outside axes
I want to draw an arrow with text that would stretch across several axes.  Reading http://matplotlib.org/users/annotations_guide.html

I got that far :

```<code>fig,ax = plt.subplots(2,3)
bbox_props = dict(boxstyle="rarrow,pad=0.2", fc="cyan", ec="b", lw=1)
t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)
</code>```

which makes

I found from text docs that bbox is a dictionary of Rectangle, which has width and height,  but when I set

```<code>bbox_props = dict(boxstyle="rarrow,pad=0.2", fc="cyan", ec="b", lw=1, width=3)
t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)
</code>```

I get a conflict :

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-255-006733283545> in <module>()
     13 # properties of a rectangle : http://matplotlib.org/api/patches_api.html#matplotlib.patches.Rectangle
     14
---> 15 t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)
     16 plt.savefig('example.png', bbox_inches='tight')

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/axes/_axes.py in text(self, x, y, s, fontdict, withdash, **kwargs)
    626         if fontdict is not None:
    627             t.update(fontdict)
--> 628         t.update(kwargs)
    629
    630         t.set_clip_path(self.patch)

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/text.py in update(self, kwargs)
    242         super(Text, self).update(kwargs)
    243         if bbox:
--> 244             self.set_bbox(bbox)  # depends on font properties
    245
    246     def __getstate__(self):

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/text.py in set_bbox(self, rectprops)
    514                                     bbox_transmuter=bbox_transmuter,
    515                                     transform=mtransforms.IdentityTransform(),
--> 516                                     **props)
    517         else:
    518             self._bbox_patch = None

TypeError: __init__() got multiple values for argument 'width'
</code>```

How can I control the size of my arrow with bbox ? Is there a way to extend it all the way to the right?

Thank you!
Chris

答:
It works if you add a bunch of spaces to both sides:

```<code>fig,axes = plt.subplots(2,3)
ax = axes[0,0]
bbox_props = dict(boxstyle="rarrow, pad=0.2", fc="cyan", ec="b", lw=1)
t = ax.text(0.15,1.15,45*' '+'Mag'+45*' ', ha="left", va="center",
            size=15,bbox=bbox_props)
plt.show()
</code>```

Resulting image:

Title: Draw arrow with text outside axes

Body:
I want to draw an arrow with text that would stretch across several axes.  Reading http://matplotlib.org/users/annotations_guide.html

I got that far :

fig,ax = plt.subplots(2,3)
bbox_props = dict(boxstyle="rarrow,pad=0.2", fc="cyan", ec="b", lw=1)
t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)

which makes

I found from text docs that bbox is a dictionary of Rectangle, which has width and height,  but when I set

bbox_props = dict(boxstyle="rarrow,pad=0.2", fc="cyan", ec="b", lw=1, width=3)
t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)

I get a conflict :

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-255-006733283545> in <module>()
     13 # properties of a rectangle : http://matplotlib.org/api/patches_api.html#matplotlib.patches.Rectangle
     14
---> 15 t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)
     16 plt.savefig('example.png', bbox_inches='tight')

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/axes/_axes.py in text(self, x, y, s, fontdict, withdash, **kwargs)
    626         if fontdict is not None:
    627             t.update(fontdict)
--> 628         t.update(kwargs)
    629
    630         t.set_clip_path(self.patch)

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/text.py in update(self, kwargs)
    242         super(Text, self).update(kwargs)
    243         if bbox:
--> 244             self.set_bbox(bbox)  # depends on font properties
    245
    246     def __getstate__(self):

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/text.py in set_bbox(self, rectprops)
    514                                     bbox_transmuter=bbox_transmuter,
    515                                     transform=mtransforms.IdentityTransform(),
--> 516                                     **props)
    517         else:
    518             self._bbox_patch = None

TypeError: __init__() got multiple values for argument 'width'

How can I control the size of my arrow with bbox ? Is there a way to extend it all the way to the right?

Thank you!
Chris

Body:
It works if you add a bunch of spaces to both sides:

fig,axes = plt.subplots(2,3)
ax = axes[0,0]
bbox_props = dict(boxstyle="rarrow, pad=0.2", fc="cyan", ec="b", lw=1)
t = ax.text(0.15,1.15,45*' '+'Mag'+45*' ', ha="left", va="center",
            size=15,bbox=bbox_props)
plt.show()

Resulting image:


问:
Can the type of a base class be obtained from a template type automatically?
I am trying to use template meta-programming to determine the base class.  Is there a way to get the base class automatically without explicitly specializing for each derived class?

```<code>class foo { public: char * Name() { return "foo"; }; };
class bar : public foo { public: char * Name() { return "bar"; }; };

template< typename T > struct ClassInfo { typedef T Base; };
template<> struct ClassInfo<bar> { typedef foo Base; };

int main()
{
  ClassInfo<foo>::Base A;
  ClassInfo<bar>::Base B;

  std::cout << A.Name();  //foo
  std::cout << B.Name();  //foo
}
</code>```

for right now any automatic method would need to select the first declared base and would  fail for private bases.

答:
With C++11, you can create a intrusive method to always have a base_t member, when your class only inherits from one parent:

```<code>template<class base_type>
struct labeled_base : public base_type
{
    using base_t = base_type; // The original parent type
    using base::base; // Inherit constructors

protected:
    using base = labeled_base; // The real parent type
};

struct A { virtual void f() {} };

struct my_class : labeled_base<A>
{
    my_class() : parent_t(required_params) {}

    void f() override
    {
        // do_something_prefix();
        base_t::f();
        // do_something_postfix();
    }
};
</code>```

With that class, you will always have a parent_t alias, to call the parent constructors as if it were the base constructors with a (probably) shorter name, and a base_t alias, to make your class non-aware of the base class type name if it's long or heavily templated.

The parent_t alias is protected to don't expose it to the public. If you don't want the base_t alias is public, you can always inherit labeled_base as protected or private, no need of changing the labeled_base class definition.

That base should have 0 runtime or space overhead since its methods are inline, do nothing, and has no own attributes.

Body:
I am trying to use template meta-programming to determine the base class.  Is there a way to get the base class automatically without explicitly specializing for each derived class?

class foo { public: char * Name() { return "foo"; }; };
class bar : public foo { public: char * Name() { return "bar"; }; };

template< typename T > struct ClassInfo { typedef T Base; };
template<> struct ClassInfo<bar> { typedef foo Base; };

int main()
{
  ClassInfo<foo>::Base A;
  ClassInfo<bar>::Base B;

  std::cout << A.Name();  //foo
  std::cout << B.Name();  //foo
}

for right now any automatic method would need to select the first declared base and would  fail for private bases.

Body:
With C++11, you can create a intrusive method to always have a base_t member, when your class only inherits from one parent:

template<class base_type>
struct labeled_base : public base_type
{
    using base_t = base_type; // The original parent type
    using base::base; // Inherit constructors

protected:
    using base = labeled_base; // The real parent type
};

struct A { virtual void f() {} };

struct my_class : labeled_base<A>
{
    my_class() : parent_t(required_params) {}

    void f() override
    {
        // do_something_prefix();
        base_t::f();
        // do_something_postfix();
    }
};

With that class, you will always have a parent_t alias, to call the parent constructors as if it were the base constructors with a (probably) shorter name, and a base_t alias, to make your class non-aware of the base class type name if it's long or heavily templated.

The parent_t alias is protected to don't expose it to the public. If you don't want the base_t alias is public, you can always inherit labeled_base as protected or private, no need of changing the labeled_base class definition.

That base should have 0 runtime or space overhead since its methods are inline, do nothing, and has no own attributes.


问:
How to resolve "Unknown Attribute Error" when importing CSV to rails?
Using the helpful answers from other questions here I set up an import in a controller to add CSV values to a DB in Rails. I continue to get the error below which doesn't give an unknown attribute (although I've quadruple-checked that they match) - it only gives a single quotation mark. Very frustrating. I've rebuilt this a couple times and yet the same error continues to come up. Does anyone have a hunch as to why?

Also, is there an easier/more reliable/more straightforward way to add these CSV values to my rails DB, perhaps using different technologies/apps?

ActiveModel::UnknownAttributeError in MatchesController#index

unknown attribute '' for Match.

```<code>  def index

    require 'csv'

    CSV.foreach(Rails.root.join('skedupdate.csv'), :headers => true) do |row|
      Match.create!(row.to_hash)
    end

  end
</code>```

答:
Generally, that error happens when you have a column (name) in the row that does not exist in the model, or in your case the row has a key " that does not exist.

You should probably print what is in row.to_hash to see the contents and to check that all the keys exist in the Match model.

Body:
Using the helpful answers from other questions here I set up an import in a controller to add CSV values to a DB in Rails. I continue to get the error below which doesn't give an unknown attribute (although I've quadruple-checked that they match) - it only gives a single quotation mark. Very frustrating. I've rebuilt this a couple times and yet the same error continues to come up. Does anyone have a hunch as to why?

Also, is there an easier/more reliable/more straightforward way to add these CSV values to my rails DB, perhaps using different technologies/apps?

ActiveModel::UnknownAttributeError in MatchesController#index

unknown attribute '' for Match.

  def index

    require 'csv'

    CSV.foreach(Rails.root.join('skedupdate.csv'), :headers => true) do |row|
      Match.create!(row.to_hash)
    end

  end


问:
What is the difference between the document selector and window selector?
I have the following JQuery function that takes user input and displays it on screen. When I select for both $(document) and $(window) the function works. What is the disadvantage to using either selector? Where can I read more on these selectors and their differences?

Thank you in advance.

```<code>  $(document).keypress(function(e) {
      if(e.keyCode == 13) {
          var id = $("input#example").val()
          console.log(id);
          $('#data').append(id);
      }
  });
</code>```

答:
To answer this question let me begin with the definition of the DOM, what we commonly know as "document".

The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense.

Now let me explain a little of what I found about browsing contexts, as that is the relationship that a Document and a Window normally have—although it is important to mention that a Document may exist without a browsing context, but you should never see that with jquery.

A user interacts with the main view of the Document. A view is defined as the media that is being used to present the Document to the user agent—e.g. screen, print, speech. The main view is the default view and is represented by an AbstractView object that implements the Window interface.

And to put it really simple, window is the container and document is the content. But I do recommend to at least skim through the documentation of this to have a better understanding.

Sources:

W3C - What is the
DOM,

W3C - Browsing
contexts

Body:
I have the following JQuery function that takes user input and displays it on screen. When I select for both $(document) and $(window) the function works. What is the disadvantage to using either selector? Where can I read more on these selectors and their differences?

Thank you in advance.

  $(document).keypress(function(e) {
      if(e.keyCode == 13) {
          var id = $("input#example").val()
          console.log(id);
          $('#data').append(id);
      }
  });


问:
JAVA- Returning an Array to main
In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main.  When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.

In main:

```<code>// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);
</code>```

In getAnswers():

```<code>// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

   // Loop to receive input into array.
   for (int index = 0; index < 20; index++)
   {
      System.out.print("Enter number " + (index + 1) +": ");
      input = keyboard.nextLine();
      array2 = input.toCharArray();
   }
   return array2;
}
</code>```

答:
It is not good idea to modify the method param. You can try : </p>

```<code>public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

String tmp = "";
for (int index = 0; index < 20; index++)
{
   System.out.print("Enter number " + (index + 1) +": ");
   input = keyboard.nextLine();
   tmp += input.chaAt(0);   // check length is > 0 here
}
return tmp.toCharArray();
}
</code>```

Title: JAVA- Returning an Array to main

Body:
In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main.  When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.

In main:

// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);

In getAnswers():

// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

   // Loop to receive input into array.
   for (int index = 0; index < 20; index++)
   {
      System.out.print("Enter number " + (index + 1) +": ");
      input = keyboard.nextLine();
      array2 = input.toCharArray();
   }
   return array2;
}

Body:
It is not good idea to modify the method param. You can try :

public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

String tmp = "";
for (int index = 0; index < 20; index++)
{
   System.out.print("Enter number " + (index + 1) +": ");
   input = keyboard.nextLine();
   tmp += input.chaAt(0);   // check length is > 0 here
}
return tmp.toCharArray();
}


问:
Not able to ssh over a public wifi network - Operation timed out
For some reason, I'm trying to access a server via ssh over a public wifi network, but I'm getting the error:

```<code>connect to host ***.***.***.*** port 22: Operation timed out
</code>```

Upon further investigation, I found out I could not ping any remote server as well:

```<code>admin ~ $ ping google.com
PING google.com (216.58.216.46): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
Request timeout for icmp_seq 3
Request timeout for icmp_seq 4
^C
--- google.com ping statistics ---
6 packets transmitted, 0 packets received, 100.0% packet loss
</code>```

I never encountered this problem from my home network, and since I'm trying this from a Library's Public Wifi network, I wonder if it's the public network that's causing hindrances. I am however able to access the internet flawlessly through my browsers. Sorry I'm really not well versed with network stuff, but I'd appreciate any insights to get through this problem.

答: It could be because port 22 is closed on that network. You could test the service over other network and it should work well. Whatever, if you are sure that port 22 is open, maybe check that in the remote machine is running SSH server and listening for clients at the port in question.</p>

Body:
For some reason, I'm trying to access a server via ssh over a public wifi network, but I'm getting the error:

connect to host ***.***.***.*** port 22: Operation timed out

Upon further investigation, I found out I could not ping any remote server as well:

admin ~ $ ping google.com
PING google.com (216.58.216.46): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
Request timeout for icmp_seq 3
Request timeout for icmp_seq 4
^C
--- google.com ping statistics ---
6 packets transmitted, 0 packets received, 100.0% packet loss

I never encountered this problem from my home network, and since I'm trying this from a Library's Public Wifi network, I wonder if it's the public network that's causing hindrances. I am however able to access the internet flawlessly through my browsers. Sorry I'm really not well versed with network stuff, but I'd appreciate any insights to get through this problem.


问:
Icon Fonts Break When Minifying CSS
So I'm using icomoon and have a group of 11 icons that break and just show squares every time I minify our site's CSS. The icons display properly with unminified CSS.

All other icomoon icons, including those used on the same page, display properly with both unminifed and minified CSS. When I take one of the 11 icon fonts that does not work, and I upload it to a spot on the page where a different icon font was working, or to a different part of the site, the icon still breaks.

Have tried reuploading the icons (plus a variety of other things) and that group of icons still does not work.

Has anyone encountered this before / any advice on how to fix?

Here is the icomoon style.css file (the top 11 icons do not work):

@font-face {
  font-family: 'icomoon';
  src:  url('fonts/icomoon.eot?543yc3');
  src:  url('fonts/icomoon.eot?543yc3#iefix') format('embedded-opentype'),
    url('fonts/icomoon.ttf?543yc3') format('truetype'),
    url('fonts/icomoon.woff?543yc3') format('woff'),
    url('fonts/icomoon.svg?543yc3#icomoon') format('svg');
  font-weight: normal;
  font-style: normal;
}

[class^="icon-"], [class*=" icon-"] {
  /* use !important to prevent issues with browser extensions that change fonts */
  font-family: 'icomoon' !important;
  speak: none;
  font-style: normal;
  font-weight: normal;
  font-variant: normal;
  text-transform: none;
  line-height: 1;

  /* Better Font Rendering =========== */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-collection:before {
  content: "\e92d";
}
.icon-data-mapping:before {
  content: "\e92e";
}
.icon-eca:before {
  content: "\e92f";
}
.icon-ecm:before {
  content: "\e930";
}
.icon-legal-project-management .path1:before {
  content: "\e931";
  color: rgb(242, 108, 56);
}
.icon-legal-project-management .path2:before {
  content: "\e932";
  margin-left: -0.9892578125em;
  color: rgb(6, 92, 115);
}
.icon-legal-project-management .path3:before {
  content: "\e933";
  margin-left: -0.9892578125em;
  color: rgb(51, 51, 51);
}
.icon-legal-project-management .path4:before {
  content: "\e934";
  margin-left: -0.9892578125em;
  color: rgb(10, 152, 189);
}
.icon-legal-project-management .path5:before {
  content: "\e935";
  margin-left: -0.9892578125em;
  color: rgb(51, 51, 51);
}
.icon-legal-project-management .path6:before {
  content: "\e936";
  margin-left: -0.9892578125em;
  color: rgb(51, 51, 51);
}
.icon-esi:before {
  content: "\e937";
}
.icon-file-analysis:before {
  content: "\e938";
}
.icon-integration-hub .path1:before {
  content: "\e939";
  color: rgb(255, 255, 255);
}
.icon-integration-hub .path2:before {
  content: "\e93a";
  margin-left: -1.5283203125em;
  color: rgb(242, 108, 56);
}
.icon-integration-hub .path3:before {
  content: "\e93b";
  margin-left: -1.5283203125em;
  color: rgb(10, 152, 189);
}
.icon-legal-hold:before {
  content: "\e93c";
}
.icon-production:before {
  content: "\e93d";
}
.icon-review:before {
  content: "\e93e";
}
.icon-cloud:before {
  content: "\e928";
}
.icon-integrations:before {
  content: "\e929";
}
.icon-nav-arrow:before {
  content: "\e92a";
}
.icon-newsletter-icon:before {
  content: "\e92b";
}
.icon-platform:before {
  content: "\e92c";
}
.icon-share-may16:before {
  content: "\e900";
}
.icon-sort-may16:before {
  content: "\e901";
}
.icon-tag-may16:before {
  content: "\e902";
}
.icon-arrow-may16:before {
  content: "\e903";
}
.icon-back-may16:before {
  content: "\e904";
}
.icon-external-link-may16:before {
  content: "\e905";
}
.icon-home-may16:before {
  content: "\e906";
}
.icon-important-may16:before {
  content: "\e907";
}
.icon-quote-may16:before {
  content: "\e908";
}
.icon-search-may16:before {
  content: "\e909";
}
.icon-sensitive:before {
  content: "\e355";
}
.icon-blog-post:before {
  content: "\e600";
}
.icon-menu:before {
  content: "\e601";
}
.icon-case-study:before {
  content: "\e602";
}
.icon-datasheet:before {
  content: "\e603";
}
.icon-e-book:before {
  content: "\e604";
}
.icon-infographic:before {
  content: "\e605";
}
.icon-webcast:before {
  content: "\e606";
}
.icon-whitepaper:before {
  content: "\e607";
}
.icon-rss:before {
  content: "\e608";
}
.icon-twitter:before {
  content: "\e609";
}
.icon-facebook:before {
  content: "\e60a";
}
.icon-googleplus:before {
  content: "\e60b";
}
.icon-linkedin:before {
  content: "\e60c";
}
.icon-comment:before {
  content: "\e60d";
}
.icon-news:before {
  content: "\e60e";
}
.icon-events:before {
  content: "\e60f";
}
.icon-live-webcast:before {
  content: "\e610";
}
.icon-solutionbrief:before {
  content: "\e611";
}
.icon-analyst-reports:before {
  content: "\e612";
}
.icon-contributed-articles:before {
  content: "\e613";
}
.icon-in-the-news:before {
  content: "\e614";
}
.icon-calculators:before {
  content: "\e615";
}
.icon-act:before {
  content: "\e616";
}
.icon-cloud-first:before {
  content: "\e617";
}
.icon-collaboration:before {
  content: "\e618";
}
.icon-cost-reduction:before {
  content: "\e619";
}
.icon-defensibility:before {
  content: "\e61a";
}
.icon-detect:before {
  content: "\e61b";
}
.icon-ease-of-use:before {
  content: "\e61c";
}
.icon-elasticity:before {
  content: "\e61d";
}
.icon-integration2:before {
  content: "\e61e";
}
.icon-interoperability:before {
  content: "\e61f";
}
.icon-know-more-sooner:before {
  content: "\e620";
}
.icon-multinational:before {
  content: "\e621";
}
.icon-reduce-review-cost:before {
  content: "\e622";
}
.icon-reporting:before {
  content: "\e623";
}
.icon-scalability:before {
  content: "\e624";
}
.icon-track:before {
  content: "\e625";
}
.icon-visibility:before {
  content: "\e626";
}
.icon-export:before {
  content: "\e627";
}
.icon-newspaper:before {
  content: "\e628";
}
.icon-in:before {
  content: "\e629";
}
.icon-play:before {
  content: "\e62a";
}
.icon-envelope:before {
  content: "\e62b";
}
.icon-slideshow:before {
  content: "\e62c";
}
.icon-close:before {
  content: "\e62d";
}
.icon-easeofuse-mar16:before {
  content: "\e90a";
}
.icon-enterprise-scalability-mar16:before {
  content: "\e90b";
}
.icon-defensible-mar16:before {
  content: "\e90c";
}
.icon-visualization-mar16:before {
  content: "\e90d";
}
.icon-interoperability-mar16:before {
  content: "\e90e";
}
.icon-consolidate-mar16:before {
  content: "\e90f";
}
.icon-identifiy-sensitive-data-mar16:before {
  content: "\e910";
}
.icon-track-mar16:before {
  content: "\e911";
}
.icon-act-mar16:before {
  content: "\e912";
}
.icon-detect-mar16:before {
  content: "\e913";
}
.icon-adaptability-mar16:before {
  content: "\e914";
}
.icon-preditibility-mar16:before {
  content: "\e915";
}
.icon-project-management-mar16:before {
  content: "\e916";
}
.icon-visibility-mar16:before {
  content: "\e917";
}
.icon-ease-of-use-mar16:before {
  content: "\e918";
}
.icon-legal-hold-mar16:before {
  content: "\e919";
}
.icon-interoperability2-mar16:before {
  content: "\e91a";
}
.icon-elasticity-and-scalability-mar16:before {
  content: "\e91b";
}
.icon-cloud-mar16:before {
  content: "\e91c";
}
.icon-collaboration-mar16:before {
  content: "\e91d";
}
.icon-data-mapping-mar16:before {
  content: "\e91e";
}
.icon-eddm-mar16:before {
  content: "\e91f";
}
.icon-integrations-mar16:before {
  content: "\e920";
}
.icon-products-mar16:before {
  content: "\e921";
}
.icon-platform-mar16:before {
  content: "\e922";
}
.icon-cloud-one-mar16:before {
  content: "\e923";
}
.icon-defensibility-mar16:before {
  content: "\e924";
}
.icon-one-click-mar16:before {
  content: "\e925";
}
.icon-reduced-costs-mar16:before {
  content: "\e926";
}
.icon-know-more-sooner-mar16:before {
  content: "\e927";
}
.icon-reduce-storage:before {
  content: "\e9c7";
}
.icon-merge:before {
  content: "\ea58";
}```

答:
Figured out the issue here.

So the minified version of the CSS was a folder level above the unminified version and was pulling from an outdated set of fonts in a folder at its level. The unminfied version was pulling from updated fonts that were placed in a folder at its level.

Hope someone sees this in the future and it saves them a bunch of time that went into solving a pretty dumb issue :)

Title: Icon Fonts Break When Minifying CSS