问:
EntityFramework Custom Association
Ok lets say i have a user table and then a table that logs all login atempts (Id(counter), userId, time and if successful or not)

Now in my Entity Model i want it to be 2 Association's one with the time of all successful attempts and one with all unsuccessful attempts how could i achieve this?

This is how the model looks now!

答:
Good question. :)

What your essentially trying to do is have a condition on your navigational property, like how you have have conditional mapping on your entities.

Unfortunately, Navigational Properties on the conceptual model must map to foreign keys on the physical model (database). And FK's cannot be conditional.

What i would do, is use TPH on UserLoginHistory.

Create two entities - UserLoginHistorySuccess and UserLoginHistoryFail.

And use a dicriminator (Success) to map to the single UserLoginHistory table.

E.g:

UserLoginHistorySuccess - maps to UserLoginHistory when Success = 1

UserLoginHistoryFail - maps to UserLoginHistory when Success = 0

That way, you can add two navigational properties on User, which maps to the two entities.

But you still only require 1 actual database table.

More on Table Per Hierachy here.

Good luck!

Title: EntityFramework Custom Association


来源: stackexchange

问:
Why isn't the jumping animation showing?
I'm a beginner programmer and I recently started trying to make a game in Java.

It's very basic and doesn't include any classes (although it should) but anyway I tried to make a jumping animation on the JPanel using a JLabel as my sprite but whenever I try to time the space between each movement of the label by using Thread.sleep(millis) the Java seems to skip it and moves the label to the last position.

```<code>JFrame frame = new JFrame("malario");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);

frame.setVisible(true);
frame.setSize(700, 700);
JPanel panel = new JPanel();

panel.setLayout(null);
panel.setBackground(Color.blue);
JLabel malario = new JLabel("Malario");
malario.setOpaque(true);
malario.setBackground(Color.green);
panel.add(malario);

malario.setBounds(100, 550, 50, 50);

JLabel platform = new JLabel();
platform.setOpaque(true);
platform.setBounds(0,600,700,50);
panel.add(platform);
frame.setContentPane(panel);
frame.addKeyListener(new KeyListener() {
    int originalx = 100;
    int originaly = 550;
    int currentlocx = originalx;
    int currentlocy = originaly;

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyPressed(KeyEvent e) {

        if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            malario.setBounds(currentlocx+10,currentlocy , 50, 50);
            currentlocx = currentlocx+10;
        }

        if(e.getKeyCode()==KeyEvent.VK_LEFT){
            malario.setBounds(currentlocx-10,currentlocy , 50, 50);
            currentlocx = currentlocx-10;
        }
        int jumpy=0;
        if(e.getKeyCode()==KeyEvent.VK_UP){
            jumpy= currentlocy-100;
            while(jumpy!=currentlocy){

                malario.setBounds(currentlocx,currentlocy-10 , 50, 50);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                currentlocy = currentlocy-10;
            }
        }
    }
});

}
public static int Time(){
    return (int)System.currentTimeMillis();
}
}
</code>```

答:
You can't use Thread.sleep().

All listener code is executed on the Event Dispatch Thread (EDT), which is the Thread responsible for handling events and painting the GUI. So, when you tell the Thread the sleep the GUI can't repaint itself until all the code in the loop has finished executing, so you only see the component at its last position.

Instead you need to use a Swing Timer to schedule the animation. Read the Swing Tutorial. There are sections on:

Concurrency in Swing- explains more about the EDT

How to Use Swing Timers - for examples on using a Timer

for more information.

Also, don't use a KeyListener. Instead it is better to use Key Bindings. The tutorial also has a section on How to Use Key Bindings.

Edit:

See: the KeyboardAnimation example from Motion Using the Keyboard for a working example that shows both:

how to use key bindings

how to do animation.

ContentLicense: CC BY-SA 3.0

Body:
I'm a beginner programmer and I recently started trying to make a game in Java.

It's very basic and doesn't include any classes (although it should) but anyway I tried to make a jumping animation on the JPanel using a JLabel as my sprite but whenever I try to time the space between each movement of the label by using Thread.sleep(millis) the Java seems to skip it and moves the label to the last position.

JFrame frame = new JFrame("malario");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);

frame.setVisible(true);
frame.setSize(700, 700);
JPanel panel = new JPanel();

panel.setLayout(null);
panel.setBackground(Color.blue);
JLabel malario = new JLabel("Malario");
malario.setOpaque(true);
malario.setBackground(Color.green);
panel.add(malario);

malario.setBounds(100, 550, 50, 50);

JLabel platform = new JLabel();
platform.setOpaque(true);
platform.setBounds(0,600,700,50);
panel.add(platform);
frame.setContentPane(panel);
frame.addKeyListener(new KeyListener() {
    int originalx = 100;
    int originaly = 550;
    int currentlocx = originalx;
    int currentlocy = originaly;

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyPressed(KeyEvent e) {

        if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            malario.setBounds(currentlocx+10,currentlocy , 50, 50);
            currentlocx = currentlocx+10;
        }

        if(e.getKeyCode()==KeyEvent.VK_LEFT){
            malario.setBounds(currentlocx-10,currentlocy , 50, 50);
            currentlocx = currentlocx-10;
        }
        int jumpy=0;
        if(e.getKeyCode()==KeyEvent.VK_UP){
            jumpy= currentlocy-100;
            while(jumpy!=currentlocy){

                malario.setBounds(currentlocx,currentlocy-10 , 50, 50);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                currentlocy = currentlocy-10;
            }
        }
    }
});

}
public static int Time(){
    return (int)System.currentTimeMillis();
}
}


问:
Am I ruining my disk by using sqlite?
So I'm running web scrapers from time to time. Sometimes a database is unavoidable, and I prefer sqlite because of its ease of use. However, I fear my latest project is putting strain on my SSD; take a look.

I have separate processes, each of them queries the database for a URL to scrape, does that, and then writes results and commits to disk. I want to, if possible, avoid unnecessary scraping, so I commit after each result so the other processes know not to scrape that one.

What I worry is that each commit is an actual write to disk. With something like a million queries, my SSD will age prematurely :/
So basically, two questions:

Does this really mean 1 commit = 1 physical disk write? Or is there buffering within SQLite, or Linux does something like that, or maybe the SSD controller itself that kind of keeps the copy of the database in RAM (or controller memory) and only infrequently syncs with the drive? The database itself is less than 20MB.

If it is how I fear, any tweaks I could do to sqlite3 or is a server-client database unavoidable? My understanding is that the database server would have exclusive access to the database, so it could just keep the working version in RAM and sync to disk regularly.

I'm sorry the question is more of a discussion :/

答:
One commit indeed results in at least one disk write, or rather more than one, because the table structure and the database header and the file system's metadata are likely to be located in other pages.

Then look up your SSD's write endurance in the datasheet. Then realize that a piddling million writes you do "from time to time" are completely harmless.

To make your database writes more SSD-friendly, you can enable WAL mode. But unless you're continuously running the database 24/7, you won't notice any difference.

Title: Am I ruining my disk by using sqlite?


问:
Integrating jQuery plugin calls inside AngularJS Directives
I've been working on converting a plain static website into an AngularJS website - just to also improve my skills on that.

So far, I've done routes and looking good so far.

Now on the home page, I made slider images load using ng-repeat directive and it's also working. But I noticed something that the slider itself isn't working its supposed functionality. So I found out that the jQuery functions I made on a separate js file isn't loading at all. And I also found out that this can be achieved by integrating the plugin calls inside a directive.

So, I made this:

```<code>app.directive('featuredSlider', [function() {
return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
        $(elem).owlCarousel({
            itemsCustom: [
                [0, 1],
                [600, 2],
                [1200, 4]
            ],
            autoPlay: 3000
        });
    }
};}]);
</code>```

I'm using OwlCarousel for the slider and it's not being triggered using the one I did above.

By the way, this is how my controller look like:

```<code>app.controller('HomeController', function($scope) {
$scope.featuredImages = []; }
</code>```

The featuredImages array above has the image URLs for the slider.

And then, this is the part where the slider is.

```<code><div class = "featured owl-carousel owl-theme featured-slider">
     <div class = "item" ng-repeat = "featured in featuredImages">
       <img ng-src = "{{featured.img}}" />
     </div>
</div>
</code>```

Anyone who can help me out? I've tried out several methods but still not showing up and working.

答: Use the controller of the directive and put the third-party library as a service so you can inject the dependency in the directive controller.</p>

ContentLicense: CC BY-SA 4.0

Body:
I've been working on converting a plain static website into an AngularJS website - just to also improve my skills on that.

So far, I've done routes and looking good so far.

Now on the home page, I made slider images load using ng-repeat directive and it's also working. But I noticed something that the slider itself isn't working its supposed functionality. So I found out that the jQuery functions I made on a separate js file isn't loading at all. And I also found out that this can be achieved by integrating the plugin calls inside a directive.

So, I made this:

app.directive('featuredSlider', [function() {
return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
        $(elem).owlCarousel({
            itemsCustom: [
                [0, 1],
                [600, 2],
                [1200, 4]
            ],
            autoPlay: 3000
        });
    }
};}]);

I'm using OwlCarousel for the slider and it's not being triggered using the one I did above.

By the way, this is how my controller look like:

app.controller('HomeController', function($scope) {
$scope.featuredImages = []; }

The featuredImages array above has the image URLs for the slider.

And then, this is the part where the slider is.

Anyone who can help me out? I've tried out several methods but still not showing up and working.


问:
how to expend link area- hit using css code
I have a site built in Joomla
I'm having a problem with my sub menu links,
I want to expend the hit area using css (like this option in a flash button)
Is that possible?
this is my code now:
(collection is the main button that open sub menu with the links I'm having problem)

```<code>#collections {
display:block;
margin:20px 0 180px 30px;
}
#collections ul {
 margin: 0;

 list-style:none;
 }
#collections ul li{
 display:inline;
 padding: 0 10px 0 0;
 font-size: 13px;
 color: #6cabe7;

}
#collections ul.menu li a span{
 color: #543019;
}
#collections ul.menu li.active a span{
 color: #6cabe7;
}
#collections ul li a:link, #collections ul li a:visited {
 color: #6cabe7;
 text-decoration:none;
}
#collections ul li a:hover {
 color: #6cabe7;
}
#collections .moduletable h3 {
 color: #6cabe7;
 font-size:16px;
 margin-bottom:9px;
}
</code>```

What to do?
thanks :)

答:
Rather telepathic response.

```<code>collections ul.menu li a {padding:10px;}
</code>```

EDIT

In your case "fading" problem can be solved with

```<code>collections ul.menu li a {position:relative;z-index:99}
</code>```

But it is quick and dirty. It's better to debug why it happens.

ContentLicense: CC BY-SA 2.5

Body:
I have a site built in Joomla
I'm having a problem with my sub menu links,
I want to expend the hit area using css (like this option in a flash button)
Is that possible?
this is my code now:
(collection is the main button that open sub menu with the links I'm having problem)

#collections {
display:block;
margin:20px 0 180px 30px;
}
#collections ul {
 margin: 0;

 list-style:none;
 }
