问:
How can using gettext help me here?
I am trying to set up a way to allow members to translate strings into other languages.  You can see an example here:  TRANSLATIONS TEST

Someone recommended that I use php's native gettext() function for this, instead of what I am already using to load the language files, which is this:

```<code>function loadLanguageFile($language, $file) {

    $temp = array();

    $data = file_get_contents('./'.$language.'/'.$file.'.'.$language.'.php');

    $codes = array (
        '/(\'\s*\.\s*\$)(.+?)(\s*\.\s*\')/',
        '/(=\s*\$)(.+?)(\s*\.\s*\')/',
        '/(\'\s*\.\s*\$)(.+?)(;)/',
        '/(\[\')(.+?)(\'\])/',
        '/<\?php/s', '/\?>/s', '/<\?/s'
    );
    $html = array (
        '{$2}',
        '= \'{$2}',
        '{$2}\';',
        '[$2]',
        '',
    );
    // Since we don't have the values for the vars.
    $data = preg_replace($codes, $html, $data);

    // We must change this because they are global.
    $data = str_replace('$txt', '$langEditor_txt', $data);
    $data = str_replace('$helptxt', '$langEditor_helptxt', $data);

    eval($data);

    if (isset($langEditor_txt)) {
        $temp['txt'] = $langEditor_txt;
        unset($GLOBALS['langEditor_txt']);
    }
    if (isset($langEditor_helptxt)) {
        $temp['helptxt'] = $langEditor_helptxt;
        unset($GLOBALS['langEditor_helptxt']);
    }

    return $temp;
}
</code>```

The strings are contained within a file that is named like so:
ManageDPModules.english.php
DreamPortal.english.php
etc.

These files can look like the following, when opened in any php editor, and can have many of these $txt variables:

```<code><?php
// Dream Portal (c) 2009-2010 Dream Portal Team
// DreamPortal.english.php; @1.1

global $scripturl, $context;

// General Strings
$txt['forum'] = 'Forum';
$txt['dream_portal'] = 'Dream Portal';
$txt['dp_core_modules'] = 'Collapse or Expand this Module';
$txt['dp_who_forum'] = 'Viewing the forum index of <a href="' . $scripturl . '?action=forum">' . $context['forum_name'] . '</a>.';
$txt['dp_who_portal'] = 'Viewing the portal index of <a href="' . $scripturl . '">' . $context['forum_name'] . '</a>.';
$txt['dp_who_page'] = 'Viewing the page "<a href="' . $scripturl . '?page=%1$s">%2$s</a>".';
?>
</code>```

I am using the following function to save the translations:

```<code>function langSave($lang, $file) {

    // We just don't get values from the form, they have to exist in the english files to be taken seriously.
    $default = loadLanguageFile('english', $file);

    if ($default['txt']) {
        foreach ($default['txt'] as $key=>$string) {
            if (isset($_REQUEST['txt'.$key]) && str_replace(' ', '', $_REQUEST['txt'.$key]) != '') {
                $data.='$txt[\''.$key.'\'] = \''.str_replace("'", "\'", $_REQUEST['txt'.$key]).'\';'."\n";
            }
        }
    }
    if ($default['helptxt']) {
        foreach ($default['helptxt'] as $key=>$string) {
            if (isset($_REQUEST['helptxt'.$key]) && str_replace(' ', '', $_REQUEST['helptxt'.$key]) != '') {
                $data.='$helptxt[\''.$key.'\'] = \''.str_replace("'", "\'", $_REQUEST['helptxt'.$key]).'\';'."\n";
            }
        }
    }

    if (isset($data)) {
        $codes = array (// '' . $test . '
            '/(\{)(.+?)(\})/',
            '/(\'\' \. \$)(.+?)( \. \')/',
            '/(\' \. \$)(.+?)( \. \'\')/',
            '/(\[\')(.+?)(\'\])/',
            '/(\[)(.+?)(\])/',
        );
        $html = array (
            '\' . \$$2 . \'',
            '\$$2 . \'',
            '\' . \$$2',
            '[$2]',
            '[\'$2\']',
        );
        // Convert the data back to normal.
        $data = preg_replace($codes, $html, $data);

        $data = '<?php'."\n".$data.'?>';
        file_put_contents('./'.$lang.'/'.$file.'.'.$lang.'.php', $data);
    }
    languageHome();
}
</code>```

Language function:

```<code>function languageHome() {

    $languages = loadLanguageList();

    echo '
    Language List
        <table>';
    foreach ($languages as $language) {
        echo '
            <tr>
                <td>
                    '.$language.'
                </td>
                <td>
                    <a href="index.php?op=langView&lang='.$language.'">View</a>
                </td>
            </tr>';
    }
    echo '
        </table>';

}
</code>```

I fail to see how gettext will help out. There is no way to update the text catalog without rebooting the server every time. Maybe if someone can create a demo of this for me?

Also, would like it to support UTF-8. The data should be consistent.

So what is wrong with this implementation??  Why use gettext??  How can it be used to improve translations to work for both UTF-8 and non UTF-8 language strings so that it can be translated.?

EDIT:
Please note, the files will eventually need to be renamed to:  ManageDPModules.[language].php, DreamPortal.[language].php, etc., etc. in order for the translations to work.  So, how would catalogs help me in this regard?  If you want to see possible END-RESULT Translations, you can download a language package located here and open up the .german.php language files to see what it should look like after the member submits a language on a file by file basis.  Noted that some of these packages have UTF-8 strings, and some do not.  The filename of the packages let you know this.  Would be nice if I can also make it support UTF-8, but it is not a requirement.  Please note, I'm not trying to create complete packages here.  I just want to create the languagefile.[language].php with all of the translated strings inside of them (which my code already does).

OK, I will provide the ENTIRE index.php file for this so you can see what it does exactly when you do translations.  Here is the index.php file for this and you'll need some english language files: DreamPortal.english.php, ManageDPModules.english.php, and DreamHelp.english-utf8.php.  Now, in order to see this, you need to upload to a server, index.php, create a few folders where index.php is, call 1 english, and create a folder in there for each additional language you want (I did 2 folders, spanish and french), than upload the 3 language files into the english folder.  Run index.php in your browser and you will see it working.

Now, how could I use gettext for catalogs with this SAME approach.  I need to enable online translation of files.  I need to create PHP files of the translations in the SAME style that the .english.php files are with the same PREFIX that is before .english.php, and I need to change the language within the filename to the same language defined for the folder name.  Online translations is the ONLY method available.  Translator's need to focus ONLY on translating the strings.  They shouldn't be focusing on installing programs, packaging it up, renaming the files, etc. etc..  This makes this process as painless as possible allowing it to be done online.  And I know there is a way to do this, and even for UTF-8 support.  But I'm using the best method that I know how at the moment.  But so many of you are MUCH smarter at this sort of thing than I am, so I ask for help from you guys.

Is there anyone that can show me a better way?  An example like the one that I have given you in this question?

I need to allow translations to be done ONLINE from translators, and would also like it to support UTF-8 files, as well as non UTF-8 files.  I like the way I have it setup for the link provided above (TRANSLATIONS TEST) so that translator's can just do the translations online and not have to worry about anything else, and it would automatically create the files needed.  Which would be the same as the english filename of the language with the folder name (representing the language) after the first . (dot) and it needs to have the extension .php (like it does in the code I am currently using).  So basically, I need an adaption of the current index.php to support UTF-8 and non UTF-8 for all or most languages, and was told that using gettext() and catalog files would help with this.

Looking for a modified version of my current index.php to use gettext() in a way that it will support most, if not all, languages and translations.  The REGEX I got going on for preg_replace isn't completely satisfactory because it seems to place a forward slash in front of double quotes when saving/submitting the translations.  So perhaps an improvement on the preg_replace would be needed also.

I provided a complete example with ACTUAL CODE bytheway. I'd like for someone to alter this example, with the CODE that I provided to USE GETTEXT instead and support UTF-8. Or actually provide a ACTUAL METHOD for me to do this myself with. Not looking for a bunch of links that I can find on my own!

Thank You!

答:
When you have been recommended to use gettext, it was actually an advise to use a gettext-like translation system. Your current code is complex because of mnemonic text indicies. And the trouble you got into with the regular expressions for editing is caused by fiddling with variables in there. Let me propose some alternative code for transitional purposes.

The beauty of gettext lies in its use of a non-obtrusive API. The function call _() is simple enough to be thoroughly used without adding much syntax or code bloat. It's preferrable to things like getTextTrans('ABBR_TXT_ID'). Using such mnemonic text ids is a widespread fallacy; because in practice there aren't frequent rewordings and _("Raw english original text.")  serves the same purpose. However, since you already have mnemonic keys in place, keep them if it's too much to change. This is just a recommendation.

Your real problem is the use of inline PHP expressions to build up the translation target strings. They are why the regular expressions for your translation editor became opaque. Therefore I'd highly recommend to use static strings and provide placeholders. The translation function should be tasked with handling it. (Don't worry about microoptimizing here!) - I would use {$url_xy} PHP/Smarty-style placeholders for example:

```<code>$txt['dp_who_forum'] = 'Viewing the forum index
of <a href="{$scripturl}?action=forum">{$forum_name}</a>.';
</code>```

