问:
JQuery .center is not a function
I am working on JQuery. I am getting this error. I ma trying to find out the root cause but i am not able to find it. If any one can help me out that would be really great.

JS ERROR:

```<code>Uncaught TypeError: $(...).center is not a function
at HTMLDivElement.<anonymous> (myjs:879)
at HTMLDivElement.opt.complete (jquery-1.8.3.js:9154)
at fire (jquery-1.8.3.js:974)
at Object.add [as done] (jquery-1.8.3.js:1020)
at Animation (jquery-1.8.3.js:8719)
at HTMLDivElement.doAnimation (jquery-1.8.3.js:9034)
at Function.dequeue (jquery-1.8.3.js:1895)
at HTMLDivElement.<anonymous> (jquery-1.8.3.js:1938)
at Function.each (jquery-1.8.3.js:611)
at init.each (jquery-1.8.3.js:241)
</code>```

My Script:

```<code>function centerdiv() {
    $('#id').show(0, function () {
         $('#id1').css('z-index','5');
        $('body').css('overflow', 'hidden');
        $('.class').center();
    });
}
</code>```

All JQuery functions are working and i am not sure why it is stating .center as not a function.

答:
Your error is telling you that there is no $.center().  But, you can make one!

Here's an example by from this answer by Tony L.

jQuery.fn.center = function(parent) {
    if (parent) {
        parent = this.parent();
    } else {
        parent = window;
    }
    this.css({
        "position": "absolute",
        "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
        "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
    });
return this;
}

$("div.target:nth-child(1)").center(true); // Center relitive to parent
$("div.target:nth-child(2)").center(false); // Center relitive to window```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.container{
    width:200px;
    height:200px;
    border:1px solid #555;
    position:relative;
    top:10px;
    left:10px;
}

div.target{
    width:60px;
    height:60px;
    color:white;
    background:rgba(30,30,30,.7);
    border-radius: 10px;
    text-align:center;
}</code>```

1
parent

2
window

```

Title: JQuery .center is not a function

Body:
I am working on JQuery. I am getting this error. I ma trying to find out the root cause but i am not able to find it. If any one can help me out that would be really great.

JS ERROR:

Uncaught TypeError: $(...).center is not a function
at HTMLDivElement.<anonymous> (myjs:879)
at HTMLDivElement.opt.complete (jquery-1.8.3.js:9154)
at fire (jquery-1.8.3.js:974)
at Object.add [as done] (jquery-1.8.3.js:1020)
at Animation (jquery-1.8.3.js:8719)
at HTMLDivElement.doAnimation (jquery-1.8.3.js:9034)
at Function.dequeue (jquery-1.8.3.js:1895)
at HTMLDivElement.<anonymous> (jquery-1.8.3.js:1938)
at Function.each (jquery-1.8.3.js:611)
at init.each (jquery-1.8.3.js:241)

My Script:

function centerdiv() {
    $('#id').show(0, function () {
         $('#id1').css('z-index','5');
        $('body').css('overflow', 'hidden');
        $('.class').center();
    });
}

All JQuery functions are working and i am not sure why it is stating .center as not a function.

Body:
Your error is telling you that there is no $.center().  But, you can make one!

Here's an example by from this answer by Tony L.

jQuery.fn.center = function(parent) {
    if (parent) {
        parent = this.parent();
    } else {
        parent = window;
    }
    this.css({
        "position": "absolute",
        "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
        "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
    });
return this;
}

$("div.target:nth-child(1)").center(true); // Center relitive to parent
$("div.target:nth-child(2)").center(false); // Center relitive to window

div.container{
    width:200px;
    height:200px;
    border:1px solid #555;
    position:relative;
    top:10px;
    left:10px;
}