#collections ul li{
 display:inline;
 padding: 0 10px 0 0;
 font-size: 13px;
 color: #6cabe7;

}
#collections ul.menu li a span{
 color: #543019;
}
#collections ul.menu li.active a span{
 color: #6cabe7;
}
#collections ul li a:link, #collections ul li a:visited {
 color: #6cabe7;
 text-decoration:none;
}
#collections ul li a:hover {
 color: #6cabe7;
}
#collections .moduletable h3 {
 color: #6cabe7;
 font-size:16px;
 margin-bottom:9px;
}

What to do?
thanks :)

Body:
Rather telepathic response.

collections ul.menu li a {padding:10px;}

EDIT

In your case "fading" problem can be solved with

collections ul.menu li a {position:relative;z-index:99}

But it is quick and dirty. It's better to debug why it happens.


问:
Postman / Curl not working with Google App engine deployed app
I've got a Django app deployed on a Google App Engine (standard) which is working fine if I access it via the browser (any). However, I cannot run any tests using curl on the terminal or using the Postman app. When I try running curl, it times out:

```<code>curl --verbose -X GET "https://SERVER.appspot.com"
Note: Unnecessary use of -X or --request, GET is already inferred.
* Rebuilt URL to: https://SERVER.appspot.com/
*   Trying x.x.x.x...
* TCP_NODELAY set
* Connected to SERVER.appspot.com (x.x.x.x) port 443 (#0)
* Operation timed out after 300225 milliseconds with 0 out of 0 bytes received
* Curl_http_done: called premature == 1
* Closing connection 0
curl: (28) Operation timed out after 300225 milliseconds with 0 out of 0 bytes received
</code>```

Any idea what I'm doing wrong? The same app runs fine locally and I can run Postman / curl on it. If I try the same (i.e. curl or Postman) with a http:// instead of https://, it works just fine (yet https:// is working when using a browser).

What do I need to do to get it to work from the terminal?

答:
Turned out to be a SSL 'trust' issue. One needs to add SSL support for each sub-domain mapped to an App Engine instance. Turns out, if you haven't done this correctly (in my case one of the CA intermediate certificates was missing from the .crt bundle), your browser may assume the site to be secure, but curl / postman will fail - or rather timeout without telling you much. I was able to run some tests on my sub-domain here: https://www.ssllabs.com/ssltest

It pointed out that the CA certificates supplied were incomplete and rated it B. Fixing this immediately fixed the curl and postman issues (and I assume postman internally is using curl ? I digress).

Body:
I've got a Django app deployed on a Google App Engine (standard) which is working fine if I access it via the browser (any). However, I cannot run any tests using curl on the terminal or using the Postman app. When I try running curl, it times out:

curl --verbose -X GET "https://SERVER.appspot.com"
Note: Unnecessary use of -X or --request, GET is already inferred.
* Rebuilt URL to: https://SERVER.appspot.com/
*   Trying x.x.x.x...
* TCP_NODELAY set
* Connected to SERVER.appspot.com (x.x.x.x) port 443 (#0)
* Operation timed out after 300225 milliseconds with 0 out of 0 bytes received
* Curl_http_done: called premature == 1
* Closing connection 0
curl: (28) Operation timed out after 300225 milliseconds with 0 out of 0 bytes received

Any idea what I'm doing wrong? The same app runs fine locally and I can run Postman / curl on it. If I try the same (i.e. curl or Postman) with a http:// instead of https://, it works just fine (yet https:// is working when using a browser).

What do I need to do to get it to work from the terminal?


问:
For each row in an R dataframe
I have a dataframe, and for each row in that dataframe I have to do some complicated lookups and append some data to a file.

The dataFrame contains scientific results for selected wells from 96 well plates used in biological research so I want to do something like:

```<code>for (well in dataFrame) {
  wellName <- well$name    # string like "H1"
  plateName <- well$plate  # string like "plate67"
  wellID <- getWellID(wellName, plateName)
  cat(paste(wellID, well$value1, well$value2, sep=","), file=outputFile)
}
</code>```

In my procedural world, I'd do something like:

```<code>for (row in dataFrame) {
    #look up stuff using data from the row
    #write stuff to the file
}
</code>```

What is the "R way" to do this?

答:
You can use the by_row function from the package purrrlyr for this:

```<code>myfn <- function(row) {
  #row is a tibble with one row, and the same
  #number of columns as the original df
  #If you'd rather it be a list, you can use as.list(row)
}

purrrlyr::by_row(df, myfn)
</code>```

By default, the returned value from myfn is put into a new list column in the df called .out.

If this is the only output you desire, you could write purrrlyr::by_row(df, myfn)$.out

Title: For each row in an R dataframe

Body:
I have a dataframe, and for each row in that dataframe I have to do some complicated lookups and append some data to a file.

The dataFrame contains scientific results for selected wells from 96 well plates used in biological research so I want to do something like:

for (well in dataFrame) {
  wellName <- well$name    # string like "H1"
  plateName <- well$plate  # string like "plate67"
  wellID <- getWellID(wellName, plateName)
  cat(paste(wellID, well$value1, well$value2, sep=","), file=outputFile)
}

In my procedural world, I'd do something like:

for (row in dataFrame) {
    #look up stuff using data from the row
    #write stuff to the file
}

What is the "R way" to do this?

Body:
You can use the by_row function from the package purrrlyr for this:

myfn <- function(row) {
  #row is a tibble with one row, and the same
  #number of columns as the original df
  #If you'd rather it be a list, you can use as.list(row)
}

purrrlyr::by_row(df, myfn)

By default, the returned value from myfn is put into a new list column in the df called .out.

If this is the only output you desire, you could write purrrlyr::by_row(df, myfn)$.out


问:
Xcode 8 - Missing Files warnings
Ever since upgrading to Xcode 8 using Swift 2.3
I have several missing files warnings. They are all related to pods that I am using.

The files that are missing are

```<code>*.xcscheme
*.cpp
*.xcuserstate
*.swift
</code>```

The pods that are showing missing files are

Realm (~38 of 43)

TextFieldEffects (~3 of 43)

BEMCheckBox (2 of 43)

How do I fix this issue?

答:
I have faced the same problem after adding custom CollectionView cell(CustomCollectionViewCell) in the project.Same error occurred as above.
No need to delete the file instead we can.

Rename Missing file for me it's "xCustomCollectionViewCell.xib" .

Now the error is gone.

Again rename the same file to original name "CustomCollectionViewCell.xib"

Title: Xcode 8 - Missing Files warnings

Body:
Ever since upgrading to Xcode 8 using Swift 2.3
I have several missing files warnings. They are all related to pods that I am using.

The files that are missing are

*.xcscheme
*.cpp
*.xcuserstate
*.swift

The pods that are showing missing files are

Realm (~38 of 43)

TextFieldEffects (~3 of 43)

BEMCheckBox (2 of 43)

How do I fix this issue?


问:
How to take a selected option with PHP
I'm new here and I'm really sorry if the subject of this ticket do not have to be at this place.

I'm working on a PrestaShop website that use SMARTY. How could I display some products with the choice that a customer done in a select tag?

Can I do this with just PHP + HTML or do I need Javascript?

Here is my code :

Page de conseil pour PC & PC portable Gamer

Dites nous quel style de Gamer vous ètes, nous nous occupons du reste

Sélectionnez le type de joueur qui vous correspond

  <select class="gameplay">
   <option value="1" selected="selected">Sélectionnez</option>
   <option value="1">Casual (de temps en temps)</option>
   <option value="1">Normal (1 à 2h/jour)</option>
   <option value="1">Régulier (2 à 4h/jour)</option>
   <option value="1">Hard Core (>4h/jour)</option>
  </select>

Sélectionnez vos types de jeux

  <select class="game">
   <option value="1" selected="selected">Sélectionnez</option>
   <option value="1">MOBA & FPS peu gourmand (Counter Strike, LOL, DOTA, Heroes Of The Storm)</option>
   <option value="1">MMORPG (WOW, Blade and Soul), FPS (type overwatch, battlefield 3)</option>
   <option value="1">FPS poussé (Battlefield 1), Aventures</option>
   <option value="1">Tout en Ultra !</option>
  </select>

  <button type="button" name="submit" class="validation-game">
   Valider
  </button>

```

I need to display 3 products that's correspond to the choice of the customer in select when he will hit the validate button.

My PHP's knowledge is not really high, if someone can guide, I don't want especially the answer just a way where I can work on it.

Thanks in advance.

答: Put all your inputs, text fields (if any), select options along with the final submit button. Give the form some id eg. id="form1" and in the select tag, write form="form1". Also don't forget to give the action attribute to the form tag. It's basically a file where the data received from can be processed. If you set action="process.php", you can retrieve the data of the select as $some_variable=$_POST["name_of_select_tag"]. Now you can use the variable to your need.

Title: How to take a selected option with PHP

Body:
I'm new here and I'm really sorry if the subject of this ticket do not have to be at this place.

I'm working on a PrestaShop website that use SMARTY. How could I display some products with the choice that a customer done in a select tag?

Can I do this with just PHP + HTML or do I need Javascript?

Here is my code :

Page de conseil pour PC & PC portable Gamer

Dites nous quel style de Gamer vous ètes, nous nous occupons du reste

Sélectionnez le type de joueur qui vous correspond

  <select class="gameplay">
   <option value="1" selected="selected">Sélectionnez</option>
   <option value="1">Casual (de temps en temps)</option>
   <option value="1">Normal (1 à 2h/jour)</option>
   <option value="1">Régulier (2 à 4h/jour)</option>
   <option value="1">Hard Core (>4h/jour)</option>
  </select>

Sélectionnez vos types de jeux

  <select class="game">
   <option value="1" selected="selected">Sélectionnez</option>
   <option value="1">MOBA & FPS peu gourmand (Counter Strike, LOL, DOTA, Heroes Of The Storm)</option>
   <option value="1">MMORPG (WOW, Blade and Soul), FPS (type overwatch, battlefield 3)</option>
   <option value="1">FPS poussé (Battlefield 1), Aventures</option>
   <option value="1">Tout en Ultra !</option>
  </select>

  <button type="button" name="submit" class="validation-game">
   Valider
  </button>

I need to display 3 products that's correspond to the choice of the customer in select when he will hit the validate button.

My PHP's knowledge is not really high, if someone can guide, I don't want especially the answer just a way where I can work on it.

Thanks in advance.


问:
User react router inside of map
I would like to use react-router (must use 2.8.1) for rendering content inside a list (using map).

However, if I display {this.props.children} outside the .map, it renders one at time.

I need it to display inline/under the list entry.

How can I achieve this?

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: x.movies
    };
  }
  render() {
    return (
      <div>
        <h2>Repos</h2>
        {x.movies.map(movie =>
          <span key={movie.id}>
            {movie.name}
            <NavLink to={"/repos/" + movie.id + "/next"}>React Router</NavLink>
          </span>
        )}
        {this.props.children}
      </div>
    );
  }
}
</code>```

答:
You are rendering the children inside the loop, which i believe is causing the extra Next Id:4 to be displayed between each entry.

Try the below, by rendering the children outside the loop.

```<code>{
  x.movies.map(movie => (
        <span>
        <Result key={movie.id} result= {movie}/>
        </span>
      ))
}
<span>{this.props.children}</span>
</code>```

Title: User react router inside of map

Body:
I would like to use react-router (must use 2.8.1) for rendering content inside a list (using map).

However, if I display {this.props.children} outside the .map, it renders one at time.

I need it to display inline/under the list entry.

How can I achieve this?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: x.movies
    };
  }
  render() {
    return (

Repos

        {x.movies.map(movie =>

            {movie.name}
            <NavLink to={"/repos/" + movie.id + "/next"}>React Router</NavLink>

        )}
        {this.props.children}

    );
  }
}