And a translation function that looks up a global placeholder table or params ($context) for replacing:

```<code>function __($text, $params=array()) {
    global $txt, $txt_placeholders;
    if (isset($txt[$text])) {
        $text = $txt[$text];
    }
    if (strpos($text, '{$')) {
        $params = array_merge($params, $txt_placeholders);
        $text= preg_replace("/\{\$(\w+)\}/e", "$params['$1']", $text);
    }
    return $text;
}
</code>```

Optimizable. But this way you can use a static mnemonic->text or english->text set of translation arrays. You only use static strings in your text-translation-editor-form thingy. Those static strings are shown as-is, and your translators edit the english text, but not any of the {$placeholders}.

Hence your code for the translation feature won't need any of the complex regular expressions (in this case they are not useful) to match strings and inline PHP variables. In fact a much simpler include() and var_export() combination can now take its place:

```<code>function langSave($lang, $file) {
    $txt = array();
    include($file);   // assuming it contains a simple $txt = array(...

    foreach ($txt as $key=>$string) {
        $txt[$key] = $_REQUEST["txt$key"];
    }
    file_put_contents($file, "<?php\n\$txt =".var_export($txt,1).';?>');
}
</code>```

Filehandling and whatnot needs to be customized of course. But still this is a simpler approach.

And it would further allow you to transition to one of the gettext variations as backends. Keep your custom wrapper function __() and use e.g. Zend_Translate as backend. This allows you to keep using your .php $txt=array() translation files (or I think so) or move to gettext-style .mo/.po files. The advantage of that being, that there is rich tool support in contrast to homebrew solutions.

Anyway this is how you use the stuff in your main application:

```<code>print "<a href='...'>" . __("link_text") . "</a>";
print __("dp_forum_link");   // uses e.g. $txt_placeholder["scripturl"]
print __("dp_param_link", array("scripturl"=>"http://override..."));
</code>```

Moving from the short_txt keys to english->foreign text translation arrays would be advisable first, but in theory any of the backends from dvbs answer would be applicable. Now you already said that native gettext is not an option for you (for non-fastcgi PHP setups the memory resistance is a drawback). But PHPs native INTL features might be of help to you. In particular http://www.php.net/manual/en/class.messageformatter.php might be more useful than the simple-minded {$var} replacement wrapper I gave you. But I've never used it, and I think Zend_Translate is likely more useful. In particular can any of those backends give you charset independence. Personally I'd just stick to UTF-8, no matter what. But gettext .mo/.po files can each have their own custom charset for example.

Title: How can using gettext help me here?

Body:
I am trying to set up a way to allow members to translate strings into other languages.  You can see an example here:  TRANSLATIONS TEST

Someone recommended that I use php's native gettext() function for this, instead of what I am already using to load the language files, which is this:

function loadLanguageFile($language, $file) {

    $temp = array();

    $data = file_get_contents('./'.$language.'/'.$file.'.'.$language.'.php');

    $codes = array (
        '/(\'\s*\.\s*\$)(.+?)(\s*\.\s*\')/',
        '/(=\s*\$)(.+?)(\s*\.\s*\')/',
        '/(\'\s*\.\s*\$)(.+?)(;)/',
        '/(\[\')(.+?)(\'\])/',
        '/<\?php/s', '/\?>/s', '/<\?/s'
    );
    $html = array (
        '{$2}',
        '= \'{$2}',
        '{$2}\';',
        '[$2]',
        '',
    );
    // Since we don't have the values for the vars.
    $data = preg_replace($codes, $html, $data);

    // We must change this because they are global.
    $data = str_replace('$txt', '$langEditor_txt', $data);
    $data = str_replace('$helptxt', '$langEditor_helptxt', $data);

    eval($data);

    if (isset($langEditor_txt)) {
        $temp['txt'] = $langEditor_txt;
        unset($GLOBALS['langEditor_txt']);
    }
    if (isset($langEditor_helptxt)) {
        $temp['helptxt'] = $langEditor_helptxt;
        unset($GLOBALS['langEditor_helptxt']);
    }

    return $temp;
}

The strings are contained within a file that is named like so:
ManageDPModules.english.php
DreamPortal.english.php
etc.

These files can look like the following, when opened in any php editor, and can have many of these $txt variables:

<?php
// Dream Portal (c) 2009-2010 Dream Portal Team
// DreamPortal.english.php; @1.1

global $scripturl, $context;

// General Strings
$txt['forum'] = 'Forum';
$txt['dream_portal'] = 'Dream Portal';
$txt['dp_core_modules'] = 'Collapse or Expand this Module';
$txt['dp_who_forum'] = 'Viewing the forum index of ' . $context['forum_name'] . '.';
$txt['dp_who_portal'] = 'Viewing the portal index of ' . $context['forum_name'] . '.';
$txt['dp_who_page'] = 'Viewing the page "%2$s".';
?>

I am using the following function to save the translations:

function langSave($lang, $file) {

    // We just don't get values from the form, they have to exist in the english files to be taken seriously.
    $default = loadLanguageFile('english', $file);

    if ($default['txt']) {
        foreach ($default['txt'] as $key=>$string) {
            if (isset($_REQUEST['txt'.$key]) && str_replace(' ', '', $_REQUEST['txt'.$key]) != '') {
                $data.='$txt[\''.$key.'\'] = \''.str_replace("'", "\'", $_REQUEST['txt'.$key]).'\';'."\n";
            }
        }
    }
    if ($default['helptxt']) {
        foreach ($default['helptxt'] as $key=>$string) {
            if (isset($_REQUEST['helptxt'.$key]) && str_replace(' ', '', $_REQUEST['helptxt'.$key]) != '') {
                $data.='$helptxt[\''.$key.'\'] = \''.str_replace("'", "\'", $_REQUEST['helptxt'.$key]).'\';'."\n";
            }
        }
    }

    if (isset($data)) {
        $codes = array (// '' . $test . '
            '/(\{)(.+?)(\})/',
            '/(\'\' \. \$)(.+?)( \. \')/',
            '/(\' \. \$)(.+?)( \. \'\')/',
            '/(\[\')(.+?)(\'\])/',
            '/(\[)(.+?)(\])/',
        );
        $html = array (
            '\' . \$$2 . \'',
            '\$$2 . \'',
            '\' . \$$2',
            '[$2]',
            '[\'$2\']',
        );
        // Convert the data back to normal.
        $data = preg_replace($codes, $html, $data);

        $data = '<?php'."\n".$data.'?>';
        file_put_contents('./'.$lang.'/'.$file.'.'.$lang.'.php', $data);
    }
    languageHome();
}

Language function:

function languageHome() {

    $languages = loadLanguageList();

    echo '
    Language List

';
    foreach ($languages as $language) {
        echo '

                    '.$language.'

                    View

';
    }
    echo '

';

}

I fail to see how gettext will help out. There is no way to update the text catalog without rebooting the server every time. Maybe if someone can create a demo of this for me?

Also, would like it to support UTF-8. The data should be consistent.

So what is wrong with this implementation??  Why use gettext??  How can it be used to improve translations to work for both UTF-8 and non UTF-8 language strings so that it can be translated.?

EDIT:
Please note, the files will eventually need to be renamed to:  ManageDPModules.[language].php, DreamPortal.[language].php, etc., etc. in order for the translations to work.  So, how would catalogs help me in this regard?  If you want to see possible END-RESULT Translations, you can download a language package located here and open up the .german.php language files to see what it should look like after the member submits a language on a file by file basis.  Noted that some of these packages have UTF-8 strings, and some do not.  The filename of the packages let you know this.  Would be nice if I can also make it support UTF-8, but it is not a requirement.  Please note, I'm not trying to create complete packages here.  I just want to create the languagefile.[language].php with all of the translated strings inside of them (which my code already does).

OK, I will provide the ENTIRE index.php file for this so you can see what it does exactly when you do translations.  Here is the index.php file for this and you'll need some english language files: DreamPortal.english.php, ManageDPModules.english.php, and DreamHelp.english-utf8.php.  Now, in order to see this, you need to upload to a server, index.php, create a few folders where index.php is, call 1 english, and create a folder in there for each additional language you want (I did 2 folders, spanish and french), than upload the 3 language files into the english folder.  Run index.php in your browser and you will see it working.

Now, how could I use gettext for catalogs with this SAME approach.  I need to enable online translation of files.  I need to create PHP files of the translations in the SAME style that the .english.php files are with the same PREFIX that is before .english.php, and I need to change the language within the filename to the same language defined for the folder name.  Online translations is the ONLY method available.  Translator's need to focus ONLY on translating the strings.  They shouldn't be focusing on installing programs, packaging it up, renaming the files, etc. etc..  This makes this process as painless as possible allowing it to be done online.  And I know there is a way to do this, and even for UTF-8 support.  But I'm using the best method that I know how at the moment.  But so many of you are MUCH smarter at this sort of thing than I am, so I ask for help from you guys.

Is there anyone that can show me a better way?  An example like the one that I have given you in this question?