div.target{
    width:60px;
    height:60px;
    color:white;
    background:rgba(30,30,30,.7);
    border-radius: 10px;
    text-align:center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="target">1<br>parent</div>
    <div class="target">2<br>window</div>
</div>


来源: stackexchange

问:
Handle SAML POST and still maintaining CSRF in Laravel 5
I use this package = https://github.com/aacotroneo/laravel-saml2
I configured everything in the SP and iDP sections in saml2_settings.php as instructed.

STEPS

I go to : /admin/login
I got redirected and landed on my iDP log-in page immediately, it is a correct behavior.

I log-in with the proper username and password.

After successfully authenticated by my iDP, I got the SAML Response from my iDP like this sample

```<code>{
"SAMLResponse": "PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnN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D0iaWQtWEVRcWVNZFRiRHRaLXNhaFN4ZnNYdVA2MWlJLSIgU2Vzc2lvbk5v\r\ndE9uT3JBZnRlcj0iMjAxNy0wMy0yOFQyMDozMzo1M1oiPjxzYW1sOkF1dGhuQ29u\r\ndGV4dD48c2FtbDpBdXRobkNvbnRleHRDbGFzc1JlZj51cm46b2FzaXM6bmFtZXM6\r\ndGM6U0FNTDoyLjA6YWM6Y2xhc3NlczpQYXNzd29yZFByb3RlY3RlZFRyYW5zcG9y\r\ndDwvc2FtbDpBdXRobkNvbnRleHRDbGFzc1JlZj48L3NhbWw6QXV0aG5Db250ZXh0\r\nPjwvc2FtbDpBdXRoblN0YXRlbWVudD48L3NhbWw6QXNzZXJ0aW9uPjwvc2FtbHA6\r\nUmVzcG9uc2U+\r\n",
"RelayState": "https://testserver.benunets.com/admin/login"
}
</code>```

kernel.php

I can only see this response only because I comment out my CFRF token on my app/Http/kernel.php

```<code>// \App\Http\Middleware\VerifyCsrfToken::class,
</code>```

ROUTE

```<code>Route::post('admin/secure/dashboard', 'SAMLController@post');
</code>```

CONTROLLER

```<code> public function post(){
    return Input::all();
}
</code>```

What is the best practice to deal with SAML POST and still maintaining CSRF protection ?

Should I create a middleware or anything similar to that ?

答:
You may exclude your endpoint by adding it to the $except property of the VerifyCsrfToken middleware.

After that you may want to add your own middleware to check if the post request came from an origin you explicitly accept.

The documentation of the package also states that you should configure a middleware group in te config which at least needs the StartSession middleware. So you can make a special middleware-group which excludes the VerifyCsrfToken middleware. However, I do believe it would be better to exclude the endpoint, and add your own middleware check.

Also, you are referencing the url admin/secure/dashboard. Are you using this for debugging the POST request? Because I believe the actual endpoint for iDP needs to be https://your-url.com/saml2/acs (unless you changed the default configuration). This page will use the post data to trigger an event with which you can login the appropriate user.

ContentLicense: CC BY-SA 3.0

Body:
I use this package = https://github.com/aacotroneo/laravel-saml2
I configured everything in the SP and iDP sections in saml2_settings.php as instructed.

STEPS

I go to : /admin/login
I got redirected and landed on my iDP log-in page immediately, it is a correct behavior.

I log-in with the proper username and password.

After successfully authenticated by my iDP, I got the SAML Response from my iDP like this sample

{
"SAMLResponse": "PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6\r\nU0FNTDoyLjA6cHJvdG9jb2wiIERlc3RpbmF0aW9uPSJodHRwczovL3Rlc3RzZXJ2\r\nZXIuYmVudW5ldHMuY29tL2FkbWluL3NlY3VyZS9kYXNoYm9hcmQiIElEPSJpZC1C\r\nNlBFSnhLNFhGWUg3T1hzbGZLU2trbGt0YmMtIiBJblJlc3BvbnNlVG89Ik9ORUxP\r\nR0lOXzIxNjFiNTA1OTFmNjc1ZmUzZGM0MmZlYzRlZDJkOGU1MWRlZmQ2ZmQiIElz\r\nc3VlSW5zdGFudD0iMjAxNy0wMy0yOFQxOTozMzo1M1oiIFZlcnNpb249IjIuMCI+\r\nPHNhbWw6SXNzdWVyIHhtbG5zOnNhbWw9InVybjpvYXNpczpuYW1lczp0YzpTQU1M\r\nOjIuMDphc3NlcnRpb24iIEZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6\r\nMi4wOm5hbWVpZC1mb3JtYXQ6ZW50aXR5Ij5UZWxlbmV0PC9zYW1sOklzc3Vlcj48\r\nc2FtbHA6U3RhdHVzPjxzYW1scDpTdGF0dXNDb2RlIFZhbHVlPSJ1cm46b2FzaXM6\r\nbmFtZXM6dGM6U0FNTDoyLjA6c3RhdHVzOlN1Y2Nlc3MiLz48L3NhbWxwOlN0YXR1\r\ncz48c2FtbDpBc3NlcnRpb24geG1sbnM6c2FtbD0idXJuOm9hc2lzOm5hbWVzOnRj\r\nOlNBTUw6Mi4wOmFzc2VydGlvbiIgSUQ9ImlkLThvWVBULWlwVFZhR2UwSHpwRGdS\r\nSEoyWEp4Zy0iIElzc3VlSW5zdGFudD0iMjAxNy0wMy0yOFQxOTozMzo1M1oiIFZl\r\ncnNpb249IjIuMCI+PHNhbWw6SXNzd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b25zPjxzYW1sOkF1dGhuU3RhdGVt\r\nZW50IEF1dGhuSW5zdGFudD0iMjAxNy0wMy0yOFQxOTozMzo1M1oiIFNlc3Npb25J\r\nbmRleD0iaWQtWEVRcWVNZFRiRHRaLXNhaFN4ZnNYdVA2MWlJLSIgU2Vzc2lvbk5v\r\ndE9uT3JBZnRlcj0iMjAxNy0wMy0yOFQyMDozMzo1M1oiPjxzYW1sOkF1dGhuQ29u\r\ndGV4dD48c2FtbDpBdXRobkNvbnRleHRDbGFzc1JlZj51cm46b2FzaXM6bmFtZXM6\r\ndGM6U0FNTDoyLjA6YWM6Y2xhc3NlczpQYXNzd29yZFByb3RlY3RlZFRyYW5zcG9y\r\ndDwvc2FtbDpBdXRobkNvbnRleHRDbGFzc1JlZj48L3NhbWw6QXV0aG5Db250ZXh0\r\nPjwvc2FtbDpBdXRoblN0YXRlbWVudD48L3NhbWw6QXNzZXJ0aW9uPjwvc2FtbHA6\r\nUmVzcG9uc2U+\r\n",
"RelayState": "https://testserver.benunets.com/admin/login"
}

kernel.php

I can only see this response only because I comment out my CFRF token on my app/Http/kernel.php

// \App\Http\Middleware\VerifyCsrfToken::class,

ROUTE

Route::post('admin/secure/dashboard', 'SAMLController@post');

CONTROLLER

 public function post(){
    return Input::all();
}

What is the best practice to deal with SAML POST and still maintaining CSRF protection ?

Should I create a middleware or anything similar to that ?


问:
Pascal - Program hangs upon form switching
I am currently developing a simple application to count the number of clicks within 10 seconds, read in names and scores from two different files, then display those names and scores with various sorts in another form. However, after the game is finished, the 'Game Over!' message appears, the Leaderboard form appears but then has no buttons, looks oddly flat and appears to crash the program.

This is how the form should look:
Leaderboard Form

And this is how it actually looks: Leaderboard Error in Form

Code for displaying the form can be found below:

```<code>if TimeLeft=0 then
     begin
          Form2.Timer1.Enabled:=False;{Disable timer}
          ShowMessage('Game Over!');{Message to show upon termination condtion being met}
          Leaderboard.Show;{Show Leaderboard Form}
          Form2.Hide;{Hide game}
          Reset(LeaderboardNamesFile);{Open file}
          while not EOF(LeaderboardNamesFile) do
                LineCount:=LineCount+1;{Increment to allow for EOF marking of the score}
          LeaderboardScoresArray[LineCount]:=Score;{Add score to array of scores}
     end;
</code>```

And the code contained in the Score display button on the Leaderboard form:

```<code>var Counter : Integer;
begin
     Counter:=1;
     Memo1.Lines.add(LeaderboardNamesArray[Counter]+' - '+IntToStr(LeaderboardScoresArray[Counter]));
end;
</code>```

I find this all very strange, as nothing actually runs when the form is shown, so it should crash before this if ever, and no crash messages appear. Any ideas? If more info if needed, please ask. New on this site!

答:
The while loop is endless, the loop contains only one command:

```<code>while not EOF(LeaderboardNamesFile) do
            LineCount:=LineCount+1;{Increment to allow for EOF marking of the score}
</code>```

So, your program count LineCount up but don't aktually read any data from the file. So the file never becomes EOF ("end of file"). You need to do something like this:

```<code>Reset(LeaderboardNamesFile);{Open file}
while not EOF(LeaderboardNamesFile) do
begin
    LineCount:=LineCount+1;{Increment to allow for EOF marking of the score}
    readln(LeaderboardNamesFile, Score);
    LeaderboardScoresArray[LineCount]:=Score;{Add score to array of scores}
end;
CloseFile(LeaderboardNamesFile);
</code>```

Body:
I am currently developing a simple application to count the number of clicks within 10 seconds, read in names and scores from two different files, then display those names and scores with various sorts in another form. However, after the game is finished, the 'Game Over!' message appears, the Leaderboard form appears but then has no buttons, looks oddly flat and appears to crash the program.

This is how the form should look:
Leaderboard Form

And this is how it actually looks: Leaderboard Error in Form

Code for displaying the form can be found below:

if TimeLeft=0 then
     begin
          Form2.Timer1.Enabled:=False;{Disable timer}
          ShowMessage('Game Over!');{Message to show upon termination condtion being met}
          Leaderboard.Show;{Show Leaderboard Form}
          Form2.Hide;{Hide game}
          Reset(LeaderboardNamesFile);{Open file}
          while not EOF(LeaderboardNamesFile) do
                LineCount:=LineCount+1;{Increment to allow for EOF marking of the score}
          LeaderboardScoresArray[LineCount]:=Score;{Add score to array of scores}
     end;

And the code contained in the Score display button on the Leaderboard form:

var Counter : Integer;
begin
     Counter:=1;
     Memo1.Lines.add(LeaderboardNamesArray[Counter]+' - '+IntToStr(LeaderboardScoresArray[Counter]));
end;

I find this all very strange, as nothing actually runs when the form is shown, so it should crash before this if ever, and no crash messages appear. Any ideas? If more info if needed, please ask. New on this site!

Body:
The while loop is endless, the loop contains only one command:

while not EOF(LeaderboardNamesFile) do
            LineCount:=LineCount+1;{Increment to allow for EOF marking of the score}

So, your program count LineCount up but don't aktually read any data from the file. So the file never becomes EOF ("end of file"). You need to do something like this:

Reset(LeaderboardNamesFile);{Open file}
while not EOF(LeaderboardNamesFile) do
begin
    LineCount:=LineCount+1;{Increment to allow for EOF marking of the score}
    readln(LeaderboardNamesFile, Score);
    LeaderboardScoresArray[LineCount]:=Score;{Add score to array of scores}
end;
CloseFile(LeaderboardNamesFile);


问:
Control the XML generated for automatic properties
Can anyone explain how to control the XML generated  ?

I have a simple test class, NumberService ...

```<code>[Serializable]
public class NumberService
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
}
</code>```

Now if I use an XmlSerializer to deserialise an instance, I get what I expected ...

```<code><NumberService>
  <Number1>23</Number1>
  <Number2>45</Number2>
</NumberService>
</code>```

but I was attempting to send this and Fiddler was showing ...

```<code><NumberService>
<_x003C_Number1_x003E_k__BackingField>10</_x003C_Number1_x003E_k__BackingField>
<_x003C_Number2_x003E_k__BackingField>2</_x003C_Number2_x003E_k__BackingField>
</NumberService>
</code>```

Poking around I've read that this is because of my use of automatic properties, and indeed if I changed to ...

```<code>public class NumberService
{
    private int _number1;
    public int Number1
    {
        get { return _number1; }
        set { _number1 = value; }
    }

    public int Number2 { get; set; }
}
</code>```

indeed the XML changes to ...

```<code><NumberService>
<_number1>4</_number1>
<_x003C_Number2_x003E_k__BackingField>6</_x003C_Number2_x003E_k__BackingField>
</NumberService>
</code>```

But of course I can't change _number1 to Number1 as it'd conflict with the property :-(

So how can you control the XML ?

... and a bit more reading ...

this is involving WCF data contracts

答: You should remove the [Serializable] attribute. It is not used by XML Serialization, and it is giving the wrong message to the Data Contract Serializer.

ContentLicense: CC BY-SA 2.5

Body:
Can anyone explain how to control the XML generated  ?

I have a simple test class, NumberService ...

[Serializable]
public class NumberService
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
}

Now if I use an XmlSerializer to deserialise an instance, I get what I expected ...

<NumberService>
  <Number1>23</Number1>
  <Number2>45</Number2>
</NumberService>

but I was attempting to send this and Fiddler was showing ...

<NumberService>
<_x003C_Number1_x003E_k__BackingField>10</_x003C_Number1_x003E_k__BackingField>
<_x003C_Number2_x003E_k__BackingField>2</_x003C_Number2_x003E_k__BackingField>
</NumberService>

Poking around I've read that this is because of my use of automatic properties, and indeed if I changed to ...

public class NumberService
{
    private int _number1;
    public int Number1
    {
        get { return _number1; }
        set { _number1 = value; }
    }

    public int Number2 { get; set; }
}

indeed the XML changes to ...

<NumberService>
<_number1>4</_number1>
<_x003C_Number2_x003E_k__BackingField>6</_x003C_Number2_x003E_k__BackingField>
</NumberService>

But of course I can't change _number1 to Number1 as it'd conflict with the property :-(

So how can you control the XML ?

... and a bit more reading ...

this is involving WCF data contracts


问:
C++ - undefined reference to 'Class::variable'
I keep getting error: undefined reference to 'Company::budget'.
My method is set so as to take the value of company's (any created) budget and subtract Employees' salary from it. I keep getting this problem. Tried both pointers and let's say "normal calling". Ok, there's the code snippet: (rest of it works)

company.h

```<code>#include <iostream>
#include <cstdlib>
#include <list>
#include <vector>
#include "employee.h"
using namespace std;

class Company
{
public:
    Company* comp;
    void  hire(Employee& emp, float putSalary);
    void  fire(Employee& emp);
    void  endOfMonth(Company& comp);
    Company(float);
 //   static float moneyamount;
private:
    static float budget;
    vector <Employee>* Employees;
};
</code>```

company.cpp

```<code>void Company::endOfMonth(Company& comp)
{
    for (iterat=0; iterat < Employees->size() ; iterat++)
    {

        cout << (*Employees)[iterat].fullName << endl;
        cout << (*Employees)[iterat].getSalary() << endl;
        comp.budget = comp.budget - (*Employees)[iterat].getSalary();
    }
}
</code>```

答:
You are missing the definition of the static class data member. Add the following line to the file company.cpp:</p>

```<code>float Company::budget;
</code>```

Body:
I keep getting error: undefined reference to 'Company::budget'.
My method is set so as to take the value of company's (any created) budget and subtract Employees' salary from it. I keep getting this problem. Tried both pointers and let's say "normal calling". Ok, there's the code snippet: (rest of it works)

company.h

#include <iostream>
#include <cstdlib>
#include <list>
#include <vector>
#include "employee.h"
using namespace std;

class Company
{
public:
    Company* comp;
    void  hire(Employee& emp, float putSalary);
    void  fire(Employee& emp);
    void  endOfMonth(Company& comp);
    Company(float);
 //   static float moneyamount;
private:
    static float budget;
    vector <Employee>* Employees;
};

company.cpp

void Company::endOfMonth(Company& comp)
{
    for (iterat=0; iterat < Employees->size() ; iterat++)
    {

        cout << (*Employees)[iterat].fullName << endl;
        cout << (*Employees)[iterat].getSalary() << endl;
        comp.budget = comp.budget - (*Employees)[iterat].getSalary();
    }
}

Body:
You are missing the definition of the static class data member. Add the following line to the file company.cpp:

float Company::budget;


问:
Getting the name of a class from within a class definition
So I have my base class:

```<code>class Foo():
    pass
</code>```

I'm never going to instantiate this class - I just want it as a custom namespace.  One of the things I want from it is its name:

```<code>>>> Foo.__name__
'Foo'
</code>```

But I want to change the interface to this, so that there's no underscores.  Getting the name of the class from the class object is going to happen a lot, so it should be cleaner:

```<code>class Foo:
    def name():
        return Foo.__name__
</code>```

This works great!  Oh, except I have the name "Foo" hard coded.  I might as well just have it return a string.  That's not good enough, because I need to inherit this adjustment:

```<code>class Bar(Foo):
   pass

>>> Bar.name()
'Foo'
</code>```

No bueno.

Basically, I need a class function that returns the name of the class, and which will still work when inherited.  I can't use self because I'm not making instances.  Is there anything which will achieve a similar result?  Do functions know about the namespace they are called from?  If I really need to use objects I will, but for my purposes that will be uglier than a simple class hierarchy.

EDIT:  I do not not believe this question is the same as the one it has been linked with.  The solutions provided to the other question - mainly invoking the .__class__ attribute - would not work as an answer to this question because in my example I explicitly avoid instantiating objects.  Also, the best answer provided here (using the @classmethod decorator to get the class object as a "self"-esque arg) appears nowhere in the linked alternative.  Also, I believe my question to be framed in a clearer and more basic way than its purported duplicate.  The same goes for the answer chosen.

答:
Just make it a class method with @classmethod and return the name of the class that's passed in:

```<code>class Foo:
    @classmethod
    def name(cls):
        return cls.__name__

class Bar(Foo): pass
</code>```

This returns the correct name in each case:

```<code>>>> Foo.name()
'Foo'
>>> Bar.name()
'Bar'
</code>```

Body:
So I have my base class:

class Foo():
    pass

I'm never going to instantiate this class - I just want it as a custom namespace.  One of the things I want from it is its name:

>>> Foo.__name__
'Foo'

But I want to change the interface to this, so that there's no underscores.  Getting the name of the class from the class object is going to happen a lot, so it should be cleaner:

class Foo:
    def name():
        return Foo.__name__

This works great!  Oh, except I have the name "Foo" hard coded.  I might as well just have it return a string.  That's not good enough, because I need to inherit this adjustment:

class Bar(Foo):
   pass

>>> Bar.name()
'Foo'

No bueno.

Basically, I need a class function that returns the name of the class, and which will still work when inherited.  I can't use self because I'm not making instances.  Is there anything which will achieve a similar result?  Do functions know about the namespace they are called from?  If I really need to use objects I will, but for my purposes that will be uglier than a simple class hierarchy.

EDIT:  I do not not believe this question is the same as the one it has been linked with.  The solutions provided to the other question - mainly invoking the .__class__ attribute - would not work as an answer to this question because in my example I explicitly avoid instantiating objects.  Also, the best answer provided here (using the @classmethod decorator to get the class object as a "self"-esque arg) appears nowhere in the linked alternative.  Also, I believe my question to be framed in a clearer and more basic way than its purported duplicate.  The same goes for the answer chosen.

Body:
Just make it a class method with @classmethod and return the name of the class that's passed in:

class Foo:
    @classmethod
    def name(cls):
        return cls.__name__

class Bar(Foo): pass

This returns the correct name in each case:

>>> Foo.name()
'Foo'
>>> Bar.name()
'Bar'


问:
how to read image file and convert it to bits in vhdl
I am trying to read an image file using textio package in vhdl.
If i open an .jpg with notepad , i will get some junk data but actually it is ASCII data . Here i am trying to read these ascii data and convert them into bytes.

below is my code:

```<code>library ieee;
use ieee.std_logic_1164.all;
use std.textio.all;
use ieee.std_logic_textio.all;

entity file_io is

 port (
     clk:             in  std_logic;
     Data:            out std_logic_vector(7 downto 0)
 );
 end entity;

 architecture behav of file_io is

signal test_data : std_logic_vector(7 downto 0);
use ieee.numeric_std.all;
use std.textio.all;
use ieee.std_logic_textio.all;
begin

File_reader:process(clk)
    file f    : text open read_mode is "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg";
    variable L:   line;
    variable var_int:   integer:= 0;
    variable var_char:   character;

begin

if rising_edge(clk) then
        while not endfile(f) loop
                 readline(f, L);
         read(L, var_char);
         var_int := character'pos(var_char);
         test_data  <= std_logic_vector(to_unsigned(var_int, test_data'length));
        end loop;
     end if;
    Data <= test_data;
  end process;
end architecture behav;
</code>```

testbench:

```<code>LIBRARY ieee;
use ieee.std_logic_1164.ALL;
use std.textio.all;

ENTITY file_io_test IS
END file_io_test;

ARCHITECTURE behavior OF file_io_test IS
use work.io.all;
    signal clk:         std_logic := '0';
    signal Data: std_logic_vector(7 downto 0);

    -- Clock period definitions
    constant clk_period : time := 10 ns;

    BEGIN
      -- Instantiate the Unit Under Test (UUT)
    UUT:
     entity work.file_io(behav)
    port map (
           clk => clk,
        Data => Data
          );

    -- Clock process definitions( clock with 50% duty cycle is generated here.
     clk_process :process
       begin
         clk <= '1';
         wait for clk_period/2;  --for 5 ns signal is '1'.
          clk <= '0';
         wait for clk_period/2;  --for next 5 ns signal is '0'.

     end process;
    end behavior;
</code>```

I am getting only one byte in waveform. expected result is : Every clock cycle new character should be rread and new byte should be obtained.

below is waveform:

below is the image I am trying to read:

答:
The question has a fundamental flaw. You can't use textio to read binary values, it's for text.

See IEEE Std 1076-2008 16.4 Package TEXTIO paragraphs 3 (in part) and 4:

Procedures READLINE, WRITELINE, and TEE declared in package TEXTIO read and write entire lines of a file of type TEXT. Procedure READLINE causes the next line to be read from the file and returns as the value of parameter L an access value that designates an object representing that line. If parameter L contains a non-null access value at the start of the call, the procedure may deallocate the object designated by that value. The representation of the line does not contain the representation of the end of the line. ...

The language does not define the representation of the end of a line. An implementation shall allow all possible values of types CHARACTER and STRING to be written to a file. However, as an implementation is permitted to use certain values of types CHARACTER and STRING as line delimiters, it might not be possible to read these values from a TEXT file.

And that can be demonstrated with your Chrysanthemum.jpg:

It is possible in VHDL to read raw characters one at a time (matching your need).

See IEEE Std 1076-2008 5.5 File types:

So all we have to do is declare a file type and we get these procedures defined implicitly.

We can use them to invoke raw read, without any end of line issues caused by textio:

```<code>library ieee;
use ieee.std_logic_1164.all;

entity file_io is
    port (
        clk:    in  std_logic;
        Data:   out std_logic_vector(7 downto 0);
        done:   out boolean
 );
 end entity;

architecture foo of file_io is
    use ieee.numeric_std.all;
begin

File_reader:
    process (clk)
        -- "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg";
        constant filename:  string := "Chrysanthemum.jpg"; -- local to sim
        variable char_val:  character;
        variable status: FILE_OPEN_STATUS;
        variable openfile:  boolean;  -- FALSE by default
        type f is file of character;
        file ffile: f;
        variable char_count:    natural := 0;
    begin
        if rising_edge (clk) then
            if not openfile then
                file_open (status, ffile, filename, READ_MODE);
                if status /= OPEN_OK then
                    report "FILE_OPEN_STATUS = " &
                            FILE_OPEN_STATUS'IMAGE(status)
                    severity FAILURE;
                end if;
                report "FILE_OPEN_STATUS = " & FILE_OPEN_STATUS'IMAGE(status);
                openfile := TRUE;
            else
                if not endfile(ffile) then
                    read(ffile, char_val);
                    -- report "char_val = " & character'image(char_val);
                    char_count := char_count + 1;
                    Data  <= std_logic_vector (
                             to_unsigned(character'pos(char_val),
                             Data'length) );
                 end if;
                 if endfile(ffile) then  -- can occur after last character
                    report "ENDFILE, read " &
                          integer'image(char_count) & "characters";
                    done <= TRUE;
                    FILE_CLOSE(ffile);
                end if;
            end if;
        end if;
    end process;
end architecture foo;

library ieee;
use ieee.std_logic_1164.all;

entity file_io_test is
end file_io_test;

architecture behavior of file_io_test is
    signal clk:         std_logic := '0';
    signal data:        std_logic_vector(7 downto 0);
    signal done:        boolean;
    constant clk_period: time := 10 ns;
begin
uut:
    entity work.file_io(foo)
        port map (
           clk => clk,
           data => data,
           done => done
        );

clk_process:
    process
    begin
        if not done then
             clk <= '1';
             wait for clk_period/2;
              clk <= '0';
             wait for clk_period/2;
         else
             wait;
         end if;
     end process;
end architecture behavior;
</code>```

Now we can have all the characters than can delimit a line show up in our read:

Note that package std.textio is not made visible through any context item.

Body:
I am trying to read an image file using textio package in vhdl.
If i open an .jpg with notepad , i will get some junk data but actually it is ASCII data . Here i am trying to read these ascii data and convert them into bytes.

below is my code:

library ieee;
use ieee.std_logic_1164.all;
use std.textio.all;
use ieee.std_logic_textio.all;

entity file_io is

 port (
     clk:             in  std_logic;
     Data:            out std_logic_vector(7 downto 0)
 );
 end entity;

 architecture behav of file_io is

signal test_data : std_logic_vector(7 downto 0);
use ieee.numeric_std.all;
use std.textio.all;
use ieee.std_logic_textio.all;
begin

File_reader:process(clk)
    file f    : text open read_mode is "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg";
    variable L:   line;
    variable var_int:   integer:= 0;
    variable var_char:   character;

begin

if rising_edge(clk) then
        while not endfile(f) loop
                 readline(f, L);
         read(L, var_char);
         var_int := character'pos(var_char);
         test_data  <= std_logic_vector(to_unsigned(var_int, test_data'length));
        end loop;
     end if;
    Data <= test_data;
  end process;
end architecture behav;

testbench:

LIBRARY ieee;
use ieee.std_logic_1164.ALL;
use std.textio.all;

ENTITY file_io_test IS
END file_io_test;

ARCHITECTURE behavior OF file_io_test IS
use work.io.all;
    signal clk:         std_logic := '0';
    signal Data: std_logic_vector(7 downto 0);

    -- Clock period definitions
    constant clk_period : time := 10 ns;

    BEGIN
      -- Instantiate the Unit Under Test (UUT)
    UUT:
     entity work.file_io(behav)
    port map (
           clk => clk,
        Data => Data
          );

    -- Clock process definitions( clock with 50% duty cycle is generated here.
     clk_process :process
       begin
         clk <= '1';
         wait for clk_period/2;  --for 5 ns signal is '1'.
          clk <= '0';
         wait for clk_period/2;  --for next 5 ns signal is '0'.

     end process;
    end behavior;

I am getting only one byte in waveform. expected result is : Every clock cycle new character should be rread and new byte should be obtained.

below is waveform:

below is the image I am trying to read:

Body:
The question has a fundamental flaw. You can't use textio to read binary values, it's for text.

See IEEE Std 1076-2008 16.4 Package TEXTIO paragraphs 3 (in part) and 4:

Procedures READLINE, WRITELINE, and TEE declared in package TEXTIO read and write entire lines of a file of type TEXT. Procedure READLINE causes the next line to be read from the file and returns as the value of parameter L an access value that designates an object representing that line. If parameter L contains a non-null access value at the start of the call, the procedure may deallocate the object designated by that value. The representation of the line does not contain the representation of the end of the line. ...

The language does not define the representation of the end of a line. An implementation shall allow all possible values of types CHARACTER and STRING to be written to a file. However, as an implementation is permitted to use certain values of types CHARACTER and STRING as line delimiters, it might not be possible to read these values from a TEXT file.

And that can be demonstrated with your Chrysanthemum.jpg:

It is possible in VHDL to read raw characters one at a time (matching your need).

See IEEE Std 1076-2008 5.5 File types:

So all we have to do is declare a file type and we get these procedures defined implicitly.

We can use them to invoke raw read, without any end of line issues caused by textio:

library ieee;
use ieee.std_logic_1164.all;

entity file_io is
    port (
        clk:    in  std_logic;
        Data:   out std_logic_vector(7 downto 0);
        done:   out boolean
 );
 end entity;

architecture foo of file_io is
    use ieee.numeric_std.all;
begin

File_reader:
    process (clk)
        -- "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg";
        constant filename:  string := "Chrysanthemum.jpg"; -- local to sim
        variable char_val:  character;
        variable status: FILE_OPEN_STATUS;
        variable openfile:  boolean;  -- FALSE by default
        type f is file of character;
        file ffile: f;
        variable char_count:    natural := 0;
    begin
        if rising_edge (clk) then
            if not openfile then
                file_open (status, ffile, filename, READ_MODE);
                if status /= OPEN_OK then
                    report "FILE_OPEN_STATUS = " &
                            FILE_OPEN_STATUS'IMAGE(status)
                    severity FAILURE;
                end if;
                report "FILE_OPEN_STATUS = " & FILE_OPEN_STATUS'IMAGE(status);
                openfile := TRUE;
            else
                if not endfile(ffile) then
                    read(ffile, char_val);
                    -- report "char_val = " & character'image(char_val);
                    char_count := char_count + 1;
                    Data  <= std_logic_vector (
                             to_unsigned(character'pos(char_val),
                             Data'length) );
                 end if;
                 if endfile(ffile) then  -- can occur after last character
                    report "ENDFILE, read " &
                          integer'image(char_count) & "characters";
                    done <= TRUE;
                    FILE_CLOSE(ffile);
                end if;
            end if;
        end if;
    end process;
end architecture foo;

library ieee;
use ieee.std_logic_1164.all;

entity file_io_test is
end file_io_test;

architecture behavior of file_io_test is
    signal clk:         std_logic := '0';
    signal data:        std_logic_vector(7 downto 0);
    signal done:        boolean;
    constant clk_period: time := 10 ns;
begin
uut:
    entity work.file_io(foo)
        port map (
           clk => clk,
           data => data,
           done => done
        );

clk_process:
    process
    begin
        if not done then
             clk <= '1';
             wait for clk_period/2;
              clk <= '0';
             wait for clk_period/2;
         else
             wait;
         end if;
     end process;
end architecture behavior;

Now we can have all the characters than can delimit a line show up in our read:

Note that package std.textio is not made visible through any context item.


问:
How to build directed graph from nested dictionary? (Python 3 | NetworkX)
I am trying to build a hierarchical directed network where some nodes can branch into others, while others do not.  The values in the inner dictionary (i.e. the integers) are to keep track of leaves in the tree-like structure.  I've created a naive way to turn this particular nested dictionary graph_data into a directed graph but it is only specific to 3 layers.  Below shows the hierarchy:

How can I create a nested function that adds edges to the directed graph for any number of levels?  For example, if there was a level-3 or a level-4 this would not work and I would have to expand it out each time. Do I need to use a while loop?

```<code>import numpy as np
from collections import *
import networkx as nx

%matplotlib inline

# Hierarchical data
graph_data = {"root": {"level-0.A":0,
                      "level-0.B":{"level-1.B.1":2,
                                   "level-1.B.2": {"level-2.B.2.1":3, "level-2.B.2.2":1}}}}
# Empty directed graph
G = nx.DiGraph()

# Helper functions
is_dict = lambda x: type(x) in {dict, OrderedDict, defaultdict}

# Iterate through the layers
for root, level_0 in graph_data.items():
    if len(level_0) > 0:
        for level_0_node, level_1 in level_0.items():
            G.add_edge(root, level_0_node)
            if is_dict(level_1):
                for level_1_node, level_2 in level_1.items():
                    G.add_edge(level_0_node, level_1_node)
                    if is_dict(level_2):
                        for level_2_node, level_3 in level_2.items():
                            G.add_edge(level_1_node, level_2_node)

np.random.seed(8)
nx.draw(G, with_labels=True)
</code>```

答:
Use a queue to hold the details, e.g.:

```<code>from collections import Mapping
graph_data = {"root": {"level-0.A":0,
                      "level-0.B":{"level-1.B.1":2,
                                   "level-1.B.2": {"level-2.B.2.1":3, "level-2.B.2.2":1}}}}
# Empty directed graph
G = nx.DiGraph()

# Iterate through the layers
q = list(graph_data.items())
while q:
    v, d = q.pop()
    for nv, nd in d.items():
        G.add_edge(v, nv)
        if isinstance(nd, Mapping):
            q.append((nv, nd))

np.random.seed(8)
nx.draw(G, with_labels=True)
</code>```

Body:
I am trying to build a hierarchical directed network where some nodes can branch into others, while others do not.  The values in the inner dictionary (i.e. the integers) are to keep track of leaves in the tree-like structure.  I've created a naive way to turn this particular nested dictionary graph_data into a directed graph but it is only specific to 3 layers.  Below shows the hierarchy:

How can I create a nested function that adds edges to the directed graph for any number of levels?  For example, if there was a level-3 or a level-4 this would not work and I would have to expand it out each time. Do I need to use a while loop?

import numpy as np
from collections import *
import networkx as nx

%matplotlib inline

# Hierarchical data
graph_data = {"root": {"level-0.A":0,
                      "level-0.B":{"level-1.B.1":2,
                                   "level-1.B.2": {"level-2.B.2.1":3, "level-2.B.2.2":1}}}}
# Empty directed graph
G = nx.DiGraph()

# Helper functions
is_dict = lambda x: type(x) in {dict, OrderedDict, defaultdict}

# Iterate through the layers
for root, level_0 in graph_data.items():
    if len(level_0) > 0:
        for level_0_node, level_1 in level_0.items():
            G.add_edge(root, level_0_node)
            if is_dict(level_1):
                for level_1_node, level_2 in level_1.items():
                    G.add_edge(level_0_node, level_1_node)
                    if is_dict(level_2):
                        for level_2_node, level_3 in level_2.items():
                            G.add_edge(level_1_node, level_2_node)

np.random.seed(8)
nx.draw(G, with_labels=True)

Body:
Use a queue to hold the details, e.g.:

from collections import Mapping
graph_data = {"root": {"level-0.A":0,
                      "level-0.B":{"level-1.B.1":2,
                                   "level-1.B.2": {"level-2.B.2.1":3, "level-2.B.2.2":1}}}}
# Empty directed graph
G = nx.DiGraph()

# Iterate through the layers
q = list(graph_data.items())
while q:
    v, d = q.pop()
    for nv, nd in d.items():
        G.add_edge(v, nv)
        if isinstance(nd, Mapping):
            q.append((nv, nd))

np.random.seed(8)
nx.draw(G, with_labels=True)


问:
Convert pandas dataframe to multi-index columns
I've got a dataframe like this:

```<code>     a  b  c
foo  1  6  9
bar  2  4  8
fud  3  5  7
</code>```

And I want to convert it to this:

```<code>     a        b        c
  name num name num name num
0  foo   1  bar   4  fud   7
1  bar   2  fud   5  bar   8
2  fud   3  foo   6  foo   9
</code>```

i.e. group each column as a name and number pair, with the numbers sorted with corresponding names that used to be indices.

I can do it with a loop, but I keep thinking there must be a more 'pandasy' way to do it.  This is the code I used for the above:

```<code>import pandas as pd

my_index=['foo','bar','fud']
orig = pd.DataFrame({'a': [1,2,3], 'b':[6,4,5], 'c':[9,8,7]}, index=my_index)
multi = pd.MultiIndex.from_product([['a','b','c'],['name','num']])
x = pd.DataFrame(index=range(3), columns=multi)

for h in orig.columns:
    s = orig[h].sort_values().reset_index()
    x[h,'name'] = s['index']
    x[h,'num'] = s[h]
</code>```

I'm sure there's a better way to do this, though, so if a pandas expert can help me out, it would be much appreciated.

Thanks!

答:
pandas

```<code>def proc(s):
    return s.sort_values().rename_axis('name').reset_index(name='num')

pd.concat({j: proc(c) for j, c in df.iteritems()}, axis=1)

     a        b        c
  name num name num name num
0  foo   1  bar   4  fud   7
1  bar   2  fud   5  bar   8
2  fud   3  foo   6  foo   9
</code>```

dash of numpy

```<code>v = df.values
a = v.argsort(0)
r = np.arange(v.shape[1])[None, :]

nums = pd.DataFrame(v[a, r], columns=df.columns)
names = pd.DataFrame(df.index.values[a], columns=df.columns)

pd.concat(
    [names, nums],
    axis=1,
    keys=['names', 'nums']
).swaplevel(0, 1, 1).sort_index(1)

     a        b        c
  name num name num name num
0  foo   1  bar   4  fud   7
1  bar   2  fud   5  bar   8
2  fud   3  foo   6  foo   9
</code>```

Body:
I've got a dataframe like this:

     a  b  c
foo  1  6  9
bar  2  4  8
fud  3  5  7

And I want to convert it to this:

     a        b        c
  name num name num name num
0  foo   1  bar   4  fud   7
1  bar   2  fud   5  bar   8
2  fud   3  foo   6  foo   9

i.e. group each column as a name and number pair, with the numbers sorted with corresponding names that used to be indices.

I can do it with a loop, but I keep thinking there must be a more 'pandasy' way to do it.  This is the code I used for the above:

import pandas as pd

my_index=['foo','bar','fud']
orig = pd.DataFrame({'a': [1,2,3], 'b':[6,4,5], 'c':[9,8,7]}, index=my_index)
multi = pd.MultiIndex.from_product([['a','b','c'],['name','num']])
x = pd.DataFrame(index=range(3), columns=multi)

for h in orig.columns:
    s = orig[h].sort_values().reset_index()
    x[h,'name'] = s['index']
    x[h,'num'] = s[h]

I'm sure there's a better way to do this, though, so if a pandas expert can help me out, it would be much appreciated.

Thanks!

Body:
pandas

def proc(s):
    return s.sort_values().rename_axis('name').reset_index(name='num')

pd.concat({j: proc(c) for j, c in df.iteritems()}, axis=1)

     a        b        c
  name num name num name num
0  foo   1  bar   4  fud   7
1  bar   2  fud   5  bar   8
2  fud   3  foo   6  foo   9

dash of numpy

v = df.values
a = v.argsort(0)
r = np.arange(v.shape[1])[None, :]

nums = pd.DataFrame(v[a, r], columns=df.columns)
names = pd.DataFrame(df.index.values[a], columns=df.columns)

pd.concat(
    [names, nums],
    axis=1,
    keys=['names', 'nums']
).swaplevel(0, 1, 1).sort_index(1)

     a        b        c
  name num name num name num
0  foo   1  bar   4  fud   7
1  bar   2  fud   5  bar   8
2  fud   3  foo   6  foo   9


问:
PHP dynamic drop down list
I am trying to make a drop down list which will contain as many options as there are in the database table.

```<code>    $qry3 = "SELECT * FROM employees WHERE buss_id_fk = '{$_SESSION ['user_id']}' ";
    $result3 = mysqli_query ( $con, $qry3);

    while ($row4 = mysqli_fetch_assoc($result3)){
    echo $row4['emp_id'] . " " . $row4['username'] . '</br>';
    }
</code>```

$qry3 is my query and it works fine with $row4 and everything shows as intended. Now when I move into my form where my drop down list should exist I made this code

```<code> <!--the list of employees the business has -->
                  <select name="employees" class="form-control">

 <?php while ($row3 = mysqli_fetch_assoc($result3)) {

 echo "<option value='" .$row3['emp_id']. "'>" .$row3['username']. "</option>" ;

                  } ?>

                  </select> <br>
</code>```

my drop down list shows zero results while it should show some, just like that $row4 did. Checked a similar question where there was a typo in the code, didn't help. Thanks!

答:
You need to reset the pointer back to the beginning of the result set if you wish to iterate through the results again:

```<code><?php
    mysqli_data_seek($result3, 0); // Zero indicates the beginning
    while ($row3 = mysqli_fetch_assoc($result3)) {
</code>```

See the manual: mysqli_data_seek()

Title: PHP dynamic drop down list

Body:
I am trying to make a drop down list which will contain as many options as there are in the database table.

    $qry3 = "SELECT * FROM employees WHERE buss_id_fk = '{$_SESSION ['user_id']}' ";
    $result3 = mysqli_query ( $con, $qry3);

    while ($row4 = mysqli_fetch_assoc($result3)){
    echo $row4['emp_id'] . " " . $row4['username'] . '
';
    }

$qry3 is my query and it works fine with $row4 and everything shows as intended. Now when I move into my form where my drop down list should exist I made this code

                  <select name="employees" class="form-control">

 <?php while ($row3 = mysqli_fetch_assoc($result3)) {

 echo "<option value='" .$row3['emp_id']. "'>" .$row3['username']. "</option>" ;

                  } ?>

                  </select>

my drop down list shows zero results while it should show some, just like that $row4 did. Checked a similar question where there was a typo in the code, didn't help. Thanks!

Body:
You need to reset the pointer back to the beginning of the result set if you wish to iterate through the results again:

<?php
    mysqli_data_seek($result3, 0); // Zero indicates the beginning
    while ($row3 = mysqli_fetch_assoc($result3)) {

See the manual: mysqli_data_seek()


问:
Inserting a value to the new field that I created in Magento database
my question might be lame for magento developers but I am very new to the platform. I added a new input field to my newsletter subscription called offer type as I am encouraging users to subscribe in order to get promo code.

I added the input type hidden in the static page

```<code><input placeholder="email: example@example.com" class="email-offer-revealer" name="email" required="" autocapitalize="off" autocorrect="off" spellcheck="false" type="email">
<input name="couponName" value="first offer" type="hidden">
</code>```

in app/code/core/Mage/Newsletter/controllers/SubscriberController.php I added the following line

```<code> $offer = (string) $this->getRequest()->getPost('couponName');
 $status = Mage::getModel('newsletter/subscriber')->subscribe($email,$offer);
</code>```

in app/code/core/Mage/Newsletter/Model/Subscriber.php I added the following

```<code> public function subscribe($email, $offer){
</code>```

The $offer as new argument to be inserted into the offer field in my newsletter table in the DB.
I've been told that Magento will give me automatic access to getOffer and setOffer so i added the following for the same method

```<code>$this->setOffer($offer);
</code>```

The problem is i can echo that value, but I can not insert it into the database only i can insert the email what is next?

Thanks

答:
When you updated some value in model you can try to call save to put the new value into database.

Something like:

$quote->setCouponCode();

$quote->save();

Body:
my question might be lame for magento developers but I am very new to the platform. I added a new input field to my newsletter subscription called offer type as I am encouraging users to subscribe in order to get promo code.

I added the input type hidden in the static page

<input placeholder="email: example@example.com" class="email-offer-revealer" name="email" required="" autocapitalize="off" autocorrect="off" spellcheck="false" type="email">
<input name="couponName" value="first offer" type="hidden">

in app/code/core/Mage/Newsletter/controllers/SubscriberController.php I added the following line

 $offer = (string) $this->getRequest()->getPost('couponName');
 $status = Mage::getModel('newsletter/subscriber')->subscribe($email,$offer);

in app/code/core/Mage/Newsletter/Model/Subscriber.php I added the following

 public function subscribe($email, $offer){

The $offer as new argument to be inserted into the offer field in my newsletter table in the DB.
I've been told that Magento will give me automatic access to getOffer and setOffer so i added the following for the same method

$this->setOffer($offer);

The problem is i can echo that value, but I can not insert it into the database only i can insert the email what is next?

Thanks


问:
Rails 3 rake task can't find model in production
My simple rake task, stored in lib/tasks/items_spider.rake runs just fine in development. All it does is call spider! on the Item model.

```<code>namespace :items do
  desc "Spider the web for data, hoorah"
  task :spider => :environment do
    Item.spider!
  end
end
</code>```

I have the :environment task as a dependency, so everything works just fine. However, when I add RAILS_ENV=production, I hit errors, both on my local server and the production server:

```<code>$ rake items:spider RAILS_ENV=production --trace
(in /home/matchu/Websites/my-rails-app)
** Invoke items:spider (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute items:spider
rake aborted!
uninitialized constant Object::Item
/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rake-0.8.7/lib/rake.rb:2503:in `const_missing'
/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rspec-core-2.0.0.beta.22/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rspec-expectations-2.0.0.beta.22/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'
/home/matchu/Websites/openneo-impress-items/lib/tasks/items_spider.rake:4:in `block (2 levels) in <top (required)>'
/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rake-0.8.7/lib/rake.rb:636:in `call'
[...trace of how rake gets to my task...]
</code>```

This just seems odd to me. Apparently the models have not been loaded correctly. I'm on Rails 3.0.3, though development on this app started back when Rails 3 was in beta. How can I go about debugging this issue? Thanks!

答:
Contrary to running your application in production, a Rake task does not eager load your entire code base. You can see it in the source:

```<code>module Rails
  class Application
    module Finisher
      # ...
      initializer :eager_load! do
        if config.cache_classes && !$rails_rake_task
          ActiveSupport.run_load_hooks(:before_eager_load, self)
          eager_load!
        end
      end
      # ...
    end
  end
end
</code>```

So only if $rails_rake_task is false, will the application be eager-loaded in production. And $rails_rake_task is set to true in the :environment Rake task.

The easiest workaround is to simply require the model that you need. However, if you really need all of your application to be loaded in the Rake task, it is quite simple to load it:

```<code>Rails.application.eager_load!
</code>```

The reason all of this work in development is because Rails autoloads your models in development mode. This also works from within a Rake task.

Body:
My simple rake task, stored in lib/tasks/items_spider.rake runs just fine in development. All it does is call spider! on the Item model.

namespace :items do
  desc "Spider the web for data, hoorah"
  task :spider => :environment do
    Item.spider!
  end
end

I have the :environment task as a dependency, so everything works just fine. However, when I add RAILS_ENV=production, I hit errors, both on my local server and the production server:

$ rake items:spider RAILS_ENV=production --trace
(in /home/matchu/Websites/my-rails-app)
** Invoke items:spider (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute items:spider
rake aborted!
uninitialized constant Object::Item
/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rake-0.8.7/lib/rake.rb:2503:in `const_missing'
/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rspec-core-2.0.0.beta.22/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rspec-expectations-2.0.0.beta.22/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'
/home/matchu/Websites/openneo-impress-items/lib/tasks/items_spider.rake:4:in `block (2 levels) in <top (required)>'
/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rake-0.8.7/lib/rake.rb:636:in `call'
[...trace of how rake gets to my task...]

This just seems odd to me. Apparently the models have not been loaded correctly. I'm on Rails 3.0.3, though development on this app started back when Rails 3 was in beta. How can I go about debugging this issue? Thanks!

Body:
Contrary to running your application in production, a Rake task does not eager load your entire code base. You can see it in the source:

module Rails
  class Application
    module Finisher
      # ...
      initializer :eager_load! do
        if config.cache_classes && !$rails_rake_task
          ActiveSupport.run_load_hooks(:before_eager_load, self)
          eager_load!
        end
      end
      # ...
    end
  end
end

So only if $rails_rake_task is false, will the application be eager-loaded in production. And $rails_rake_task is set to true in the :environment Rake task.

The easiest workaround is to simply require the model that you need. However, if you really need all of your application to be loaded in the Rake task, it is quite simple to load it:

Rails.application.eager_load!

The reason all of this work in development is because Rails autoloads your models in development mode. This also works from within a Rake task.


问:
Component not rendering in simple React.js app
I'm trying to get a simple "Hello, World"-type React.js app from the book React and React Native running under Node/webpack-dev-server. I'm not seeing any errors, but the page is blank when I visit it in my browser.

Here's how I tried—and failed—to run the book's very first example:

Install node and npm using these steps (adapted from this gist):

```<code>$ mkdir ~/.local/node-latest-install
$ cd ~/.local/node-latest-install
$ curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
$ ./configure --prefix=~/.local
$ make -j install
$ curl https://www.npmjs.com/install.sh | sh
$ node -v; npm -v
v7.7.4
4.1.2
</code>```

Clone the examples repo from the book:

```<code>$ git clone https://github.com/PacktPublishing/React-and-React-Native.git
</code>```

Run npm install from the top-level examples folder:

```<code>$ cd React-and-React-Native
$ npm install
</code>```

Attempt to compile/run hello-jsx example:

```<code>$ cd Chapter02/hello-jsx
$ node ../../node_modules/webpack-dev-server/bin/webpack-dev-server.js
...
ERROR in ./main.js
Module build failed: Error: React Hot Loader: The Webpack loader is now exported separately. If you use Babel, we recommend that you remove "react-hot-loader" from the "loaders" section of your Webpack configuration altogether, and instead add "react-hot-loader/babel" to the "plugins" section of your .babelrc file. If you prefer not to use Babel, replace "react-hot-loader" or "react-hot" with "react-hot-loader/webpack" in the "loaders" section of your Webpack configuration.
at Object.warnAboutIncorrectUsage (/home/evadeflow/.local/React-and-React-Native/node_modules/react-hot-loader/lib/index.js:7:11)
@ multi main
webpack: Failed to compile.
</code>```

Edit hello-jsx/webpack.config.js to work around the above error:

```<code>diff --git a/Chapter02/hello-jsx/webpack.config.js b/Chapter02/hello-jsx/webpack.config.js
index 312f152..592e767 100644
--- a/Chapter02/hello-jsx/webpack.config.js
+++ b/Chapter02/hello-jsx/webpack.config.js
@@ -13,7 +13,7 @@ module.exports = {
       {
         test: /\.jsx?$/,
         exclude: /node_modules/,
-        loaders: ['react-hot', 'babel?presets[]=es2015'],
+        loaders: ['react-hot-loader/webpack', 'babel?presets[]=es2015'],
       },
     ],
   },
</code>```

Recompile/re-run:

```<code>$ node ../../node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /home/evadeflow/.local/React-and-React-Native/Chapter02/hello-jsx
Hash: 590282c761dccbb5710a
Version: webpack 1.14.0
Time: 1260ms
         Asset    Size  Chunks             Chunk Names
main-bundle.js  978 kB       0  [emitted]  main
chunk    {0} main-bundle.js (main) 923 kB [rendered]
    [0] multi main 52 bytes {0} [built]
    [1] (webpack)-dev-server/client?http://0.0.0.0:8080 3.97 kB {0} [built]
    [2] /home/evadeflow/.local/React-and-React-Native/~/url/url.js 23.3 kB {0} [built]
    [3] /home/evadeflow/.local/React-and-React-Native/~/url/~/punycode/punycode.js 14.6 kB {0} [built]

  <... lots of similar output omitted ...>

  [251] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMUnknownPropertyHook.js 4.32 kB {0} [built]
  [252] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMNullInputValuePropHook.js 1.37 kB {0} [built]
  [253] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMInvalidARIAHook.js 3.14 kB {0} [built]
webpack: Compiled successfully.
</code>```

After the last step, node is running. However, I see a blank page when I hit localhost:8080 in my browser:

Am I doing something wrong?

答:
Try the following:

1) Install webpack both globally and locally, i.e. at the base directory of the code do the following:

```<code>npm install webpack --global
npm install webpack --save-dev
</code>```

2) Install the webpack dev server, also both globally and locally:

```<code>npm install webpack-dev-server --global
npm install webpack-dev-server --save-dev
</code>```

3) Update the webpack.config.js files, in particular the "loader" line, as follows:

(A) Replace 'react-hot' with 'react-hot-loader/webpack'

(B) Replace 'babel' with 'babel-loader'

So for example, the "hello-jsx" file here is the line in the OLD, ORIGINAL webpack.config.js file:

```<code>loaders: ['react-hot', 'babel?presets[]=es2015'],
</code>```

And here is the line in the NEW, UPDATE webpack.config.js file:

```<code>loaders: ['react-hot-loader/webpack', 'babel-loader?presets[]=es2015'],
</code>```

4) Run the webpack dev server (from the subdirectory) with the hot and inline options, e.g.

```<code>$ pwd
[whatever_base_directory]/Chapter02/hello-jsx
$ webpack-dev-server --hot --inline
</code>```

Body:
I'm trying to get a simple "Hello, World"-type React.js app from the book React and React Native running under Node/webpack-dev-server. I'm not seeing any errors, but the page is blank when I visit it in my browser.

Here's how I tried—and failed—to run the book's very first example:

Install node and npm using these steps (adapted from this gist):

$ mkdir ~/.local/node-latest-install
$ cd ~/.local/node-latest-install
$ curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
$ ./configure --prefix=~/.local
$ make -j install
$ curl https://www.npmjs.com/install.sh | sh
$ node -v; npm -v
v7.7.4
4.1.2

Clone the examples repo from the book:

$ git clone https://github.com/PacktPublishing/React-and-React-Native.git

Run npm install from the top-level examples folder:

$ cd React-and-React-Native
$ npm install

Attempt to compile/run hello-jsx example:

$ cd Chapter02/hello-jsx
$ node ../../node_modules/webpack-dev-server/bin/webpack-dev-server.js
...
ERROR in ./main.js
Module build failed: Error: React Hot Loader: The Webpack loader is now exported separately. If you use Babel, we recommend that you remove "react-hot-loader" from the "loaders" section of your Webpack configuration altogether, and instead add "react-hot-loader/babel" to the "plugins" section of your .babelrc file. If you prefer not to use Babel, replace "react-hot-loader" or "react-hot" with "react-hot-loader/webpack" in the "loaders" section of your Webpack configuration.
at Object.warnAboutIncorrectUsage (/home/evadeflow/.local/React-and-React-Native/node_modules/react-hot-loader/lib/index.js:7:11)
@ multi main
webpack: Failed to compile.

Edit hello-jsx/webpack.config.js to work around the above error:

diff --git a/Chapter02/hello-jsx/webpack.config.js b/Chapter02/hello-jsx/webpack.config.js
index 312f152..592e767 100644
--- a/Chapter02/hello-jsx/webpack.config.js
+++ b/Chapter02/hello-jsx/webpack.config.js
@@ -13,7 +13,7 @@ module.exports = {
       {
         test: /\.jsx?$/,
         exclude: /node_modules/,
-        loaders: ['react-hot', 'babel?presets[]=es2015'],
+        loaders: ['react-hot-loader/webpack', 'babel?presets[]=es2015'],
       },
     ],
   },

Recompile/re-run:

$ node ../../node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /home/evadeflow/.local/React-and-React-Native/Chapter02/hello-jsx
Hash: 590282c761dccbb5710a
Version: webpack 1.14.0
Time: 1260ms
         Asset    Size  Chunks             Chunk Names
main-bundle.js  978 kB       0  [emitted]  main
chunk    {0} main-bundle.js (main) 923 kB [rendered]
    [0] multi main 52 bytes {0} [built]
    [1] (webpack)-dev-server/client?http://0.0.0.0:8080 3.97 kB {0} [built]
    [2] /home/evadeflow/.local/React-and-React-Native/~/url/url.js 23.3 kB {0} [built]
    [3] /home/evadeflow/.local/React-and-React-Native/~/url/~/punycode/punycode.js 14.6 kB {0} [built]

  <... lots of similar output omitted ...>

  [251] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMUnknownPropertyHook.js 4.32 kB {0} [built]
  [252] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMNullInputValuePropHook.js 1.37 kB {0} [built]
  [253] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMInvalidARIAHook.js 3.14 kB {0} [built]
webpack: Compiled successfully.

After the last step, node is running. However, I see a blank page when I hit localhost:8080 in my browser:

Am I doing something wrong?

Body:
Try the following:

1) Install webpack both globally and locally, i.e. at the base directory of the code do the following:

npm install webpack --global
npm install webpack --save-dev

2) Install the webpack dev server, also both globally and locally:

npm install webpack-dev-server --global
npm install webpack-dev-server --save-dev

3) Update the webpack.config.js files, in particular the "loader" line, as follows:

(A) Replace 'react-hot' with 'react-hot-loader/webpack'

(B) Replace 'babel' with 'babel-loader'

So for example, the "hello-jsx" file here is the line in the OLD, ORIGINAL webpack.config.js file:

loaders: ['react-hot', 'babel?presets[]=es2015'],

And here is the line in the NEW, UPDATE webpack.config.js file:

loaders: ['react-hot-loader/webpack', 'babel-loader?presets[]=es2015'],

4) Run the webpack dev server (from the subdirectory) with the hot and inline options, e.g.