Body:
You are rendering the children inside the loop, which i believe is causing the extra Next Id:4 to be displayed between each entry.

Try the below, by rendering the children outside the loop.

{
  x.movies.map(movie => (
        <span>
        <Result key={movie.id} result= {movie}/>
        </span>
      ))
}
<span>{this.props.children}</span>


问:
Decode - From bytes to any
This is Python 2

My understanding is,

decode is about decoding from bytes to anything(ascii/codepoint/utf-8/whatever..)

encode is about encoding from unicode code points to anything(bytes/ascii/utf-8/...)

From the below code,

```<code>>>> myUtf8
'Hi \xe2\x84\x99\xc6\xb4\xe2\x98\x82\xe2\x84\x8c\xc3\xb8\xe1\xbc\xa4'
>>> myUtf8.decode("ascii", "replace")
u'Hi \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd'
>>> myUtf8.decode('utf-16')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_16.py", line 16, in decode
    return codecs.utf_16_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0xa4 in position 18: truncated data
</code>```

Question:

Why code point \ufffd is replaced for the bytes that can't be decoded?

Edit:

Question:

Agreement (say) is bytes are being received. how to find, bytes are expressed in which encoding? Assuming those bytes are being received from network.

答:
Your understanding is wrong. decode is "from bytes expressed in the encoding you pass as first parameter to unicode"; encode is "from unicode to bytes expressed in the encoding you pass as first parameter".

In your example, you give some bytes expressed in UTF-8 and tell to Python to interpret them as ASCII to then build a unicode string; given that all the >127 bytes aren't valid ASCII, they are considered garbage, and thus, as you requested with the "replace" parameter, they are replaced with the Unicode replacement character.

Title: Decode - From bytes to any

Body:
This is Python 2

My understanding is,

decode is about decoding from bytes to anything(ascii/codepoint/utf-8/whatever..)

encode is about encoding from unicode code points to anything(bytes/ascii/utf-8/...)

From the below code,

>>> myUtf8
'Hi \xe2\x84\x99\xc6\xb4\xe2\x98\x82\xe2\x84\x8c\xc3\xb8\xe1\xbc\xa4'
>>> myUtf8.decode("ascii", "replace")
u'Hi \ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd'
>>> myUtf8.decode('utf-16')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_16.py", line 16, in decode
    return codecs.utf_16_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0xa4 in position 18: truncated data

Question:

Why code point \ufffd is replaced for the bytes that can't be decoded?

Edit:

Question:

Agreement (say) is bytes are being received. how to find, bytes are expressed in which encoding? Assuming those bytes are being received from network.


问:
Update map panes and legend dynamically on leaflet
I'm trying to use leaflet to make an interactive map (like a choropleth) using data from geojson files and I've a problem to update data and legend on the map, dynamically.

My code use a leaflet map with a mapbox-light baselayer, a dropdownlist and a legend. Two jsons files are loaded and I use two map panes to use them and set their z-index. Dropdownlist has two options and is used to change the selected geojsons to expand this example; the real case has 25 values to choose.

I use $(id_dropdownlist).change to make everything. If ddl change:

remove panes if these exists.

select geojsons files using ddl value (default url myjson files + ajax for this example).

add panes, load and color polygons.

When I make the first change in the ddl works fine: select geojsons files, load and color polygons. My problem appears from the second change onwards, after remove panes: geojsons are loaded successfully but these are not showed/colored on my map.

My amateur debugging detect than in the first change the div leaflet-pane element has the geojsons values, but from the second change onwards the same div leaflet-pane has not data.

Also, I want to update the legend at same time after load the geojsons, but I do not have any idea how to make that.

Here is a functional example in JSFiddle.

If someone could help me step by step, for learn it, I would be very grateful. If panes are not the way to do this, or another way to do this better, please tell me how.

答:
When user changes the selection of your drop down list, you first try to clear your map by removing your previously created custom panes from the DOM.

There is a very high chance Leaflet does not expect such fiddling with its panes, even if they are custom. That is probably why when you create new custom panes with the same names, Leaflet does not reference them correctly, hence it does not display your new layers in those new panes.

For adding and removing your layers dynamically to / from the map, you should simply use Layer Groups instead. In particular, it provides you with a clearLayers method that does what you are trying to achieve.

Therefore, you just add your polygons and markers to that Layer Group (instead of directly to the map), so that you can easily clear them when the user selects a new value. The custom panes remain unaffected.

// Initialize the Layer Group.
// Add it to map so that its children will appear on map.
var layerGroup = L.layerGroup().addTo(map);

// On <select> "change" event:
layerGroup.clearLayers();

// When you have retrieved your data and are ready to convert it to layers:
L.geoJSON(data, {
  style: { // Can be a function as usual.
    pane: 'polygon'
  },
  pointToLayer: function(feature, latlng) {
    return L.circleMarker(latlng, {
      pane: 'POI'
    });
  }
}).addTo(layerGroup); // Add to layerGroup instead of directly to map.
```

Updated JSFiddle: https://jsfiddle.net/Ljetvd2x/4/

As for updating your legend, I am sure you should be able to find some resources on that topic, including here on SO. If you still need help, that should very probably be separated into a new post.

Body:
When user changes the selection of your drop down list, you first try to clear your map by removing your previously created custom panes from the DOM.

There is a very high chance Leaflet does not expect such fiddling with its panes, even if they are custom. That is probably why when you create new custom panes with the same names, Leaflet does not reference them correctly, hence it does not display your new layers in those new panes.

For adding and removing your layers dynamically to / from the map, you should simply use Layer Groups instead. In particular, it provides you with a clearLayers method that does what you are trying to achieve.

Therefore, you just add your polygons and markers to that Layer Group (instead of directly to the map), so that you can easily clear them when the user selects a new value. The custom panes remain unaffected.

// Initialize the Layer Group.
// Add it to map so that its children will appear on map.
var layerGroup = L.layerGroup().addTo(map);

// On <select> "change" event:
layerGroup.clearLayers();

// When you have retrieved your data and are ready to convert it to layers:
L.geoJSON(data, {
  style: { // Can be a function as usual.
    pane: 'polygon'
  },
  pointToLayer: function(feature, latlng) {
    return L.circleMarker(latlng, {
      pane: 'POI'
    });
  }
}).addTo(layerGroup); // Add to layerGroup instead of directly to map.

Updated JSFiddle: https://jsfiddle.net/Ljetvd2x/4/

As for updating your legend, I am sure you should be able to find some resources on that topic, including here on SO. If you still need help, that should very probably be separated into a new post.


问:
Calling a chart from different sheet
I have 12 charts in sheet 'A' in excel. In sheet 'B' there are 2 drop downs and based on that value I want to call a particular chart in sheet 'B'. How do I do that? Can i write a vba program for each chart?
Pls help</p>

答:
People will have downvoted this because you haven't included any information about what you have tried.

It is also not clear what you want to do. You have 12 charts on sheet A, do you want to copy one of these to sheet B when you select a dropdown option? If so, you can attach macro to the dropdown box, and use the chartobject.copy method (link) to copy it to a good place in Sheet B.

You'll need to figure out a method for identifying charts based on the selection in the dropdown too. I also don't know what the second dropdown does or is supposed to do. If it is for comparing, you can attach the same macro to both and use the application.caller method to find out which dropdown invoked the macro, and position the charts accordingly.

Title: Calling a chart from different sheet


问:
New window size
I know that this question is been asked tons of times, but I'm asking not exactly that. This code belongs to website menu bar, so I have to keep this code, otherwise design would be totally different.
Code:

```<code><li class="removable-parent">
<a class="removable-parent" href="http://88.88.209.56:12/player.html" data-
link-type="EXTERNAL"  target= "_blank">
<span id="4884dd90"  class="preview-element Link item-link magic-circle-
holder text-element custom" data-menu-name="PREVIEW_LINK" >Spiller</span>
</a>
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
 } document.getElementById("http://88.88.209.56:12/player.html").onclick=clickHandler
  }
</script>
</li>
</code>```

So how can I make that this code opens window in decided size?

答:
You will need to use javascript.

Get a reference to your  object and handle the click event. In that event, use window.open with the proper parameters to set the width and height of your pop-up window.

Make sure you cancel the original event so you don't end up with two pop-ups.

Something like:

```<code><script>
     function clickHandler() {
        window.open(this.href, "_blank", "width=640,height=480");
        return false; // to prevent default action.
    }

    var elems = document.querySelectorAll(".removable-parent");
    for (var i = 0, elem; elem = elems[i]; ++i) {
        elem.onclick = clickHandler;
    }