I need to allow translations to be done ONLINE from translators, and would also like it to support UTF-8 files, as well as non UTF-8 files.  I like the way I have it setup for the link provided above (TRANSLATIONS TEST) so that translator's can just do the translations online and not have to worry about anything else, and it would automatically create the files needed.  Which would be the same as the english filename of the language with the folder name (representing the language) after the first . (dot) and it needs to have the extension .php (like it does in the code I am currently using).  So basically, I need an adaption of the current index.php to support UTF-8 and non UTF-8 for all or most languages, and was told that using gettext() and catalog files would help with this.

Looking for a modified version of my current index.php to use gettext() in a way that it will support most, if not all, languages and translations.  The REGEX I got going on for preg_replace isn't completely satisfactory because it seems to place a forward slash in front of double quotes when saving/submitting the translations.  So perhaps an improvement on the preg_replace would be needed also.

I provided a complete example with ACTUAL CODE bytheway. I'd like for someone to alter this example, with the CODE that I provided to USE GETTEXT instead and support UTF-8. Or actually provide a ACTUAL METHOD for me to do this myself with. Not looking for a bunch of links that I can find on my own!

Thank You!

Body:
When you have been recommended to use gettext, it was actually an advise to use a gettext-like translation system. Your current code is complex because of mnemonic text indicies. And the trouble you got into with the regular expressions for editing is caused by fiddling with variables in there. Let me propose some alternative code for transitional purposes.

The beauty of gettext lies in its use of a non-obtrusive API. The function call _() is simple enough to be thoroughly used without adding much syntax or code bloat. It's preferrable to things like getTextTrans('ABBR_TXT_ID'). Using such mnemonic text ids is a widespread fallacy; because in practice there aren't frequent rewordings and _("Raw english original text.")  serves the same purpose. However, since you already have mnemonic keys in place, keep them if it's too much to change. This is just a recommendation.

Your real problem is the use of inline PHP expressions to build up the translation target strings. They are why the regular expressions for your translation editor became opaque. Therefore I'd highly recommend to use static strings and provide placeholders. The translation function should be tasked with handling it. (Don't worry about microoptimizing here!) - I would use {$url_xy} PHP/Smarty-style placeholders for example:

$txt['dp_who_forum'] = 'Viewing the forum index
of <a href="{$scripturl}?action=forum">{$forum_name}</a>.';

And a translation function that looks up a global placeholder table or params ($context) for replacing:

function __($text, $params=array()) {
    global $txt, $txt_placeholders;
    if (isset($txt[$text])) {
        $text = $txt[$text];
    }
    if (strpos($text, '{$')) {
        $params = array_merge($params, $txt_placeholders);
        $text= preg_replace("/\{\$(\w+)\}/e", "$params['$1']", $text);
    }
    return $text;
}

Optimizable. But this way you can use a static mnemonic->text or english->text set of translation arrays. You only use static strings in your text-translation-editor-form thingy. Those static strings are shown as-is, and your translators edit the english text, but not any of the {$placeholders}.

Hence your code for the translation feature won't need any of the complex regular expressions (in this case they are not useful) to match strings and inline PHP variables. In fact a much simpler include() and var_export() combination can now take its place:

function langSave($lang, $file) {
    $txt = array();
    include($file);   // assuming it contains a simple $txt = array(...

    foreach ($txt as $key=>$string) {
        $txt[$key] = $_REQUEST["txt$key"];
    }
    file_put_contents($file, "<?php\n\$txt =".var_export($txt,1).';?>');
}

Filehandling and whatnot needs to be customized of course. But still this is a simpler approach.

And it would further allow you to transition to one of the gettext variations as backends. Keep your custom wrapper function __() and use e.g. Zend_Translate as backend. This allows you to keep using your .php $txt=array() translation files (or I think so) or move to gettext-style .mo/.po files. The advantage of that being, that there is rich tool support in contrast to homebrew solutions.

Anyway this is how you use the stuff in your main application:

print "<a href='...'>" . __("link_text") . "</a>";
print __("dp_forum_link");   // uses e.g. $txt_placeholder["scripturl"]
print __("dp_param_link", array("scripturl"=>"http://override..."));

Moving from the short_txt keys to english->foreign text translation arrays would be advisable first, but in theory any of the backends from dvbs answer would be applicable. Now you already said that native gettext is not an option for you (for non-fastcgi PHP setups the memory resistance is a drawback). But PHPs native INTL features might be of help to you. In particular http://www.php.net/manual/en/class.messageformatter.php might be more useful than the simple-minded {$var} replacement wrapper I gave you. But I've never used it, and I think Zend_Translate is likely more useful. In particular can any of those backends give you charset independence. Personally I'd just stick to UTF-8, no matter what. But gettext .mo/.po files can each have their own custom charset for example.


来源: stackexchange

问:
Two-sample Kolmogorov-Smirnov test, difference in result between raw data and precomputed percentage data
I'm trying to implement the two-sample Kolmogorov-Smirnov test from the Scipy package to test if there is a difference in the distribution of two samples. The samples are T-shirts sizes (S, M, L, XL and XXL) sold in two different periods. I want to test whether the distribution of sizes differs between the two periods.

The problem I have is that I get very different results when I pre-calculate the percentages of total for each size compared to using the raw data. I don't understand this as the percentages still represent the same distribution.

Here is the code I've used (x and y is raw data, x1 and y1 is the calculated percentages):

```<code>from scipy.stats import ks_2samp

x = (254, 526, 576, 622, 409)
y = (92, 214, 366, 365, 287)

x1 = (10.6, 21.9, 24.0, 25.9, 17.1)
y1 = (7.0, 16.2, 27.7, 27.7, 21.7)

print(ks_2samp(x, y))
print(ks_2samp(x1, y1))
</code>```

And these are the two different results that I get:

Ks_2sampResult(statistic=0.80000000000000004, pvalue=0.03614619076928504)
Ks_2sampResult(statistic=0.40000000000000002, pvalue=0.69740487802059081)

答:
The test is invariant under a scaling of the data, if the same scaling is applied to both samples.  By converting the samples to percentages, you have applied a different scaling to the two samples.  Specifically, you multiplied the first data set by 100/2387, while multiplying the second data set by 100/1324.

By the way, I don't think the Kolmogorov-Smirnov (KS) test is appropriate for this data.  The KS test is for samples from a continuous distribution.  I would expect to model your data as the observed frequencies in a sample from a discrete distribution whose sample space is {S, M, L, XL, XXL}.  One common tool for the analysis of such data is the chi-squared test for a contingency table, which is implemented in scipy as scipy.stats.chi2_contingency:

```<code>In [110]: x
Out[110]: array([254, 526, 576, 622, 409])

In [111]: y
Out[111]: array([ 92, 214, 366, 365, 287])

In [112]: a = np.vstack((x, y))

In [113]: a
Out[113]:
array([[254, 526, 576, 622, 409],
       [ 92, 214, 366, 365, 287]])

In [114]: from scipy.stats import chi2_contingency

In [115]: chi2, p, dof, expected = chi2_contingency(a)

In [116]: p
Out[116]: 2.1980217327784848e-08
</code>```

Be careful how you interpret this, because "with enough data, everything is significant".

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to implement the two-sample Kolmogorov-Smirnov test from the Scipy package to test if there is a difference in the distribution of two samples. The samples are T-shirts sizes (S, M, L, XL and XXL) sold in two different periods. I want to test whether the distribution of sizes differs between the two periods.

The problem I have is that I get very different results when I pre-calculate the percentages of total for each size compared to using the raw data. I don't understand this as the percentages still represent the same distribution.

Here is the code I've used (x and y is raw data, x1 and y1 is the calculated percentages):

from scipy.stats import ks_2samp

x = (254, 526, 576, 622, 409)
y = (92, 214, 366, 365, 287)

x1 = (10.6, 21.9, 24.0, 25.9, 17.1)
y1 = (7.0, 16.2, 27.7, 27.7, 21.7)

print(ks_2samp(x, y))
print(ks_2samp(x1, y1))

And these are the two different results that I get:

Ks_2sampResult(statistic=0.80000000000000004, pvalue=0.03614619076928504)
Ks_2sampResult(statistic=0.40000000000000002, pvalue=0.69740487802059081)

Body:
The test is invariant under a scaling of the data, if the same scaling is applied to both samples.  By converting the samples to percentages, you have applied a different scaling to the two samples.  Specifically, you multiplied the first data set by 100/2387, while multiplying the second data set by 100/1324.

By the way, I don't think the Kolmogorov-Smirnov (KS) test is appropriate for this data.  The KS test is for samples from a continuous distribution.  I would expect to model your data as the observed frequencies in a sample from a discrete distribution whose sample space is {S, M, L, XL, XXL}.  One common tool for the analysis of such data is the chi-squared test for a contingency table, which is implemented in scipy as scipy.stats.chi2_contingency:

In [110]: x
Out[110]: array([254, 526, 576, 622, 409])

In [111]: y
Out[111]: array([ 92, 214, 366, 365, 287])

In [112]: a = np.vstack((x, y))

In [113]: a
Out[113]:
array([[254, 526, 576, 622, 409],
       [ 92, 214, 366, 365, 287]])

In [114]: from scipy.stats import chi2_contingency

In [115]: chi2, p, dof, expected = chi2_contingency(a)