$ pwd
[whatever_base_directory]/Chapter02/hello-jsx
$ webpack-dev-server --hot --inline


问:
DELETE from ListObject table rows meeting condition using VBA
Is it possible in VBA to DELETE all the rows meeting condition from Excel ListObject table? I am looking for something similar to SQL statement:

DELETE FROM MyListObjectTable WHERE MyColumn='Some Condition'

答:
Try this:

.- Break the connection,

.- Sort the ListObject as per condition (Optional just to have the results of  the condition in one Range.Area for the deletion),

.- AutoFilter the ListObject as per condition,

.- Delete visible rows of the ListObject.DataBodyRange

.- Clear AutoFilter


问:
Unexpected infinite loop in Javascript
I was doing a cookie practice in javascript and developed the following code:

```<code>function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {
    var cookie = acookies[i];
    while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
      cookie = cookie.substring(1);
    }
    if(cookie.indexOf(fullkeyname) == 0) {
    return cookie.substring(fullkeyname.length, cookie.length);
  }
}
return "";
}
</code>```

It didnt worked and seemed to rise and infinite loop so I tracked my code with "document.write" in various parts and discovered that if I change the "while" condition it will work as follows:

```<code>function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {
    var cookie = acookies[i];
    while (cookie.charAt(0) == " ") { //RIGHT HERE
      cookie = cookie.substring(1);
    }
    if (acookies[i].indexOf(fullkeyname) == 0) {
      return cookie.substring(fullkeyname.length, cookie.length);
    }
  }
  return "";
}
</code>```