</script>
</code>```

Or, if you wish to apply this behavior on one link, first add an id attribute to your link:

```<code><a class="removable-parent" id="myelement" href="http://88.88.209.56:12/player.html" data-link-type="EXTERNAL" target= "_blank">
</code>```

The script should then be simplified so it applies only on that element:

```<code><script>
    function clickHandler() {
        window.open(this.href, "_blank", "width=640,height=480");
        return false; // to prevent default action.
    }
    document.getElementById("myelement").onclick = clickHandler;
</script>
</code>```

Title: New window size

Body:
I know that this question is been asked tons of times, but I'm asking not exactly that. This code belongs to website menu bar, so I have to keep this code, otherwise design would be totally different.
Code:

Spiller

So how can I make that this code opens window in decided size?

Body:
You will need to use javascript.

Get a reference to your  object and handle the click event. In that event, use window.open with the proper parameters to set the width and height of your pop-up window.

Make sure you cancel the original event so you don't end up with two pop-ups.

Something like:

<script>
     function clickHandler() {
        window.open(this.href, "_blank", "width=640,height=480");
        return false; // to prevent default action.
    }

    var elems = document.querySelectorAll(".removable-parent");
    for (var i = 0, elem; elem = elems[i]; ++i) {
        elem.onclick = clickHandler;
    }
</script>

Or, if you wish to apply this behavior on one link, first add an id attribute to your link:

<a class="removable-parent" id="myelement" href="http://88.88.209.56:12/player.html" data-link-type="EXTERNAL" target= "_blank">

The script should then be simplified so it applies only on that element:

<script>
    function clickHandler() {
        window.open(this.href, "_blank", "width=640,height=480");
        return false; // to prevent default action.
    }
    document.getElementById("myelement").onclick = clickHandler;
</script>


问:
Notify user if wrong data type entered (Python 3)
How do I change this code so that the program can notify the user that he/she has entered a text instead of a number? </p>

```<code>Enter_a_Number = int(input("Enter a Number: "))
if Enter_a_Number == str:
    print("Only Numbers Allowed")
</code>```

答:
You need to explore the basics of error-handling.

See Python.org Tutorial - Handling Exceptions

```<code>while (True):
    try:
        Enter_a_Number = int(input("Enter a Number: "))
        break
    except ValueError:
        print("Invalid number")

print(Enter_a_Number)
</code>```

In this specific case, the int() function will 'throw' a ValueError if it can not convert the string to an integer.  You can decide what to do when that happens.

Body:
How do I change this code so that the program can notify the user that he/she has entered a text instead of a number?

Enter_a_Number = int(input("Enter a Number: "))
if Enter_a_Number == str:
    print("Only Numbers Allowed")

Body:
You need to explore the basics of error-handling.

See Python.org Tutorial - Handling Exceptions

while (True):
    try:
        Enter_a_Number = int(input("Enter a Number: "))
        break
    except ValueError:
        print("Invalid number")

print(Enter_a_Number)

In this specific case, the int() function will 'throw' a ValueError if it can not convert the string to an integer.  You can decide what to do when that happens.


问:
SystemJS not loading modules from node_modules
I'm using SystemJS to load a simple JavaScript file:

```<code>define("main", ["require", "exports", "jquery"], function (require, exports, $) {
    "use strict";
    exports.__esModule = true;
    console.log($(document).html());
});
</code>```

I'm loading it like so:

```<code><script>require("systemjs")</script>
<script>
    SystemJS.import('./dist/app.js').then(null, console.error.bind(console));
</script>
</code>```

But I am getting an error when I run it in electron:

GET file:///D:/Projects/myapp/app/jquery net::ERR_FILE_NOT_FOUND

Why is SystemJS not looking for jquery in node_modules like any other sane javascript loader? How do I get it to look there?

答: It turns out the problem was that my compiler hadn't detected the changes yet so the generated file contained code for a different module. It still isn't working the way I want it too, but at least it's not erroring :/</p>

Body:
I'm using SystemJS to load a simple JavaScript file:

define("main", ["require", "exports", "jquery"], function (require, exports, $) {
    "use strict";
    exports.__esModule = true;
    console.log($(document).html());
});

I'm loading it like so:

But I am getting an error when I run it in electron:

GET file:///D:/Projects/myapp/app/jquery net::ERR_FILE_NOT_FOUND

Why is SystemJS not looking for jquery in node_modules like any other sane javascript loader? How do I get it to look there?


问:
Can custom elements' attributes be camelCased?
I have a custom element with attributes:

```<code>class MyElement extends HTMLElement {
    ...
    static get observedAttributes() {
        return ["camelCaseAttribute"];
    }

    set camelCaseAttribute(a) {
        this._a = a;
    }
    ...
 }
</code>```

I use it in my HTML like so:

```<code><my-element camelCaseAttribute="blubb"></my-element>
</code>```

The attribute camelCaseAttribute is not set when writing it in camelCase, but writing it without upper-case-letters works. Why?

答:
This link may help: HTML spec says this about data attributes

A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters.

Body:
I have a custom element with attributes:

class MyElement extends HTMLElement {
    ...
    static get observedAttributes() {
        return ["camelCaseAttribute"];
    }

    set camelCaseAttribute(a) {
        this._a = a;
    }
    ...
 }

I use it in my HTML like so:

<my-element camelCaseAttribute="blubb"></my-element>

The attribute camelCaseAttribute is not set when writing it in camelCase, but writing it without upper-case-letters works. Why?


问:
SwiftyJSON Item At Index Not Working
I have the following dummy JSON data:

```<code>{
 "folder": {
     "id": 1,
     "name": "Home",
     "parent_folder_id": null,
     "num_of_items": 10,
     "num_of_items_complete": 10,
     "children": {
         "folders": [
               {
                   "id": 2,
                   "name": "Identification",
                   "num_of_items": 4,
                   "num_complete": 4
               },
               {
                   "id": 3,
                   "name": "House and Household Equipment",
                   "num_of_items": 6,
                   "num_complete": 2
               },
               {
                   "id": 4,
                   "name": "Insurance",
                   "num_of_items": 4,
                   "num_complete": 3
               },
               {
                   "id": 5,
                   "name": "Owned Items",
                   "num_of_items": 6,
                   "num_complete": 5
               }
        ],
         "input_fields": [
            {
                "id": 1,
                "key": "Something",
                "value": "Dark Side",
                "type": "text"
            }
        ],
        "shortcuts": [

        ]
     }
  }
}
</code>```

And I need to access each child in "children" with an INDEX rather than by it's NAME for a collectionView:

```<code>func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.data["folder"]["children"][section].count
    }