In [116]: p
Out[116]: 2.1980217327784848e-08

Be careful how you interpret this, because "with enough data, everything is significant".


问:
Filter list of strings starting with specific keyword
How can I find a string (PartialWord) inside a List (WordList) in Python 2.7?

```<code>PartialWord = "ab"
WordList = ['absail', 'rehab', 'dolphin']
</code>```

A search with a wildcard like: ab*

Where it would ONLY find the word, if it starts with those letters (i.e. the result should only give absail, but not rehab, despite both having 'ab').

The WordList would be a dictionary, which is over 700KB.

答:
You may use str.startswith(..) along with a list comprehension to get the list of the words starting with some string as:

```<code>>>> PartialWord = "ab"
>>> WordList = ['absail', 'rehab', 'dolphin']

>>> [word for word in WordList if word.startswith(PartialWord)]
['absail']
</code>```

As per the str.startswith document:

str.startswith(prefix[, start[, end]]):

Return True if string starts
  with the prefix, otherwise return False. prefix can also be a tuple of
  prefixes to look for. With optional start, test string beginning at
  that position. With optional end, stop comparing string at that
  position.

ContentLicense: CC BY-SA 4.0

Body:
How can I find a string (PartialWord) inside a List (WordList) in Python 2.7?

PartialWord = "ab"
WordList = ['absail', 'rehab', 'dolphin']

A search with a wildcard like: ab*

Where it would ONLY find the word, if it starts with those letters (i.e. the result should only give absail, but not rehab, despite both having 'ab').

The WordList would be a dictionary, which is over 700KB.

Body:
You may use str.startswith(..) along with a list comprehension to get the list of the words starting with some string as:

>>> PartialWord = "ab"
>>> WordList = ['absail', 'rehab', 'dolphin']

>>> [word for word in WordList if word.startswith(PartialWord)]
['absail']

As per the str.startswith document:

str.startswith(prefix[, start[, end]]):

Return True if string starts
  with the prefix, otherwise return False. prefix can also be a tuple of
  prefixes to look for. With optional start, test string beginning at
  that position. With optional end, stop comparing string at that
  position.