Now my code works as expected, however I dont know why, since I have set the value of cookies to "cookie=acookies[i]" I dont understand why it should loop indefinetly if I dont use the "cookie" variable.
Question is: why does the code works with my "cookie" variable and not with the "acookies[i]" even though the sould have the same value at that given moment?

答:
I see a problem in while loop

```<code>while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
      cookie = cookie.substring(1);
}
</code>```

once acookies[i].charAt(0) == " " becomes true, it will keep on looping and will never get to go outside while loop to increment the value of 'i'.

and in the second version of the code you're modifying the cookie variable itself which make the while condition false which moves the control out of the loop and continue execution.

Title: Unexpected infinite loop in Javascript

Body:
I was doing a cookie practice in javascript and developed the following code:

function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {
    var cookie = acookies[i];
    while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
      cookie = cookie.substring(1);
    }
    if(cookie.indexOf(fullkeyname) == 0) {
    return cookie.substring(fullkeyname.length, cookie.length);
  }
}
return "";
}

It didnt worked and seemed to rise and infinite loop so I tracked my code with "document.write" in various parts and discovered that if I change the "while" condition it will work as follows:

function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {
    var cookie = acookies[i];
    while (cookie.charAt(0) == " ") { //RIGHT HERE
      cookie = cookie.substring(1);
    }
    if (acookies[i].indexOf(fullkeyname) == 0) {
      return cookie.substring(fullkeyname.length, cookie.length);
    }
  }
  return "";
}