</code>```

But it always returns 0 for the count. Is there anyway I can do this?

答:
Try with this:

```<code>return self.data["folder"]["children"]["folders"].count
</code>```

I think is the only way you can do it.

Title: SwiftyJSON Item At Index Not Working

Body:
I have the following dummy JSON data:

{
 "folder": {
     "id": 1,
     "name": "Home",
     "parent_folder_id": null,
     "num_of_items": 10,
     "num_of_items_complete": 10,
     "children": {
         "folders": [
               {
                   "id": 2,
                   "name": "Identification",
                   "num_of_items": 4,
                   "num_complete": 4
               },
               {
                   "id": 3,
                   "name": "House and Household Equipment",
                   "num_of_items": 6,
                   "num_complete": 2
               },
               {
                   "id": 4,
                   "name": "Insurance",
                   "num_of_items": 4,
                   "num_complete": 3
               },
               {
                   "id": 5,
                   "name": "Owned Items",
                   "num_of_items": 6,
                   "num_complete": 5
               }
        ],
         "input_fields": [
            {
                "id": 1,
                "key": "Something",
                "value": "Dark Side",
                "type": "text"
            }
        ],
        "shortcuts": [

        ]
     }
  }
}

And I need to access each child in "children" with an INDEX rather than by it's NAME for a collectionView:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.data["folder"]["children"][section].count
    }

But it always returns 0 for the count. Is there anyway I can do this?

Body:
Try with this:

return self.data["folder"]["children"]["folders"].count

I think is the only way you can do it.


问:
Cucumber gives Sqlite3 error
I just started using Cucumber, but I am running into a weird error:

```<code>SQLite3::SQLException: no such table: venues: SELECT "venues".* FROM "venues" (ActiveRecord::StatementInvalid)
./app/controllers/venues_controller.rb:5:in `index'
<internal:prelude>:10:in `synchronize'
./features/step_definitions/web_steps.rb:18:in `/^(?:|I )am on (.+)$/'
features/most_popular_bands.feature:8:in `Given I am on the home page'
</code>```

This comes from the Given step, where I mention the home page, which has a list of items from the venues tables. I wonder why Cucumber cannot find that table.

Btw, I am not running it with autotest. I am using bundle exec cucumber.

答: I got it working with rake cucumber.

Title: Cucumber gives Sqlite3 error

Body:
I just started using Cucumber, but I am running into a weird error:

SQLite3::SQLException: no such table: venues: SELECT "venues".* FROM "venues" (ActiveRecord::StatementInvalid)
./app/controllers/venues_controller.rb:5:in `index'
<internal:prelude>:10:in `synchronize'
./features/step_definitions/web_steps.rb:18:in `/^(?:|I )am on (.+)$/'
features/most_popular_bands.feature:8:in `Given I am on the home page'

This comes from the Given step, where I mention the home page, which has a list of items from the venues tables. I wonder why Cucumber cannot find that table.

Btw, I am not running it with autotest. I am using bundle exec cucumber.

Body: I got it working with rake cucumber.


问:
Program cores in openssl when i link it with protobuf-generated file
I have such code in attribute constructor function "ConnectionInit" in file, written in C.

```<code>SSL_load_error_strings();
SSL_library_init();
DefaultSSLConnectionContext = SSL_CTX_new(SSLv23_client_method ());
</code>```

When i link it with protobuf-generated pb.cc file (without calling it's code, just link), it cores with such dump:

```<code>#0 0x00007f269454acea in pthread_rwlock_wrlock () from /lib64/libpthread.so.0
#0 0x00007f269454acea in pthread_rwlock_wrlock () from /lib64/libpthread.so.0
#1 0x00007f26843dbcbb in ?? () from /usr/lib64/libcrypto.so.10
#2 0x00007f26843dba0b in ?? () from /usr/lib64/libcrypto.so.10
#3 0x00007f26843db3bc in ?? () from /usr/lib64/libcrypto.so.10
#4 0x00007f26843dc9b1 in ERR_load_ERR_strings () from /usr/lib64/libcrypto.so.10
#5 0x00007f26843dcb99 in ERR_load_crypto_strings () from /usr/lib64/libcrypto.so.10
#6 0x00007f268471ced9 in SSL_load_error_strings () from /usr/lib64/libssl.so.10
#7 0x00007f26778414f9 in ConnectionInit (verbose=0) at connection.c:79
#8 0x00007f2695a5f74f in _dl_init_internal () from /lib64/ld-linux-x86-64.so.2
#9 0x00007f2695a63f75 in dl_open_worker () from /lib64/ld-linux-x86-64.so.2
#10 0x00007f2695a5f366 in _dl_catch_error () from /lib64/ld-linux-x86-64.so.2
#11 0x00007f2695a6371a in _dl_open () from /lib64/ld-linux-x86-64.so.2
#12 0x00007f2693fa8f66 in dlopen_doit () from /lib64/libdl.so.2
#13 0x00007f2695a5f366 in _dl_catch_error () from /lib64/ld-linux-x86-64.so.2
#14 0x00007f2693fa929c in _dlerror_run () from /lib64/libdl.so.2
#15 0x00007f2693fa8ee1 in dlopen@@GLIBC_2.2.5 () from /lib64/libdl.so.2
</code>```

I examined, if protobuf uses libssl. But it doesn't. How can *.pb.cc file affect my openSSL initialization?

答:
The presence of a protobuf file isn't what is causing your crash. More likely, you have a subtle bug somewhere that is making an invalid memory access. By coincidence, the memory access doesn't happen to do any harm when your program is compiled without the .pb.cc file, but when you add the .pb.cc file, some things move around, and now the bad memory access is doing damage. Probably you'd find that other small changes to your code will also cause the bug to come and go.

To debug memory violations, I highly recommend using Valgrind. All you have to do is install Valgrind and run valgrind myprogram and it will tell you where the illegal memory access is happening.

Body:
I have such code in attribute constructor function "ConnectionInit" in file, written in C.

SSL_load_error_strings();
SSL_library_init();
DefaultSSLConnectionContext = SSL_CTX_new(SSLv23_client_method ());

When i link it with protobuf-generated pb.cc file (without calling it's code, just link), it cores with such dump:

#0 0x00007f269454acea in pthread_rwlock_wrlock () from /lib64/libpthread.so.0
#0 0x00007f269454acea in pthread_rwlock_wrlock () from /lib64/libpthread.so.0
#1 0x00007f26843dbcbb in ?? () from /usr/lib64/libcrypto.so.10
#2 0x00007f26843dba0b in ?? () from /usr/lib64/libcrypto.so.10
#3 0x00007f26843db3bc in ?? () from /usr/lib64/libcrypto.so.10
#4 0x00007f26843dc9b1 in ERR_load_ERR_strings () from /usr/lib64/libcrypto.so.10
#5 0x00007f26843dcb99 in ERR_load_crypto_strings () from /usr/lib64/libcrypto.so.10
#6 0x00007f268471ced9 in SSL_load_error_strings () from /usr/lib64/libssl.so.10
#7 0x00007f26778414f9 in ConnectionInit (verbose=0) at connection.c:79
#8 0x00007f2695a5f74f in _dl_init_internal () from /lib64/ld-linux-x86-64.so.2
#9 0x00007f2695a63f75 in dl_open_worker () from /lib64/ld-linux-x86-64.so.2
#10 0x00007f2695a5f366 in _dl_catch_error () from /lib64/ld-linux-x86-64.so.2
#11 0x00007f2695a6371a in _dl_open () from /lib64/ld-linux-x86-64.so.2
#12 0x00007f2693fa8f66 in dlopen_doit () from /lib64/libdl.so.2
#13 0x00007f2695a5f366 in _dl_catch_error () from /lib64/ld-linux-x86-64.so.2
#14 0x00007f2693fa929c in _dlerror_run () from /lib64/libdl.so.2
#15 0x00007f2693fa8ee1 in dlopen@@GLIBC_2.2.5 () from /lib64/libdl.so.2

I examined, if protobuf uses libssl. But it doesn't. How can *.pb.cc file affect my openSSL initialization?


问:
GIT lets me checkout another branch with uncommitted changes, and alters files in that branch
GIF demonstrating the sequence of events

I create a branch foo, alter a file, then without committing the change I checkout master. GIT lets me do the checkout and the modification is carried over.

I commit this change.

Switch back to the branch foo, alter a file -- coincidentally in a way that makes it identical to the version in master -- then without committing the change I checkout master. This time I get an error "Error: Your local changes to the following files would be overwritten by checkout: index.html Please commit your changes or stash them before you can switch branches.  Aborting"

What is responsible for this inconsistent behavior?

答:
This is a misunderstanding of what branching does, and how it works.

You check out a branch, make a change to a file related to that branch, but you do not commit that change in that branch.  The change you've made is in your uncommitted files space.  This means, so long as your file doesn't conflict with another branch, Git will allow you to carry that uncommited change around with you.

If you add the file to the index, you should get a message like this when you switch branches:

```<code>M   foo
</code>```

That means the file foo was modified, and this is your visual cue.

Now that you've switched over back to your other branch, and you edit the same file with the same content, Git cannot keep track of that because you haven't really told it to.  You've created, in Git's mind, two completely different revisions to the same file, and it results in a conflict.

My recommendation:

Commit the change in your foo branch

Merge the change into master

Since you're in this state...

Rebase master onto foo to ensure their histories line up

Body:
This is a misunderstanding of what branching does, and how it works.

You check out a branch, make a change to a file related to that branch, but you do not commit that change in that branch.  The change you've made is in your uncommitted files space.  This means, so long as your file doesn't conflict with another branch, Git will allow you to carry that uncommited change around with you.

If you add the file to the index, you should get a message like this when you switch branches:

M   foo

That means the file foo was modified, and this is your visual cue.

Now that you've switched over back to your other branch, and you edit the same file with the same content, Git cannot keep track of that because you haven't really told it to.  You've created, in Git's mind, two completely different revisions to the same file, and it results in a conflict.

My recommendation:

Commit the change in your foo branch

Merge the change into master

Since you're in this state...

Rebase master onto foo to ensure their histories line up


问:
Collecting and retrieving the principal variation from an alphabeta framework
I am trying to write a chess engine in python, i can find the best move given a position, but i am struggling to collect the principal variation from that position, the following is what i have tried so far:

```<code>def alphabeta(board, alpha, beta, depth, pvtable):

    if depth == 0:
        return evaluate.eval(board)

    for move in board.legal_moves:
        board.push(move)
        score = -alphabeta(board, -beta, -alpha, depth - 1, pvtable)
        board.pop()
        if score >= beta:
            return beta
        if score > alpha:
            alpha = score
            pvtable[depth-1] = str(move)
    return alpha
</code>```

i am using pvtable[depth - 1] = str(move) to append moves but in the end i find that pvtable contains random non consistent moves, things like ['g1h3', 'g8h6', 'h3g5', 'd8g5'] for the starting position.

I know that similar questions about that have been asked but i still didn't figure out how i can solve this problem.

答:
I think your moves are overwritten when the search reaches the same depth again (in a different branch of the game tree).

This site explains quite good how to retrieve the principal variation: https://web.archive.org/web/20071031100114/http://www.brucemo.com:80/compchess/programming/pv.htm

Applied to your code example, it should be something like this (I didn't test it):

def alphabeta(board, alpha, beta, depth, pline):

    line = []
    if depth == 0:
        return evaluate.eval(board)

    for move in board.legal_moves:
        board.push(move)
        score = -alphabeta(board, -beta, -alpha, depth - 1, line)
        board.pop()
        if score >= beta:
            return beta
        if score > alpha:
            alpha = score
        pline[:] = [str(move)] + line

    return alpha
```

Body:
I am trying to write a chess engine in python, i can find the best move given a position, but i am struggling to collect the principal variation from that position, the following is what i have tried so far:

def alphabeta(board, alpha, beta, depth, pvtable):

    if depth == 0:
        return evaluate.eval(board)

    for move in board.legal_moves:
        board.push(move)
        score = -alphabeta(board, -beta, -alpha, depth - 1, pvtable)
        board.pop()
        if score >= beta:
            return beta
        if score > alpha:
            alpha = score
            pvtable[depth-1] = str(move)
    return alpha

i am using pvtable[depth - 1] = str(move) to append moves but in the end i find that pvtable contains random non consistent moves, things like ['g1h3', 'g8h6', 'h3g5', 'd8g5'] for the starting position.

I know that similar questions about that have been asked but i still didn't figure out how i can solve this problem.


问:
The meaning of android:colorForeground
I'm writing a new theme by copying parts from the builtin Theme.Light, and I don't understand what android:colorForeground means.

The only info I could find is "Default color of foreground imagery" here but I still can't understand what it means.

Can someone please enlighten me?

The layout I use for testing:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:colorForeground="#80ff8000" >

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="First EditText"
        android:colorForeground="#ffffffff" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="First TextView"
        android:colorForeground="#ff000000" />

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:colorForeground="#ffffffff" >
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Second EditText, inside a RelativeLayout"
            android:colorForeground="#ff0000ff"
            android:layout_alignParentTop="true"
            android:layout_marginTop="10dip" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Second TextView, inside a RelativeLayout"
            android:colorForeground="#ff00ff00"
            android:layout_alignParentTop="true" />
    </RelativeLayout>
</LinearLayout>
</code>```

答:
You can see a sample of usage of "android:colorForeground" in SwitchCompat styling:

the style (theme) for it:

```<code><style name="MySwitch" parent="Theme.AppCompat.Light">
    <!-- active thumb & track color (30% transparency) -->
    <item name="colorControlActivated">@color/indigo</item>

    <!-- inactive thumb color -->
    <item name="colorSwitchThumbNormal">@color/pink</item>

    <!-- inactive track color (30% transparency) -->
    <item name="android:colorForeground">@color/grey</item>