问:
Unresolved reference: LinearLayoutManager/RecyclerView
I started building a movie database app using Kotlin based on a tutorial I found online (see this link for details.  While building the movie fragment file, I noticed an "unresolved reference:  LinearLayoutManager" and an "unresolved reference:  RecyclerView" error.
 I have included the code below to and everything matches up like the tutorial except for those errors:

```<code>import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.dburgnerjr.movietvshowdatabase.R
import com.dburgnerjr.movietvshowdatabase.commons.inflate
import kotlinx.android.synthetic.main.movie_fragment.*

class MovieFragment : Fragment() {

    private val movieList by lazy {
        movie_list
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return container?.inflate(R.layout.movie_fragment)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        movieList.setHasFixedSize(true)
        movieList.layoutManager = LinearLayoutManager(context)
    }
}
</code>```

Anything I overlooked?

答:
I figured it out.  I saw this post and noticed that I missed a

```<code>compile 'com.android.support:recyclerview-v7:25.3.1'
</code>```

reference in my build.gradle file.  Problem solved.

Body:
I started building a movie database app using Kotlin based on a tutorial I found online (see this link for details.  While building the movie fragment file, I noticed an "unresolved reference:  LinearLayoutManager" and an "unresolved reference:  RecyclerView" error.
 I have included the code below to and everything matches up like the tutorial except for those errors:

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.dburgnerjr.movietvshowdatabase.R
import com.dburgnerjr.movietvshowdatabase.commons.inflate
import kotlinx.android.synthetic.main.movie_fragment.*

class MovieFragment : Fragment() {

    private val movieList by lazy {
        movie_list
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return container?.inflate(R.layout.movie_fragment)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        movieList.setHasFixedSize(true)
        movieList.layoutManager = LinearLayoutManager(context)
    }
}

Anything I overlooked?

Body:
I figured it out.  I saw this post and noticed that I missed a

compile 'com.android.support:recyclerview-v7:25.3.1'

reference in my build.gradle file.  Problem solved.


答:
```<code>for word in WordList:
    if word.startswith(PartialWord):
        print word
</code>```

Title: Filter list of strings starting with specific keyword


问:
npm can't find package.json
I'm trying to install the dependencies of some example: npm's express 2.5.8 that I've downloaded, but all of the apps throw the same error:

```<code>c:\node\stylus>npm install -d
npm info it worked if it ends with ok
npm info using npm@1.1.1
npm info using node@v0.6.11
npm ERR! Couldn't read dependencies.

npm ERR! Error: ENOENT, no such file or directory 'c:\node\stylus\package.json'
npm ERR! You may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>
npm ERR!
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program File
s (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-d"
npm ERR! cwd c:\node\stylus
npm ERR! node -v v0.6.11
npm ERR! npm -v 1.1.1
npm ERR! path c:\node\stylus\package.json
npm ERR! code ENOENT
npm ERR! message ENOENT, no such file or directory 'c:\node\stylus\package.json'

npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     c:\node\stylus\npm-debug.log
npm not ok
</code>```

The blockage appears to be:

no such file or directory 'c:\node\stylus\package.json

Did I miss a step that creates the package.json ?

I'm running:

Windows 7 64 bit

npm 1.1.1

node 6.11

express 2.5.8

答: Adding -g before the package name worked for me. Looking for documentation to explain why this works..</p>

Title: npm can't find package.json

Body:
I'm trying to install the dependencies of some example: npm's express 2.5.8 that I've downloaded, but all of the apps throw the same error:

c:\node\stylus>npm install -d
npm info it worked if it ends with ok
npm info using npm@1.1.1
npm info using node@v0.6.11
npm ERR! Couldn't read dependencies.

npm ERR! Error: ENOENT, no such file or directory 'c:\node\stylus\package.json'
npm ERR! You may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>
npm ERR!
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program File
s (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-d"
npm ERR! cwd c:\node\stylus
npm ERR! node -v v0.6.11
npm ERR! npm -v 1.1.1
npm ERR! path c:\node\stylus\package.json
npm ERR! code ENOENT
npm ERR! message ENOENT, no such file or directory 'c:\node\stylus\package.json'

npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     c:\node\stylus\npm-debug.log
npm not ok

The blockage appears to be:

no such file or directory 'c:\node\stylus\package.json

Did I miss a step that creates the package.json ?

I'm running:

Windows 7 64 bit

npm 1.1.1

node 6.11

express 2.5.8


问:
Using STL algorithms with Qt containers
I have a problem, using STL algorithm with QList: while executing it crashes. Debuger takes one more step into lambda, so before to crash entry is . (So, if list is empty is crashes at 1 iteration, if list has 1 element - at 2 iteration etc.).

```<code>void FindDialog::findEntries()
{
    QList<StudentEntry> searchResult;

    condition = [this] (const StudentEntry &entry) -> bool {
                // crashes here
                return entry.name.getSurname() == surnameEdt1->text() &&
                       entry.group.getValue() == groupEdt->text();
                };

    std::copy_if(model->getStudentEntryList().begin(),
                 model->getStudentEntryList().end(),
                 searchResult.begin(),
                 condition);
}
</code>```

How can I solve the problem?

答:
std::copy_if increments the output iterator when copying elements. You passed it searchResult.begin() which is equally an end() iterator since searchResult is an empty container. And increment(ing) an iterator passed the end() iterator invokes Undefined Behavior.

since QList<T> supports a push_back(T) member function, you should use std::back_inserter to create a std::back_insert_iterator that will be doing push back's to searchResult

```<code>std::copy_if(model->getStudentEntryList().begin(),
             model->getStudentEntryList().end(),
             std::back_inserter(searchResult),
             condition);
</code>```

Title: Using STL algorithms with Qt containers

Body:
I have a problem, using STL algorithm with QList: while executing it crashes. Debuger takes one more step into lambda, so before to crash entry is . (So, if list is empty is crashes at 1 iteration, if list has 1 element - at 2 iteration etc.).

void FindDialog::findEntries()
{
    QList<StudentEntry> searchResult;

    condition = [this] (const StudentEntry &entry) -> bool {
                // crashes here
                return entry.name.getSurname() == surnameEdt1->text() &&
                       entry.group.getValue() == groupEdt->text();
                };

    std::copy_if(model->getStudentEntryList().begin(),
                 model->getStudentEntryList().end(),
                 searchResult.begin(),
                 condition);
}

How can I solve the problem?

Body:
std::copy_if increments the output iterator when copying elements. You passed it searchResult.begin() which is equally an end() iterator since searchResult is an empty container. And increment(ing) an iterator passed the end() iterator invokes Undefined Behavior.

since QList<T> supports a push_back(T) member function, you should use std::back_inserter to create a std::back_insert_iterator that will be doing push back's to searchResult

std::copy_if(model->getStudentEntryList().begin(),
             model->getStudentEntryList().end(),
             std::back_inserter(searchResult),
             condition);


问:
Should I use cookies, session values, or hidden fields to store data items that need to be persisted between requests?
This is a Rails 3 project.

Am I abusing the use of cookies if I store query values there? I have a dataset that a user can "drill-down" through, so as the user clicks through the data, he amasses a bunch of query values that further limit the data presented on the next request.

Right now I'm doing this with a cookie, and it works great, except that I can't figure out to check to see if cookies are enabled. So some people using IE are giving me fits because the app just fails with no errors.

I used to put values like this in a session variable, which worked great until it mysteriously didn't, i.e. when memcached aged or cleared them out.  I wouldn't want to keep the values in a session in the db because I don't want the extra hits on every request.

So I suppose I could put the values either in hidden form fields, or append them to the links on the page that I'm presenting each time.  Is there a conventional Rails Way to do this that I'm missing?

答:
If you're showing a different set of results, the URL should reflect this. This makes URL query parameters the natural choice. This provides several benefits:

There is no state at all. You don't have to store anything or break the stateless nature of HTTP.

There is a one-to-one correspondence between sets of query results and URLs.

You can link to query results.

Works on everything, ever.

ContentLicense: CC BY-SA 2.5


问:
R: Convert binary categorical variables to long data format
```<code>mydata <- structure(list(id = 1:10, cafe = c(0, 1, 0, 0, 1, 1, 0, 0, 1,
1), playground = c(1, 1, 1, 1, 1, 1, 0, 1, 1, 0), classroom = c(0,
0, 0, 0, 0, 1, 1, 1, 1, 1), gender = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 2L), .Label = c("Female", "Male"), class = "factor"),
    job = structure(c(2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L), .Label = c("Student",
    "Teacher"), class = "factor")), .Names = c("id", "cafe",
"playground", "classroom", "gender", "job"), row.names = c(NA,
-10L), class = "data.frame")

> mydata
   id cafe playground classroom gender     job
1   1    0          1         0   Male Teacher
2   2    1          1         0   Male Student
3   3    0          1         0   Male Teacher
4   4    0          1         0   Male Student
5   5    1          1         0   Male Teacher
6   6    1          1         1   Male Teacher
7   7    0          0         1 Female Teacher
8   8    0          1         1   Male Teacher
9   9    1          1         1 Female Teacher
10 10    1          0         1   Male Student
</code>```

My desired long format data set should look like:

```<code>id      response    gender        job
1     playground      Male    Teacher
2           cafe      Male    Student
2     playground      Male    Student
3     playground      Male    Teacher
...
</code>```

Essentially, the response column corresponds to which of the cafe, playground, and classroom columns have a value of 1. I've looked into several examples here and here, but they do not deal with binary data columns.

答:
This can be done by using the melt(data, ...) function from the reshape package.

```<code>library(reshape)
</code>```

First, we assign the variables that we want to keep as columns.

```<code>id <- c("id", "gender", "job")
</code>```

Then, we change the wide format to long format and keep only the rows that contain a 1.

```<code>df <- melt(mydata, id=id)
df[df[,5]==1,-5]
</code>```

Then, order the data by id.

```<code>df <- df[order(df[,"id"]),]
</code>```

Finally, we change the column name and rearrange the columns.

```<code>colnames(df)[4] <- "response"
df <- df[,c(1,4,2,3)]

## id   response  gender    job
## 1  playground   Male Teacher
## 2        cafe   Male Student
## 2  playground   Male Student
## 3  playground   Male Teacher
## ...
## ...
## 9   classroom Female Teacher
## 10       cafe   Male Student
## 10  classroom   Male Student
</code>```

Body:
mydata <- structure(list(id = 1:10, cafe = c(0, 1, 0, 0, 1, 1, 0, 0, 1,
1), playground = c(1, 1, 1, 1, 1, 1, 0, 1, 1, 0), classroom = c(0,
0, 0, 0, 0, 1, 1, 1, 1, 1), gender = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 2L), .Label = c("Female", "Male"), class = "factor"),
    job = structure(c(2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L), .Label = c("Student",
    "Teacher"), class = "factor")), .Names = c("id", "cafe",
"playground", "classroom", "gender", "job"), row.names = c(NA,
-10L), class = "data.frame")

> mydata
   id cafe playground classroom gender     job
1   1    0          1         0   Male Teacher
2   2    1          1         0   Male Student
3   3    0          1         0   Male Teacher
4   4    0          1         0   Male Student
5   5    1          1         0   Male Teacher
6   6    1          1         1   Male Teacher
7   7    0          0         1 Female Teacher
8   8    0          1         1   Male Teacher
9   9    1          1         1 Female Teacher
10 10    1          0         1   Male Student

My desired long format data set should look like:

id      response    gender        job
1     playground      Male    Teacher
2           cafe      Male    Student
2     playground      Male    Student
3     playground      Male    Teacher
...

Essentially, the response column corresponds to which of the cafe, playground, and classroom columns have a value of 1. I've looked into several examples here and here, but they do not deal with binary data columns.

Body:
This can be done by using the melt(data, ...) function from the reshape package.

library(reshape)

First, we assign the variables that we want to keep as columns.

id <- c("id", "gender", "job")

Then, we change the wide format to long format and keep only the rows that contain a 1.

df <- melt(mydata, id=id)
df[df[,5]==1,-5]

Then, order the data by id.

df <- df[order(df[,"id"]),]

Finally, we change the column name and rearrange the columns.

colnames(df)[4] <- "response"
df <- df[,c(1,4,2,3)]

## id   response  gender    job
## 1  playground   Male Teacher
## 2        cafe   Male Student
## 2  playground   Male Student
## 3  playground   Male Teacher
## ...
## ...
## 9   classroom Female Teacher
## 10       cafe   Male Student
## 10  classroom   Male Student


问:
How to resolve this ‘Unresolved reference’ when I have defined the function?
I am just a beginner in programming, started learning Kotlin today. I am getting this error.

```<code>fun main(args: Array<String>) {

    val (two, three) = nextTwo(1) // Unresolved reference: nextTwo
    println("1, $two, $three")

    fun nextTwo(num: Int) : Pair<Int, Int> {
        return Pair(num+1, num+10)
    }

}
</code>```

Picture of the error.

答:
Local functions can only be used in their local scope after their definition.

You can either move the nextTwo function out of the main function, like this (in this case, it doesn't matter whether it's before or after main):

```<code>fun nextTwo(...) {}

fun main(args: Array<String>) {
    nextTwo(...)
}
</code>```

Or you can just move it before its usages inside main:

```<code>fun main(args: Array<String>) {
    fun nextTwo(...) {}

    nextTwo(...)
}
</code>```

Body:
I am just a beginner in programming, started learning Kotlin today. I am getting this error.

fun main(args: Array<String>) {

    val (two, three) = nextTwo(1) // Unresolved reference: nextTwo
    println("1, $two, $three")

    fun nextTwo(num: Int) : Pair<Int, Int> {
        return Pair(num+1, num+10)
    }

}

Picture of the error.

Body:
Local functions can only be used in their local scope after their definition.

You can either move the nextTwo function out of the main function, like this (in this case, it doesn't matter whether it's before or after main):

fun nextTwo(...) {}

fun main(args: Array<String>) {
    nextTwo(...)
}

Or you can just move it before its usages inside main:

fun main(args: Array<String>) {
    fun nextTwo(...) {}

    nextTwo(...)
}


问:
How to search for specific maven plugin
How can I find maven plugin ? e.g I am searching findbugs-maven-plugin in https://mvnrepository.com/ but this will search for dependencies:

```<code><dependency>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <version>3.0.4</version>
</dependency>
</code>```

I am searching for:

```<code> <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>3.0.5-SNAPSHOT</version>
      </plugin>
    </plugins>
</code>```

答:
I think you just forgot to setup maven plugin repositories (or maybe you forgot to mention about it)

For example:

```<code>  <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <url>https://repo1.maven.org/maven2</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </pluginRepository>
  </pluginRepositories>
</code>```

also you could read little bit more about maven pom format on official site

Title: How to search for specific maven plugin

Body:
How can I find maven plugin ? e.g I am searching findbugs-maven-plugin in https://mvnrepository.com/ but this will search for dependencies:

<dependency>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <version>3.0.4</version>
</dependency>

I am searching for:

 <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>3.0.5-SNAPSHOT</version>
      </plugin>
    </plugins>

Body:
I think you just forgot to setup maven plugin repositories (or maybe you forgot to mention about it)

For example:

  <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <url>https://repo1.maven.org/maven2</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </pluginRepository>
  </pluginRepositories>

also you could read little bit more about maven pom format on official site


问:
How are dependencies managed when developing a python package to be distributed on PyPI?
I have a python package whose source looks like this

```<code>├── MANIFEST.in
├── README.rst
├── setup.cfg
├── setup.py
└── sqlemon
    ├── connection_strings.py
    └── __init__.py
</code>```

Most of the code is in __init__.py, which has the following imports:

```<code>import os
import sqlemon.connections_strings as sqlcs
import yaml  #This is the problem
</code>```

If we run

```<code>python setup.py sdist
</code>```

we see the following error

```<code>Traceback (most recent call last):
  File "setup.py", line 2, in <module>
    import sqlemon
  File "/home/danielsank/src/sqlemon/sqlemon/__init__.py", line 4, in <module>
    import yaml
ImportError: No module named yaml
</code>```

This suggests that the virtualenv in which I work on my project must have all of the project's dependencies installed in order to do development.
I guess that's not unreasonable, but I'm not entirely sure what the workflow should look like because the project's dependencies are listed in setup.py:

```<code>from distutils.core import setup
import sqlemon

version = sqlemon.__version__
project_name = sqlemon.__project_name__

setup(name=project_name,
      # Irrelevant lines removed
      install_requires=[
          'sqlalchemy',
          'alembic',
          'pyyaml',
          'sqlalchemy-schemadisplay'
          ],
)
</code>```

I usually put requirements in requirements.txt so the developer can do pip install -r requirements.txt, but since the requirements are already in setup.py that seems redundant.

Furthermore, after uploading my project to PyPI, when I try to pip install  from pypi, the installation fails unless I already have pyyaml installed in my virtualenv.
Obviously this is not the behavior we want; pyyaml should install automatically as it is listed in the install_requires list in setup.py.

What is the recommended workflow for this situation?

答:
The problem is that setup.py imports sqlemon which imports pyyaml (and in principle any other dependencies) so it's impossible to process it without having those dependencies installed.
The reason I had setup.py importing sqlemon was to get the version number.
A better strategy for the version numbers is explained here, which allows us to not import our own project in setup.py.

Body:
I have a python package whose source looks like this

├── MANIFEST.in
├── README.rst
├── setup.cfg
├── setup.py
└── sqlemon
    ├── connection_strings.py
    └── __init__.py

Most of the code is in __init__.py, which has the following imports:

import os
import sqlemon.connections_strings as sqlcs
import yaml  #This is the problem

If we run

python setup.py sdist

we see the following error

Traceback (most recent call last):
  File "setup.py", line 2, in <module>
    import sqlemon
  File "/home/danielsank/src/sqlemon/sqlemon/__init__.py", line 4, in <module>
    import yaml
ImportError: No module named yaml

This suggests that the virtualenv in which I work on my project must have all of the project's dependencies installed in order to do development.
I guess that's not unreasonable, but I'm not entirely sure what the workflow should look like because the project's dependencies are listed in setup.py:

from distutils.core import setup
import sqlemon

version = sqlemon.__version__
project_name = sqlemon.__project_name__

setup(name=project_name,
      # Irrelevant lines removed
      install_requires=[
          'sqlalchemy',
          'alembic',
          'pyyaml',
          'sqlalchemy-schemadisplay'
          ],
)

I usually put requirements in requirements.txt so the developer can do pip install -r requirements.txt, but since the requirements are already in setup.py that seems redundant.

Furthermore, after uploading my project to PyPI, when I try to pip install  from pypi, the installation fails unless I already have pyyaml installed in my virtualenv.
Obviously this is not the behavior we want; pyyaml should install automatically as it is listed in the install_requires list in setup.py.

What is the recommended workflow for this situation?


问:
Getting encoding error while writing data to csv file
```<code>from tweetpy import *
import re
import json
from pprint import pprint
import csv

# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream

# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN =  ''
ACCESS_SECRET = ''
CONSUMER_KEY = ''
CONSUMER_SECRET = ''

oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)

# Initiate the connection to Twitter Streaming API
twitter_stream = TwitterStream(auth=oauth)

# Get a sample of the public data following through Twitter
iterator = twitter_stream.statuses.filter(track="#kindle",language="en",replies="all")
 # Print each tweet in the stream to the screen

 # Here we set it to stop after getting 10000000 tweets.
 # You don't have to set it to stop, but can continue running
 # the Twitter API to collect data for days or even longer.

tweet_count = 10000000

file = "C:\\Users\\WELCOME\\Desktop\\twitterfeeds.csv"
with open(file,"w") as csvfile:
    fieldnames=['Username','Tweet','Timezone','Timestamp','Location']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for tweet in iterator:
        #pprint(tweet)
        username = str(tweet['user']['screen_name'])
        tweet_text = str(tweet['text'])
        user_timezone = str(tweet['user']['time_zone'])
        tweet_timestamp=str(tweet['created_at'])
        user_location = str(tweet['user']['location'])
        print tweet
        tweet_count -= 1
        writer.writerow({'Username':username,'Tweet':tweet_text,'Timezone':user_timezone,'Location':user_location,'Timestamp':tweet_timestamp})

        if tweet_count <= 0:
            break
</code>```

I am trying to write tweets to to csv file with columns 'username', 'Tweet', 'Timezone', 'Location', and 'Timestamp'.

But I am getting the following error:

tweet_text = str(tweet['text'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 139: ordinal not in range(128).
```

I know it is encoding issue but I dont know the exact position of the variable to encode.

答:
Use Python 3, because the Python 2 csv module doesn't do encodings well.

Use open with the encoding and newline options.

Remove str conversion (In Python 3 str is Unicode strings already.

Result:

```<code>with open(file,"w",encoding='utf8',newline='') as csvfile:
    fieldnames=['Username','Tweet','Timezone','Timestamp','Location']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for tweet in iterator:
        username = tweet['user']['screen_name']
        tweet_text = tweet['text']
        user_timezone = tweet['user']['time_zone']
        tweet_timestamp = tweet['created_at']
        user_location = tweet['user']['location']
            .
            .
            .
</code>```

If using Python 2, get the 3rd party unicodecsv module to overcome csv shortcomings.

Body:
from tweetpy import *
import re
import json
from pprint import pprint
import csv

# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream

# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN =  ''
ACCESS_SECRET = ''
CONSUMER_KEY = ''
CONSUMER_SECRET = ''

oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)

# Initiate the connection to Twitter Streaming API
twitter_stream = TwitterStream(auth=oauth)

# Get a sample of the public data following through Twitter
iterator = twitter_stream.statuses.filter(track="#kindle",language="en",replies="all")
 # Print each tweet in the stream to the screen

 # Here we set it to stop after getting 10000000 tweets.
 # You don't have to set it to stop, but can continue running
 # the Twitter API to collect data for days or even longer.

tweet_count = 10000000

file = "C:\\Users\\WELCOME\\Desktop\\twitterfeeds.csv"
with open(file,"w") as csvfile:
    fieldnames=['Username','Tweet','Timezone','Timestamp','Location']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for tweet in iterator:
        #pprint(tweet)
        username = str(tweet['user']['screen_name'])
        tweet_text = str(tweet['text'])
        user_timezone = str(tweet['user']['time_zone'])
        tweet_timestamp=str(tweet['created_at'])
        user_location = str(tweet['user']['location'])
        print tweet
        tweet_count -= 1
        writer.writerow({'Username':username,'Tweet':tweet_text,'Timezone':user_timezone,'Location':user_location,'Timestamp':tweet_timestamp})

        if tweet_count <= 0:
            break

I am trying to write tweets to to csv file with columns 'username', 'Tweet', 'Timezone', 'Location', and 'Timestamp'.

But I am getting the following error:

tweet_text = str(tweet['text'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 139: ordinal not in range(128).

I know it is encoding issue but I dont know the exact position of the variable to encode.

Body:
Use Python 3, because the Python 2 csv module doesn't do encodings well.

Use open with the encoding and newline options.

Remove str conversion (In Python 3 str is Unicode strings already.

Result:

with open(file,"w",encoding='utf8',newline='') as csvfile:
    fieldnames=['Username','Tweet','Timezone','Timestamp','Location']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for tweet in iterator:
        username = tweet['user']['screen_name']
        tweet_text = tweet['text']
        user_timezone = tweet['user']['time_zone']
        tweet_timestamp = tweet['created_at']
        user_location = tweet['user']['location']
            .
            .
            .

If using Python 2, get the 3rd party unicodecsv module to overcome csv shortcomings.


问:
How to pass array as url parameter to Azure Function
Having a bit of problem with Azure Functions parameters
I understood that url parameters are sent as usual to Azure Function "www.asdf.com?myParam=arnold" and being read like this

```<code>req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "myParam", true) == 0).Value
</code>```

What i don't understant is how to send array as a parameter.

答:
One way would be to send parameters like this:

```<code>www.asdf.com?myParam=arnold&myParam=james&myParam=william
</code>```

and then read them as

```<code>var params = req
    .GetQueryNameValuePairs()
    .Where(q => string.Compare(q.Key, "myParam", true) == 0)
    .Select(q => q.Value);
</code>```

Body:
Having a bit of problem with Azure Functions parameters
I understood that url parameters are sent as usual to Azure Function "www.asdf.com?myParam=arnold" and being read like this

req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "myParam", true) == 0).Value

What i don't understant is how to send array as a parameter.

Body:
One way would be to send parameters like this:

www.asdf.com?myParam=arnold&myParam=james&myParam=william

and then read them as

var params = req
    .GetQueryNameValuePairs()
    .Where(q => string.Compare(q.Key, "myParam", true) == 0)
    .Select(q => q.Value);


问:
How do I align something in a  in the top-left corner - without aligning everything?
Say I have something that looks like this: http://jsfiddle.net/Dtsjh/

How do I align the numbers in each cell to be in the top-left corner of each cell - without aligning the words?

Preferably in just HTML/CSS - but if you can't do it any of those, then jQuery is fine.

答:
In the TD tag you can use the align="left".  Inside of the style attribute you can also try and add a horizontal alignment or text-alignment:left.   Try to add a div, and a span inside a div for some more complex alignment with the style attribute  style="text-align:left;".

see link: link text

Title: How do I align something in a <td> in the top-left corner - without aligning everything?


问:
Is there a way to delete call logs and SMS programmatically in iOS?
I want the ability for a user to specify a time-frame and delete all call logs and sms created during that time-frame. Does Apple allow this functionality?

I know this is like accessing the sandbox mode of a private app but just want to confirm if there is a way.

答:
Sadly, There is no way to access the SMS or Call Logs.

Apple encourages third party apps to be developed to carry unique functions. Not the ones that are already available from First party which is apple itself.

Call log and sms are synced to iCloud. So i guess even if you figure out a way to access them using some private api, you might not be able to update them. so apparently they will be resynched.


问:
check if string contains only unique chars using .at(int)
Really basic question but I can't figure this out.  My program checks if a string is unique by setting flags for each ASCII in an array to true if found in the string.  It's not working(it compiles, but doesn't give correct answer), and I can't for the life of my figure out why.

The output I get is 0:

main.cpp

```<code>#include "main.hpp"
#include <iostream>

bool isUnique(std::string str) {

    if(str.length() > 128)
        return false;

    bool theChars[128];

    for(int i = 0; i < str.length(); i++) {
        int loc = str.at(i);

        if(theChars[loc])
            return false;
        else
            theChars[loc] = true;
    }

    return true;
}

int main() {

    std::string timmy = "abcdefghijklmnop";
    std::cout << isUnique(timmy);

    return 0;
}
</code>```

答:
```<code>std::sort(str.begin(), str.end());
return std::adjacent_find(str.begin(), str.end()) == str.end();
</code>```

This doesn't use any additional space, and works for any character encoding.

Body:
Really basic question but I can't figure this out.  My program checks if a string is unique by setting flags for each ASCII in an array to true if found in the string.  It's not working(it compiles, but doesn't give correct answer), and I can't for the life of my figure out why.

The output I get is 0:

main.cpp

#include "main.hpp"
#include <iostream>

bool isUnique(std::string str) {

    if(str.length() > 128)
        return false;

    bool theChars[128];

    for(int i = 0; i < str.length(); i++) {
        int loc = str.at(i);

        if(theChars[loc])
            return false;
        else
            theChars[loc] = true;
    }

    return true;
}

int main() {

    std::string timmy = "abcdefghijklmnop";
    std::cout << isUnique(timmy);

    return 0;
}

Body:
std::sort(str.begin(), str.end());
return std::adjacent_find(str.begin(), str.end()) == str.end();

This doesn't use any additional space, and works for any character encoding.


问:
JQuery / Javascript add dates to select but exclude Sundays
I would like to add 5 dates to a select but exclude Sundays.  If a date lands on a sunday show the date for the next day.

This is what I am trying so far:

```<code>var startDate = "6-JUN-2017";
    startDate = new Date(startDate.replace(/-/g, "/"));
    var Dates = "",  noOfDaysToAdd = 5, count = 0;
    while (count < noOfDaysToAdd) {
        Dates = new Date(startDate.setDate(startDate.getDate() + 1));
        if (Dates.getDay() != 0 && Dates.getDay() != 7) {
            //    count++;
            var Day = $('<option value="' + Dates.getDay() + '">' + Dates.getDay() + '</option>');
            $('select').append(Day);
        }

    }
</code>```

But this crashes my browser. Any help would be appreciated please.

答:
Your code nearly works. However, you need to increase count, if youre not doing so you'll have an infinite loop. And as youve said, you want to increase the Day if the Day is Sunday:

```<code>while (count < noOfDaysToAdd) {
    startDate.setDate(startDate.getDate() + 1);
    if (startDate.getDay() === 0) {
     //if sunday take next day
     startDate.setDate(startDate.getDate()+1);
    }
   //always add:
    var Day = $('<option value="' + startDate.getDay() + '">' + startDate.getDay() + '</option>');
    $('select').append(Day);
 count++;//no crashing
}
</code>```

Also theres no need to clone startDate...

Body:
I would like to add 5 dates to a select but exclude Sundays.  If a date lands on a sunday show the date for the next day.

This is what I am trying so far:

var startDate = "6-JUN-2017";
    startDate = new Date(startDate.replace(/-/g, "/"));
    var Dates = "",  noOfDaysToAdd = 5, count = 0;
    while (count < noOfDaysToAdd) {
        Dates = new Date(startDate.setDate(startDate.getDate() + 1));
        if (Dates.getDay() != 0 && Dates.getDay() != 7) {
            //    count++;
            var Day = $('<option value="' + Dates.getDay() + '">' + Dates.getDay() + '</option>');
            $('select').append(Day);
        }

    }

But this crashes my browser. Any help would be appreciated please.

Body:
Your code nearly works. However, you need to increase count, if youre not doing so you'll have an infinite loop. And as youve said, you want to increase the Day if the Day is Sunday:

while (count < noOfDaysToAdd) {
    startDate.setDate(startDate.getDate() + 1);
    if (startDate.getDay() === 0) {
     //if sunday take next day
     startDate.setDate(startDate.getDate()+1);
    }
   //always add:
    var Day = $('<option value="' + startDate.getDay() + '">' + startDate.getDay() + '</option>');
    $('select').append(Day);
 count++;//no crashing
}

Also theres no need to clone startDate...


问:
List of most occurrences of element
I have a list let's say {1,1,2,2,3,3,3,4,4,4}. I want to find a List of the elements that occur the most often (it has to be a list as there can be a situation like here that 3 and 4 occur most and I need to get that information. How can I achieve this using LINQ?</p>

答:
```<code>var highCountItems = source
  .GroupBy(item => item)
  .GroupBy(g => g.Count(), g => g.Key)
  .OrderByDescending(counts => counts.Key)
  .First();

int theCount = highCountItems.Key;
var theItems = highCountItems.ToList();
</code>```

Title: List of most occurrences of element


问:
Nodemailer using gmail, Cannot create property 'mailer' on string 'SMTP'
I am trying to send the data from the form I created to my gmail account, when clicking the sumbit button I always get the same error.
I found a lot of issues about nodemailer, but none of them seem to be the same issue as I am experiencing.

Ofcourse I have stated my clientId but just deleted for this post.

```<code>TypeError: Cannot create property 'mailer' on string 'SMTP'
at Mail (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\nodemailer\lib\mailer\index.js:45:33)
   at Object.module.exports.createTransport (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\nodemailer\lib\nodemailer.js:46:14)
   at C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\src\app.js:39:26
   at Layer.handle [as handle_request] (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\layer.js:95:5)
   at next (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\layer.js:95:5)
   at C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:277:22
   at Function.process_params (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:330:12)
   at next (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:271:10)
   at serveStatic (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\node_modules\serve-static\index.js:75:16)
   at Layer.handle [as handle_request] (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\layer.js:95:5)
   at trim_prefix (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:312:13)
   at C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:280:7
   at Function.process_params (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:330:12)
   at next (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:271:10)
</code>```

this is my app.js:

```<code>// require modules
const express = require('express');
const app = express();
const pug = require('pug');
const fs = require('fs')
const bodyParser = require('body-parser');
const pg = require('pg');
const nodemailer = require('nodemailer');
const xoauth2 = require('xoauth2');

//set view engine and views
app.set('views', 'src/views');
app.set('view engine', 'pug');

app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('./resources/'));