Now my code works as expected, however I dont know why, since I have set the value of cookies to "cookie=acookies[i]" I dont understand why it should loop indefinetly if I dont use the "cookie" variable.
Question is: why does the code works with my "cookie" variable and not with the "acookies[i]" even though the sould have the same value at that given moment?

Body:
I see a problem in while loop

while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
      cookie = cookie.substring(1);
}

once acookies[i].charAt(0) == " " becomes true, it will keep on looping and will never get to go outside while loop to increment the value of 'i'.

and in the second version of the code you're modifying the cookie variable itself which make the while condition false which moves the control out of the loop and continue execution.


问:
Null terminator not getting added at end of initializer in case of unsigned char[]!
I have the following four lines of code:

```<code>unsigned char key[] = {1,2,3,4,5,6,7,8,8,7,6,5,4,3,2,1};
unsigned char iv[] = {1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8};
printf("key = %s length = %d\n",key, strlen((char *)key));
printf("iv = %s length = %d\n",iv, strlen((char *)iv));
</code>```

With the initializer i expect a NULL character to be appended at the end of both the variables key and iv, so i expect the length for both to be 16, but the output i get when i compile and run this code is as shown below:

key = (32 binary characters) length = 32

iv = (16 binary characters) length = 16

But as we can see, the length of iv is 16 as expected, but the length of iv is greater than 16. Not sure why the null terminator was not added in case of key. Can someone please indicate if the null terminator is added by default or not.

