问:
Initializing React number input control with blank value?
I'd like my controlled input to initialize with no value in the box.
The input is a number, so I don't pass in an empty ''.
Using defaultProps, I initialize the input with a null.

When typing into the input the console reports this message:

<MyInput> is changing an uncontrolled input of type number to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

To prevent this normally I initialize with an empty string to prevent this "switching" from happening. But with a number (I don't want to show a 0, I want nothing to show) I am not sure how to do it.

```<code>static defaultProps = {
    estimatedHours: null,
    estimatedMinutes: null,
  }
</code>```

defalut values ^^

```<code><input
   type="number"
   onChange={(e) => this.handleChange('Hours', e.target.value)}
   onKeyDown={this.handleKeyDown}
   onPaste={this.handlePaste}
   value={estimatedHours}
   placeholder={hoursText}
   className="slds-input th-trailmix-textbox th-time-component__input"
/>
</code>```

答:
You can set value Undefined,

Also add a check for input type if required

```<code>class Input extends React.Component {

    constructor(props) {
        super(props);
        this.state = {value: undefined};

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange = (event) => {
        const isnum = /^\d+$/.test(event.target.value);
        if (isnum) {
            return this.setState({
                value: Number(event.target.value),
            });
        }
    };

    render() {
        return (
            <input
                type="number"
                onChange={this.handleChange}
                value={String(this.state.value)}
                placeholder={"Please enter number"}
            />
        );
    }
}
</code>```

and convert String to Number and vice versa

This won't throw you an error for uncontrolled input

Body:
I'd like my controlled input to initialize with no value in the box.
The input is a number, so I don't pass in an empty ''.
Using defaultProps, I initialize the input with a null.

When typing into the input the console reports this message:

<MyInput> is changing an uncontrolled input of type number to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

To prevent this normally I initialize with an empty string to prevent this "switching" from happening. But with a number (I don't want to show a 0, I want nothing to show) I am not sure how to do it.

static defaultProps = {
    estimatedHours: null,
    estimatedMinutes: null,
  }

defalut values ^^

<input
   type="number"
   onChange={(e) => this.handleChange('Hours', e.target.value)}
   onKeyDown={this.handleKeyDown}
   onPaste={this.handlePaste}
   value={estimatedHours}
   placeholder={hoursText}
   className="slds-input th-trailmix-textbox th-time-component__input"
/>

Body:
You can set value Undefined,

Also add a check for input type if required

class Input extends React.Component {

    constructor(props) {
        super(props);
        this.state = {value: undefined};

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange = (event) => {
        const isnum = /^\d+$/.test(event.target.value);
        if (isnum) {
            return this.setState({
                value: Number(event.target.value),
            });
        }
    };

    render() {
        return (
            <input
                type="number"
                onChange={this.handleChange}
                value={String(this.state.value)}
                placeholder={"Please enter number"}
            />
        );
    }
}

and convert String to Number and vice versa

This won't throw you an error for uncontrolled input


来源: stackexchange

问:
How to generate SpreasheetML samples for all three date compatibility settings from Excel 2010?
According to the ECMA-376, Second Edition, Part 1 - Fundamentals And Markup Language Reference SpreadsheetML supports date serial values with three possible compatibility settings and various ranges.

http://www.documentinteropinitiative.com/implnotes/ISO-IEC29500-2008/001.018.017.004.001.000.000.aspx

In the 1900 date base system, the lower limit is January 1, -9999, which has serial value -4346018. The base date for this date base system is December 30, 1899, which has a serial value of 0.

In the 1900 backward compatibility date-base system, the lower limit is January 1, 1900, which
  has serial value 1. The base date for this date base system is December 31, 1899, which has a serial
  value of 0.

In the 1904 backward compatibility date-base system, the lower limit is January 1, 1904, which
  has serial value 0. The base date for this date base system is January 1, 1904, which has a serial value
  of 0.

However, when I use Microsoft Office Excel 2010 to generate a *.xlsx file with a date serial of 1, the *.xlsx file does not have any dateCompatibility attribute set (indicating "1900 date base system") but the date associated with date serial 1 is January 1, 1900 (indicating "1900 backward compatibility").

The workbookPr element is this, unedited, no dateCompatibility attribute.

```<code><x:workbookPr defaultThemeVersion="124226" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main" />
</code>```

And here is a row of data that shows a date serial of 1 and the text result of formatting it as a date:

```<code>   <x:row r="3" spans="1:2">
     <x:c r="A3">
       <x:v>1</x:v>
     </x:c>
     <x:c r="B3" t="str">
       <x:f t="shared" si="0" />
       <x:v>1900-01-01 00:00:00.0</x:v>
     </x:c>
   </x:row>
</code>```

the formula is just date formatting, referenced earlier in the worksheet:

```<code>    <x:f t="shared" ref="B1:B42" si="0">TEXT(A1, "yyyy-mm-dd HH:mm:ss.0")</x:f>
</code>```

This formula gives the same result as applying a date format pattern to the date serial number, demonstrated in the below screen shot.

Also formatting negative dates results in an error, another indicator that Excel is actually using backwards-compatible date system despite the absence of the dateCompatibility attribute on workbookPr.

The options for the workbook only show an unchecked checkbox for 1904 date system.  I don't see any option for 1900 date based vs. 1900 backwards-compatibility.

Am I reading the spec wrong? Or the SpreadsheetML? Or something else?

答:
The default implementation in Excel is dateCompatibility="1" (i.e. 1900 backward compatibility), so if it is absent, it is still dateCompatibility="1". Note that Excel doesn't fully implement SpreadsheetML (as Word and PowerPoint also do not fully implement their respective MLs and with 2010 client versions, extend the ML in ways not supported by the standard(s)). 1 and 3 don't appear to be implemented (very well) in conversion of serial values to date values.

There's been some push-back to ECMA on this and the use of date1904, see: http://xmlguru.cz/2008/01/ecma-response-to-czech-ooxml-comments and search on dateCompatibility

ContentLicense: CC BY-SA 2.5

Body:
According to the ECMA-376, Second Edition, Part 1 - Fundamentals And Markup Language Reference SpreadsheetML supports date serial values with three possible compatibility settings and various ranges.

http://www.documentinteropinitiative.com/implnotes/ISO-IEC29500-2008/001.018.017.004.001.000.000.aspx

In the 1900 date base system, the lower limit is January 1, -9999, which has serial value -4346018. The base date for this date base system is December 30, 1899, which has a serial value of 0.

In the 1900 backward compatibility date-base system, the lower limit is January 1, 1900, which
  has serial value 1. The base date for this date base system is December 31, 1899, which has a serial
  value of 0.

In the 1904 backward compatibility date-base system, the lower limit is January 1, 1904, which
  has serial value 0. The base date for this date base system is January 1, 1904, which has a serial value
  of 0.

However, when I use Microsoft Office Excel 2010 to generate a *.xlsx file with a date serial of 1, the *.xlsx file does not have any dateCompatibility attribute set (indicating "1900 date base system") but the date associated with date serial 1 is January 1, 1900 (indicating "1900 backward compatibility").

The workbookPr element is this, unedited, no dateCompatibility attribute.

<x:workbookPr defaultThemeVersion="124226" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main" />

And here is a row of data that shows a date serial of 1 and the text result of formatting it as a date:

   <x:row r="3" spans="1:2">
     <x:c r="A3">
       <x:v>1</x:v>
     </x:c>
     <x:c r="B3" t="str">
       <x:f t="shared" si="0" />
       <x:v>1900-01-01 00:00:00.0</x:v>
     </x:c>
   </x:row>

the formula is just date formatting, referenced earlier in the worksheet:

    <x:f t="shared" ref="B1:B42" si="0">TEXT(A1, "yyyy-mm-dd HH:mm:ss.0")</x:f>

This formula gives the same result as applying a date format pattern to the date serial number, demonstrated in the below screen shot.

Also formatting negative dates results in an error, another indicator that Excel is actually using backwards-compatible date system despite the absence of the dateCompatibility attribute on workbookPr.

The options for the workbook only show an unchecked checkbox for 1904 date system.  I don't see any option for 1900 date based vs. 1900 backwards-compatibility.

Am I reading the spec wrong? Or the SpreadsheetML? Or something else?


问:
Speed up the calculation of proportion of most frequent digits in a string, in R
I need help with speeding up a function to compute the proportion repeating digits (ignoring any non-digit). The function helps identify fake entries from a user, before running any check-digit verification (if such is even available). Think fake phone number, fake student number, fake checking account number, fake credit card number, fake any identifier, and so on.

The function is a generalization from this post.

Here is what it does. For the specified number of most frequently appearing digits, it computes the proportion of top digits to all digits in a string, ignoring all non-digits. If there are no digits in a string, it returns 1.0. All calculations are done on a vector of strings.

```<code>library(microbenchmark)
V = c('(12) 1221-12121,one-twoooooooooo', 'twos:22-222222222', '34-11111111, ext.123',
        '01012', '123-456-789 valid', 'no digits', '', NaN, NA)

Fake_Similarity = function(V, TopNDigits) {
    vapply(V, function(v) {
        freq = sort(tabulate(as.integer(charToRaw(v)))[48:57], decreasing = T);
        ratio = sum(freq[1:TopNDigits], na.rm = T) / sum(freq, na.rm = T)
        if (is.nan(ratio)) ratio = 1
        ratio
    },
    double(1))
}

t(rbind(Top1Digit = Fake_Similarity(v, 1), Top2Digits = Fake_Similarity(v, 2), Top3Digits = Fake_Similarity(v, 3)))

microbenchmark(Fake_Similarity(v, 2))
</code>```

with the output. The labels are not important, but the order ratios must match the original order of corresponding strings.

```<code>                                 Top1Digit Top2Digits Top3Digits
(12) 1221-12121,one-twoooooooooo 0.5454545  1.0000000  1.0000000
twos:22-222222222                1.0000000  1.0000000  1.0000000
34-11111111, ext.123             0.6923077  0.8461538  0.9230769
01012                            0.4000000  0.8000000  1.0000000
123-456-789 valid                0.1111111  0.2222222  0.3333333
no digits                        1.0000000  1.0000000  1.0000000
                                 1.0000000  1.0000000  1.0000000
NaN                              1.0000000  1.0000000  1.0000000
<NA>                             1.0000000  1.0000000  1.0000000
Unit: milliseconds
                  expr      min       lq     mean   median       uq      max neval
 Fake_Similarity(v, 2) 1.225418 1.283113 1.305139 1.292755 1.304262 1.769703   100
</code>```

For example, twos:22-222222222 has 11 digits and all of them are the same. So, for the Top1Digit we have 11/11=1, for the Top2Digits we have (11+0)/11=1 again, and so on. In other words, this is a fake number by any measure. It is highly unlikely for, let's say, a person's phone number to have identical digits, including the area code.

答:
You can use this Rcpp function:

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

// [[Rcpp::export]]
double prop_top_digit(const RawVector& x, int top_n_digits) {

  // counts occurence of each character
  IntegerVector counts(256);
  RawVector::const_iterator it;
  for(it = x.begin(); it != x.end(); ++it) counts[*it]--;

  // partially sort first top_n_digits (negative -> decreasing)
  IntegerVector::iterator it2 = counts.begin() + 48, it3;
  std::partial_sort(it2, it2 + top_n_digits, it2 + 10);

  // sum the first digits
  int top = 0;
  for(it3 = it2; it3 != (it2 + top_n_digits); ++it3) top += *it3;

  // add the rest -> sum all
  int div = top;
  for(; it3 != (it2 + 10); ++it3) div += *it3;

  // return the proportion
  return div == 0 ? 1 : top / (double)div;
}
</code>```

Verification:

```<code>Fake_Similarity2 <- function(V, TopNDigits) {
  vapply(V, function(v) prop_top_digit(charToRaw(v), TopNDigits), 1)
    }
t(rbind(Top1Digit = Fake_Similarity2(v, 1),
        Top2Digits = Fake_Similarity2(v, 2),
        Top3Digits = Fake_Similarity2(v, 3)))
                                 Top1Digit Top2Digits Top3Digits
(12) 1221-12121,one-twoooooooooo 0.5454545  1.0000000  1.0000000
twos:22-222222222                1.0000000  1.0000000  1.0000000
34-11111111, ext.123             0.6923077  0.8461538  0.9230769
01012                            0.4000000  0.8000000  1.0000000
123-456-789 valid                0.1111111  0.2222222  0.3333333
no digits                        1.0000000  1.0000000  1.0000000
                                 1.0000000  1.0000000  1.0000000
NaN                              1.0000000  1.0000000  1.0000000
<NA>                             1.0000000  1.0000000  1.0000000
</code>```

Benchmark:

```<code>microbenchmark(Fake_Similarity(v, 2), Fake_Similarity2(v, 2))
Unit: microseconds
                   expr     min       lq      mean   median      uq     max neval cld
  Fake_Similarity(v, 2) 298.972 306.0905 328.69384 312.5465 328.108 600.924   100   b
 Fake_Similarity2(v, 2)  25.163  27.1495  30.18863  29.1350  30.460  52.975   100  a
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need help with speeding up a function to compute the proportion repeating digits (ignoring any non-digit). The function helps identify fake entries from a user, before running any check-digit verification (if such is even available). Think fake phone number, fake student number, fake checking account number, fake credit card number, fake any identifier, and so on.

The function is a generalization from this post.

Here is what it does. For the specified number of most frequently appearing digits, it computes the proportion of top digits to all digits in a string, ignoring all non-digits. If there are no digits in a string, it returns 1.0. All calculations are done on a vector of strings.

library(microbenchmark)
V = c('(12) 1221-12121,one-twoooooooooo', 'twos:22-222222222', '34-11111111, ext.123',
        '01012', '123-456-789 valid', 'no digits', '', NaN, NA)

Fake_Similarity = function(V, TopNDigits) {
    vapply(V, function(v) {
        freq = sort(tabulate(as.integer(charToRaw(v)))[48:57], decreasing = T);
        ratio = sum(freq[1:TopNDigits], na.rm = T) / sum(freq, na.rm = T)
        if (is.nan(ratio)) ratio = 1
        ratio
    },
    double(1))
}

t(rbind(Top1Digit = Fake_Similarity(v, 1), Top2Digits = Fake_Similarity(v, 2), Top3Digits = Fake_Similarity(v, 3)))

microbenchmark(Fake_Similarity(v, 2))

with the output. The labels are not important, but the order ratios must match the original order of corresponding strings.

                                 Top1Digit Top2Digits Top3Digits
(12) 1221-12121,one-twoooooooooo 0.5454545  1.0000000  1.0000000
twos:22-222222222                1.0000000  1.0000000  1.0000000
34-11111111, ext.123             0.6923077  0.8461538  0.9230769
01012                            0.4000000  0.8000000  1.0000000
123-456-789 valid                0.1111111  0.2222222  0.3333333
no digits                        1.0000000  1.0000000  1.0000000
                                 1.0000000  1.0000000  1.0000000
NaN                              1.0000000  1.0000000  1.0000000
<NA>                             1.0000000  1.0000000  1.0000000
Unit: milliseconds
                  expr      min       lq     mean   median       uq      max neval
 Fake_Similarity(v, 2) 1.225418 1.283113 1.305139 1.292755 1.304262 1.769703   100

For example, twos:22-222222222 has 11 digits and all of them are the same. So, for the Top1Digit we have 11/11=1, for the Top2Digits we have (11+0)/11=1 again, and so on. In other words, this is a fake number by any measure. It is highly unlikely for, let's say, a person's phone number to have identical digits, including the area code.

Body:
You can use this Rcpp function:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double prop_top_digit(const RawVector& x, int top_n_digits) {

  // counts occurence of each character
  IntegerVector counts(256);
  RawVector::const_iterator it;
  for(it = x.begin(); it != x.end(); ++it) counts[*it]--;

  // partially sort first top_n_digits (negative -> decreasing)
  IntegerVector::iterator it2 = counts.begin() + 48, it3;
  std::partial_sort(it2, it2 + top_n_digits, it2 + 10);

  // sum the first digits
  int top = 0;
  for(it3 = it2; it3 != (it2 + top_n_digits); ++it3) top += *it3;

  // add the rest -> sum all
  int div = top;
  for(; it3 != (it2 + 10); ++it3) div += *it3;

  // return the proportion
  return div == 0 ? 1 : top / (double)div;
}

Verification:

Fake_Similarity2 <- function(V, TopNDigits) {
  vapply(V, function(v) prop_top_digit(charToRaw(v), TopNDigits), 1)
    }
t(rbind(Top1Digit = Fake_Similarity2(v, 1),
        Top2Digits = Fake_Similarity2(v, 2),
        Top3Digits = Fake_Similarity2(v, 3)))
                                 Top1Digit Top2Digits Top3Digits
(12) 1221-12121,one-twoooooooooo 0.5454545  1.0000000  1.0000000
twos:22-222222222                1.0000000  1.0000000  1.0000000
34-11111111, ext.123             0.6923077  0.8461538  0.9230769
01012                            0.4000000  0.8000000  1.0000000
123-456-789 valid                0.1111111  0.2222222  0.3333333
no digits                        1.0000000  1.0000000  1.0000000
                                 1.0000000  1.0000000  1.0000000
NaN                              1.0000000  1.0000000  1.0000000
<NA>                             1.0000000  1.0000000  1.0000000

Benchmark:

microbenchmark(Fake_Similarity(v, 2), Fake_Similarity2(v, 2))
Unit: microseconds
                   expr     min       lq      mean   median      uq     max neval cld
  Fake_Similarity(v, 2) 298.972 306.0905 328.69384 312.5465 328.108 600.924   100   b
 Fake_Similarity2(v, 2)  25.163  27.1495  30.18863  29.1350  30.460  52.975   100  a


问:
EAOutputStream write:maxLength: - 230 failed to write because stream does not have space available
I was using this. It was working well till I upgraded my iphone to IOS 6.1.

```<code>[[session_ipos outputStream] write:ui8Buff maxLength:tot];
</code>```

Now its giving an error message:

ERROR -
  /SourceCache/ExternalAccessory/ExternalAccessory-213/EAOutputStream.m:-[EAOutputStream
  write:maxLength:] - 230 failed to write because stream does not have
  space available

答:
try to write in UI Thread</p>

```<code>EASession _session

InvokeOnMainThread (() => {
   _session.OutputStream.Write(byteArray);
});
</code>```

Body:
I was using this. It was working well till I upgraded my iphone to IOS 6.1.

[[session_ipos outputStream] write:ui8Buff maxLength:tot];

Now its giving an error message:

ERROR -
  /SourceCache/ExternalAccessory/ExternalAccessory-213/EAOutputStream.m:-[EAOutputStream
  write:maxLength:] - 230 failed to write because stream does not have
  space available

Body:
try to write in UI Thread

EASession _session

InvokeOnMainThread (() => {
   _session.OutputStream.Write(byteArray);
});


问:
Conditional Formatting based on cell color
Consider a list with 3 columns.

Column 1 holds a list of dates.

Column 2 holds fixed values, special days such national holidays (Easter) and special days such as Mothersday.

Column 3 holds user defined events.

Column 2 is populated via VBA code and the national holidays are colored blue by the same code but the special days such as Mothersday are not. The user can not manipulate this column.

Column 3 is populated by the users on the sheet itself. If the user adds an event in the third column, the row is colored green by means of conditional formatting.

The problem is that if an event coincides with a national holiday, the blue color is overwritten.

My goal is to add a second conditional formatting rule which checks for:

A user defined event is added

that the color of the row is blue

If both conditions are met a pattern color, pattern style and background color will be set so I'll get a combination of both colors.

If only the first condition is met, only the background color will be set.

In short: I need a way to check for a cell color and incorporate this in a conditional format rule.

答:
I think that you need to create a new VBA function that can determine whether or not a cell is a particular color. For example, the following code could be used to determine if a cell in a range is blue:

```<code>If range.Interior.Color = RGB(0, 0, 256) Then
    colorAction = "Something"
</code>```

Then, call the VBA function from the cell's macro.

```<code>=CheckIfBlue(B5)
</code>```

Allen Wyatt has a good article on conditionally taking an action depending on a cell's color.

Body:
I think that you need to create a new VBA function that can determine whether or not a cell is a particular color. For example, the following code could be used to determine if a cell in a range is blue:

If range.Interior.Color = RGB(0, 0, 256) Then
    colorAction = "Something"

Then, call the VBA function from the cell's macro.

=CheckIfBlue(B5)

Allen Wyatt has a good article on conditionally taking an action depending on a cell's color.


问:
Laravel 5 - Custom Package "Class Not Found" When Pushed to Heroku
I'm having a bit of trouble getting a custom package to work when deploying my Laravel app to Heroku. It works fine locally, but when pushed I get the following error:

```<code>In ProviderRepository.php line 208: Class 'totalWebConnections\simpleBlog\simpleBlogServiceProvider' not found
</code>```

It looks like the server is correctly loading the package from my composer file, just above the error in the log:

```<code>Installing totalwebconnections/simple-blog (1.0.0)
</code>```

In my composer.json

```<code>"require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0",
        "totalwebconnections/simple-blog": "1.0.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.0"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "totalWebConnections\\simpleBlog\\": "vendor/totalWebConnections/simple-blog/src/"

        }
    },
</code>```

And then in my app.php

```<code>    totalWebConnections\simpleBlog\simpleBlogServiceProvider::class,
</code>```

I'm not sure what the issue is?

答: I think you should double check your namespaces and case of file names - when you deploy on Windows for example it doesn't care whether it's simpleBlog or SimpleBog but when deployed to Linux server it won't work if it's not 100% same as it should be.</p>

Body:
I'm having a bit of trouble getting a custom package to work when deploying my Laravel app to Heroku. It works fine locally, but when pushed I get the following error:

In ProviderRepository.php line 208: Class 'totalWebConnections\simpleBlog\simpleBlogServiceProvider' not found

It looks like the server is correctly loading the package from my composer file, just above the error in the log:

Installing totalwebconnections/simple-blog (1.0.0)

In my composer.json

"require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0",
        "totalwebconnections/simple-blog": "1.0.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.0"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "totalWebConnections\\simpleBlog\\": "vendor/totalWebConnections/simple-blog/src/"

        }
    },

And then in my app.php

    totalWebConnections\simpleBlog\simpleBlogServiceProvider::class,

I'm not sure what the issue is?


问:
Standards Document
I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.

I've looked at roughly 10 projects written over the last 3 years from this team and I'm,  obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.

I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?

How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.

Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?

What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:

```<code><com|org|...>.<company>.<app>.<layer>.<function>.ClassName
</code>```

I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.

答: It obviously varies depending on languages and technologies.  By the look of your example name space I am going to guess java, in which case http://java.sun.com/docs/codeconv/ is a really good place to start.  You might also want to look at something like maven's standard directory structure which will make all your projects look similar.  </p>

OwnerDisplayName: Luther Baker

Title: Standards Document

Body:
I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.

I've looked at roughly 10 projects written over the last 3 years from this team and I'm,  obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.

I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?

How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.

Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?

What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:

<com|org|...>.<company>.<app>.<layer>.<function>.ClassName

I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.

OwnerDisplayName: stimms


问:
Parsing date/time string with timezone abbreviated name in Python?
I'm trying to parse timestamp strings like "Sat, 11/01/09 8:00PM EST" in Python, but I'm having trouble finding a solution that will handle the abbreviated timezone.

I'm using dateutil's parse() function, but it doesn't parse the timezone. Is there an easy way to do this?

答:
dateutil's parser.parse() accepts as keyword argument tzinfos a dictionary of the kind {'EST': -5*3600} (that is, matching the zone name to GMT offset in seconds). So assuming we have that, we can do:

```<code>>>> import dateutil.parser as dp
>>> s = 'Sat, 11/01/09 8:00PM'
>>> for tz_code in ('PST','PDT','MST','MDT','CST','CDT','EST','EDT'):
>>>     dt = s+' '+tz_code
>>>     print dt, '=', dp.parse(dt, tzinfos=tzd)

Sat, 11/01/09 8:00PM PST = 2009-11-01 20:00:00-08:00
Sat, 11/01/09 8:00PM PDT = 2009-11-01 20:00:00-07:00
Sat, 11/01/09 8:00PM MST = 2009-11-01 20:00:00-07:00
Sat, 11/01/09 8:00PM MDT = 2009-11-01 20:00:00-06:00
Sat, 11/01/09 8:00PM CST = 2009-11-01 20:00:00-06:00
Sat, 11/01/09 8:00PM CDT = 2009-11-01 20:00:00-05:00
Sat, 11/01/09 8:00PM EST = 2009-11-01 20:00:00-05:00
Sat, 11/01/09 8:00PM EDT = 2009-11-01 20:00:00-04:00
</code>```

Regarding the content of tzinfos, here is how i populated mine:

```<code>tz_str = '''-12 Y
-11 X NUT SST
-10 W CKT HAST HST TAHT TKT
-9 V AKST GAMT GIT HADT HNY
-8 U AKDT CIST HAY HNP PST PT
-7 T HAP HNR MST PDT
-6 S CST EAST GALT HAR HNC MDT
-5 R CDT COT EASST ECT EST ET HAC HNE PET
-4 Q AST BOT CLT COST EDT FKT GYT HAE HNA PYT
-3 P ADT ART BRT CLST FKST GFT HAA PMST PYST SRT UYT WGT
-2 O BRST FNT PMDT UYST WGST
-1 N AZOT CVT EGT
0 Z EGST GMT UTC WET WT
1 A CET DFT WAT WEDT WEST
2 B CAT CEDT CEST EET SAST WAST
3 C EAT EEDT EEST IDT MSK
4 D AMT AZT GET GST KUYT MSD MUT RET SAMT SCT
5 E AMST AQTT AZST HMT MAWT MVT PKT TFT TJT TMT UZT YEKT
6 F ALMT BIOT BTT IOT KGT NOVT OMST YEKST
7 G CXT DAVT HOVT ICT KRAT NOVST OMSST THA WIB
8 H ACT AWST BDT BNT CAST HKT IRKT KRAST MYT PHT SGT ULAT WITA WST
9 I AWDT IRKST JST KST PWT TLT WDT WIT YAKT
10 K AEST ChST PGT VLAT YAKST YAPT
11 L AEDT LHDT MAGT NCT PONT SBT VLAST VUT
12 M ANAST ANAT FJT GILT MAGST MHT NZST PETST PETT TVT WFT
13 FJST NZDT
11.5 NFT
10.5 ACDT LHST
9.5 ACST
6.5 CCT MMT
5.75 NPT
5.5 SLT
4.5 AFT IRDT
3.5 IRST
-2.5 HAT NDT
-3.5 HNT NST NT
-4.5 HLV VET
-9.5 MART MIT'''

tzd = {}
for tz_descr in map(str.split, tz_str.split('\n')):
    tz_offset = int(float(tz_descr[0]) * 3600)
    for tz_code in tz_descr[1:]:
        tzd[tz_code] = tz_offset
</code>```

ps. per @Hank Gay time zone naming is not clearly defined. To form my table i used http://www.timeanddate.com/library/abbreviations/timezones/ and http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations . I looked at each conflict and resolved conflicts between obscure and popular names towards the popular (more used ones). There was one - IST - that was not as clear cut (it can mean Indian Standard Time, Iran Standard Time, Irish Standard Time or Israel Standard Time), so i left it out of the table - you may need to chose what to add for it based on your location. Oh - and I left out the Republic of Kiribati with their absurd "look at me i am first to celebrate New Year" GMT+13 and GMT+14 time zones.

Body:
dateutil's parser.parse() accepts as keyword argument tzinfos a dictionary of the kind {'EST': -5*3600} (that is, matching the zone name to GMT offset in seconds). So assuming we have that, we can do:

>>> import dateutil.parser as dp
>>> s = 'Sat, 11/01/09 8:00PM'
>>> for tz_code in ('PST','PDT','MST','MDT','CST','CDT','EST','EDT'):
>>>     dt = s+' '+tz_code
>>>     print dt, '=', dp.parse(dt, tzinfos=tzd)

Sat, 11/01/09 8:00PM PST = 2009-11-01 20:00:00-08:00
Sat, 11/01/09 8:00PM PDT = 2009-11-01 20:00:00-07:00
Sat, 11/01/09 8:00PM MST = 2009-11-01 20:00:00-07:00
Sat, 11/01/09 8:00PM MDT = 2009-11-01 20:00:00-06:00
Sat, 11/01/09 8:00PM CST = 2009-11-01 20:00:00-06:00
Sat, 11/01/09 8:00PM CDT = 2009-11-01 20:00:00-05:00
Sat, 11/01/09 8:00PM EST = 2009-11-01 20:00:00-05:00
Sat, 11/01/09 8:00PM EDT = 2009-11-01 20:00:00-04:00

Regarding the content of tzinfos, here is how i populated mine:

tz_str = '''-12 Y
-11 X NUT SST
-10 W CKT HAST HST TAHT TKT
-9 V AKST GAMT GIT HADT HNY
-8 U AKDT CIST HAY HNP PST PT
-7 T HAP HNR MST PDT
-6 S CST EAST GALT HAR HNC MDT
-5 R CDT COT EASST ECT EST ET HAC HNE PET
-4 Q AST BOT CLT COST EDT FKT GYT HAE HNA PYT
-3 P ADT ART BRT CLST FKST GFT HAA PMST PYST SRT UYT WGT
-2 O BRST FNT PMDT UYST WGST
-1 N AZOT CVT EGT
0 Z EGST GMT UTC WET WT
1 A CET DFT WAT WEDT WEST
2 B CAT CEDT CEST EET SAST WAST
3 C EAT EEDT EEST IDT MSK
4 D AMT AZT GET GST KUYT MSD MUT RET SAMT SCT
5 E AMST AQTT AZST HMT MAWT MVT PKT TFT TJT TMT UZT YEKT
6 F ALMT BIOT BTT IOT KGT NOVT OMST YEKST
7 G CXT DAVT HOVT ICT KRAT NOVST OMSST THA WIB
8 H ACT AWST BDT BNT CAST HKT IRKT KRAST MYT PHT SGT ULAT WITA WST
9 I AWDT IRKST JST KST PWT TLT WDT WIT YAKT
10 K AEST ChST PGT VLAT YAKST YAPT
11 L AEDT LHDT MAGT NCT PONT SBT VLAST VUT
12 M ANAST ANAT FJT GILT MAGST MHT NZST PETST PETT TVT WFT
13 FJST NZDT
11.5 NFT
10.5 ACDT LHST
9.5 ACST
6.5 CCT MMT
5.75 NPT
5.5 SLT
4.5 AFT IRDT
3.5 IRST
-2.5 HAT NDT
-3.5 HNT NST NT
-4.5 HLV VET
-9.5 MART MIT'''

tzd = {}
for tz_descr in map(str.split, tz_str.split('\n')):
    tz_offset = int(float(tz_descr[0]) * 3600)
    for tz_code in tz_descr[1:]:
        tzd[tz_code] = tz_offset

ps. per @Hank Gay time zone naming is not clearly defined. To form my table i used http://www.timeanddate.com/library/abbreviations/timezones/ and http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations . I looked at each conflict and resolved conflicts between obscure and popular names towards the popular (more used ones). There was one - IST - that was not as clear cut (it can mean Indian Standard Time, Iran Standard Time, Irish Standard Time or Israel Standard Time), so i left it out of the table - you may need to chose what to add for it based on your location. Oh - and I left out the Republic of Kiribati with their absurd "look at me i am first to celebrate New Year" GMT+13 and GMT+14 time zones.


问:
Re-signing an IPA that contains a Framework
I'm re-signing an iOS app (using iResign) in order to upload it to the App Store; and as part of this I'm changing the bundle ID.
I only have the IPA (not the source code).

The app contains a third party framework.

The resign appears to go fine; but when I upload using Application Loader, I get the following error:

```<code>ERROR ITMS-90046: "Invalid Code Signing Entitlements. Your application bundle's signature
contains code signing entitlements that are not supported on iOS.
Specifically, value 'XXXXXXXXXX.COM.X.Y.Z.A' for key 'application-identifier' in
'Payload/APPNAME.app/Frameworks/FRAMEWORKNAME.framework/FRAMEWORKNAME' is not supported.
This value should be a string starting with your TEAMID, followed by a dot '.', followed by
the bundle identifier."
</code>```

(Obviously I've changed the values shown in CAPS)

I'm assuming that the problem is that the application-identifier in my entitlements.plist matches the Bundle identifier in my app, but does not match the Bundle identifier in the framework.

Just to rule it out, I set the same Bundle identifier on the framework and the app. This did allow me to upload to the app store; but failed with an error when I tried to install the app onto an iPad.

Do I need to provide a separate entitlements file for the framework?
How can I get around this issue?

UPDATE: Just to rule it out, I've tried using a wildcard provisioning profile and entitlements plist; but that gives the same error

答:
Assuming you run all your regular actions like removing app signature then remove the old signature on frameworks and resign those frameworks without including the entitlements:

```<code>rm -r Payload/"$ipaExe"/Frameworks/*/_CodeSignature
codesign -f -s "$certificate" Payload/"$ipaExe"/Frameworks/*
</code>```

Then sign your app itself:

```<code>codesign -f -s "$certificate" --entitlements $entitlementFile Payload/"$ipaExe"
</code>```

Body:
I'm re-signing an iOS app (using iResign) in order to upload it to the App Store; and as part of this I'm changing the bundle ID.
I only have the IPA (not the source code).

The app contains a third party framework.

The resign appears to go fine; but when I upload using Application Loader, I get the following error:

ERROR ITMS-90046: "Invalid Code Signing Entitlements. Your application bundle's signature
contains code signing entitlements that are not supported on iOS.
Specifically, value 'XXXXXXXXXX.COM.X.Y.Z.A' for key 'application-identifier' in
'Payload/APPNAME.app/Frameworks/FRAMEWORKNAME.framework/FRAMEWORKNAME' is not supported.
This value should be a string starting with your TEAMID, followed by a dot '.', followed by
the bundle identifier."

(Obviously I've changed the values shown in CAPS)

I'm assuming that the problem is that the application-identifier in my entitlements.plist matches the Bundle identifier in my app, but does not match the Bundle identifier in the framework.

Just to rule it out, I set the same Bundle identifier on the framework and the app. This did allow me to upload to the app store; but failed with an error when I tried to install the app onto an iPad.

Do I need to provide a separate entitlements file for the framework?
How can I get around this issue?

UPDATE: Just to rule it out, I've tried using a wildcard provisioning profile and entitlements plist; but that gives the same error

Body:
Assuming you run all your regular actions like removing app signature then remove the old signature on frameworks and resign those frameworks without including the entitlements:

rm -r Payload/"$ipaExe"/Frameworks/*/_CodeSignature
codesign -f -s "$certificate" Payload/"$ipaExe"/Frameworks/*

Then sign your app itself:

codesign -f -s "$certificate" --entitlements $entitlementFile Payload/"$ipaExe"


问:
Exporting results from powershell into a CSV document not working
I wrote a script in Powershell that will pull all files in a directory from the past seven years (this is my first time using Powershell).

I am trying to Export my results from the script below into a TXT or CSV document.

```<code>get-childitem -Path P:\ -recurse | where-object {$_.LastWriteTime -lt (getdate).Addyears(-7)}
</code>```

What should I add to the end of this script to get this data written to a file?

答: get-childitem -path p:\ -recurse | where-object{$_.lastwritetime -lt((get-date).adddyears(-7))} | export-csv c:\temp\test.csv</p>

Body:
I wrote a script in Powershell that will pull all files in a directory from the past seven years (this is my first time using Powershell).

I am trying to Export my results from the script below into a TXT or CSV document.

get-childitem -Path P:\ -recurse | where-object {$_.LastWriteTime -lt (getdate).Addyears(-7)}

What should I add to the end of this script to get this data written to a file?


问:
Tensorflow can not restore vocabulary in evaluation process
I am new to tensorflow and neural network. I started a project which is about detecting errors in persian texts. I used the code in this address and developed the code in here. please check the code because I can not put all the code here.

What I want to do is to give several persian sentences to the model for training and then see if model can detect wrong sentences. The model works fine with english data but when I use it for persian data I encounter this issue.

The code is too long to be written here so I try to point to the part I think might be causing the issue. I used these lines in train.py which works fine and stores vocabularies:

```<code>x_text, y = data_helpers.load_data_labels(datasets)
# Build vocabulary
max_document_length = max([len(x.split(" ")) for x in x_text])
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
x = np.array(list(vocab_processor.fit_transform(x_text)))
</code>```

however after training when I try this code in eval.py:

```<code>vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab")
vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
x_test = np.array(list(vocab_processor.transform(x_raw)))
</code>```

this error happens:

```<code>vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\contrib\learn\python\learn\preprocessing\text.py", line 226, in restore
return pickle.loads(f.read())
File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 118, in read
self._preread_check()
 File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 78, in _preread_check
  compat.as_bytes(self.__name), 1024 * 512, status)
 File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\contextlib.py", line 66, in __exit__
 next(self.gen)
 File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: ..\vocab : The system cannot find the file specified.
</code>```

I think the problem is because it can not read the vocabulary stored after training ,as the data is in unicode and it's not english. Can anyone help me please

答:
Have you tried adding this at the top of your file?</p>

```<code># -*- coding: utf-8 -*-
</code>```

Body:
I am new to tensorflow and neural network. I started a project which is about detecting errors in persian texts. I used the code in this address and developed the code in here. please check the code because I can not put all the code here.

What I want to do is to give several persian sentences to the model for training and then see if model can detect wrong sentences. The model works fine with english data but when I use it for persian data I encounter this issue.

The code is too long to be written here so I try to point to the part I think might be causing the issue. I used these lines in train.py which works fine and stores vocabularies:

x_text, y = data_helpers.load_data_labels(datasets)
# Build vocabulary
max_document_length = max([len(x.split(" ")) for x in x_text])
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
x = np.array(list(vocab_processor.fit_transform(x_text)))

however after training when I try this code in eval.py:

vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab")
vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
x_test = np.array(list(vocab_processor.transform(x_raw)))

this error happens:

vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\contrib\learn\python\learn\preprocessing\text.py", line 226, in restore
return pickle.loads(f.read())
File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 118, in read
self._preread_check()
 File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 78, in _preread_check
  compat.as_bytes(self.__name), 1024 * 512, status)
 File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\contextlib.py", line 66, in __exit__
 next(self.gen)
 File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: ..\vocab : The system cannot find the file specified.

I think the problem is because it can not read the vocabulary stored after training ,as the data is in unicode and it's not english. Can anyone help me please

Body:
Have you tried adding this at the top of your file?

# -*- coding: utf-8 -*-


问:
PyQt QProgressDialog not reponding
I am new in programming in PyQt (python interface), I like to use QProgressDialog, to show the progress of some tasks, so, the problem is, I had this:

while the change the value of progress , thank you for the help

```<code>def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(800, 600)
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.label = QtWidgets.QLabel(self.centralwidget)
    self.label.setGeometry(QtCore.QRect(250, 160, 231, 161))
    self.label.setObjectName("label")
    MainWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtWidgets.QMenuBar(MainWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
    self.menubar.setObjectName("menubar")
    MainWindow.setMenuBar(self.menubar)
    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)
    self.p = QProgressDialog('titel','',0,10000)
    self.p.setValue(0)
    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
    self.label.setText(_translate("label test"))
def work(self):
    for index in range(10001):
       time.sleep(2)
       self.p.setValue(index)
       print(index)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.work()
    sys.exit(app.exec_())
</code>```

答:
PyQt creates a loop through app.exec_(), and this serves to manage the GUI dynamics such as signals, events, etc. So if you interrupt that cycle you would have problems like the one shown. And in its case sleep() blocks the execution of the program. One way to solve this problem is using a QTimer as shown below:

```<code>[...]
    self.p = QProgressDialog('title','',0,10000)
    self.p.setValue(0)
    self.timer = QtCore.QTimer(MainWindow)
    self.timer.timeout.connect(self.work)
    self.timer.start(2000)

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)
[...]
def work(self):
    self.p.setValue(self.p.value()+1)
    if self.p.value() == self.p.maximum():
        self.timer.stop()
[...]
</code>```

Title: PyQt QProgressDialog not reponding

Body:
I am new in programming in PyQt (python interface), I like to use QProgressDialog, to show the progress of some tasks, so, the problem is, I had this:

while the change the value of progress , thank you for the help

def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(800, 600)
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.label = QtWidgets.QLabel(self.centralwidget)
    self.label.setGeometry(QtCore.QRect(250, 160, 231, 161))
    self.label.setObjectName("label")
    MainWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtWidgets.QMenuBar(MainWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
    self.menubar.setObjectName("menubar")
    MainWindow.setMenuBar(self.menubar)
    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)
    self.p = QProgressDialog('titel','',0,10000)
    self.p.setValue(0)
    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
    self.label.setText(_translate("label test"))
def work(self):
    for index in range(10001):
       time.sleep(2)
       self.p.setValue(index)
       print(index)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.work()
    sys.exit(app.exec_())

Body:
PyQt creates a loop through app.exec_(), and this serves to manage the GUI dynamics such as signals, events, etc. So if you interrupt that cycle you would have problems like the one shown. And in its case sleep() blocks the execution of the program. One way to solve this problem is using a QTimer as shown below:

[...]
    self.p = QProgressDialog('title','',0,10000)
    self.p.setValue(0)
    self.timer = QtCore.QTimer(MainWindow)
    self.timer.timeout.connect(self.work)
    self.timer.start(2000)

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)
[...]
def work(self):
    self.p.setValue(self.p.value()+1)
    if self.p.value() == self.p.maximum():
        self.timer.stop()
[...]


问:
MVC ListBoxFor missing special char
I have an MVC4 app that uses bootstrap
on one view I have

```<code>@Html.ListBoxFor(x=>x.ids,Model.OPtions,new {@class = "form-control",multiple ="multiple",id ="optionid",data_placeHolder ="Something}
</code>```

Model.OPtions have a string value that has special characters in it.
These are being stripped out

It is an IEmumerable<SelectListItem>

any ideas?

答: I feel a fool, it was being created by a an ajax call, someone stuffed a million abstract methods in the javascript file for layoutMaster.js</p>

Title: MVC ListBoxFor missing special char

Body:
I have an MVC4 app that uses bootstrap
on one view I have

@Html.ListBoxFor(x=>x.ids,Model.OPtions,new {@class = "form-control",multiple ="multiple",id ="optionid",data_placeHolder ="Something}

Model.OPtions have a string value that has special characters in it.
These are being stripped out

It is an IEmumerable<SelectListItem>

any ideas?


问:
Why is gcc failing with 'unrecognized command line option "-L/lusr/opt/mpfr-2.4.2/lib"'?
My sysadmin recently installed a new version of GCC, in /lusr/opt/gcc-4.4.3. I tested it as follows:

```<code>mike@canon:~$ cat test.c
int main(){
  return 0;
}
mike@canon:~$ gcc test.c
/lusr/opt/gcc-4.4.3/libexec/gcc/i686-pc-linux-gnu/4.4.3/cc1: error while loading shared libraries: libmpfr.so.1: cannot open shared object file: No such file or directory
</code>```

After informing my sysadmin about this, he said to add /lusr/opt/mpfr-2.4.2/lib:/lusr/opt/gmp-4.3.2/lib to my LD_LIBRARY_PATH. After doing this, I get the following error:

```<code>mike@canon:~$ gcc test.c
cc1: error: unrecognized command line option "-L/lusr/opt/mpfr-2.4.2/lib"
</code>```

First, my sysadmin wasn't entirely sure this was the best workaround(though he did say it worked for him...), so is there a better solution?

Second, why am I getting a linker error from cc, and how can I fix it?

Some information which may be helpful:

```<code>mike@canon:~$ env | grep mpfr
OLDPWD=/lusr/opt/mpfr-2.4.2/lib
LD_LIBRARY_PATH=/lusr/opt/mpfr-2.4.2/lib:/lusr/opt/gmp-4.3.2/lib:

mike@canon:~$ echo $LDFLAGS

(the above is a blank line)
</code>```

答:
This looks like some buggy argument parsing by gcc (it shouldn't complain about -Lfoo).

Can you try setting

```<code>LD_LIBRARY_PATH=\ /lusr/opt/mpfr-2.4.2/lib:/lusr/opt/gmp-4.3.2/lib
</code>```

so that there's a leading space before that mpfr library path?

OwnerDisplayName: Mike

Body:
My sysadmin recently installed a new version of GCC, in /lusr/opt/gcc-4.4.3. I tested it as follows:

mike@canon:~$ cat test.c
int main(){
  return 0;
}
mike@canon:~$ gcc test.c
/lusr/opt/gcc-4.4.3/libexec/gcc/i686-pc-linux-gnu/4.4.3/cc1: error while loading shared libraries: libmpfr.so.1: cannot open shared object file: No such file or directory

After informing my sysadmin about this, he said to add /lusr/opt/mpfr-2.4.2/lib:/lusr/opt/gmp-4.3.2/lib to my LD_LIBRARY_PATH. After doing this, I get the following error:

mike@canon:~$ gcc test.c
cc1: error: unrecognized command line option "-L/lusr/opt/mpfr-2.4.2/lib"

First, my sysadmin wasn't entirely sure this was the best workaround(though he did say it worked for him...), so is there a better solution?

Second, why am I getting a linker error from cc, and how can I fix it?

Some information which may be helpful:

mike@canon:~$ env | grep mpfr
OLDPWD=/lusr/opt/mpfr-2.4.2/lib
LD_LIBRARY_PATH=/lusr/opt/mpfr-2.4.2/lib:/lusr/opt/gmp-4.3.2/lib:

mike@canon:~$ echo $LDFLAGS

(the above is a blank line)

Body:
This looks like some buggy argument parsing by gcc (it shouldn't complain about -Lfoo).

Can you try setting

LD_LIBRARY_PATH=\ /lusr/opt/mpfr-2.4.2/lib:/lusr/opt/gmp-4.3.2/lib

so that there's a leading space before that mpfr library path?

OwnerDisplayName: Nick Dixon


问:
Removing element in multiple XML files that contain specific attribute
First, I'd like to reference this as it is what I've based the powershell script off of with minor modifications.

The goal of the modified script (seen below) is to go through every XML in a folder and if it has an object within an object, where the source file ends with an .eps, then to remove the object and everything within. From the referenced link above, it looked as if I would have to ensure that all objects in the attribute is accounted for. I have tried to use wildcards and when I ran it, it didn't pop any errors, however, it also didn't remove the secondary object tag.

Here is a sample XML of the object/object:

```<code><object class="graphic svg eps file_name:AR1.svg name:AR1" data="sample.svg"     height="100" type="image/svg+xml" width="100">
    <object class="graphic svg eps file_name:AR1.eps name:AR1" data="sample.eps" height="400" type="application/postscript" width="400">
        <p>NONE</p>
    </object>
</object>
</code>```

Here is the modification:

```<code>Get-ChildItem 'C:\test\*.xml' | ForEach-Object {
  $xml = [xml](Get-Content $_.FullName)

  $xml.SelectNodes("//object/object") | Where-Object {
    $_.class -eq "*" -and
    $_.data -eq "*.eps" -and
    $_.height -eq "*" -and
    $_.type -eq "application/postscript" -and
    $_.width -eq "*"
  } | ForEach-Object {
    $_.ParentNode.RemoveChildNode($_)
  }

  $xml.Save($_.FullName)
}
</code>```

I was under the impression that wildcards should still work, and because the attributes with wildcards are random based on the XML filename and image filename that using a wildcard would be best.

I'm very still very green and new to PowerShell but appreciate any help that can be given.

Edit:

With the help of @TheMadTechnician, I've updated the script to below which works!

```<code>    $items | ForEach-Object {
      $xml = [xml](Get-Content $_.FullName)

      $xml.SelectNodes("//*[@type='application/postscript']") | %{ $_.parentnode.removechild($_) }

      $xml.Save($_.FullName)
</code>```

答:
The issue is that your Where statement doesn't work. You can see this if you just run the first part of that command:

```<code>$xml.SelectNodes("//object/object") | Where-Object {
  $_.class -eq "*" -and
  $_.data -eq "*.eps" -and
  $_.height -eq "*" -and
  $_.type -eq "application/postscript" -and
  $_.width -eq "*"
}
</code>```

That returns nothing because only 1 of those evaluate to True, and that's the type which literally equals what you indicate

Wildcards are great, but you have to use them appropriately. The -eq operator is literal, and does not accept wildcards. So when you say $_.class -eq "*" that only returns $true when $_.class is a string containing only *. Where you can use wildcards like that is the -like operator.

```<code>$xml.SelectNodes("//object[contains(@data,'.eps') and @type='application/postscript']") |
Where-Object {
    $_.data -like "*.eps" -and
    $_.type -eq "application/postscript"
  }|%{$_.parentnode.removechild($_)}
</code>```

This could all be simplified with a better XPath query:

```<code>$xml.SelectNodes("//object[contains(@data,'.eps') and @type='application/postscript']") | %{ $_.ParentNode.RemoveChild($_) }
</code>```

Body:
First, I'd like to reference this as it is what I've based the powershell script off of with minor modifications.

The goal of the modified script (seen below) is to go through every XML in a folder and if it has an object within an object, where the source file ends with an .eps, then to remove the object and everything within. From the referenced link above, it looked as if I would have to ensure that all objects in the attribute is accounted for. I have tried to use wildcards and when I ran it, it didn't pop any errors, however, it also didn't remove the secondary object tag.

Here is a sample XML of the object/object:

<object class="graphic svg eps file_name:AR1.svg name:AR1" data="sample.svg"     height="100" type="image/svg+xml" width="100">
    <object class="graphic svg eps file_name:AR1.eps name:AR1" data="sample.eps" height="400" type="application/postscript" width="400">

NONE

    </object>
</object>

Here is the modification:

Get-ChildItem 'C:\test\*.xml' | ForEach-Object {
  $xml = [xml](Get-Content $_.FullName)

  $xml.SelectNodes("//object/object") | Where-Object {
    $_.class -eq "*" -and
    $_.data -eq "*.eps" -and
    $_.height -eq "*" -and
    $_.type -eq "application/postscript" -and
    $_.width -eq "*"
  } | ForEach-Object {
    $_.ParentNode.RemoveChildNode($_)
  }

  $xml.Save($_.FullName)
}

I was under the impression that wildcards should still work, and because the attributes with wildcards are random based on the XML filename and image filename that using a wildcard would be best.

I'm very still very green and new to PowerShell but appreciate any help that can be given.

Edit:

With the help of @TheMadTechnician, I've updated the script to below which works!

    $items | ForEach-Object {
      $xml = [xml](Get-Content $_.FullName)

      $xml.SelectNodes("//*[@type='application/postscript']") | %{ $_.parentnode.removechild($_) }

      $xml.Save($_.FullName)

Body:
The issue is that your Where statement doesn't work. You can see this if you just run the first part of that command:

$xml.SelectNodes("//object/object") | Where-Object {
  $_.class -eq "*" -and
  $_.data -eq "*.eps" -and
  $_.height -eq "*" -and
  $_.type -eq "application/postscript" -and
  $_.width -eq "*"
}

That returns nothing because only 1 of those evaluate to True, and that's the type which literally equals what you indicate

Wildcards are great, but you have to use them appropriately. The -eq operator is literal, and does not accept wildcards. So when you say $_.class -eq "*" that only returns $true when $_.class is a string containing only *. Where you can use wildcards like that is the -like operator.

$xml.SelectNodes("//object[contains(@data,'.eps') and @type='application/postscript']") |
Where-Object {
    $_.data -like "*.eps" -and
    $_.type -eq "application/postscript"
  }|%{$_.parentnode.removechild($_)}

This could all be simplified with a better XPath query:

$xml.SelectNodes("//object[contains(@data,'.eps') and @type='application/postscript']") | %{ $_.ParentNode.RemoveChild($_) }


问:
SQL Server truncation and 8192 limitation
In SQL Server 2005 I am trying to query a varchar(MAX) column which has some rows with text data that exceed the 8192.  Yet, In Management Studio I have under Tools --> Options --> Query Results --> Results to Text --> Max numbers of characters displayed in each column = 8192, which is a maximum.  Accordingly, it seems the truncation on these rows occurs only due to the limitation imposed by text output.

The only thing I see to get around this is to use a SUBSTRING function to grab say the first 8000 chars, then the next 8000 chars etc. etc.  But this is ugly and error prone.

I should mention that SSIS and BCP are not options for me.

Does anyone have a better suggestion?  Thanks!

答:
Did you try this simple solution? Only 2 clicks away!

At the query window,

set query options to "Results to Grid", run your query

Right click on the results tab at the grid corner, save results as any files

You will get all the text you want to see in the file!!! I can see 130,556 characters for my result of a varchar(MAX) field


问:
UnboundStackError, referenced before assignment? Python
Here is some code im using in a larger program about bowling scoreboards, I have an almost identical snippet of code that works perfectly that declares the winner with the max, but I continue to get an error on this bit. It says that the "minname" in the print code is referenced before assignment but I can't for the life of me figure out whats up. FYI this is code in python.

```<code>print()
#Print a message to declare the loser (min)
for i in range(total-1):
    if bowlerscorelist[i] < bowlerscorelist[i+1]:
        minscore = bowlerscorelist[i]
        minname = bowlernamelist[i]
print(minname, "got the lowest score with: ", minscore)
</code>```

Any help?

答:
It's not entering the if statement (condition not met ofc), so "minscore" and "minname" are being referenced before assigment.</p>

```<code>minname = ''
minscore = 0
 for i in range(total-1):
    if bowlerscorelist[i] < bowlerscorelist[i+1]:
        minscore = bowlerscorelist[i]
        minname = bowlernamelist[i]
print(minname, "got the lowest score with: ", minscore)
</code>```

Body:
Here is some code im using in a larger program about bowling scoreboards, I have an almost identical snippet of code that works perfectly that declares the winner with the max, but I continue to get an error on this bit. It says that the "minname" in the print code is referenced before assignment but I can't for the life of me figure out whats up. FYI this is code in python.

print()
#Print a message to declare the loser (min)
for i in range(total-1):
    if bowlerscorelist[i] < bowlerscorelist[i+1]:
        minscore = bowlerscorelist[i]
        minname = bowlernamelist[i]
print(minname, "got the lowest score with: ", minscore)

Any help?

Body:
It's not entering the if statement (condition not met ofc), so "minscore" and "minname" are being referenced before assigment.

minname = ''
minscore = 0
 for i in range(total-1):
    if bowlerscorelist[i] < bowlerscorelist[i+1]:
        minscore = bowlerscorelist[i]
        minname = bowlernamelist[i]
print(minname, "got the lowest score with: ", minscore)


问:
What is this Rspec syntax exactly asking for?
TL;DR I am going to a bootcamp next year and one their assessments to get in is learning ruby. I have a background in JS and am very new to ruby. I have this assessment in which case I am not familiar with what the test wants me to do. Below is the test case(Rspec) and right below that is my answer.

```<code>describe "some silly block functions" do
  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end

  expect(result).to eq("olleh")
end

it "reverses each word in the string returned by the default block" do
  result = reverser do
    "hello dolly"
  end

  expect(result).to eq("olleh yllod")
  end
end
</code>```

This is my answer code:

```<code>def reverser sentence
  words = sentence.split(" ")
  result = []

  words.length.times do |i|
    result.push(yield(words[i]))
  end

  result.join(" ")
end

reverser("hello dolly") {|n| n.reverse} #=> 'olleh yllod'
</code>```

As I mentioned above I am new to ruby and the idea of yielding is like a callback function for JS. I am having a hard time figuring out what expected code the test case wants me to write. It says that 'it reverses each word in the string returned by the default block' from the statement I just created a block outside of the function where the words are being reversed. I appreciate the help and guidance from whoever can give advice.

答:
I think the point of the question should be to explain about RSpec and TDD if you're going on a bootcamp. I think giving you the answer to the problem is only part of what you need to know in this case. So...

One of the principles of TDD is to write the least amount of code to get the tests to pass. If I go back to the start.

You have written a reverser method that takes sentence as an argument:

```<code>def reverser sentence
  'olleh'
end
</code>```

Run the test and the test should fail with an error: wrong number of arguments. Remove the argument and try that and run RSpec again:

```<code>def reverser
  'olleh'
end
</code>```

The first test should pass, but it will fail the second test as we've hard coded the return value of olleh. Clearly it's no good returning a hard coded value — it just helped the test to pass — so I need to figure out how to yield a return value.

```<code>def reverser
  yield.reverse
end
</code>```

And this perhaps will get the second test to pass...

This is the guiding principle of TDD, take small steps and get your code to pass. Once it's passing then go back and refactor and improve your code.

As you probably know already TDD is invaluable for writing good quality code - it makes writing code fun, it helps with refactoring.

I found a page with some resources and I would recommend codeschool but they've retired their course which is a pity but there is a PluralSight TDD course that might be useful and also there is a Udemy course on TDD that might be useful too in giving you a head start.

Body:
TL;DR I am going to a bootcamp next year and one their assessments to get in is learning ruby. I have a background in JS and am very new to ruby. I have this assessment in which case I am not familiar with what the test wants me to do. Below is the test case(Rspec) and right below that is my answer.

describe "some silly block functions" do
  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end

  expect(result).to eq("olleh")
end

it "reverses each word in the string returned by the default block" do
  result = reverser do
    "hello dolly"
  end

  expect(result).to eq("olleh yllod")
  end
end

This is my answer code:

def reverser sentence
  words = sentence.split(" ")
  result = []

  words.length.times do |i|
    result.push(yield(words[i]))
  end

  result.join(" ")
end

reverser("hello dolly") {|n| n.reverse} #=> 'olleh yllod'

As I mentioned above I am new to ruby and the idea of yielding is like a callback function for JS. I am having a hard time figuring out what expected code the test case wants me to write. It says that 'it reverses each word in the string returned by the default block' from the statement I just created a block outside of the function where the words are being reversed. I appreciate the help and guidance from whoever can give advice.

Body:
I think the point of the question should be to explain about RSpec and TDD if you're going on a bootcamp. I think giving you the answer to the problem is only part of what you need to know in this case. So...

One of the principles of TDD is to write the least amount of code to get the tests to pass. If I go back to the start.

You have written a reverser method that takes sentence as an argument:

def reverser sentence
  'olleh'
end

Run the test and the test should fail with an error: wrong number of arguments. Remove the argument and try that and run RSpec again:

def reverser
  'olleh'
end

The first test should pass, but it will fail the second test as we've hard coded the return value of olleh. Clearly it's no good returning a hard coded value — it just helped the test to pass — so I need to figure out how to yield a return value.

def reverser
  yield.reverse
end

And this perhaps will get the second test to pass...

This is the guiding principle of TDD, take small steps and get your code to pass. Once it's passing then go back and refactor and improve your code.

As you probably know already TDD is invaluable for writing good quality code - it makes writing code fun, it helps with refactoring.

I found a page with some resources and I would recommend codeschool but they've retired their course which is a pity but there is a PluralSight TDD course that might be useful and also there is a Udemy course on TDD that might be useful too in giving you a head start.


问:
How to access and print dictionary values that contain nested lists?
I'm learning Python and am a bit stuck with the concept of dictionaries and nested lists.

The lab I'm currently working on calls for us to create a dict with some keys having just a single list of values and other keys having two or more lists associated. The code below properly prints the list elements for the key that has multiple lists, but if I change the get statement to a key with a single list I just get the first two digits of the string.

```<code>my_dict = {1: ['test', 'values'],
           2: [['test2', 'value2'], ['test3', 'value3']],
           3: ['test4', 'value4']}

for item in my_dict.get(2):
   print('%s, %s' %(item[0], item[1]))
</code>```

Would someone explain how to access list values from the dictionary regardless of whether the key has a single list, or multiple lists?

Ultimately the output if key 1 or 3 is used would be

```<code>test, values  or test4, value4
</code>```

If key 2 is selected the output would be

```<code>test2, value2
test3, value3
</code>```

答:
Based on the updated information you added and comments under your question, this seems to work for the specific case you're dealing with:

```<code>my_dict = {1: ['test', 'values'],
           2: [['test2', 'value2'], ['test3', 'value3']],
           3: ['test4', 'value4']}

for key, values in my_dict.items():
    if not isinstance(values[0], list):  # Not a nested list-of-lists?
        print(', '.join(map(str, values)))
    else:
        for value in values:
            print(', '.join(map(str, value)))
</code>```

Output:

test, values
test2, value2
test3, value3
test4, value4
```

<p>To handle single dictionary values as shown in the code in your question, you could do something very similar to the above like this:</p>

```elems = my_dict.get(2)
if not isinstance(elems[0], list):  # Not a nested list-of-lists?
    print(', '.join(map(str, elems)))
else:
    for value in elems:
        print(', '.join(map(str, value)))
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>test2, value2
test3, value3
</code>```

Comment: Although it may be obvious, this would much easier if you could make the dictionary more consistent, where the values in it were always lists-of-lists as shown below:

```<code>my_dict = {1: [['test', 'values']],
           2: [['test2', 'value2'], ['test3', 'value3']],
           3: [['test4', 'value4']]}
</code>```

Body:
I'm learning Python and am a bit stuck with the concept of dictionaries and nested lists.

The lab I'm currently working on calls for us to create a dict with some keys having just a single list of values and other keys having two or more lists associated. The code below properly prints the list elements for the key that has multiple lists, but if I change the get statement to a key with a single list I just get the first two digits of the string.

my_dict = {1: ['test', 'values'],
           2: [['test2', 'value2'], ['test3', 'value3']],
           3: ['test4', 'value4']}

for item in my_dict.get(2):
   print('%s, %s' %(item[0], item[1]))

Would someone explain how to access list values from the dictionary regardless of whether the key has a single list, or multiple lists?

Ultimately the output if key 1 or 3 is used would be

test, values  or test4, value4

If key 2 is selected the output would be

test2, value2
test3, value3

Body:
Based on the updated information you added and comments under your question, this seems to work for the specific case you're dealing with:

my_dict = {1: ['test', 'values'],
           2: [['test2', 'value2'], ['test3', 'value3']],
           3: ['test4', 'value4']}

for key, values in my_dict.items():
    if not isinstance(values[0], list):  # Not a nested list-of-lists?
        print(', '.join(map(str, values)))
    else:
        for value in values:
            print(', '.join(map(str, value)))

Output:

test, values
test2, value2
test3, value3
test4, value4

To handle single dictionary values as shown in the code in your question, you could do something very similar to the above like this:

elems = my_dict.get(2)
if not isinstance(elems[0], list):  # Not a nested list-of-lists?
    print(', '.join(map(str, elems)))
else:
    for value in elems:
        print(', '.join(map(str, value)))

Output:

test2, value2
test3, value3

Comment: Although it may be obvious, this would much easier if you could make the dictionary more consistent, where the values in it were always lists-of-lists as shown below:

my_dict = {1: [['test', 'values']],
           2: [['test2', 'value2'], ['test3', 'value3']],
           3: [['test4', 'value4']]}


问:
Does assembler code compiled on a 32bit machine differ from code compiled with "gcc -m32"?
I'm learnin about assembler language right now. The code examples in the book I'm learning from are all compiled on a x86 32bit machine (i think) with gcc. To match my outputs with the one from the book i compiled my simple helloworld.c with "gcc -m32".

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

int main(){
    int i;
    for(i=0;i<10;i++){
      printf("Hello World!\n");
    }
    return 0;
}
</code>```

The output i get from running "objdump -D a32.out | grep -A20 main.:" looks like this:

```<code>0000051d <main>:
51d:    8d 4c 24 04             lea    0x4(%esp),%ecx
521:    83 e4 f0                and    $0xfffffff0,%esp
524:    ff 71 fc                pushl  -0x4(%ecx)
527:    55                      push   %ebp
528:    89 e5                   mov    %esp,%ebp
52a:    53                      push   %ebx
52b:    51                      push   %ecx
52c:    83 ec 10                sub    $0x10,%esp
52f:    e8 ec fe ff ff          call   420 <__x86.get_pc_thunk.bx>
534:    81 c3 cc 1a 00 00       add    $0x1acc,%ebx
53a:    c7 45 f4 00 00 00 00    movl   $0x0,-0xc(%ebp)
541:    eb 16                   jmp    559 <main+0x3c>
543:    83 ec 0c                sub    $0xc,%esp
546:    8d 83 f0 e5 ff ff       lea    -0x1a10(%ebx),%eax
54c:    50                      push   %eax
54d:    e8 5e fe ff ff          call   3b0 <puts@plt>
552:    83 c4 10                add    $0x10,%esp
555:    83 45 f4 01             addl   $0x1,-0xc(%ebp)
559:    83 7d f4 09             cmpl   $0x9,-0xc(%ebp)
55d:    7e e4                   jle    543 <main+0x26>
</code>```

But in the book it looks like this:

It misses the first three lines from the output I get and doesn't look anything like it except for the next two lines. Why is that ? And how can i change my compiler/disassembly settings to make it look alike ?

答:
Your compiler is configured to produce position-independent binary by default, and that causes significant divergence from the book. (This is a fairly recent GCC development).

You will get much closer to the book if you disable this:

```<code>gcc -fno-pie -no-pie -m32 hello.c
</code>```

As others have stated, there is no guarantee that you will get identical code to what's in the book, unless you get exact same compiler built in exactly the same configuration.

Body:
I'm learnin about assembler language right now. The code examples in the book I'm learning from are all compiled on a x86 32bit machine (i think) with gcc. To match my outputs with the one from the book i compiled my simple helloworld.c with "gcc -m32".

#include <stdio.h>

int main(){
    int i;
    for(i=0;i<10;i++){
      printf("Hello World!\n");
    }
    return 0;
}

The output i get from running "objdump -D a32.out | grep -A20 main.:" looks like this:

0000051d :
51d:    8d 4c 24 04             lea    0x4(%esp),%ecx
521:    83 e4 f0                and    $0xfffffff0,%esp
524:    ff 71 fc                pushl  -0x4(%ecx)
527:    55                      push   %ebp
528:    89 e5                   mov    %esp,%ebp
52a:    53                      push   %ebx
52b:    51                      push   %ecx
52c:    83 ec 10                sub    $0x10,%esp
52f:    e8 ec fe ff ff          call   420 <__x86.get_pc_thunk.bx>
534:    81 c3 cc 1a 00 00       add    $0x1acc,%ebx
53a:    c7 45 f4 00 00 00 00    movl   $0x0,-0xc(%ebp)
541:    eb 16                   jmp    559
543:    83 ec 0c                sub    $0xc,%esp
546:    8d 83 f0 e5 ff ff       lea    -0x1a10(%ebx),%eax
54c:    50                      push   %eax
54d:    e8 5e fe ff ff          call   3b0 <puts@plt>
552:    83 c4 10                add    $0x10,%esp
555:    83 45 f4 01             addl   $0x1,-0xc(%ebp)
559:    83 7d f4 09             cmpl   $0x9,-0xc(%ebp)
55d:    7e e4                   jle    543

But in the book it looks like this:

It misses the first three lines from the output I get and doesn't look anything like it except for the next two lines. Why is that ? And how can i change my compiler/disassembly settings to make it look alike ?

Body:
Your compiler is configured to produce position-independent binary by default, and that causes significant divergence from the book. (This is a fairly recent GCC development).

You will get much closer to the book if you disable this:

gcc -fno-pie -no-pie -m32 hello.c

As others have stated, there is no guarantee that you will get identical code to what's in the book, unless you get exact same compiler built in exactly the same configuration.


问:
C get and instantiate struct type from array of different structs
I'm having trouble figuring this out...

I have a bunch of structs defining message types from a data stream that look like this:

```<code>struct QM_lUpdP
{
    char type [6];
    char exchange_id [6];
    char currency_id [4];
    char hour [3];
    char minute [3];
    char second [3];
    char millisecond [4];
    char instrument_type [3];
    char order_reference [31];
    char price_type [2];
    char price [11];
    char mmid [5];

} QM_lUpdP;
</code>```

There are many of them with different names and formats.

What I want to be able to do is... dynamically, given a struct name, get and instantiate that struct, so far I'm doing this..

```<code>char data_struct_names[NUMBER_OF_MESSAGE_TYPES + 1][16] = {
    "QM_BkCan",
    "QM_BkChg",
    "QM_BkDel",
    "QM_BkExc",
     ...
    "QM_lEquI",
};

void * QM_get_data_struct (char * struct_name)
{
    void * data_structs [NUMBER_OF_MESSAGE_TYPES + 1] = {
        &QM_BkCan,
        &QM_BkChg,
        &QM_BkDel,
        &QM_BkExc,
        ...
        &QM_lEquI
    };

    for (int i = 0; i < NUMBER_OF_MESSAGE_TYPES; i++)
    {
        if (strcmp(data_struct_names[i], struct_name) == 0) return data_structs[i];
    }

    fprintf( stderr, "%s is an invalid or unimplemented struct!!\n", struct_name);
    return (void *)0;
}
</code>```

So, given a name, we can search through the list of names, find the index, and then grab that struct from the list of structs that has identical indexes.

Right now, I'm just returning a void pointer, which returns a reliable address depending on the struct. Is there a way to unwrap this pointer and use it as a struct?

...how to instantiate it and use it in code. Is this even possible because the type of struct is not known so I can't just do...

```<code>QM_BkCan data = QM_get_data_struct("BkCan");
</code>```

Is this even possible? Is there a different way I should be approaching this?

```<code>Ideally I would have...

data_struct = get_struct(NAME_STRING);

data_struct.value = "hello!";

printf("%s", data_struct.value); // hello!
</code>```

Thank you.

答:
What you're wanting isn't possible in C.

I think you might need to do this a different way. You could do something like:

```<code>struct QM_BkCan {
    ...
}
struct QM_BkChg {
    ...
}
struct QM_BkDel {
    ...
}
struct QM_BkExc {
    ...
}
struct QM_lEquI {
    ...
}

enum QM_Types {
    QM_Type_BkCan = 0,
    QM_Type_BkChg,
    QM_Type_BkDel,
    QM_Type_BkExc,
    QM_Type_lEquI
}

union QM_Structs {
    struct QM_BkCan QM_BkCan;
    struct QM_BkChg QM_BkChg;
    struct QM_BkDel QM_BkDel;
    struct QM_BkExc QM_BkExc;
    struct QM_lEquI QM_lEquI;
}
</code>```

As you need to use a dynamic string, you can use your function (but modified):

```<code>char data_struct_names[NUMBER_OF_MESSAGE_TYPES + 1][16] = {
    "QM_BkCan",
    "QM_BkChg",
    "QM_BkDel",
    "QM_BkExc",
    "QM_lEquI",
};

enum QM_Types QM_get_data_struct (char * struct_name)
{
    for (int i = 0; i < NUMBER_OF_MESSAGE_TYPES; i++)
    {
        if (strcmp(data_struct_names[i], struct_name) == 0)
            return (enum QM_Types)((int)QM_Type_BkCan + i);
    }

    fprintf( stderr, "%s is an invalid or unimplemented struct!!\n", struct_name);
    return (void *)0;
}
</code>```

Then, you can use it as follows:

```<code>struct QM_Structs * s = (QM_Structs *)your_data_array;

switch (QM_get_data_struct(YOUR_STRING)) {
    case QM_Type_BkCan:
        s->QM_BkCan.something = something_else;
        break;
    case QM_Type_BkChg:
        s->QM_BkChg.something = something_else;
        break;
    ...
}
</code>```

It's not a very nice way of doing it, but I don't believe there is any other way.

Body:
I'm having trouble figuring this out...

I have a bunch of structs defining message types from a data stream that look like this:

struct QM_lUpdP
{
    char type [6];
    char exchange_id [6];
    char currency_id [4];
    char hour [3];
    char minute [3];
    char second [3];
    char millisecond [4];
    char instrument_type [3];
    char order_reference [31];
    char price_type [2];
    char price [11];
    char mmid [5];

} QM_lUpdP;

There are many of them with different names and formats.

What I want to be able to do is... dynamically, given a struct name, get and instantiate that struct, so far I'm doing this..

char data_struct_names[NUMBER_OF_MESSAGE_TYPES + 1][16] = {
    "QM_BkCan",
    "QM_BkChg",
    "QM_BkDel",
    "QM_BkExc",
     ...
    "QM_lEquI",
};

void * QM_get_data_struct (char * struct_name)
{
    void * data_structs [NUMBER_OF_MESSAGE_TYPES + 1] = {
        &QM_BkCan,
        &QM_BkChg,
        &QM_BkDel,
        &QM_BkExc,
        ...
        &QM_lEquI
    };

    for (int i = 0; i < NUMBER_OF_MESSAGE_TYPES; i++)
    {
        if (strcmp(data_struct_names[i], struct_name) == 0) return data_structs[i];
    }

    fprintf( stderr, "%s is an invalid or unimplemented struct!!\n", struct_name);
    return (void *)0;
}

So, given a name, we can search through the list of names, find the index, and then grab that struct from the list of structs that has identical indexes.

Right now, I'm just returning a void pointer, which returns a reliable address depending on the struct. Is there a way to unwrap this pointer and use it as a struct?

...how to instantiate it and use it in code. Is this even possible because the type of struct is not known so I can't just do...

QM_BkCan data = QM_get_data_struct("BkCan");

Is this even possible? Is there a different way I should be approaching this?

Ideally I would have...

data_struct = get_struct(NAME_STRING);

data_struct.value = "hello!";

printf("%s", data_struct.value); // hello!

Thank you.

Body:
What you're wanting isn't possible in C.

I think you might need to do this a different way. You could do something like:

struct QM_BkCan {
    ...
}
struct QM_BkChg {
    ...
}
struct QM_BkDel {
    ...
}
struct QM_BkExc {
    ...
}
struct QM_lEquI {
    ...
}

enum QM_Types {
    QM_Type_BkCan = 0,
    QM_Type_BkChg,
    QM_Type_BkDel,
    QM_Type_BkExc,
    QM_Type_lEquI
}

union QM_Structs {
    struct QM_BkCan QM_BkCan;
    struct QM_BkChg QM_BkChg;
    struct QM_BkDel QM_BkDel;
    struct QM_BkExc QM_BkExc;
    struct QM_lEquI QM_lEquI;
}

As you need to use a dynamic string, you can use your function (but modified):

char data_struct_names[NUMBER_OF_MESSAGE_TYPES + 1][16] = {
    "QM_BkCan",
    "QM_BkChg",
    "QM_BkDel",
    "QM_BkExc",
    "QM_lEquI",
};

enum QM_Types QM_get_data_struct (char * struct_name)
{
    for (int i = 0; i < NUMBER_OF_MESSAGE_TYPES; i++)
    {
        if (strcmp(data_struct_names[i], struct_name) == 0)
            return (enum QM_Types)((int)QM_Type_BkCan + i);
    }

    fprintf( stderr, "%s is an invalid or unimplemented struct!!\n", struct_name);
    return (void *)0;
}

Then, you can use it as follows:

struct QM_Structs * s = (QM_Structs *)your_data_array;

switch (QM_get_data_struct(YOUR_STRING)) {
    case QM_Type_BkCan:
        s->QM_BkCan.something = something_else;
        break;
    case QM_Type_BkChg:
        s->QM_BkChg.something = something_else;
        break;
    ...
}

It's not a very nice way of doing it, but I don't believe there is any other way.


问:
*10 upstream timed out (110: Connection timed out) while reading response header from upstream with uwsgi
I currently have a server setup with nginx and uwsgi with django
This error doesn't happen until I try to change my rds instance

my fully error message is
*10 upstream timed out (110: Connection timed out) while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: xxx.xxx.xxx.xxx, request: "GET /load/ HTTP/1.1", upstream: "uwsgi://unix:/tmp/load.sock", host: "example.com", referrer: "https://example.com/"

I was using aws rds (postgres) which works perfectly fine.  The only change I made is changing from regular postgres service to aurora postgres I didn't upgrade the db, from regular to aurora.  I created a new aurora postgres.  I got everything setup...changed host and everything in my django db setting.  runserver locally works fine.  It does connect to db with read and write.  Works perfectly.  But when I deploy to server, open up my domain.  Anything ui related looks fine but db related, NO.  Took awhile then of course the 504 gateway timeout.  I went to checkout the nginx error log.  That's the error message I found.  Googled, tried a few settings other stackoverflow posts suggested such as addingsingle-interpreter = true into uwsgi.ini file.  No luck.

Can someone please give me an idea where I should look into for this problem?

Thanks in advance.

答: try going to your rds instance, check its' security group setting.  Happened to me once, too me a while to find out that the security group setting is the problem.  I didn't recall setting up the security group but it restricted with local IP</p>


问:
Recompile Nginx with additional modules
I installed Nginx via apt-get on Debian a while ago, and I've got a couple of sites live on it. Now I need to install some additional modules, and as I don't want to mess anything up I'd like to double check my process before I perform it. Hopefully this will also help others that are unsure about this part.

As I've understood it I have to do the following to minimize the downtime:

Download the source for Nginx

Add the additional modules with ./configure --additional-module

Compile Nginx with make

Stop the current server (service nginx stop)

Install Nginx with make install

Start the new server (service nginx start)

Or do I have to uninstall Nginx first, as it's not compiled from source at this point?

答:
nginx -V - helpful command which shows options for .\configure which was used to make nginx, which is actually working.
Helpful to get detail imagination about.

apt-get source nginx - to get source

install will automatically substitute actual installed version by new one

Keep also in mind that some nginx-modules can require additional libs on server. geoip module is classical example of it

Title: Recompile Nginx with additional modules


问:
Movie is not a constructor - Mongoose
I'm using the MEAN stack and trying to save data to my MongoDB database with Mongoose. However, I keep getting the error
"Movie is not a constructor" for my model. But this is how the Mongoose docs show it, so i'm not sure what i'm doing wrong..

Please help!

Movie.js

```<code>let mongoose = require('mongoose');

let MovieSchema = new mongoose.Schema({
    title: String,
    genre: String
});

export let Movie = mongoose.model("Movie", MovieSchema);
</code>```

route.js

```<code>import express = require('express');
import mongoose = require('mongoose');
let Movie = require('../models/Movie');
let router = express.Router();

router.post('/movies', function(req, res, next) {
  let new_movie = new Movie(req.body);
  new_movie.save(function(err, movie) {
    if(err) return next(err);
    res.send(movie);
  });
});
</code>```

答:
This problem happens when you forget to export your model from the model file or exports in a  wrong way. your model should export like this:

```<code>let Movie = mongoose.model("Movie", MovieSchema);
module.exports=Movie;
</code>```

Or in a shorthand you can simply write:

```<code>module.exports=mongoose.model('Movie',MovieSchema);
</code>```

Title: Movie is not a constructor - Mongoose

Body:
I'm using the MEAN stack and trying to save data to my MongoDB database with Mongoose. However, I keep getting the error
"Movie is not a constructor" for my model. But this is how the Mongoose docs show it, so i'm not sure what i'm doing wrong..

Please help!

Movie.js

let mongoose = require('mongoose');

let MovieSchema = new mongoose.Schema({
    title: String,
    genre: String
});

export let Movie = mongoose.model("Movie", MovieSchema);

route.js

import express = require('express');
import mongoose = require('mongoose');
let Movie = require('../models/Movie');
let router = express.Router();

router.post('/movies', function(req, res, next) {
  let new_movie = new Movie(req.body);
  new_movie.save(function(err, movie) {
    if(err) return next(err);
    res.send(movie);
  });
});

Body:
This problem happens when you forget to export your model from the model file or exports in a  wrong way. your model should export like this:

let Movie = mongoose.model("Movie", MovieSchema);
module.exports=Movie;

Or in a shorthand you can simply write:

module.exports=mongoose.model('Movie',MovieSchema);


问:
PHP script stops running arbitrarily with no errors
I have a PHP script that seemed to stop running after about 20 minutes.

To try to figure out why, I made a very simple script to see how long it would run without any complex code to confuse me.

I found that the same thing was happening with this simple infinite loop. At some point between 15 and 25 minutes of running, it stops without any message or error.  The browser says "Done".

I've been over every single possible thing I could think of:

```<code>set_time_limit ( session.gc_maxlifetime in the php.ini)
memory_limit
max_execution_time
</code>```

The point that the script is stopped is not consistent.  Sometimes it will stop at 15 minutes, sometimes 22 minutes.

Please, any help would be greatly appreciated.

It is hosted on a 1and1 server. I contacted them and they don't provide support for bugs caused by developers.

答:
in such cases, i turn on all the development settings in php.ini, of course on a development server.  This display many more messages, including deprecation warnings.

In my experience of debugging long running php scripts, the most common cause was memory allocation failure (Fatal error: Allowed memory size of xxxx bytes exhausted...)

Body:
I have a PHP script that seemed to stop running after about 20 minutes.

To try to figure out why, I made a very simple script to see how long it would run without any complex code to confuse me.

I found that the same thing was happening with this simple infinite loop. At some point between 15 and 25 minutes of running, it stops without any message or error.  The browser says "Done".

I've been over every single possible thing I could think of:

set_time_limit ( session.gc_maxlifetime in the php.ini)
memory_limit
max_execution_time

The point that the script is stopped is not consistent.  Sometimes it will stop at 15 minutes, sometimes 22 minutes.

Please, any help would be greatly appreciated.

It is hosted on a 1and1 server. I contacted them and they don't provide support for bugs caused by developers.


问:
How To Append Javascript Date To Multiple Inputs With Same ClassName?
I'm trying to append today's date to multiple inputs generated with a while statement. But each one of them returns blank. Any way to make this work? Thanks

PHP

```<code>//rest of code here
while ($row = mysqli_fetch_array($result)) {
<input class="Paydate"  name="Paydate" value="" type="text">
}
</code>```

JS

```<code><script>
var mydate;
mydate = new Date();
document.getElementsByClassName('Paydate').value = mydate.toISOString().slice(0, 19).replace('T', ' ');
</script>
</code>```

答:
You are almost there, getElementsByClassName returns an HTMLCollection see MDN for more info. You are treating it as if it returned a single HTML element.

What you'll need to do is iterate over the results returned and set the value property on each element returned not on the collection.

var dateISOString =  new Date().toISOString().slice(0, 19).replace('T', ' ');
Array.from(document.getElementsByClassName('Paydate')).forEach(element => {
    element.value = dateISOString;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class='Paydate' />
<input class='Paydate' />
<input class='Paydate' />
<input class='Paydate' /></code>```

Body:
I'm trying to append today's date to multiple inputs generated with a while statement. But each one of them returns blank. Any way to make this work? Thanks

PHP

//rest of code here
while ($row = mysqli_fetch_array($result)) {
<input class="Paydate"  name="Paydate" value="" type="text">
}

JS

Body:
You are almost there, getElementsByClassName returns an HTMLCollection see MDN for more info. You are treating it as if it returned a single HTML element.

What you'll need to do is iterate over the results returned and set the value property on each element returned not on the collection.

var dateISOString =  new Date().toISOString().slice(0, 19).replace('T', ' ');
Array.from(document.getElementsByClassName('Paydate')).forEach(element => {
    element.value = dateISOString;
});

<input class='Paydate' />
<input class='Paydate' />
<input class='Paydate' />
<input class='Paydate' />


答:
Evaluation of item[x] is equivalent to item.__getitem__(x). For a string, this will be the xth character in the string (you could think of it as a list of characters). For a list, it will be the xth item in the list.

You can use isinstance to determine if each item in the higher level list is a string or list:

```<code>if isinstance(item, list):
    # Do something with list
elif isinstance(item, str):
    # Do something with string
else:
    raise TypeError("expected list or string")
</code>```

You could also think about how you could use a recursive function to accomplish this task.

Title: How to access and print dictionary values that contain nested lists?

Body:
Evaluation of item[x] is equivalent to item.__getitem__(x). For a string, this will be the xth character in the string (you could think of it as a list of characters). For a list, it will be the xth item in the list.

You can use isinstance to determine if each item in the higher level list is a string or list:

if isinstance(item, list):
    # Do something with list
elif isinstance(item, str):
    # Do something with string
else:
    raise TypeError("expected list or string")

You could also think about how you could use a recursive function to accomplish this task.