//display index page
app.get('/', function ( req, res ){
  console.log('Index is displayed on localhost');
    res.render('index');
});

app.post('/zorginstelling/ziekenhuis-olvg-locatie-west-voorheen-sint-lucas-andreas-ziekenhuis-amsterdam-109428/waardeer', function (req, res) {
  var mailOpts, smtpTrans;
  console.log('form word gepost')
  //Setup Nodemailer transport, I chose gmail.
  smtpTrans = nodemailer.createTransport('SMTP', {
      service: 'Gmail',
      auth: {
        xoauth2: xoauth2.createXOAuth2Generator({
            user: 'kylevantil14@gmail.com',
            clientId: '-' ,
            clientSecret: '-' ,
            refreshToken: '-'
        })
       }
  });

   //Mail options
  mailOpts = {
      from: req.body.rating[name] + ' <' + req.body.rating[email][first] + '>',
      to: 'kylevantil14@gmail.com',
      subject: 'Test',
      text: req.body.rating[comment] + req.body.rating[questions][behandeling] + req.body.rating[name]
  };

    smtpTrans.sendMail(mailOpts, function (error, response) {
      //Email not sent
      if (error) {
          console.log('There was a problem')
      }
      //Yay!! Email sent
      else {
          console.log('Email sent!')
      }
  });
});