</style>
</code>```

and applying:

```<code><android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:theme="@style/MySwitch"/>
</code>```

As you can see, "android:colorForeground" determine inactive track color of SwitchCompat.

"MySwitch" theme extends some activity theme ("Theme.AppCompat.Light") and "android:colorForeground" was overrided to change some default value from the activity theme.

So it's a sample of "android:colorForeground" use. Probably there is not the only meaning..

This is the sample link: http://www.materialdoc.com/switch/

Title: The meaning of android:colorForeground

Body:
I'm writing a new theme by copying parts from the builtin Theme.Light, and I don't understand what android:colorForeground means.

The only info I could find is "Default color of foreground imagery" here but I still can't understand what it means.

Can someone please enlighten me?

The layout I use for testing:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:colorForeground="#80ff8000" >

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="First EditText"
        android:colorForeground="#ffffffff" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="First TextView"
        android:colorForeground="#ff000000" />

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:colorForeground="#ffffffff" >
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Second EditText, inside a RelativeLayout"
            android:colorForeground="#ff0000ff"
            android:layout_alignParentTop="true"
            android:layout_marginTop="10dip" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Second TextView, inside a RelativeLayout"
            android:colorForeground="#ff00ff00"
            android:layout_alignParentTop="true" />
    </RelativeLayout>
</LinearLayout>

Body:
You can see a sample of usage of "android:colorForeground" in SwitchCompat styling:

the style (theme) for it:

<style name="MySwitch" parent="Theme.AppCompat.Light">
    <!-- active thumb & track color (30% transparency) -->
    <item name="colorControlActivated">@color/indigo</item>

    <!-- inactive thumb color -->
    <item name="colorSwitchThumbNormal">@color/pink</item>

    <!-- inactive track color (30% transparency) -->
    <item name="android:colorForeground">@color/grey</item>
</style>

and applying:

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:theme="@style/MySwitch"/>

As you can see, "android:colorForeground" determine inactive track color of SwitchCompat.

"MySwitch" theme extends some activity theme ("Theme.AppCompat.Light") and "android:colorForeground" was overrided to change some default value from the activity theme.

So it's a sample of "android:colorForeground" use. Probably there is not the only meaning..

This is the sample link: http://www.materialdoc.com/switch/


问:
Django test with pgcrypto failing
I'm using a PostgreSQL database for my Django app with pgcryto extension installed. On the production server I manually create a user and then run CREATE EXTENSION pgcrypto; in order to install the extension.

However when I run ./manage.py test it fails because my models are using the EncryptedTextField field from pgcrypto_expressions, the test database that's automatically created does not have the extension installed naturally (since it needs to be enabled explicitly for every database created). How can I 'inject' code / commands between the time Django sets up my test database and begins migrations?

Or rather, how can I enable this extension globally in PostgreSQL?

答: With help primarily from @Alasdair, I was able to setup a dummy app that sits between my app and the rest. I was then able to tweak my dependencies such that the build-server continues to clean up migrations in the real app, while always installing the pgcrypto extension before my app is migrated.</p>

Title: Django test with pgcrypto failing


问:
How to turn arrays into a dataframe?
I have this array, and wish to turn it into a DataFrame, but get an error.

The array k looks like this:

```<code>In[10]: print(k)

Out[10]:
(array([        nan,         nan,         nan, ...,  0.73820147,
        0.7381864 ,  0.73820208]), array([        nan,         nan,         nan, ...,  0.74638753,
        0.74618251,  0.745983  ]))
</code>```

Then I tried to:

```<code>In[11]: df=pd.DataFrame(k)

Out[11]:..

  File "C:\Users\admin\Anaconda2\lib\site-packages\pandas\core\frame.py", line 354, in __init__
    raise ValueError('DataFrame constructor not properly called!')

ValueError: DataFrame constructor not properly called!
</code>```

答:
Your k is a tuple containing your numpy arrays. Try

```<code>df = pd.DataFrame(list(k))
</code>```

instead. This makes a list from your tuple elements.

Title: How to turn arrays into a dataframe?

Body:
I have this array, and wish to turn it into a DataFrame, but get an error.

The array k looks like this:

In[10]: print(k)

Out[10]:
(array([        nan,         nan,         nan, ...,  0.73820147,
        0.7381864 ,  0.73820208]), array([        nan,         nan,         nan, ...,  0.74638753,
        0.74618251,  0.745983  ]))

Then I tried to:

In[11]: df=pd.DataFrame(k)

Out[11]:..

  File "C:\Users\admin\Anaconda2\lib\site-packages\pandas\core\frame.py", line 354, in __init__
    raise ValueError('DataFrame constructor not properly called!')

ValueError: DataFrame constructor not properly called!

Body:
Your k is a tuple containing your numpy arrays. Try

df = pd.DataFrame(list(k))

instead. This makes a list from your tuple elements.


问:
Bit shift in array and write score to another array
I write method to bit shift by one in array and save to second array. Let me explain on below example:

```<code> unsigned int firstNumber[2]  = { 0x00000001, 0x8FFFFFFF };
 unsigned int resultNumber[2];
</code>```

And result should be:

```<code>unsigned int resultNumber[2] = { 0x00000000, 0xC7FFFFFF };
</code>```

Below this is my function:

```<code>void bitShiftByOneInRight_1(unsigned int firstNumber[2], unsigned int resultNumber[2])
{
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {
        resultNumber[i] = 0;
        //  example        11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        resultNumber[i] = firstNumber[i] >> 1;
        resultNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled  = lastBit;
    }
}
</code>```

I get answer as the same array firstNumber[2]:

```<code>unsigned int resultNumber[2] = { 0x00000001, 0x8FFFFFFF };
</code>```

Simple example, we have array:
 [0b00000001, 0b01111111] then answer should be
 [0b00000000, 0b10111111]

Furthermore when function is this form, which mean use one argument as input and output method, work correctly:

```<code>void bitShiftByOneInRight(unsigned int firstNumber[2]) {
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {

        //  example         11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        firstNumber[i] = firstNumber[i] >> 1;
        firstNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled = lastBit;
    }

}
</code>```

Anyone know what I make wrong?
Each answer is welcome for me! Thanks

答:
Did you take the one argument form and tweak it so it has separate input and output arguments? Look more closely at these two lines, they aren't doing what you think at first glance.</p>

```<code>    resultNumber[i] = firstNumber[i] >> 1;
    resultNumber[i] = firstNumber[i] | lastBitEnabled;
</code>```

Body:
I write method to bit shift by one in array and save to second array. Let me explain on below example:

 unsigned int firstNumber[2]  = { 0x00000001, 0x8FFFFFFF };
 unsigned int resultNumber[2];

And result should be:

unsigned int resultNumber[2] = { 0x00000000, 0xC7FFFFFF };

Below this is my function:

void bitShiftByOneInRight_1(unsigned int firstNumber[2], unsigned int resultNumber[2])
{
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {
        resultNumber[i] = 0;
        //  example        11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        resultNumber[i] = firstNumber[i] >> 1;
        resultNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled  = lastBit;
    }
}

I get answer as the same array firstNumber[2]:

unsigned int resultNumber[2] = { 0x00000001, 0x8FFFFFFF };

Simple example, we have array:
 [0b00000001, 0b01111111] then answer should be
 [0b00000000, 0b10111111]

Furthermore when function is this form, which mean use one argument as input and output method, work correctly:

void bitShiftByOneInRight(unsigned int firstNumber[2]) {
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {

        //  example         11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        firstNumber[i] = firstNumber[i] >> 1;
        firstNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled = lastBit;
    }

}

Anyone know what I make wrong?
Each answer is welcome for me! Thanks

Body:
Did you take the one argument form and tweak it so it has separate input and output arguments? Look more closely at these two lines, they aren't doing what you think at first glance.

    resultNumber[i] = firstNumber[i] >> 1;
    resultNumber[i] = firstNumber[i] | lastBitEnabled;


问:
How to get ID of the Last Inserted Record in SQL using ASP.net
Here is my code

```<code> protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
    {
        string clientId = Context.User.Identity.GetUserId();

        if (clientId != null)
        {

            int id = Convert.ToInt32(Request.QueryString["id"]);
            customize1 customize = new customize1
            {
                client_id = clientId,
                product_id = id,
                paper_type = Labelpt.Text,
                corner = Labelpc.Text,
                shipping_type = Labelsp.Text,
                text = TextBox3.Text,

                amount = Convert.ToInt32(lbResult.Text)

            };
            customizeModel model = new customizeModel();
            Label9.Text = model.Insertcustomize(customize);
            con.Open();
            SqlCommand cmd2 = con.CreateCommand();
            cmd2.CommandType = CommandType.Text;
            cmd2.CommandText = "select top 1 * from customize1 where client_id='"+clientId+"' order by Id desc ";
            cmd2.ExecuteNonQuery();
            DataTable dt2 = new DataTable();
            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
            da2.Fill(dt2);
            foreach (DataRow dr2 in dt2.Rows)
            {
                customizeid = dr2["Id"].ToString();
            }
            con.Close();
        }
    }
}
</code>```

I need the last row id but my query does not generate any value.I also check my query in SSMS and query is working fine but in asp it is not generating any data and for inserting record i used the concept of class and entity relationship.
Any Solution.

答:
Brother there are two ways:

One is when you insert your row place after the Insert query this:

```<code>SELECT SCOPE_IDENTITY()
</code>```

For example:

```<code>INSERT INTO table_name (column1, column2, column3, ...)
        VALUES (value1, value2, value3, ...);
SELECT SCOPE_IDENTITY()
</code>```

It gives the inserted ID back.

The second way is this query;

```<code>SELECT id FROM table ORDER BY id DESC LIMIT 1
</code>```

If you keep struggling with problems be open to ask more.

Body:
Here is my code

 protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
    {
        string clientId = Context.User.Identity.GetUserId();

        if (clientId != null)
        {

            int id = Convert.ToInt32(Request.QueryString["id"]);
            customize1 customize = new customize1
            {
                client_id = clientId,
                product_id = id,
                paper_type = Labelpt.Text,
                corner = Labelpc.Text,
                shipping_type = Labelsp.Text,
                text = TextBox3.Text,

                amount = Convert.ToInt32(lbResult.Text)

            };
            customizeModel model = new customizeModel();
            Label9.Text = model.Insertcustomize(customize);
            con.Open();
            SqlCommand cmd2 = con.CreateCommand();
            cmd2.CommandType = CommandType.Text;
            cmd2.CommandText = "select top 1 * from customize1 where client_id='"+clientId+"' order by Id desc ";
            cmd2.ExecuteNonQuery();
            DataTable dt2 = new DataTable();
            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
            da2.Fill(dt2);
            foreach (DataRow dr2 in dt2.Rows)
            {
                customizeid = dr2["Id"].ToString();
            }
            con.Close();
        }
    }
}

I need the last row id but my query does not generate any value.I also check my query in SSMS and query is working fine but in asp it is not generating any data and for inserting record i used the concept of class and entity relationship.
Any Solution.

Body:
Brother there are two ways:

One is when you insert your row place after the Insert query this:

SELECT SCOPE_IDENTITY()

For example:

INSERT INTO table_name (column1, column2, column3, ...)
        VALUES (value1, value2, value3, ...);
SELECT SCOPE_IDENTITY()

It gives the inserted ID back.

The second way is this query;

SELECT id FROM table ORDER BY id DESC LIMIT 1

If you keep struggling with problems be open to ask more.


问:
Unity EditorGUI.PropertyField can't fully disable array or List
So, here is the code:

```<code>// ReadOnlyAttribyte,cs
public class ReadOnlyAttribute : PropertyAttribute
{

}