答:
To answer your question: This type of initialization does not append the NULL Terminator at the end of the char array. You can for example look at the debug output from lldb:

As already mentioned strlen() is looking for the position of the NULL Terminator and as he can not find one, he reads into not allocated memory, which is undefinied behaviour

Body:
I have the following four lines of code:

unsigned char key[] = {1,2,3,4,5,6,7,8,8,7,6,5,4,3,2,1};
unsigned char iv[] = {1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8};
printf("key = %s length = %d\n",key, strlen((char *)key));
printf("iv = %s length = %d\n",iv, strlen((char *)iv));

With the initializer i expect a NULL character to be appended at the end of both the variables key and iv, so i expect the length for both to be 16, but the output i get when i compile and run this code is as shown below:

key = (32 binary characters) length = 32

iv = (16 binary characters) length = 16

But as we can see, the length of iv is 16 as expected, but the length of iv is greater than 16. Not sure why the null terminator was not added in case of key. Can someone please indicate if the null terminator is added by default or not.


问:
Why does php returns a json when I look for some columns and not for others?
Here is my code, it works like it is right now:

```<code>$con = @mysql_connect($server_name, $mysql_username, $mysql_password) or die("cannot connect");

mysql_select_db($db_name) or die("cannot select DB");

$sql="SELECT `idComp`,`nombre`,`foto` from RECURSOHUMANO;";
$result = mysql_query($sql);
$json= array();

if(mysql_num_rows($result)>0){
    while($row=mysql_fetch_assoc($result)){
        $json['Data'][]=$row;
    }
}

mysql_close($con);
echo json_encode($json);

?>
</code>```