var server = app.listen(4000, function () {
        console.log('Example app listening on port: ' + server.address().port);
    });
</code>```

答:
The current problem Today for help is the change of information faster, and Alexander was good when he said "nodemailer is reworked";

i use this easy line to define the transporter:

```<code>    var smtpTransport = nodemailer.createTransport("smtps://youruser%40gmail.com:"+encodeURIComponent('yourpass#123') + "@smtp.gmail.com:465");
</code>```

i got it from here https://community.nodemailer.com/

Body:
I am trying to send the data from the form I created to my gmail account, when clicking the sumbit button I always get the same error.
I found a lot of issues about nodemailer, but none of them seem to be the same issue as I am experiencing.

Ofcourse I have stated my clientId but just deleted for this post.

TypeError: Cannot create property 'mailer' on string 'SMTP'
at Mail (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\nodemailer\lib\mailer\index.js:45:33)
   at Object.module.exports.createTransport (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\nodemailer\lib\nodemailer.js:46:14)
   at C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\src\app.js:39:26
   at Layer.handle [as handle_request] (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\layer.js:95:5)
   at next (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\layer.js:95:5)
   at C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:277:22
   at Function.process_params (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:330:12)
   at next (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:271:10)
   at serveStatic (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\node_modules\serve-static\index.js:75:16)
   at Layer.handle [as handle_request] (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\layer.js:95:5)
   at trim_prefix (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:312:13)
   at C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:280:7
   at Function.process_params (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:330:12)
   at next (C:\Users\snowr\Documents\dev\zorgkaartnl\zorgkaartnl\node_modules\express\lib\router\index.js:271:10)

this is my app.js:

// require modules
const express = require('express');
const app = express();
const pug = require('pug');
const fs = require('fs')
const bodyParser = require('body-parser');
const pg = require('pg');
const nodemailer = require('nodemailer');
const xoauth2 = require('xoauth2');

//set view engine and views
app.set('views', 'src/views');
app.set('view engine', 'pug');

app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('./resources/'));

//display index page
app.get('/', function ( req, res ){
  console.log('Index is displayed on localhost');
    res.render('index');
});

app.post('/zorginstelling/ziekenhuis-olvg-locatie-west-voorheen-sint-lucas-andreas-ziekenhuis-amsterdam-109428/waardeer', function (req, res) {
  var mailOpts, smtpTrans;
  console.log('form word gepost')
  //Setup Nodemailer transport, I chose gmail.
  smtpTrans = nodemailer.createTransport('SMTP', {
      service: 'Gmail',
      auth: {
        xoauth2: xoauth2.createXOAuth2Generator({
            user: 'kylevantil14@gmail.com',
            clientId: '-' ,
            clientSecret: '-' ,
            refreshToken: '-'
        })
       }
  });

   //Mail options
  mailOpts = {
      from: req.body.rating[name] + ' <' + req.body.rating[email][first] + '>',
      to: 'kylevantil14@gmail.com',
      subject: 'Test',
      text: req.body.rating[comment] + req.body.rating[questions][behandeling] + req.body.rating[name]
  };

    smtpTrans.sendMail(mailOpts, function (error, response) {
      //Email not sent
      if (error) {
          console.log('There was a problem')
      }
      //Yay!! Email sent
      else {
          console.log('Email sent!')
      }
  });
});

var server = app.listen(4000, function () {
        console.log('Example app listening on port: ' + server.address().port);
    });

Body:
The current problem Today for help is the change of information faster, and Alexander was good when he said "nodemailer is reworked";

i use this easy line to define the transporter:

    var smtpTransport = nodemailer.createTransport("smtps://youruser%40gmail.com:"+encodeURIComponent('yourpass#123') + "@smtp.gmail.com:465");

i got it from here https://community.nodemailer.com/


问:
How can I get the author of each post in the query?
Here is my current query:

```<code>SELECT id,
       subject,
       category cat,
       keywords tags,
       body_html, amount,
       date_time,
       (SELECT COALESCE(sum(vv.value),0)
          FROM votes vv
          WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
       (SELECT COALESCE(sum(vt.total_viewed),0)
          FROM viewed_total vt
          WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
FROM qanda WHERE type = 0 $query_where
ORDER BY $query_order
LIMIT :j,11;
</code>```

It provides a list (maximum 10 cases) of posts. Now I need to also get the author's name of each post. How can I do that?

My tables structure look like this:

```<code>// users
+----+--------+-----------------+--------
| id |  name  |      email      |  ....
+----+--------+-----------------+--------

// qanda
+----+------------+-----------------------+-----------+--------
| id |    title   |          body         | author_id |  ....
+----+------------+-----------------------+-----------+--------
-- author_id refers to the id column of users table
</code>```

I can add one more sub query to get author's name for each post. But I think using join would be better.

答:
could be you need  a inner join woth users

```<code>  SELECT a.id,
         a.subject,
         a.category cat,
         a.keywords tags,
         a.body_html,
         a.amount,
         a.date_time,
         u.name
         (SELECT COALESCE(sum(vv.value),0)
            FROM votes vv
            WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
         (SELECT COALESCE(sum(vt.total_viewed),0)
            FROM viewed_total vt
            WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
  FROM qanda a
  INNER JOIN users u on a.id = u.author_id
  WHERE type = 0 $query_where
  ORDER BY $query_order
  LIMIT :j,11;
</code>```

and if some post have not author you must use left join

```<code>    SELECT a.id,
         a.subject,
         a.category cat,
         a.keywords tags,
         a.body_html,
         a.amount,
         a.date_time,
         u.name
         (SELECT COALESCE(sum(vv.value),0)
            FROM votes vv
            WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
         (SELECT COALESCE(sum(vt.total_viewed),0)
            FROM viewed_total vt
            WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
  FROM qanda a
  LEFT JOIN users u on a.id = u.author_id
  WHERE type = 0 $query_where
  ORDER BY $query_order
  LIMIT :j,11;
</code>```

Body:
Here is my current query:

SELECT id,
       subject,
       category cat,
       keywords tags,
       body_html, amount,
       date_time,
       (SELECT COALESCE(sum(vv.value),0)
          FROM votes vv
          WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
       (SELECT COALESCE(sum(vt.total_viewed),0)
          FROM viewed_total vt
          WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
FROM qanda WHERE type = 0 $query_where
ORDER BY $query_order
LIMIT :j,11;

It provides a list (maximum 10 cases) of posts. Now I need to also get the author's name of each post. How can I do that?

My tables structure look like this:

// users
+----+--------+-----------------+--------
| id |  name  |      email      |  ....
+----+--------+-----------------+--------

// qanda
+----+------------+-----------------------+-----------+--------
| id |    title   |          body         | author_id |  ....
+----+------------+-----------------------+-----------+--------
-- author_id refers to the id column of users table

I can add one more sub query to get author's name for each post. But I think using join would be better.

Body:
could be you need  a inner join woth users

  SELECT a.id,
         a.subject,
         a.category cat,
         a.keywords tags,
         a.body_html,
         a.amount,
         a.date_time,
         u.name
         (SELECT COALESCE(sum(vv.value),0)
            FROM votes vv
            WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
         (SELECT COALESCE(sum(vt.total_viewed),0)
            FROM viewed_total vt
            WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
  FROM qanda a
  INNER JOIN users u on a.id = u.author_id
  WHERE type = 0 $query_where
  ORDER BY $query_order
  LIMIT :j,11;

and if some post have not author you must use left join

    SELECT a.id,
         a.subject,
         a.category cat,
         a.keywords tags,
         a.body_html,
         a.amount,
         a.date_time,
         u.name
         (SELECT COALESCE(sum(vv.value),0)
            FROM votes vv
            WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
         (SELECT COALESCE(sum(vt.total_viewed),0)
            FROM viewed_total vt
            WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
  FROM qanda a
  LEFT JOIN users u on a.id = u.author_id
  WHERE type = 0 $query_where
  ORDER BY $query_order
  LIMIT :j,11;


问:
Is SAJAX dead? What to replace with?
We use Sajax for adding small Ajax code to sites.  After running into a problem and doing some digging, it seems the library hasn't been updated since 2005.

I've appreciated Sajax for being lightweight, easy to use, and easy to install (just include the file in PHP).

So, on the LAMP stack, if you  have used Sajax before, what would you upgrade to?  Ease of use is key since some semi-programmer web developers use the code too.

I know a lot of people would say jQuery, but is that as simple as Sajax?

答: There is also my branch over at http://sajax.info/ it mainly just fixes the outstanding issues with 0.12 and focuses on speeding sajax up even more.</p>

OwnerDisplayName: tkotitan

Title: Is SAJAX dead? What to replace with?


问:
Filter list of strings starting with specific keyword
How can I find a string (PartialWord) inside a List (WordList) in Python 2.7?

```<code>PartialWord = "ab"
WordList = ['absail', 'rehab', 'dolphin']
</code>```

A search with a wildcard like: ab*

Where it would ONLY find the word, if it starts with those letters (i.e. the result should only give absail, but not rehab, despite both having 'ab').

The WordList would be a dictionary, which is over 700KB.

答: As everybody mentioned before, str.startswith is your function. You can study regex patterns for more complex operations. regex

Body:
How can I find a string (PartialWord) inside a List (WordList) in Python 2.7?

PartialWord = "ab"
WordList = ['absail', 'rehab', 'dolphin']

A search with a wildcard like: ab*

Where it would ONLY find the word, if it starts with those letters (i.e. the result should only give absail, but not rehab, despite both having 'ab').

The WordList would be a dictionary, which is over 700KB.