// ReadOnlyDrawer.cs
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer
{
 public override float GetPropertyHeight(SerializedProperty property,
                                         GUIContent label)
 {
     return EditorGUI.GetPropertyHeight(property, label, true);
 }

 public override void OnGUI(Rect position,
                            SerializedProperty property,
                            GUIContent label)
 {
     GUI.enabled = false;
     EditorGUI.PropertyField(position, property, label, true);
     GUI.enabled = true;
 }
}

// test
[System.Serializable]
public class GridObjectData : ScriptableObject
{
    [ReadOnly]
    public int ID;

[ReadOnly]
public List<GridCell> Grid;
}
</code>```

Here is a simple custom attribute and attribute drawer that allows us to disable all marked(by [ReadOnly]) fields to be disabled in GUI. So the elements of the List are disabled, however the size of the list is still enabled in GUI. How could I fix that ?

Thank you.

Update:
Please take a look how it looks in the inspector

答:
The problem is that your Property Drawer is used for rendering each element (property) in the list, and not the list itself as a whole.

As such. every property does become read only, but the list object itself is still rendered the same, and the way Unity presents it is by showing the "Size" property.

Body:
So, here is the code:

// ReadOnlyAttribyte,cs
public class ReadOnlyAttribute : PropertyAttribute
{

}

// ReadOnlyDrawer.cs
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer
{
 public override float GetPropertyHeight(SerializedProperty property,
                                         GUIContent label)
 {
     return EditorGUI.GetPropertyHeight(property, label, true);
 }

 public override void OnGUI(Rect position,
                            SerializedProperty property,
                            GUIContent label)
 {
     GUI.enabled = false;
     EditorGUI.PropertyField(position, property, label, true);
     GUI.enabled = true;
 }
}

// test
[System.Serializable]
public class GridObjectData : ScriptableObject
{
    [ReadOnly]
    public int ID;

[ReadOnly]
public List<GridCell> Grid;
}

Here is a simple custom attribute and attribute drawer that allows us to disable all marked(by [ReadOnly]) fields to be disabled in GUI. So the elements of the List are disabled, however the size of the list is still enabled in GUI. How could I fix that ?

Thank you.

Update:
Please take a look how it looks in the inspector


问:
Splitting time column into start time / end time columns
I have a table that contains information regarding what they've done throughout the day.  I need to get the start time/end time for each task.

Currently I am able to pull the timestamp of each task, but I am hoping to create Start Times and End Times columns.  Start time would be the timestamp from the previous row, and end time would be the timestamp from the current row.

Is there any simple way to do this?  Here is the query that I am currently using.

```<code>select
Timestamp,
Sku,
Station,
Username,
ActionType
from OverallLogs

where
and ActionType = 'Put'
and Username = 'Name'
and timestamp < DateAdd(Day, DateDiff(Day, 0, GetDate())+1, 0)
AND timestamp >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)

Order by timestamp desc
</code>```

答:
you might want to use sql cte option, look for some help on the link, SQL Find difference between previous and current row

My suggestion would be keep single record for activity, if your first record is start and next is end of that task.

If you do not want to change schema, then may add one more column depicting the task type column that it was a start or end. It will help you in future in queries.

Body:
I have a table that contains information regarding what they've done throughout the day.  I need to get the start time/end time for each task.

Currently I am able to pull the timestamp of each task, but I am hoping to create Start Times and End Times columns.  Start time would be the timestamp from the previous row, and end time would be the timestamp from the current row.

Is there any simple way to do this?  Here is the query that I am currently using.

select
Timestamp,
Sku,
Station,
Username,
ActionType
from OverallLogs

where
and ActionType = 'Put'
and Username = 'Name'
and timestamp < DateAdd(Day, DateDiff(Day, 0, GetDate())+1, 0)
AND timestamp >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)

Order by timestamp desc


问:
How can I get greasemonkey to call a function on a page after it loads
I have a very simple greasemonkey script that I want to call an already existing javascript function on the page. I've read the documentation and nothing seems to work</p>

```<code>window.setTimeout(function() {
    alert('test') // This alert works, but nothing after it does
    myFunction() // undefined
    window.myFunction() // undefined
    document.myFunction() // undefined
}, 1000);
</code>```

答:
One way to call a function in the original page is like this:

```<code>location.href = "javascript:void(myFunction());";
</code>```

It is a bit ugly. There is also the unsafeWindow provided by GreaseMonkey too, but the authors advise against using it.

```<code>unsafeWindow.myFunction();
</code>```

Looks neater but make sure you understand the ramifications. From the manual:

unsafeWindow bypasses Greasemonkey's
  XPCNativeWrapper-based security model,
  which exists to make sure that
  malicious web pages cannot alter
  objects in such a way as to make
  greasemonkey scripts (which execute
  with more privileges than ordinary
  Javascript running in a web page) do
  things that their authors or users did
  not intend. User scripts should
  therefore avoid calling or in any
  other way depending on any properties
  on unsafeWindow - especally if if they
  are executed for arbitrary web pages,
  such as those with @include *, where
  the page authors may have subverted
  the environment in this way.

In other words, your script elevates the privileges available to the original page script if you use unsafeWindow.

OwnerDisplayName: Asa Ayers

Body:
I have a very simple greasemonkey script that I want to call an already existing javascript function on the page. I've read the documentation and nothing seems to work

window.setTimeout(function() {
    alert('test') // This alert works, but nothing after it does
    myFunction() // undefined
    window.myFunction() // undefined
    document.myFunction() // undefined
}, 1000);

Body:
One way to call a function in the original page is like this:

location.href = "javascript:void(myFunction());";

It is a bit ugly. There is also the unsafeWindow provided by GreaseMonkey too, but the authors advise against using it.

unsafeWindow.myFunction();

Looks neater but make sure you understand the ramifications. From the manual:

unsafeWindow bypasses Greasemonkey's
  XPCNativeWrapper-based security model,
  which exists to make sure that
  malicious web pages cannot alter
  objects in such a way as to make
  greasemonkey scripts (which execute
  with more privileges than ordinary
  Javascript running in a web page) do
  things that their authors or users did
  not intend. User scripts should
  therefore avoid calling or in any
  other way depending on any properties
  on unsafeWindow - especally if if they
  are executed for arbitrary web pages,
  such as those with @include *, where
  the page authors may have subverted
  the environment in this way.

In other words, your script elevates the privileges available to the original page script if you use unsafeWindow.

OwnerDisplayName: Paul Dixon


问:
Exception class for forms
Should form errors throw exceptions, for example if the username is incorrect, or password is wrong/too short .etc

I've used exceptions with forms, however when the exception is thrown only the exceptions is shown and not the form and which field the error occurred on, an excerpt from my exception class is as follows :

throw new InputException($field, $message);

e.g.
//username too short:

throw new InputException('username', 'Username must be 6 or more characters');

And then this message should appear underneath the username text field. The main thing I want is for the form to show when the exception is thrown.

答:
Exceptions do not have to be thrown. For user interfaces, I will usually stack them.

Consider the following example (built in Zend Framework):

```<code>class MyController extends Zend_Controller_Action {

   protected $_exceptions = array();

   // Controller action, which displays a form
   public function indexAction() {
      $username = $this->_getParam('username');
      if (empty($username)) {
         $this->addException(
             new InvalidArgumentException('Username cannot be empty')
         );
      }
      // more handling code...
   }

   public function addException(Exception $e) {
      $this->exceptions[] = $e;
   }

   // executing just before displaying the user interface
   public function postDispatch() {
      // assign the exception stack to the view file
      $this->view->exceptions = $this->_exceptions;
      parent::postDispatch();
   }

}
</code>```

You can still instanciate Exception classes without throwing them. In the example above, I stack them in the controller, and pass them to the view before displaying it. In the view, I can simply do:

```<code>if (!empty($this->exceptions)) {
   foreach ($this->exceptions as $exception) {
      // display something
   }
}
</code>```

Of course, you can customize your exception classes (i.e.: an InputException like in your example), and you can still throw them if necessary, like in AJAX requests and such.

Hope this helps!

Title: Exception class for forms

Body:
Exceptions do not have to be thrown. For user interfaces, I will usually stack them.

Consider the following example (built in Zend Framework):

class MyController extends Zend_Controller_Action {

   protected $_exceptions = array();

   // Controller action, which displays a form
   public function indexAction() {
      $username = $this->_getParam('username');
      if (empty($username)) {
         $this->addException(
             new InvalidArgumentException('Username cannot be empty')
         );
      }
      // more handling code...
   }

   public function addException(Exception $e) {
      $this->exceptions[] = $e;
   }

   // executing just before displaying the user interface
   public function postDispatch() {
      // assign the exception stack to the view file
      $this->view->exceptions = $this->_exceptions;
      parent::postDispatch();
   }

}

You can still instanciate Exception classes without throwing them. In the example above, I stack them in the controller, and pass them to the view before displaying it. In the view, I can simply do:

if (!empty($this->exceptions)) {
   foreach ($this->exceptions as $exception) {
      // display something
   }
}

Of course, you can customize your exception classes (i.e.: an InputException like in your example), and you can still throw them if necessary, like in AJAX requests and such.

Hope this helps!


问:
Aborting task that contains never-ending library method (no ability of checking cancellation requests)
I use Pcap.Net for traffic monitoring, and I need it to receive packets until user requests cancellation. I create monitoring task this way (simplified):

```<code>var task1 = Task.Run(() => { communicator.ReceivePackets(0, PacketHandlerCallback); } /*, token*/);
</code>```

Here 0 says execution of ReceivePackets never ends, PacketHandlerCallback is a method that will be executed for each received packet. ReceivePackets is synchronous and does not support cancellation. Generally in my question it could be any other endless synchronous method which code we cannot edit.

The question is how to stop this method execution?

Just passing cancellation token to the task doesn't help because we should also explicitly check if cancellation is requested, e. g. by calling token.throwIfCancellationRequested().

Passing token to callback method is not a solution too because this method will not be invoked until new packet is received but I'd like to stop my task immediately after cancellation.

Using BackgroundWorker causes the same question since we should check CancellationPending.

Creating task2 that periodically checks cancellation requests and then writing var task = Task.WhenAny(task1, task2) doesn't help since ReceivePackets will still be executing.

Should I use Thread.Abort() or maybe there is any other elegant solution?

There are similar questions about TPL on SO but I cannot find any simple and helpful answer.

答:
In situations where you can't cancel the much better solution than Thread.Abort is to put the non-cancelable code in to a separate process you can kill.

This gives you a guaranteed release of all resources the thread held because the OS will release any held unmanaged OS resources like handles when a process exits, you don't get this behavior if you abort a thread or if you use a separate AppDomain you shutdown.

When you have a 2nd process written you can use something like WCF over named pipes so you can interact with the external process like you would any other normal function that is inside your process.

Body:
I use Pcap.Net for traffic monitoring, and I need it to receive packets until user requests cancellation. I create monitoring task this way (simplified):

var task1 = Task.Run(() => { communicator.ReceivePackets(0, PacketHandlerCallback); } /*, token*/);

Here 0 says execution of ReceivePackets never ends, PacketHandlerCallback is a method that will be executed for each received packet. ReceivePackets is synchronous and does not support cancellation. Generally in my question it could be any other endless synchronous method which code we cannot edit.

The question is how to stop this method execution?

Just passing cancellation token to the task doesn't help because we should also explicitly check if cancellation is requested, e. g. by calling token.throwIfCancellationRequested().

Passing token to callback method is not a solution too because this method will not be invoked until new packet is received but I'd like to stop my task immediately after cancellation.

Using BackgroundWorker causes the same question since we should check CancellationPending.

Creating task2 that periodically checks cancellation requests and then writing var task = Task.WhenAny(task1, task2) doesn't help since ReceivePackets will still be executing.

Should I use Thread.Abort() or maybe there is any other elegant solution?

There are similar questions about TPL on SO but I cannot find any simple and helpful answer.


问:
How do you add code with quotes to a file using batch?
I am trying to create a batch file that will create a file that will send an email through powershell. It does many things, but email is just a snippet of it. Here is what I have so far:

REM Creates batch file with contents of the powershell script
echo "I need to add the below powershell script" > email.bat
echo "into email.bat with all the quotes included">> email.bat
echo "like what I'm doing now with appending text">> email.bat
REM powershell script to send email.

$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com")

if( $Env:SmtpUseCredentials -eq "true" ) {
    $credentials = new-object Net.NetworkCredential("username","password")
    $smtp.Credentials = $credentials
}
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "myemail@gmail.com"
$objMailMessage.To.Add("whereImsendingto@gmail.com")
$objMailMessage.Subject = "Logs for today"
$objMailMessage.Body = "(the logs)"

$smtp.send($objMailMessage)```