The table that i'm working on has other columns and would like to add some of them to the SELECT query, but when I add another one, say apPat, it stops working.

Just to be clear Ill write how I would normally do it:

```<code>$sql="SELECT `idComp`,`nombre`,`apPat`,`foto` from RECURSOHUMANO;";
</code>```

apPat is exactly like 'nombre', so I dont see why it doesn't work.

Also when I add other columns it works, it just breaks with a couple of them, but I need them.

UPDATE:
Just to clarify. The MySQL query is correct, if I run it by itself it gives me what I want, even when I add the other columns. The problem, I think is in the php.

答:
When using single or double quotes in your field list, you are telling mysql to make a column that has that exact string inside of it.

So your results more like likely look like this, correct?

mysql> select `pid`, `source`, `alias` from url_alias limit 5;
+-----+--------------------+--------------------------+
| pid | source             | alias                    |
+-----+--------------------+--------------------------+
|   1 | /taxonomy/term/16  | /blah/project-management |
|   2 | /taxonomy/term/14  | /blah/development        |
|   3 | /taxonomy/term/137 | /blah/business           |
|   4 | /taxonomy/term/13  | /blah/design             |
|   5 | /taxonomy/term/15  | /blah/quality-assurance  |
+-----+--------------------+--------------------------+
5 rows in set (0.00 sec)

Notice now the single quotes around 'i am a string' and how the results are shown:

mysql> select `pid`, 'i am a string', `alias` from url_alias limit 5;
+-----+---------------+--------------------------+
| pid | i am a string | alias                    |
+-----+---------------+--------------------------+
|   1 | i am a string | /blah/project-management |
|   2 | i am a string | /blah/development        |
|   3 | i am a string | /blah/business           |
|   4 | i am a string | /blah/design             |
|   5 | i am a string | /blah/quality-assurance  |
+-----+---------------+--------------------------+
5 rows in set (0.00 sec)

I hope this helps!

Body:
Here is my code, it works like it is right now:

$con = @mysql_connect($server_name, $mysql_username, $mysql_password) or die("cannot connect");

mysql_select_db($db_name) or die("cannot select DB");

$sql="SELECT `idComp`,`nombre`,`foto` from RECURSOHUMANO;";
$result = mysql_query($sql);
$json= array();

if(mysql_num_rows($result)>0){
    while($row=mysql_fetch_assoc($result)){
        $json['Data'][]=$row;
    }
}

mysql_close($con);
echo json_encode($json);

?>

The table that i'm working on has other columns and would like to add some of them to the SELECT query, but when I add another one, say apPat, it stops working.

Just to be clear Ill write how I would normally do it:

$sql="SELECT `idComp`,`nombre`,`apPat`,`foto` from RECURSOHUMANO;";

apPat is exactly like 'nombre', so I dont see why it doesn't work.

Also when I add other columns it works, it just breaks with a couple of them, but I need them.

UPDATE:
Just to clarify. The MySQL query is correct, if I run it by itself it gives me what I want, even when I add the other columns. The problem, I think is in the php.


问:
Highcharts Solid Gauge Legend Symbol
Is it possible to style the legend symbol for a solid gauge? I'm need the legend symbols to be colored squares but adding squareSymbol: true isn't working. Here's a fiddle: http://jsfiddle.net/0krjsy5n/

```<code>legend: {
    squareSymbol: true
},

series: [{
    name: 'Speed',
    data: [80],
    showInLegend: true,
    dataLabels: {
        format: '<div style="text-align:center"><span style="font-size:25px;color:' +
            ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
               '<span style="font-size:12px;color:silver">km/h</span></div>'
    },
    tooltip: {
        valueSuffix: ' km/h'
    }
}]
</code>```

答:
The legend symbol is a representation of the series marker. You can manipulate the legend symbol by editing the series marker. For other charts this will alter the marker shown in the series, but in your case (for gauge) the marker is never shown in the actual graph.

For example, in your case (JSFiddle):

```<code>series: [{
    marker: {
        symbol: 'square', // Make it a square
        fillColor: 'red', // With color red
    },
    lineWidth: 0 // With no line going through it
    // ...
}]
</code>```

Title: Highcharts Solid Gauge Legend Symbol

Body:
Is it possible to style the legend symbol for a solid gauge? I'm need the legend symbols to be colored squares but adding squareSymbol: true isn't working. Here's a fiddle: http://jsfiddle.net/0krjsy5n/

legend: {
    squareSymbol: true
},

series: [{
    name: 'Speed',
    data: [80],
    showInLegend: true,
    dataLabels: {
        format: '
{y}
' +
               'km/h
'
    },
    tooltip: {
        valueSuffix: ' km/h'
    }
}]

Body:
The legend symbol is a representation of the series marker. You can manipulate the legend symbol by editing the series marker. For other charts this will alter the marker shown in the series, but in your case (for gauge) the marker is never shown in the actual graph.

For example, in your case (JSFiddle):

series: [{
    marker: {
        symbol: 'square', // Make it a square
        fillColor: 'red', // With color red
    },
    lineWidth: 0 // With no line going through it
    // ...
}]


问:
How to count integer values stored in a variable using php?
I am developing a web form which have a field 'marks' where user can put marks... I want to force the user to  input only marks less then 4 digits. Here is function for this purpose but it is not working...

```<code>Function validate($marks)
If(strlen($marks)<=4 && !filter_var($marks, FILTER_VALIDATE_INT)
</code>```

)

```<code>Return false;
</code>```

Else

```<code>Return true ;
</code>```

答:
If you want to do it with php you can do it like this if the data type is an integer or a float:

```<code>if ($marks <= 9999.99) {
    //do something
}
</code>```

If it is a string representation of numbers, you can do it like this:

```<code>if (strlen($marks) <= 4) {
    // do something
}
</code>```

Body:
I am developing a web form which have a field 'marks' where user can put marks... I want to force the user to  input only marks less then 4 digits. Here is function for this purpose but it is not working...

Function validate($marks)
If(strlen($marks)<=4 && !filter_var($marks, FILTER_VALIDATE_INT)

)

Return false;

Else

Return true ;

Body:
If you want to do it with php you can do it like this if the data type is an integer or a float:

if ($marks <= 9999.99) {
    //do something
}

If it is a string representation of numbers, you can do it like this:

if (strlen($marks) <= 4) {
    // do something
}


问:
Developing a Counter for Outputting Data Info into a specific range of excel rows & columns?
I am a beginner in Python with just basic fundamentals under my belt, ie. loops and modules.  I have some data that I want to automate by exporting it as text into specific Microsoft excel cells.

Specifically, I have 3 folders each with image files in them, a total of 10 image files.  My goal is to make a code that opens up excel and outputs the name of the folder path in each descending row of Column A and the respective image file name in descending rows of column B.

So far, I have defined the folder and path, and have allowed my code to open up Excel and name the sheet and put a title in.  I encountered my problem when trying to individually iterate each folder/file into a new cell. I tried using the range function, but it doesn't work with strings and I feel like a simple counter variable would work, but again, excel column and row names are strings.

Here is my code so far:

```<code>import win32com.client

import sys, os, string, arcpy

data_folder = "F:\\School\\GEOG_390\\Week11\\data"

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()

print(xlApp.Worksheets("Sheet1").Name)
xlApp.Worksheets("Sheet1").Range("A1").Value= "Data Files:"

for root, folders, files, in os.walk(data_folder):
for folder in folders:
    workspace = os.path.join(root, folder)
    print( "Processing" + " " + workspace)

    arcpy.env.workspace = workspace

    rasters = arcpy.ListRasters("*", "IMG")

    for raster in rasters:
        arcpy.BuildPyramids_management(raster)
        arcpy.CalculateStatistics_management(raster)

        print(raster)

        sheet = xlApp.Worksheets("Sheet1")
        sheet.Range("A2").Value = "Folder:" + folder
        sheet.Range("B2").Value = "Raster:" + raster

        print(sheet.Range("A2").Value)
        print(sheet.Range("B2").Value)
</code>```

I need the code to put folder name 1 in cell A2 and the image file name in B2, and from there on, folder 2 in cell A3 and file 2 in cell B3, all the way until cells A11 and B11.

答:
you need to think of it programatically start with a method name

```<code>def get_xls_range(start,end):
    letter1,num1 = start[0],int(start[1:]) # get the alpha part and the numeric part
    letter2,num2 = end[0],int(end[1:]) # same for end
    #convert the letters to a range
    range_rows = [chr(x) for x in range(ord(letter1),ord(letter2)+1)]
    #convert the numerics to a range
    range_cols = range(num1,num2+1)
    for row in range_rows:
        for col in range_cols:
            yield "%s%s"%(row,col)
</code>```

then all you need to do is interact with your new function

```<code>  for cell in get_xls_range("A1","B22"):
      print cell
</code>```

Body:
I am a beginner in Python with just basic fundamentals under my belt, ie. loops and modules.  I have some data that I want to automate by exporting it as text into specific Microsoft excel cells.

Specifically, I have 3 folders each with image files in them, a total of 10 image files.  My goal is to make a code that opens up excel and outputs the name of the folder path in each descending row of Column A and the respective image file name in descending rows of column B.

So far, I have defined the folder and path, and have allowed my code to open up Excel and name the sheet and put a title in.  I encountered my problem when trying to individually iterate each folder/file into a new cell. I tried using the range function, but it doesn't work with strings and I feel like a simple counter variable would work, but again, excel column and row names are strings.

Here is my code so far:

import win32com.client

import sys, os, string, arcpy

data_folder = "F:\\School\\GEOG_390\\Week11\\data"

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()

print(xlApp.Worksheets("Sheet1").Name)
xlApp.Worksheets("Sheet1").Range("A1").Value= "Data Files:"

for root, folders, files, in os.walk(data_folder):
for folder in folders:
    workspace = os.path.join(root, folder)
    print( "Processing" + " " + workspace)

    arcpy.env.workspace = workspace

    rasters = arcpy.ListRasters("*", "IMG")

    for raster in rasters:
        arcpy.BuildPyramids_management(raster)
        arcpy.CalculateStatistics_management(raster)

        print(raster)

        sheet = xlApp.Worksheets("Sheet1")
        sheet.Range("A2").Value = "Folder:" + folder
        sheet.Range("B2").Value = "Raster:" + raster

        print(sheet.Range("A2").Value)
        print(sheet.Range("B2").Value)

I need the code to put folder name 1 in cell A2 and the image file name in B2, and from there on, folder 2 in cell A3 and file 2 in cell B3, all the way until cells A11 and B11.

Body:
you need to think of it programatically start with a method name

def get_xls_range(start,end):
    letter1,num1 = start[0],int(start[1:]) # get the alpha part and the numeric part
    letter2,num2 = end[0],int(end[1:]) # same for end
    #convert the letters to a range
    range_rows = [chr(x) for x in range(ord(letter1),ord(letter2)+1)]
    #convert the numerics to a range
    range_cols = range(num1,num2+1)
    for row in range_rows:
        for col in range_cols:
            yield "%s%s"%(row,col)

then all you need to do is interact with your new function

  for cell in get_xls_range("A1","B22"):
      print cell


问:
Debugging in Unity (C#) + Visual Studio Code Work on OS X?
I really like the idea of working with Visual Studio, C# and Unity on OS X.

Has anyone made debugging with C# in Unity work with Visual Studio Code on OS X?

答:
To build Unity in Visual Studio Code, you can hook up Mono xbuild compiler as a task runner, so you don't even have to leave IDE to have errors and warnings.

See https://twitter.com/_eppz/status/846859856787259392 for more.


问:
Unix sort treatment of underscore character
I have two linux machines, on which unix sort seems to behave differently. I believe I've narrowed it down to the treatment of the underscore character.

If I run sort tmp, where tmp contains the following two lines:

```<code>aa_d_hh
aa_dh_ey
</code>```

one machine outputs

```<code>aa_d_hh
aa_dh_ey
</code>```

(i.e. '_' precedes 'h') while the other outputs

```<code>aa_dh_ey
aa_d_hh
</code>```

(i.e. 'h' precedes '_'). I need these machines to behave together (as I use sort -m later, to merge very large files).

Is there any way I can force sort to behave in one way or the other?

Thanks.

答:
This is likely caused by a difference in locale. In the en_US.UTF-8 locale, underscores (_) sort after letters and numbers, whereas in the POSIX C locale they sort after uppercase letters and numbers, but before lowercase letters.

# won't change LC_COLLATE=C after execution
$ LC_COLLATE=C sort filename
```
<p>You can also use <code>sort --debug</code> to show more information about the sorting behavior in general:</p>
```$ (echo 'foo_bar'; echo 'fooAbar'; echo 'foo0bar'; echo 'fooabar') |
      LC_COLLATE=en_US.UTF-8 sort --debug
sort: using ‘en_US.UTF-8’ sorting rules
foo0bar
fooabar
fooAbar
foo_bar

$ (echo 'foo_bar'; echo 'fooAbar'; echo 'foo0bar'; echo 'fooabar') |
      LC_COLLATE=C sort --debug
sort: using simple byte comparison
foo0bar
fooAbar
foo_bar
fooabar
```

As also shown in this answer, you can use the above formula to force LC_COLLATE=C for a single command, without modifying your shell environment:

Body:
I have two linux machines, on which unix sort seems to behave differently. I believe I've narrowed it down to the treatment of the underscore character.

If I run sort tmp, where tmp contains the following two lines:

aa_d_hh
aa_dh_ey

one machine outputs

aa_d_hh
aa_dh_ey

(i.e. '_' precedes 'h') while the other outputs

aa_dh_ey
aa_d_hh

(i.e. 'h' precedes '_'). I need these machines to behave together (as I use sort -m later, to merge very large files).

Is there any way I can force sort to behave in one way or the other?

Thanks.

Body:
This is likely caused by a difference in locale. In the en_US.UTF-8 locale, underscores (_) sort after letters and numbers, whereas in the POSIX C locale they sort after uppercase letters and numbers, but before lowercase letters.

# won't change LC_COLLATE=C after execution
$ LC_COLLATE=C sort filename

You can also use sort --debug to show more information about the sorting behavior in general:

$ (echo 'foo_bar'; echo 'fooAbar'; echo 'foo0bar'; echo 'fooabar') |
      LC_COLLATE=en_US.UTF-8 sort --debug
sort: using ‘en_US.UTF-8’ sorting rules
foo0bar
fooabar
fooAbar
foo_bar

$ (echo 'foo_bar'; echo 'fooAbar'; echo 'foo0bar'; echo 'fooabar') |
      LC_COLLATE=C sort --debug
sort: using simple byte comparison
foo0bar
fooAbar
foo_bar
fooabar

As also shown in this answer, you can use the above formula to force LC_COLLATE=C for a single command, without modifying your shell environment:

ContentLicense: CC BY-SA 4.0