In batch, I have the way to append text to another file down if what I'm adding does not have quotes, but I need to add text that includes quotes to the file.

答:
Why don't you simply echo whithout quotes and escape possible chars <>|& with a caret ^ and double percent signs?

In a (code block) you've to also escape closing parentheses ^)

```<code>@Echo off
( Echo:$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com"^)
  Echo:
  Echo:if( $Env:SmtpUseCredentials -eq "true" ^) {
  Echo:    $credentials = new-object Net.NetworkCredential("username","password"^)
  Echo:    $smtp.Credentials = $credentials
  Echo:}
  Echo:$objMailMessage = New-Object System.Net.Mail.MailMessage
  Echo:$objMailMessage.From = "myemail@gmail.com"
  Echo:$objMailMessage.To.Add("whereImsendingto@gmail.com"^)
  Echo:$objMailMessage.Subject = "Logs for today"
  Echo:$objMailMessage.Body = "(the logs^)"
  Echo:
  Echo:$smtp.send($objMailMessage^)
) > "SomeFile.ps1"
</code>```

Body:
I am trying to create a batch file that will create a file that will send an email through powershell. It does many things, but email is just a snippet of it. Here is what I have so far:

REM Creates batch file with contents of the powershell script
echo "I need to add the below powershell script" > email.bat
echo "into email.bat with all the quotes included">> email.bat
echo "like what I'm doing now with appending text">> email.bat
REM powershell script to send email.

$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com")

if( $Env:SmtpUseCredentials -eq "true" ) {
    $credentials = new-object Net.NetworkCredential("username","password")
    $smtp.Credentials = $credentials
}
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "myemail@gmail.com"
$objMailMessage.To.Add("whereImsendingto@gmail.com")
$objMailMessage.Subject = "Logs for today"
$objMailMessage.Body = "(the logs)"

$smtp.send($objMailMessage)

In batch, I have the way to append text to another file down if what I'm adding does not have quotes, but I need to add text that includes quotes to the file.

Body:
Why don't you simply echo whithout quotes and escape possible chars <>|& with a caret ^ and double percent signs?

In a (code block) you've to also escape closing parentheses ^)

@Echo off
( Echo:$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com"^)
  Echo:
  Echo:if( $Env:SmtpUseCredentials -eq "true" ^) {
  Echo:    $credentials = new-object Net.NetworkCredential("username","password"^)
  Echo:    $smtp.Credentials = $credentials
  Echo:}
  Echo:$objMailMessage = New-Object System.Net.Mail.MailMessage
  Echo:$objMailMessage.From = "myemail@gmail.com"
  Echo:$objMailMessage.To.Add("whereImsendingto@gmail.com"^)
  Echo:$objMailMessage.Subject = "Logs for today"
  Echo:$objMailMessage.Body = "(the logs^)"
  Echo:
  Echo:$smtp.send($objMailMessage^)
) > "SomeFile.ps1"


问:
Comprehensive list of command line flags/options for Burn/bootstrapper in WiX
I can't seem to find a comprehensive list of commands, flags, and things I can do from the command line.

答:
WiX installers will take the standard Windows Installer commandline switches, as documented in Command-Line Options.

Any additional parameters that are added to the commandline will be passed on to your installer if you're using a custom Burn installer.

This was confirmed by the primary WiX maintainer on the WiX mailing list: http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Running-Burn-driven-installer-in-quiet-mode-command-line-parameters-tp5913001p5913628.html

Yes, absolutely. Burn supports parsing the "standard package switches"  and will pass extra switches on the Bootstrapper
Application so it can apply  additional behavior.

The complete list is dependent on the Bootstrapper Application you pick.  The wixstdba supports only the "standard package switches":

```<code> -q, -quiet, -s, -silent = silent install
 -passive = progress bar only install
 -norestart = suppress any restarts
 -forcerestart = restart no matter what (I don't know why this is still  around)
 -promptrestart = prompt if a restart is required (default)
 -layout = create a local image of the bootstrapper (i.e. download files so  they can be burned to DVD)
 -l, -log = log to a specific file (default is controled by bundle developer)
 -uninstall = uninstall
 -repair = repair (or install if not installed)
 -package,-update = install (default if no -uninstall or -repair)
</code>```

Yes, as noted above extra command-line parameters are passed to the >  BootstrapperApplication and it can set Variables to flow into Chained  Packages (ExePackage XxxCommand attributes or
MsiPackage/MsiProperty  element).

You may want to also be familiar with the standard installer command line parameters: Microsoft Standard Installer Command-Line Options

Body:
WiX installers will take the standard Windows Installer commandline switches, as documented in Command-Line Options.

Any additional parameters that are added to the commandline will be passed on to your installer if you're using a custom Burn installer.

This was confirmed by the primary WiX maintainer on the WiX mailing list: http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Running-Burn-driven-installer-in-quiet-mode-command-line-parameters-tp5913001p5913628.html

Yes, absolutely. Burn supports parsing the "standard package switches"  and will pass extra switches on the Bootstrapper
Application so it can apply  additional behavior.

The complete list is dependent on the Bootstrapper Application you pick.  The wixstdba supports only the "standard package switches":

 -q, -quiet, -s, -silent = silent install
 -passive = progress bar only install
 -norestart = suppress any restarts
 -forcerestart = restart no matter what (I don't know why this is still  around)
 -promptrestart = prompt if a restart is required (default)
 -layout = create a local image of the bootstrapper (i.e. download files so  they can be burned to DVD)
 -l, -log = log to a specific file (default is controled by bundle developer)
 -uninstall = uninstall
 -repair = repair (or install if not installed)
 -package,-update = install (default if no -uninstall or -repair)

Yes, as noted above extra command-line parameters are passed to the >  BootstrapperApplication and it can set Variables to flow into Chained  Packages (ExePackage XxxCommand attributes or
MsiPackage/MsiProperty  element).

You may want to also be familiar with the standard installer command line parameters: Microsoft Standard Installer Command-Line Options


问:
Creating a Div that pops and then disppear in javascript
I am trying to write in javascript a code that shows a div in a random place, then blacks it out after 1000ms and waits for a user's click. My problem is in blackening it (the line that start in //). Could you explain me what's wrong in this?  </p>

```<code> <style type="text/css">
    #test {
    position:absolute;
    width:40px;
    height:40px;
    background-color:#d2fcd9;
}

  </style>

  <title></title>

<script type="text/javascript">//<![CDATA[
$(function(){
$('#test').click(function() {
    var docHeight = $(document).height(),
        docWidth = $(document).width(),
        $div = $('#test'),
        divWidth = $div.width(),
        divHeight = $div.height(),
        heightMax = docHeight - divHeight,
        widthMax = docWidth - divWidth;

    $div.css({
        left: Math.floor( Math.random() * widthMax ),
        top: Math.floor( Math.random() * heightMax ),

    });

    //setTimeout(function() {    $div.css({background-color: '#000000'  }); },          300);

});
});//]]>

</script>

</head>

<body bgcolor="#000000">
  <div id="test" style="left: 1168px; top: 222px;"></div>
</code>```

答:
I would suggest using a toggle.
Write $('#test').toggle(); Make sure to target the div id.
This will add on the first click and remove on the second click. Additionally, you can set the time on it to whatever you see fit. http://api.jquery.com/toggle/.  </p>

Body:
I am trying to write in javascript a code that shows a div in a random place, then blacks it out after 1000ms and waits for a user's click. My problem is in blackening it (the line that start in //). Could you explain me what's wrong in this?

  <title></title>