text:
Q: Auto replace number from a string in perl I have a file test.xml, something like this:
<manifest XML:android="http://schemas.android.com/apk/res/android"

package="com.connect"

android:versionCode="32"

android:versionName="9.3.0.114" >

I want to used script to open file test.xml.
Then find string android:versionName="9.3.0.114" > to update automatic become android:versionName="9.3.0.115" >
So the last number start 100 to 999 will  +1 dy by day.
I tried something like below but not correctly
#!/usr/bin/perl
my $test= "test.xml";
open my $fh,"<", "$test" or die $!;

while (my $srt = <$fh>) {
$str = "android:versionName=\"9.3.0.114\" >";
$str =~s/((?:[^\=]*)=\"(?:[^"]*)\.)(\d+)\"/my $ret = "$1".($2+1)."\""; ($ret);/ge;
print $srt;
}
close($fh);

Please help me.

A: Please - don't use regular expressions to hack XML. It's brittle. XML is contextual, and regular expressions are not.
But this is surprisingly easy using a real parser:
#!/usr/bin/env perl
use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig -> new -> parsefile ( 'test.xml')

foreach my $manifest ( $twig -> findnodes ( '//manifest' ) ) {
    my @version = split /\./, $manifest->att('android:versionName');
    $version[-1]++;   #or whatever mechanism you want to use to update
    $manifest -> set_att('android:versionName', join ".", @version );
}

$twig -> set_pretty_print('indented_a');
$twig -> print;

open ( my $output, '>', 'test_new.xml') or die $!;
print {$output} $twig -> sprint;

A: Just a simple regex makes fine (I have updated your code here):
#!/usr/bin/perl
use Tie::File;

my $infile = 'test.xml';
my @lines;

tie(@lines, 'Tie::File', $infile) or die("can't open $infile: $!");

$srt = join "\n", @lines;
$srt=~s/(android\:versionName=\"(?:[^"]*)\.)(\d+)\"/my $ret = "$1".($2+1)."\""; ($ret);/ge;

@lines = split /\n/, $srt;

untie @lines;

Input test.xml:
<manifest XML:android="http://schemas.android.com/apk/res/android"
package="com.connect"
android:versionCode="32"
android:versionName="9.3.0.114">

<manifest XML:android="http://schemas.android.com/apk/res/android"
package="com.connect"
android:versionCode="32"
android:versionName="9.3.0.200">

Output:
<manifest XML:android="http://schemas.android.com/apk/res/android"
package="com.connect"
android:versionCode="32"
android:versionName="9.3.0.115">

<manifest XML:android="http://schemas.android.com/apk/res/android"
package="com.connect"
android:versionCode="32"
android:versionName="9.3.0.201">

However if you are using fully XML based process so then you will try XML::Twig as better output.


text:
Q: Nilpotent matrices and inverses Can somebody give me a hint for showing that:
The matrix $A+I$ is invertible if there is an integer $k\gt 0$ so that $A^k=0$.

A: Hint
$$(1+x)\sum_{p=0}^\infty(-1)^p x^p=1$$

A: Consider the formula for summing the finite geometric series $$I+(-A)+(-A)^2+\cdots+(-A)^{k-1}$$
(since everything commutes, the basic algebraic manipulations involved here are valid). The formula requires dividing by $I-(-A)=I+A$, which is precisely what you are trying to justify here; as a consequence this does not give you a proof, just an idea. However the proof of the geometric series formula is by multiplying out the denominator, and that can be validly done here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: call an array method I have this method, and I am trying to call that method doing [self getUsers ObjectAtIndex:0] but compiler won't compile that line at all and says it's unknown. How do I call an array method to display all the string in it?
- (NSArray*)getUsers

{
NSArray *getUsers = [[NSArray alloc] init];
NSString *databasepath;

NSString *docsDir;
NSArray *dirPaths;
//NSString *databasePath;

//get the document directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];

//build the path to the database file
databasepath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:
                                                  @"users.db"]];

const char *dbPath = [databasepath UTF8String];
sqlite3_stmt *statement;
sqlite3 *userdb;

if (sqlite3_open(dbPath, &userdb) == SQLITE_OK)
{
    NSString *querySQL = [NSString stringWithFormat:@"SELECT * FROM USERS WHERE username = \"%@\"", txtUsername.text];
    const char *sql_stmt = [querySQL UTF8String];
    if (sqlite3_prepare_v2(userdb, sql_stmt, -1, &statement, NULL) == SQLITE_OK)
    {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            char *field = (char*) sqlite3_column_text(statement, 1);
            NSString *usernameField = [[NSString alloc]initWithUTF8String:field];
            //NSLog(@"%@", usernameField);
            getUsers = [NSArray arrayWithObject:usernameField];

        }

    }
    sqlite3_finalize(statement);
}

sqlite3_close(userdb);

return getUsers;

}

A: Use [[self getUsers] objectAtIndex:0].
If you use the latest Xcode/clang version, you can also use [self getUsers][0], since arrays now support indexing.

A: Consider say you had a method -(id)someMethod, and then called it like this:
id myValue = [self someMethod];

Inside someMethod, there is a return statement - whatever is to the right of the return is what will be assigned to myValue in the calling method or function.
Just call like this:
NSArray *arrAllUsers = [self getUsers]; //As getUsers is method which returns nsarray.


text:
Q: How to get the browser to save the password even though it's not sending it to server The situation :
For security reasons, I never send the clear password to my server.
It is sha1ed client side and only the hash is sent to the server.
edit : This is only part of my security (I use also SSL, serverside hash, synchronised salts, ...) Please dont make it a thread about security
To do that, I have 2 inputs, first one one is visible and named "password" and another one is hidden named "sha1password".
When the user click the "login" button, a JS code sha1s the "input#password", put it into "input#sha1passord" and empties the "input#password" before sending a POST to the server.
This last step is to prevent the browser from saving the sha1 password. Because if you do that, the form will be filled with a 50 caracters password and the user would be annoyed.
The problem :
This works well but the browser dont save the passord as "input#password" is empty when sending the POST. Is there a way to allow the browser to save the password without sending it to the server ?

A: Things to remember

*

*Chrome dont save password if there is many password input

*Chrome check for many passwords is called after the page is loaded (even after jquery $(function(){}) initialisation )

*To add another password input, just user a setTimeout function after 100 ms

My solution
Hi, I finally found how browsers works.
They don't like forms with many input type=password.
I renamed #sha1password to #password. In the first HTML page, there must me no other password input so I only echo the #password input ! This way, after loading the page, the browser sees a simple login form and enables the autocomplete feature (except IE but this one is stupid and I dont care with it... How microsoft people can always develop different softwares ?).
After page initialisation + 100ms timeout, I add a new input type=password called #clearPassword. I then copy the autocompleted value which is in the #password input. Then I hide the #password input using a width+height to 0px (display none make it unsent to the server).
When the user types a password in the #clearPassword input, I empty the #password input box. This will make the new typed password hashed, other wise #clearPassword stays with a hashed value.
When the user clicks LOGIN, only if the #password box is empty I sha1 the #clearPassword input and out the value in #clearPassword. If the #password is not empty, it is the autocompleted hashed value, this is OK.
And most important thing, before sending the form to the server, I detach the $clearPassword to prevent chrome from sending it to the server.
And you're done ;) chrome stores only a hash of the clear password


text:
Q: SQL Injection, Quotes and PHP I'm quite confused now and would like to know, if you could clear things up for me.
After the lateste Anon/Lulsec attacks, i was questioning my php/mysql security.
So, i thought, how could I protect both, PHP and Mysql.
Question: Could anyone explain me, what's best practice to handle PHP and Mysql when it comes to quotes?

*

*Especially in forms, I would need some kind of htmlspecialchars in order to protect the html, correct?

*Can PHP be exploitet at all with a form? Is there any kind of protection needed?

*Should I use real_escape_string just before a query? Would it be wrong/bad to use it already within PHP (see sanitize_post function)?

Currently i'm using the following function. The function "sanitizes" all $_POST and $_GET variables. Is this "safe"?
function sanitize_post($array) {
    global $db;
    if(is_array($array)) {
        foreach($array as $key=>$value) {
            if(is_array($array[$key])) {
                $array[$key] = sanitize_post($array[$key]);
            } elseif(is_string($array[$key])) {
                $array[$key] = $db->real_escape_string(strtr(stripslashes(trim($array[$key])), array("'" => '', '"' => '')));
            }
        }
    } elseif(is_string($array)) {
        $array = $db->real_escape_string(strtr(stripslashes(trim($array)), array("'" => '', '"' => '')));
    }
    return $array;
}

I'm using PHP 5.3.5 with Mysql 5.1.54.
Thanks.

A: mysql_real_escape_string deserves your attention.
However direct queries are a quagmire and no longer considered safe practice.  You should read up on PDO prepared statements and binding parameters which has a side benefit of quoting, escaping, etc. built-in.

A: BEST practice is always to use prepared statements. This makes SQL injection impossible. This is done with either PDO or mysqli. Forget about all the mysql_* functions. They are old and obsolete.

A:
Question: Could anyone explain me, what's best practice to handle PHP
  and Mysql when it comes to quotes?

That's easy: Use prepared statements, e. g. with PDO::prepare or mysqli_prepare.

A: Don't waste the effort using mysql_real_escape_string() or anything like that. Just use prepared statements with PDO and SQL injection is impossible.

A: There is nothing like "universal sanitization". Let's call it just quoting, because that's what its all about.
When quoting, you always quote text for some particular output, like:

*

*string value for mysql query

*like expression for mysql query

*html code

*json

*mysql regular expression

*php regular expression

For each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc are broken (always assure it is switched off!!!).
So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)

*

*mysql_real_escape_string($str)

*mysql_real_escape_string(addcslashes($str, "%_"))

*htmlspecialchars($str)

*json_encode() - only for utf8! I use my function for iso-8859-2

*mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}')) - you cannot use preg_quote in this case because backslash would be escaped two times!

*preg_quote()

A: I usually use the PHP functions stripslashes and strip_tags on the variables as they come in via $_POST (or $_GET, depending on what you use) and mysql_real_escape_string during the query. (I'm not sure if this is "right" but it's worked for me so far.) You can also use PHP's built in validate filters to check things like email addresses, url's, data types, etc. PDO is supposedly decent at preventing SQL injection but I haven't had any experience with it yet.

A: The basic workflow should be
$data = $_POST['somefield which will go into the database'];

... do data validation ...

if (everything ok) {
    $escaped_data = escape_function($data);
    $sql = " ... query here with $escaped_data ... ";
    do_query($sql);
}

Basically, data that's been escaped for database insertion should ONLY be used for database insertion. There's no point in pre-processing everything and overwriting all data with db-escaped values, when only 2 or 3 of 50(say) values actually go anywhere near the db.
Ditto for htmlspecialchars. Don't send data through htmlspecialchars unless it's headed for an HTML-type display.
Don't store data in the DB formatted for one particular purpose, because if you ever need the data in a different form for some other purpose, you have to undo the escaping. Always store raw/unformatted data in the db. And note: the escaping done with mysql_real_escape_string() and company does not actually get stored in the db. It's there only to make sure the data gets into the database SAFELY. What's actually stored in the db is the raw unescaped/unquoted data. Once it's in the database, it's "safe".
e.g. consider the escaping functions as handcuffs on a prisoner being transferred. While the prisoner is inside either jail, cuffs are not needed.


text:
Q: Where to store string constants in my ASP.NET MVC app? Specifically, I have a phone number that is used in a bunch of views(and a couple actions), and I would like to centralize that somewhere in case it changes. Is web.config good enough? Is there a better place for this? Ideally, I wouldn't have to recompile if the value changed. Thanks!
Update: So far, I like the partial view the best, the main reason being no recompile, no adding it to viewmodels. Another option I've explored is Application_Start in global.asax and using the Application dictionary(although it sounds like the use of this dictionary is frowned upon in mvc). One thing to note is that I need to use this number in some actions also. Any more thoughts/opinions?

A: *

*Resx Files, resource: http://msdn.microsoft.com/en-us/library/ekyft91f(v=vs.90).aspx

*Config Files, resource: How to use .NET configuration files (app.config, settings.settings) to save and restore all application data?

*Class Files, resource: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769510(v=vs.105).aspx

*Settings Files, resource: http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx

*also if you would like to be able to update the settings without touching the database, it will be a great idea to save it in database or xml files. Then create an interface(web page) which communicates with that table and updates the settings. Create a repository which caches the settings every time app starts and invalidates the settings every time one gets updated.
For this case specifically, I would save it in class file. but the best solution depends on the project, later scale of it, and etc, etc.

A: In no uncertain terms do you want a view accessing your web.config file.
If this is something which shows up in many places in your views and requires a static set variable, then make a partial view to display the number, and call the partial view multiple times.
The advantage is that you are keeping it in a re-usable area so that if you change it once, it changes everywhere, and also that you are not going to have any separation of concern violations by having your view make calls where it shouldn't have access. Updating the partial will also not require a re-compile.
/Shared/_PhoneNumberPartial.cshtml
555-1234

Used in a view

Phone Number

 @Html.Partial("_PhoneNumberPartial")

A: You can add the phone number to appSetting key/value in web config like below:
<appSettings>
     <add key="PhoneNum" value="1234567890"/>
 </appSettings>

Then you can use it
using System.Configuration;
string Phone = ConfigurationManager.AppSettings["PhoneNum"].ToString();

A: For something like a phone number I'd put it in a data storage of some kind. If you don't need a full database consider something simple like a file based storage or even a simple *.json or *.xml file, preferably in the AppData folder. However if you do this you should be passing it to your view via a ViewModel and let your controller or some other method do the actual reading from your data storage. Views should not access these directly.
I find the web.config is best suited for configuration settings. It is a config file after all. It's not the best place to put content. Your phone number is content, and to me Content should be in a dynamic and structured location.


text:
Q: Create dynamic questionnaire from web service .NET i just want to know, which do you think would be the best aproach to do this. I am consuming a web service who gives me the questions, the posible anwsers and the correct anwser, and what i have to do is validate the anwsers from the user. But if i just create the form on the init event, in order to .net to see the created controls for validating i need to recreate the controls in postback, but i can't do that because the webservice would give me another questionnaire. Is it okay to store the questionnaire on a cache object and rebuild the controls from there? What do you think? Thanks in advance.

A: You can store the question and the answers in the viewstate or session.


text:
Q: Getting the Mouse Movement Direction with javascript Why this code is not working? What is the "e" parameter in the getMouseDirection function? What is the value of this e parameter?

var bodyElement = document.querySelector("body");
bodyElement.addEventListener("mousemove", getMouseDirection, false);

var xDirection = "";
var yDirection = "";

var oldX = 0;
var oldY = 0;

function getMouseDirection(e) {
    //deal with the horizontal case
    if (oldX < e.pageX) {
        xDirection = "right";
    } else {
        xDirection = "left";
    }

    //deal with the vertical case
    if (oldY < e.pageY) {
        yDirection = "down";
    } else {
        yDirection = "up";
    }

    oldX = e.pageX;
    oldY = e.pageY;

    console.log(xDirection + " " + yDirection);
}


text:
Q: Reconfiguring dual boot (Ubuntu and Windows) - Grub2 I have new Acer Nitro 5 which has both SSD and HDD disks in it, also it came with  Windows 10 pre-installed in SSD.
I have migrated the Windows OS to HDD, and installed Ubuntu 18 in SSD.
But while doing that I have messed up EFI partitions.
Now I one-one EFI partitions on both SSD and HDD each, and on boot menu (in BIOS settings), I have four options:

*

*ubuntu boot-loader (SSD)

*ubuntu boot-loader (HDD)

*Windows (SSD)

*Windows (HDD)

And Windows boot option from grub boot-loader does not work, for which I have to select Windows (HDD) option from BIOS settings.
How do I reconfigure my grub2 to correct this?


text:
Q: Twitter Data Mining: Degrees of separation What ready available algorithms could I use to data mine twitter to find out the degrees of separation between 2 people on twitter.
How does it change when the social graph keeps changing and updating constantly.
And then, is there any dump of twitter social graph data which I could use rather than making so many API calls to start over.

A: From the Twitter API
What's the Data Mining Feed and can I have access to it?
The Data Mining Feed is an expanded version of our /statuses/public_timeline REST API method. It returns 600 recent public statuses, cached for a minute at a time. You can request it up to once per minute to get a representative sample of the public statuses on Twitter. We offer this for free (and with no quality of service guarantees) to researchers and hobbyists. All we ask is that you provide a brief description of your research or project and the IP address(es) you'll be requesting the feed from; just fill out this form. Note that the Data Mining Feed is not intended to provide a contiguous stream of all public updates on Twitter; please see above for more information on the forthcoming "firehose" solution.
and also see: Streaming API Documentation

A: There was a company offering a dump of the social graph, but it was taken down and no longer available. As you already realized - it is kind of hard, as it is changing all the time.
I would recommend checking out their social_graph api methods as they give the most info with the least API calls.

A: There might be other ways of doing it but I've just spent the past 10 minutes looking at doing something similar and stumbled upon this Q.
I'd use an undirected (& weighted - as I want to look at location too) graph - use JgraphT or similar in py; JGraphT is java based but includes different prewritten algos.
You can then use an algorithm called BellmanFord; takes an integer input and searches the graph for the shortest path with the integer input, and only integer input, unlike Dijkstras.
http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
I used it recently in a project for flight routing, iterating up to find shortest path with shortest 'hops' (edges).


text:
Q: How do I create a link to another html page? I have a form on one page that I want to submit to another page.  I can't figure out how to create the link to that second page.
Project layout:
Fileserver/
    config.py
    requirements.txt
    run.py
    setup.py
    app/
        __init__.py
        static/
            css/
            img/
            js/
        templates/
            formAction.html
            formSubmit.html
            index.html

__init__.py:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    ip = request.remote_addr
    return render_template('index.html', user_ip=ip)

index.html:
<!DOCTYPE html>

Check Out This Form!

I can see the page at localhost:5000/ without issue.
I have also tried:

as well as:

What am I missing?

A: url_for generates urls to routes defined in your application.  There are no (or should probably not be any) raw html files being served, especially out of the templates folder.  Each template should be something rendered by Jinja.  Each location you want to display or post a form to should be handled and generated by a route on your application.
In this case, you probably want to have one route to both render the form on GET and handle the form submit on POST.
__init__.py:
from flask import Flask, request, url_for, redirect, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
    if request.method == 'POST':
        # do stuff when the form is submitted

        # redirect to end the POST handling
        # the redirect can be to the same route or somewhere else
        return redirect(url_for('index'))

    # show the form, it wasn't submitted
    return render_template('cool_form.html')

templates/index.html:
<!doctype html>

Check out this cool form!

templates/cool_form.html:
<!doctype html>

    <form method="post">
        <button type="submit">Do it!</button>
    </form>

I don't know what your forms and routes actually do, so this is just an example.

If you need to link static files, put them in the static folder, then use:
url_for('static', filename='a_picture.png')

A: So what I just found was that if I don't wrap the href in parenthesis it works and I also created a link to return back a page
@app.route('/blog')
def blog():
    return '
These are my thoughts on dogs
'

@app.route('/blog/2020/dogs')
def blog2():
    return '
these are my dogs home
'


text:
Q: While loop deletes all files and becomes stuck in loop I'm having trouble using a while loop to delete files until a certain amount of files remain.
This is what I have:
touch while/151234
touch while/152355
touch while/151694
touch while/153699
touch while/156946
NUMSNAPS=$(ls while | awk '{print $1}' | wc -l)
RETAIN=2

while [ "$RETAIN" -le "$NUMSNAPS" ]; do
    OLDEST=$(ls | awk '{print $1}' | head -n 1)
    rm "$OLDEST"
done

I cannot use find to delete these files as this is really a test to use with another third-party command. I plan on looking for snapshots with DOCTL and deleting them until a certain one remains.

A: You have a loop that tests a certain condition based on two variables that you never change. I'm assuming you were meaning to decrease the NUMSNAPS value by one in each iteration.

In the zsh shell, you may do
retain=2

rm -f while/*(DN.Om[retain+1,-1])

to delete all regular files (including files with hidden names) apart from the $retain most recently modified files.  If this happens to be several thousands of files, you may want to use zargs instead:
retain=2

autoload -U zargs
zargs -- while/*(DN.Om[retain+1,-1]) -- rm

If you want to order the files by name instead, then replace Om ("order by mtime timestamp, in decreasing order") by On ("order by name, in decreasing order").
You could obviously call this from another shell than zsh by using e.g.
retain=2

zsh -c 'rm -f $2/*(DN.Om[$1+1,-1])' zsh "$retain" "while"

This also passes the name of the directory and the number of files to retain into the in-line script, making it easier to incorporate into an existing non-zsh script.

In the bash shell, you don't really want to parse the output of ls.  Instead you may want to use
shopt -s dotglob nullglob

retain=2

set -- while/*

while [ "$#" -gt "$retain" ]; do
    rm -f "$1"
    shift
done

This would set the list of positional parameters to the list of files in the while directory (including hidden names), and then remove files form that list until there are only retain files left in the list.
This avoids issues with awkward filenames, and it also avoids calling ls once for every file removed.
This code would delete files based on their names (not by last-modified timestamp). This seems to be what your code is also attempting to do.

A: But why you can't get whole list and just keep number of files you need?
For example:
ls -r while | tail -n +${retain} | xargs echo rm

A: Here is how I would fix and improve your script:
#!/bin/bash

touch while/151234
touch while/152355
touch while/151694
touch while/153699
touch while/156946

NUMSNAPS=$(ls -1 while | wc -l)
RETAIN=2

while (( RETAIN < NUMSNAPS )); do
    OLDEST=$(ls -1t while | tail -n 1)
    rm "while/$OLDEST"
    (( --NUMSNAPS ))
done


text:
Q: my plot y-axis is not ordered when I split the text I am creating this plot and when I try to string wrap the text on the y axis the ordered of the questions gets messy. If I do not wrap the text it remains intact. Where am I mistaking?
So, if I use qtxt4.1 in my code the questions are ordered (1-> 17), if I use qtxt4.2 (string wrapped text) the questions are no longer ordered. Why??
      qtxt4 <- c("I am fully satisfied with the safety and hygiene measures implemented by the hotel / restaurant(Q1)",
       "I fully understand why safety and protection measures must be taken against the Sars-cov-2 virus(Q2)",
       "I felt absolutely no threat that I might be infected during my stay at the hotel / restaurant(Q3)",
       "I'm not afraid of being infected with the Sars-Cov-2 virus by other hotel / restaurant customers(Q4)",
       "I consider that the services offered by the hotel are in full compliance with my expectations(Q5)",
       "I am fully satisfied with the safety and hygiene measures in my hotel room(Q6)",
       "I am not afraid of being infected with the Sars-cov-2 virus by restaurant / hotel employees(Q7)",
       "I certainly would not have chosen this restaurant / hotel if I had another option(Q8)",
       "I am convinced that the most effective methods of maintaining safety have been used(Q9)",
       "I'm concerned about public health issues(Q15)",
       "I am particularly concerned about my health and the health of my family(Q16)",
       "I have taken extreme measures for my health and that of my family(Q17)")
       qtxt4.1 <- factor(qtxt4, ordered = TRUE, levels = c("I am fully satisfied with the safety and hygiene measures implemented by the hotel / restaurant(Q1)",
                                                "I fully understand why safety and protection measures must be taken against the Sars-cov-2 virus(Q2)",
                                                "I felt absolutely no threat that I might be infected during my stay at the hotel / restaurant(Q3)",
                                                "I'm not afraid of being infected with the Sars-Cov-2 virus by other hotel / restaurant customers(Q4)",
                                                "I consider that the services offered by the hotel are in full compliance with my expectations(Q5)",
                                                "I am fully satisfied with the safety and hygiene measures in my hotel room(Q6)",
                                                "I am not afraid of being infected with the Sars-cov-2 virus by restaurant / hotel employees(Q7)",
                                                "I certainly would not have chosen this restaurant / hotel if I had another option(Q8)",
                                                "I am convinced that the most effective methods of maintaining safety have been used(Q9)",
                                                "I'm concerned about public health issues(Q15)",
                                                "I am particularly concerned about my health and the health of my family(Q16)",
                                                "I have taken extreme measures for my health and that of my family(Q17)"))

   qnum4 <- c("Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q15","Q16","Q17")

   questions4 <- data.frame(qnum4, qtxt4.1)
   qtxt4.2 <- stringr::str_wrap(qtxt4.1, width = 35)
   questions4 <- data.frame(qnum4, qtxt4.2)

   df_c2%>%
    pivot_longer(-Studies, names_to = "qnum4") %>%
    left_join(questions4, by = "qnum4") %>%
    ggplot(aes(value, qtxt4.2)) +
    geom_point(aes(color = Studies)) +
    labs(x = NULL, y = NULL) +
    scale_x_continuous(limits = c(1, 5)) +
    theme(text = element_text(size = 12)) +
    theme(axis.text = element_text(size = 10))

A: In your second example you need to set qtxt4.2 as an ordered factor.  One way, using forcats::fct_reorder would be...
questions4 <- data.frame(qnum4, qtxt4.2) %>%
        mutate(qtxt4.2 = fct_reorder(qtxt4.2, parse_number(qnum4)))

This uses readr::parse_number to order qnum4 numerically rather than alphabetically, and uses this to reorder qtxt4.2.  Both of these packages are in the tidyverse.


text:
Q: Access denied for user 'root'@'localhost' (using password: YES) after setting mysql_native_password I have a brand new installation of MySQL on Ubuntu 20.04.
During the installation I picked a password for root. After the installation, I did the following:
sudo mysql -u root

It logged me in without asking for password. Then:
mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;

I thought by doing this it would ask for my password on the next login. However, now when I try to log in it gives me:
user@machine:~/Work$ mysql -u root -p
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I type my correct password and cannot login.
How can I solve this and achieve what I trying to setup (login with root but having to type my password)?
Iḿ on version mysql  Ver 8.0.27-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))
Thanks!

A: Its recommend to stop copying off old blogs (and perhaps StackOverflow/DBAExchange answers too) to do any authentication relates changes in MySQL and MariaDB, the mechanisms are being updated and no longer apply. Always check the official documentation.
Use SET PASSWORD or ALTER USER to manage user authentication.
Also modifying a user/host component of the username will put triggers, events, plugins, grants, roles etc out of sync with the combined username (aka broken).
Evidently changing the plugin also has consequences that using SET PASSWORD and ALTER USER will prevent the creating of an invalid configuration.
Since you've stuffed it up already, the official documentation also describes the mechanism for how to reset the root password.


text:
Q: Use ::: or export everything when developing multiple, related R packages? I am working on a family of R packages, all of which share substantial common code which is housed in an internal package, lets call it myPackageUtilities. So I have several packages
myPackage1, myPackage2, etc...
All of these packages depend on every method in myPackageUtilities. For a real-world example, please see statnet on CRAN. Each dependent package, of course, has
Depends: myPackageUtilities
in its DESCRIPTION file.
My question is: In the R code for myPackage1, which of the following two techniques for accessing methods from myPackageUtilities is preferable:

*

*Use ::: to access the methods in myPackageUtilities, or

*Export everything from myPackageUtilities (e.g. by including exportPattern("^[^\\.]") in the NAMESPACE)?

Option 2 clutters the end-user's search path, but the R gurus recommend against using :::.
Follow-up question: If (2) is the better choice, is there a way to export everything using roxygen2?

A: Suppose we have a package called randomUtils and this package has a function called sd that calculates the Slytherin Defiance Quotient.
Now I write a package called spellbound. If spellbound Depends on randomUtils, then randomUtils::sd will be found in the search path and can conflict with calculating standard deviation.
If spellbound Imports randomUtils, however, then R will install randomUtils but will not load it when spellbound is loaded. Thus, the new version of sd can't be found on the search path, but can still be accessed by randomUtils::sd
With an ever growing body of contributed work on CRAN, it is becoming very important that we use Imports as much as possible so that we don't introduce unexpected behaviors by having conflicting function definitions.
An example of when I have used Depends: when writing the HydeNet package, I wanted the end user to be able to use the rjags package in concert with HydeNet. So I put rjags in Depends so that library (HydeNet) would loaf both packages. (In other words, put rjags on the search path.
Moral of the story, if you don't intend for the user to directly access the functions, it should go in Imports.


text:
Q: I want to get what I have saved in the Query database and convert it into an array. Using php I want to get what I have saved in the Query database and convert it into an array. And I want to pass data to the variables that I have passed. Using php
How can I turn a string below into an array?
"UserID=$api_username&Token=$api_token&Account=$number&Amount=$amount&SPKey=$op&APIRequestID=$ref_id&Optional1={Optional1}&Optional2={Optional2}&Optional3={Optional3}&Optional4={Optional4}&GEOCode=[18.273827, 73.879353]&CustomerNumber=1234567890&Pincode=123456&Format=1"
This is the array I am looking for,

    array(
        "UserID" => $api_username,
        "Token" => $api_token,
        "Account" => $number,
        "Amount" => $amount,
        "SPKey" => $op,
        "APIRequestID" => $ref_id,
        "Optional1" => "{Optional1}",
        "Optional2" => "{Optional2}",
        "Optional3" => "{Optional3}",
        "Optional4" => "{Optional4}",
        "GEOCode" => "[18.273827, 73.879353]",
        "CustomerNumber" => "1234567890",
        "Pincode" => "123456",
        "Format" => "1"
    )

I used php parse_url() function but I get such an array.

    [
      "UserID" => "$api_username"
      "Token" => "$api_token"
      "Account" => "$number"
      "Amount" => "$amount"
      "SPKey" => "$op"
      "APIRequestID" => "$ref_id"
      "Optional1" => "{Optional1}"
      "Optional2" => "{Optional2}"
      "Optional3" => "{Optional3}"
      "Optional4" => "{Optional4}"
      "GEOCode" => "[18.273827, 73.879353]"
      "CustomerNumber" => "1234567890"
      "Pincode" => "123456"
      "Format" => "1"
    ]

But I should be Comma Separated.


text:
Q: Change/spoof JSON manifest for android app I need to use old version of apk and i wonder if there is a way to change respond from website that is hardcoded into app. App connect with some website and there is path with websiteurl/update/project.manifest/ It is simple plain text which contains some strings and app compare response with installed files.
JSON file contain string "Version_id: 12.5.3" which is newest app version. I need to spoof version to match old apk before update as app lost important function and devs removed functions for export data. I tried to manual edit response with http toolkit but it doesnt come as response it is downloaded right from url and compared with installed version. Hope somone have some idea, I tried editing apk so it shows as newer version but app check hash and closes with error.
Try edit external website plaintext, any MITM way. Modified response json match old apk version and allow to use without update.


text:
Q: CollapsingToolbarLayout elevation not showing I have a programmatically added collapsingToolbarLayout. For some reason, I do not see the elevation, either in its collapsed or expanded state.
I've tried the following to no avail:
Resources r = getResources();
AppBarLayout appBarLayout = (AppBarLayout)collapsingToolbarLayout.getParent();

/* none of these work */
ViewCompat.setElevation(collapsingToolbarLayout,r.getDimension(R.dimen.toolbar_elevation));
ViewCompat.setElevation(appBarLayout, r.getDimension(R.dimen.toolbar_elevation));
ViewCompat.setElevation(getPrimaryToolbar(), r.getDimension(R.dimen.toolbar_elevation));

Would there be a reason for this?


text:
Q: MVC Models, what are they for? The time has come for me to understand MVC, so that's what I'm trying to do; and I'm having trouble getting what a model is supposed to do. According to Wikipedia, a model:

The model manages the behaviour and data of the application domain,
  responds to requests for information about its state (usually from the
  view), and responds to instructions to change state (usually from the
  controller). In event-driven systems, the model notifies observers
  (usually views) when the information changes so that they can react.

And in CakePHP, you supposedly set up a model in this very simple way:
<?php

class Posts extends AppModel {
    var $name = 'Posts';
}

?>

So if I wanted, for example, the last 10 posts in my database, I would create a controller which would look something like this:
<?php

class PostsController {
    function retrieve_latest($number = 10) {
        $posts = $this->Users->find(array(
                'fields' => '*',
                'order' => 'posts.post_id DESC',
                'limit' => $number,
                'page' => '1',
                'conditions' => array('posts.post_display == 1')
        ));

        $this->set('posts', $posts);
    }
}

?>

And this guy would pass a variable called posts to my view, which would then render it accordingly. The thing is, isn't my model supposed to do anything else?, because if its as simple as this, there would be no point for custom models at all, I mean, its just an empty extension to the model class.

A: This "empty extension to the model class" already does a lot of things: It hooks up to the database and does all the minute handling of retrieving and saving data. It is supposed to do a lot more though, including holding validation rules which are enforced anytime you're writing to the database, any data massaging necessary in before/after filters and any other custom business logic you need in your application. Models are for storing your central business data logic, so anything that's not presentation or input/output related but essentially models the core logic of your application. Just because the basics are simple to set up doesn't mean there isn't more to them.

A: Models also encapsulate business logic and handle interactions with each other.  For example, if a Post has Comments, that's something that would be handled in the model.  You wouldn't want the controller to fetch the Post and then fetch the Comments and assemble them.  That would put the responsibility of knowing the model structure on the controller, where it doesn't belong.
There are, indeed, many applications where the models don't contain very much logic, if any at all.  A model with just data fields and no business logic can be thought of as a DTO (data transfer object) or just an "object" since it doesn't "model" any kind of business logic.  This isn't necessarily a bad thing, it depends on the needs.  Many application are simple forms-over-data apps and don't need any additional logic.
But if your application has more logic than just the data that's in any given table, that logic goes in the models.  They don't just model the data, they model the domain.  In fact, it's not uncommon for the models to not directly have the same structure of the database.  Models are object-oriented, whereas databases are much more commonly relational.  These two don't always solve problems in the same way.  If your models need to exactly copy your tables then you limit yourself from more object-oriented capabilities.
In short, anything that explains what the business does goes into the models.  The controllers are just event handlers, responding to user interface requests.  The controllers are generally customized for the application at hand, whereas models should be re-usable across multiple applications because they represent the core of the business logic.

A: To use your example, the ideal is thin controllers and fat models. That means your code should ideally be refactored to the following:
class Post extends AppModel {
    var $name = 'Post';

    function retrieveLatest($limit = 10) {

        return $this->find('all', array(
            'order'=>'Post.id'=>'DESC',
            'limit'=>$limit
        );

    }

}

class PostsController extends AppController {

    function retrieve_latest($limit) {

      $posts = $this->Post->retrieveLatest($limit);

      $this->set(compact('posts'));

    }

}

Your controller shouldn't be concerned with the intricate details of what is neccessary to fetch the most recent, thats business logic and goes in the model, close to the data. Another benefit is you can also retrieve the latest posts from any related model:
$posts = $this->User->Post->retrieveLatest();

You could even go one stage further and move the retrieveLatest() code into your AppModel so every model would inherit it:
class AppModel extends Model {

    function retrieveLatest($limit = 10) {

        $model = $this->alias;

        return $this->find('all', array(
            'limit'=>$limit,
            'order'=>array(
                $model . ".id"=>'DESC'
            )
        );

    }

}

As a rule of thumb, any time you find yourself building queries in your controllers, move them into the model and give them a descriptive name.


text:
Q: Replace part of matrix by another matrix I have a matrix A of size 1024x1024 and another matrix B of 512x512. How can I replace the central 512x512 portion of A by B?

A: Suppose you want to replace the elements from (row_index, col_index) = (r, c) (in your case probably 256,256).
This should work:
A(r:(r+size(B,1)-1),c:(c+size(B,2)-1)) = B;

An example:
A = magic(6);
B = 2*ones(3);

r = 2;
c = 2;

A(r:(r+size(B,1)-1),c:(c+size(B,2)-1)) = B
A =

   35    1    6   26   19   24
    3    2    2    2   23   25
   31    2    2    2   27   20
    8    2    2    2   10   15
   30    5   34   12   14   16
    4   36   29   13   18   11


text:
Q: How to generate table from csv in postgres sql I am new to database management and we are using psql. All I need to do is to migrate csv (around 200 tables) to our database. Manually creating tables for every csv file is bit tiresome so please help me out, Is there any way to generate table from csv file?

A: Answered at DBA Stackexchange by the OP. I'm copying the answer here because this was the first link returned by my search engine.
OP made a script like:
DATADIR='data'                      # this directory name

PREFIX='jobd'
DBNAME='divacsv'

function createSchema {
    COLUMNS=`head -n 1 $1 |
        awk -F, '{for(i=1; i<=NF; i++){out=out $i" text, ";} print out;}' |
        sed 's/ text, $/MYEXTRA text/' |
        sed 's/"//g'`
    CMD_CREATE="psql $DBNAME -c \"CREATE TABLE $2 ($COLUMNS);\""

    echo $CMD_CREATE
    sh -c "$CMD_CREATE"

    CMD_COPY="psql divacsv  -c \"COPY $2 FROM '"`pwd`"/$1' DELIMITER ',' CSV;\""
    echo $CMD_COPY
    sh -c "$CMD_COPY"
}

for file in $DATADIR/*.csv; do
    table=$PREFIX"_"`echo $file | sed 's/.*\///' | sed 's/.csv//' `
    createSchema "$file" $table
done

Comments advise that HEADER might be needed to avoid loading first line with header texts, which is true.
I've tested this code but couldn't make it work under CentOS.


text:
Q: Toggle attribute and css data I am trying to make a follow button - and when clicked it sends an ajax request to my backend script and if it executes it returns a value that triggers the button's text to go from "follow" to "following" - and that part works just fine. But the jquery part where I send the user data in a data-attribute "data-follow" won't toggle with "data-unfollow". It only works when you refresh the browser which means you can only click the follow button, see it and the data attribute to change to "unfollow" but if you click once more it does not work. I cant figure it out and i've done my searching at the stack.
ERROR
TypeError: $(...).attr(...) is undefined

HTML
<button id="follow" data-follow="1, username1, username2">

Follow

</button>

JQuery
$("button[data-follow]").click(function(){

    var button = $(this);
    var data = $(this).attr("data-follow").split(",");
    alert(data);
    button.find(" > div:last-child").animate({opacity: "0"},200, function(){
       $(this).animate({opacity: "1"},200);
       $(this).html("Following");
       var dataValue = $(this).closest("#follow").attr("data-follow");
       $(this).closest("#follow").attr("data-unfollow", dataValue);
       $(this).closest("#follow").removeAttr("data-follow");
   });

});

$("button[data-unfollow]").click(function(){

    var button = $(this);
    var data = $(this).attr("data-unfollow").split(",");
    alert(data)
    button.find(" > div:last-child").animate({opacity: "0"},200, function(){
       $(this).animate({opacity: "1"},200);
       $(this).html("Follow");
       var dataValue = $(this).closest("#follow").attr("data-unfollow");
       $(this).closest("#follow").attr("data-follow", dataValue);
       $(this).closest("#follow").removeAttr("data-unfollow");
   });

});

A: $(document).on('click', 'button[data-follow]', function() {...});
$(document).on('click', 'button[data-unfollow]', function() {...});

Try it this way.

A: More Generic answer!
You can simply change the state of a button by removing, adding and toggling css classes via jQuery.
At (document.ready) check if follwing or unfollowed state via your ajax request and change the button's css class.
if(following){
  $("#buttonID").toggleClass('following_btn');
} else{
  $("#buttonID").toggleClass('unfollowing_btn');
}

Once clicked, process your code in the web service. Follow if unfollowed or Unfollow if followed. Then if you're rturning the updated state use that to re-update your button's css class accordingly. Or perform ajax call to verify the new state after the button click's ajax call finishes.
CSS:
.following_btn{
  //your following style
 }
.unfollowing_btn{
  //your un-following style
 }

Hope it helps!


text:
Q: reduce() can't be interpreted? $ python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def add(x,y): return x+y
... reduce(add, range(1, 11))
  File "<stdin>", line 2
    reduce(add, range(1, 11))
         ^
SyntaxError: invalid syntax

I am new to python.
Any idea?
I am guessing reduce() isn't available in 2.6.6; is there a way to check?  I only see 2.6.9 online document, which has reduce().

A: You are using invalid Python syntax; it is not the reduce() call that is the problem.
In the interactive interpreter, you must close a compound block statement with a newline:
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55

Note the empty ... after the def add() definition.
Quoting the Interactive input section of the top-level components reference documentation:

Note that a (top-level) compound statement must be followed by a blank line in interactive mode; this is needed to help the parser detect the end of the input.


text:
Q: How to change h2 to h3 products in woocommerce home page? I was looking for change the h2 of my products in the homepage of my website into h3 and i found this snippet :
remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );
add_action('woocommerce_shop_loop_item_title', 'abChangeProductsTitle', 10 );
function abChangeProductsTitle() {
echo '
' . get_the_title() . '
';
}

The thing is that it add a h3 to my products but it don't delete the h2 ones. I have now both headings and i am looking for delete h2 of my products in the store front.
As you can guess I am beggining with coding but I presume that it's probably due to the first line, i did research about how I can fix it but i found nothing.
Do you have any solution ? Thank you in advance

A: One of the ways to achieve this easily is using a child theme (which I hope you are).

*

*In your child theme, copy the WooCommerce file you want to change the H2 tag to H3. make sure in your child theme you follow the exact directory structure as in the WooCommerce directory.

*Once you have moved the file, simply change the H2 tag to H3 using your favourite editor.

The solution above gets the work done.
One issue you might face sometime in the future is when WooCommerce makes a major update to their plugin. You will need to then

*

*Update WooCommerce

*Migrate the new template into the child theme

However, whenever there is a major update, WordPress will alert you on the outdated files in your child theme that need to be updated.
In a nutshell, as long as you are regularly maintaining your site, this solution works perfectly and you do not need to figure out which hooks to use.


text:
Q: Creating PetroSIM COM-object in Mathematica fails I'm trying to invoke Petro-SIM from Mathematica using the following command:
petrosim = CreateCOMObject["PetroSIM.Application"];

This returns the following error-message:
CreateCOMObject::netexcptn: A .NET exception occurred:
System.Runtime.InteropServices.COMException (0x800401F3):
Ungültige Klassenzeichenfolge (Ausnahme von HRESULT: 0x800401F3 (CO_E_CLASSSTRING)) bei System.RuntimeType.GetTypeFromProgIDImpl(String progID, String server, Boolean throwOnError) bei Wolfram.NETLink.Internal.COM.COMUtilities.createCOMObject(String clsIDOrProgID) bei Wolfram.NETLink.Internal.CallPacketHandler.createCOM(KernelLinkImpl ml).

Sorry about the german, last line should translate to something like:
Invalid string-class (Exception of HRESULT: 0x800401F3 (CO_E_CLASSSTRING)) at System.RuntimeType.GetTypeFromProgIDImpl(String progID, String server, Boolean throwOnError) at Wolfram.NETLink.Internal.COM.COMUtilities.createCOMObject(String clsIDOrProgID) at Wolfram.NETLink.Internal.CallPacketHandler.createCOM(KernelLinkImpl ml).

I'm using the same Mathematica version and Petro-Sim version on a different computer and it's working fine. I've no knowledge about .NET and these kind of things and all the problems I've found on the internet so far didn't help. Do you have any idea where this issue comes from? thanks in advance!

A: First you need to verify that HKCR\PetroSIM.Application is in the registry. Then verify that the CLSID is in the registry, then verify that the application is installed.
You could verify running this Powershell macro which will give the pertinent information:
param
(
 [Parameter(Mandatory=$true)] [string]  $ProgId
)

$ProgIdPath = join-path "hklm:\software\classes" $ProgId

$ProgIdPath = join-path $ProgIdPath "CLSID"

Try
{
    $ProgIdEntry = gi $ProgIdPath

    $CLSID = $ProgIdEntry.GetValue("")

    Write-Host "CLSID: " $CLSID

    $CLSIDPath = join-path "hklm:\software\classes\clsid" $CLSID

    $CLSIDEntry = gi -path $CLSIDPath

    ls $CLSIDEntry.PSPath
}
Catch
{
}


text:
Q: How to convert docker run command into json file? I was wondering if anyone knows how to create a json file that would be the same as running:
docker run -p 80:80 -p 443:443 starblade/pydio-v4
I trying something very ambitious, I want to start my docker container in kubernetes-mesos cluster but can't seem to get the ports correct in the json file, alas I am still very new to this.
Thanks,
TT
Here are my json files:
`
{
"id": "frontend-controller",
"kind": "ReplicationController",
"apiVersion": "v1beta1",
"desiredState": {
"replicas": 3,
"replicaSelector": {"name": "frontend"},
"podTemplate": {
"desiredState": {
"manifest": {
"version": "v1beta1",
"id": "frontend-controller",
"containers": [{
"name": "pydio-v4",
"image": "starblade/pydio-v4",
"ports": [{"containerPort": 10001, "protocol": "TCP"}]
}]
}
},
"labels": {"name": "frontend"}
}},
"labels": {"name": "frontend"}
}

{
"id": "frontend",
"kind": "Service",
"apiVersion": "v1beta1",
"port": 80,
"port": 443,
"targetPort": 10001,
"selector": {
"name": "frontend"
},
"publicIPs": [
"${servicehost}"
]
}

Docker container Env info pulled from docker inspect command:

"Env": [
"FRONTEND_SERVICE_HOST=10.10.10.14",
"FRONTEND_SERVICE_PORT=443",
"FRONTEND_PORT=tcp://10.10.10.14:443",
"FRONTEND_PORT_443_TCP=tcp://10.10.10.14:443",
"FRONTEND_PORT_443_TCP_PROTO=tcp",
"FRONTEND_PORT_443_TCP_PORT=443",
"FRONTEND_PORT_443_TCP_ADDR=10.10.10.14",
"KUBERNETES_SERVICE_HOST=10.10.10.2",
"KUBERNETES_SERVICE_PORT=443",
"KUBERNETES_PORT=tcp://10.10.10.2:443",
"KUBERNETES_PORT_443_TCP=tcp://10.10.10.2:443",
"KUBERNETES_PORT_443_TCP_PROTO=tcp",
"KUBERNETES_PORT_443_TCP_PORT=443",
"KUBERNETES_PORT_443_TCP_ADDR=10.10.10.2",
"KUBERNETES_RO_SERVICE_HOST=10.10.10.1",
"KUBERNETES_RO_SERVICE_PORT=80",
"KUBERNETES_RO_PORT=tcp://10.10.10.1:80",
"KUBERNETES_RO_PORT_80_TCP=tcp://10.10.10.1:80",
"KUBERNETES_RO_PORT_80_TCP_PROTO=tcp",
"KUBERNETES_RO_PORT_80_TCP_PORT=80",
"KUBERNETES_RO_PORT_80_TCP_ADDR=10.10.10.1",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"PYDIO_VERSION=6.0.5"
],
"ExposedPorts": {
"443/tcp": {},
"80/tcp": {}
},

`
The pod and service both start and run ok.
However I am unable to access the running Pydio site on any of the master, minion or frontend ips.
Note:
I am running a modified version of the this docker container:
https://registry.hub.docker.com/u/kdelfour/pydio-docker/
My container has been tested and it runs as expected.
You should see the login screen once it is running.
Please let me know if I can provide any other information.
Thanks again.

A: So, I finally got this to work using the following .json files:
frontend-service.json
    {
  "id": "frontend",
  "kind": "Service",
  "apiVersion": "v1beta1",
  "port": 443,
  "selector": {
    "name": "frontend"
  },
  "publicIPs": [
    "${servicehost}"
  ]
}

frontend-controller.json
{
  "id": "frontend-controller",
  "kind": "ReplicationController",
  "apiVersion": "v1beta1",
  "desiredState": {
    "replicas": 1,
    "replicaSelector": {"name": "frontend"},
    "podTemplate": {
      "desiredState": {
         "manifest": {
           "version": "v1beta1",
           "id": "frontend-controller",
           "containers": [{
             "name": "pydio-v4",
             "image": "starblade/pydio-v4",
             "ports": [{"containerPort": 443, "hostPort": 31000}]
           }]
         }
       },
       "labels": {"name": "frontend"}
      }},
  "labels": {"name": "frontend"}
}

I now have pydio with SSL running in a Mesos-Kubernetes env on GCE.
Going to run some tests using more hostPorts to see if I can get more than one replica running on one host. At this point I can resize up to 3.
Hope this helps someone.
Thanks,
TT


text:
Q: Absorbed Brownian motion probability Let $X(t)$ is a Brownian motion, and $S(t)$ is an abosrbed Brownian with two boundaries at $a$ and $b$.
I have defined $S(t)$ as
\begin{align*}
     S(t) =
    \begin{cases}
      a, & \text{ for $\left(m(t) \leq a\right) \cap \left( M(t) < b \right)$  } \\
      b, & \text{ for $\left( M(t) \geq b \right) \cap \left(m(t) > a \right)$ } \\
      X(t), & \text{ otherwise },
     \end{cases}
\end{align*}
where
\begin{align*}
    & m({t}) = \min_{0 \leq u \leq t} \left \{ X(u) \right \}, \\
    & M({t}) = \max_{0 \leq u \leq t} \left \{ X(u) \right \}.
    % & \Pr \Big(X(t) > y,  \min_{0 \leq u \leq t} X(u) > 0, \\
    %  & \max_{0 \leq u \leq t} X(u) < R | X(0) = x \Big) = B(x,y).
\end{align*}
Based on the definition, I tried to determine the probability of $S(t)$ in regard to $X(t)$ as
\begin{align*}
     \Pr(S(t) = a) = \Pr(m(t) \leq a, M(t) < b), \\
     \Pr(S(t) = b) = \Pr(m(t) > a, M(t) \geq b). \\
\end{align*}
However, I have a feeling that my definition is wrong but I could not find where the mistake is.
Could you guys please give me some comments about my problems, especially about the probability of $S(t)$ based on $X(t)$. Thank you very much.

A: I think this might be of help. Consider the stopping times
$$\tau_{a,t}=\inf\{s \in [0,t]:X_s\leq a\}$$
$$\tau_{b,t}=\inf\{s \in [0,t]:X_s\geq b\}$$
and set $\inf\{\emptyset\}=\infty$. We have
$$S_{t}=a\mathbb{I}_{\{\tau_{a,t}<\tau_{b,t}\}}+b\mathbb{I}_{\{\tau_{a,t}>\tau_{b,t}\}}+X_t\mathbb{I}_{\{\tau_{a,t}=\infty\}\cap\{\tau_{b,t}=\infty\}}$$
So $S_t$ yields $a$ if $X_t$ hit $a$ first, yields $b$ if $X_t$ hit $b$ first, and yields $X_t$ if it stayed in $(a,b)$, that is, it never hit neither $a$ nor $b$. Therefore we have
$$P(S_t=a)=P(\tau_{a,t}<\tau_{b,t})$$
and similarly for $P(S_t=b)$.

A: Your definition of $S(t)$ is probably incorrect. Hint: What if the brownian motion hits a at time 1 and b at time 2 and is now at 0 at time 3? What is S(t) as per your definition? (It is 0 (do you see why?), but that should not be. (and can you fix it?))


text:
Q: Setting link hover property with jQuery I want to change the background color of a link with jQuery,
the orginal CSS for the link is
#container ul li:hover ul li a{
    background: #FF0000
}

I'm trying the following jQuery code, but it does not seem to work.
jQuery('#container ul li:hover ul li a').css('background', '#FF0000');

I can set the css for the normal links, but its only causing problem with the link hover.

A: try this:
jQuery('#container ul li ul li a').hover(function(){
   $(this).css('background', '#FF0000');
})

or this :
jQuery('#container ul li').hover(function(){
   $(this).find("ul li a").css('background', '#FF0000');
})

A: You could try it with the jquery hover function. http://api.jquery.com/hover/
And re-set the color.


text:
Q: Converting RGB to CMYK color profile in GIMP I want to convert an sRGB image in gimp to CMYK.
Heres what I did:

*

*Downloaded CMYK color profiles from Adobe.

*Extracted them in the icc folder (/usr/share/color/icc/)

*I opened my xcf image in gimp and went to Image -> Seperate -> Seperate

*I selected the folder (icc folder) where the color profiles were and clicked the convert button.
It shows me a new duplicate of the image except that its changed the color to grayscale and the image to .tif!
The other thing I did was:

*

*Went to Image -> Mode -> Convert To color profile...

*It asked me to select to what workspace I needed to convert and I went into the folder (/usr/share/color/icc/) and selected a CMYK color profile.

*After clicking Convert it gives me the error: "Destination profile is not for RGB color space"
Now how do I really convert my image which is an ad by the way so I can give it to the newspaper?
PS: I need some quick and great response on this within 2 hours! So please help!
Bravo.I

A: GIMP doesn't really support CMYK yet, though it's in development.  There's a plugin called Separate+ that can do CMYK separations — looks like it exports the CMYK data directly to a file, since it can't be stored in a GIMP image buffer.


text:
Q: Equivalancy of using typedef and an anonymous class definition to conventional class definition
Possible Duplicate:
Difference between 'struct' and 'typedef struct' in C++?

An answer to this question led me to wonder about the following:
I presume that defining a class as follows:
typedef class {int i;} C;

would be completely equivalent to defining it in the conventional manner:
class C
{
   int i;
};

Is this presumption correct?

A: In this isolated example they are functionally the same, at least from the outside.
However there are differences.  One instance in particular, you cannot declare a constructor for a struct or a class declared in this way, simply because the class is unnamed.  Similarly you cannot declare any function that involves the class' name.  Here are some examples:
typedef class
{
public:
  Gizmo() : n_(42) {}; // NOT OK
  ~Gizmo();
  Gizmo& operator<<(int n);
private:
  int n_;
} Gizmo;

You also cannot forward declare an anonymous class:
class Gizmo;

In C++ I have never seen a case where typedefing an anonymous struct or a class is preferable to simply declaring a class or a struct that is named.  In some cases the traditional method is definitely preferred.  The moral of the story is:  don't use typedef class {} Name; in C++.  It buys you nothing, and costs you something.

A: From a practical standpoint yes, because the standard says (9.1/5) that

A typedef-name (7.1.3) that names a class type, or a cv-qualified version thereof, is also > a class-name. If a typedef-name that names a cv-qualified class type is used where a
  class-name is required, the cv-qualifiers are ignored.

7.1/3 says:

A name declared with the typedef specifier becomes a typedef-name.
  Within the scope of its declaration, a typedef-name is syntactically
  equivalent to a keyword and names the type associated with the
  identifier in the way described in Clause 8. A typedef-name is thus a
  synonym for another type.

From a theoretical standpoint no, because you could (and indeed I see people already have) draft programs that are valid or invalid depending on which version was used, since 7.1/3 continues from where I cut it off to say:

A typedef-name does
  not introduce a new type the way a class declaration (9.1) or enum declaration does.

A: I believe this is a duplicate question (can't find), but if not, observe that this compiles:
class C
{
   int i;
};
void C() {}

class C x;

while this won't:
typedef class
{
   int i;
} C;
void C() {}

C x;

The name spaces are different.

A: They're not equivalent. In particular,
int main()
{
    class C c;
}

will only compile for one of the two definitions.

A: Here is yet another difference: the latter can be forward-declared, the former can't.


text:
Q: Select a timespan in a Visual Studio Chart (C#) Is it possible (maybe with third-party tools) to add a two lines in a Chart which can be moved and then get the two Dates (strings) on the edges of these two lines?
Maybe this picture describes the problem better. It should look similiar to this:
Mockup_picture
Thank you already for your help!

A: You can try to chart.SelectionRangeChanging event to select a timespan and get the correspond datetime.
Here is a code example you can refer to.
private void Form1_Load(object sender, EventArgs e)
        {
            var s = new Series();
            s.ChartType = SeriesChartType.Column;

            var d = new DateTime(2020,10,1);

            s.Points.AddXY(d, 30);
            s.Points.AddXY(d.AddDays(1), 20);
            s.Points.AddXY(d.AddDays(2), 70);
            s.Points.AddXY(d.AddDays(3), 90);
            s.Points.AddXY(d.AddDays(4), 80);
            s.Points.AddXY(d.AddDays(5), 50);
            s.Points.AddXY(d.AddDays(6), 60);
            s.Points.AddXY(d.AddDays(7), 80);
            s.Points.AddXY(d.AddDays(8), 90);

            chart1.Series.Clear();
            chart1.Series.Add(s);

            chart1.Series[0].XValueType = ChartValueType.DateTime;
            chart1.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd";
            chart1.ChartAreas[0].AxisX.Interval = 1;
            chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Days;
            chart1.ChartAreas[0].AxisX.IntervalOffset = 1;

            chart1.Series[0].XValueType = ChartValueType.DateTime;
            DateTime minDate = new DateTime(2020, 10, 01).AddSeconds(-1);
            DateTime maxDate = new DateTime(2020, 10, 08); // or DateTime.Now;
            chart1.ChartAreas[0].AxisX.Minimum = minDate.ToOADate();
            chart1.ChartAreas[0].AxisX.Maximum = maxDate.ToOADate();
            chart1.ChartAreas[0].CursorX.IsUserEnabled = false;         // red cursor at SelectionEnd
            chart1.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
            chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = false;     // zoom into SelectedRange
            chart1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
        }

        private void chart1_SelectionRangeChanging(object sender, CursorEventArgs e)
        {
            double x1 = e.NewSelectionStart;
            double x2 = e.NewSelectionEnd;
            DateTime date1 = DateTime.FromOADate(x1);
            DateTime date2 = DateTime.FromOADate(x2);
            txtStart.Text = date1.ToString("yyyy-MM-dd");
            txtEnd.Text = date2.ToString("yyyy-MM-dd");
        }

Result:


text:
Q: python googlefinance api getQuote breaks the passed StockSymbl into array of characters When I use method getQuotes( ) from googlefinance0.7, it is breaking String into characters and running for each characters. so getQuote('PG') is churning output as getQuote('P') , '\n' ,  getQuote('G').
I must be doing something wrong ?
Could not find API documentation for googpefinance0.7 either to see if other methods would provide an alternative.
Thanks.
-PL
code :
searchStrNameAry = np.array(['X' , 'PG'])

for item in searchStrNameAry:
    print (item, "\n")
    print (json.dumps(getQuotes(item), indent=2))

This outputs :
X

[
  {
    "LastTradeDateTimeLong": "Apr 26, 1:11PM EDT",
    "StockSymbol": "X",
    "LastTradeWithCurrency": "23.20",
    "Index": "NYSE",
    "LastTradeDateTime": "2017-04-26T13:11:50Z",
    "ID": "38983",
    "LastTradePrice": "23.20",
    "LastTradeTime": "1:11PM EDT"
  }
]
PG

[
  {
    "LastTradeDateTimeLong": "Apr 26, 1:11PM EDT",
    "StockSymbol": "P",
    "LastTradeWithCurrency": "10.94",
    "Index": "NYSE",
    "LastTradeDateTime": "2017-04-26T13:11:23Z",
    "ID": "4592563",
    "LastTradePrice": "10.94",
    "LastTradeTime": "1:11PM EDT"
  },
  {
    "LastTradeDateTimeLong": "Apr 26, 1:10PM EDT",
    "StockSymbol": "G",
    "LastTradeWithCurrency": "24.66",
    "Index": "NYSE",
    "LastTradeDateTime": "2017-04-26T13:10:55Z",
    "ID": "716027",
    "LastTradePrice": "24.66",
    "LastTradeTime": "1:10PM EDT"
  }
]

A: getQuotes() take a str or an iterable, unfortunately because you have created a numpy array the type of searchStrNameAry[0] is numpy.str_ which it is not expected, so is treated like an iterable.
Either explicitly ensure the type is str:
for item in searchStrNameAry:
    print (item, "\n")
    print (json.dumps(getQuotes(str(item)), indent=2))

Or get all the quotes in one call:
print (json.dumps(getQuotes(searchStrNameAry), indent=2))


text:
Q: Can't get code to write to text file in Python 3 I am was tasked with commanding a multimeter from my computer using python and storing the information into a text file. I have tried altering the code in a million ways and I can not figure out what I am doing wrong. The file already exists in my computer but nothing ever gets displayed there.
import serial
import time
import math
import string

#setting up connection to Multimeter through COM6
ser = serial.Serial('COM6')
ser.baudrate = 9600
ser.bytesize = 8
ser.parity = 'N'
ser.stopbites = 1
ser.timeout = 1

class testing():
    def test():

        #getting user input
        serialNum = input("Serial number: ")
        date = input("Date: ")
        time = input("Time: ")

        x = 1
        if x==1:
            ser.write(b'meas:volt:dc?\r\n')
            returnBytes = ser.readline()
            fbytes = float(returnBytes)
            #print("DC voltage: " + returnBytes)
            ser.close()
            return fbytes

        #saving and printing information to text file
        lines = [serialNum, date, time, fbytes]
        file = open('/Users/myname/test.txt', 'w')
        file.write(''.join(lines))
        file.close()

A: I solved the problem i posted about, however the code is still spitting out an error that I am trying to solve. but for the sake of the question, this is what i revised my code to so that the information would display in the text file
import serial
import time
import math
import string

#setting up connection to Multimeter through COM6
ser = serial.Serial('COM6')
ser.baudrate = 9600
ser.bytesize = 8
ser.parity = 'N'
ser.stopbites = 1
ser.timeout = 1

#getting user input
serialNum = str(input("Serial number: "))
date = str(input("Date: "))
time = str(input("Time: "))

#getting measurement of DC voltage
ser.write(b'meas:volt:dc?\n')         #'b' encodes info from meter to bytes
returnDC = ser.readline()
fbytesDC = float(returnDC)

#getting resistance measurement
ser.write(b'meas:res?\n')             #'b' encodes info from meter to bytes
returnRes = ser.readline()
fbytesRes = float(returnRes)

#close the active port
ser.close()

#saving and printing information to text file
lines = [serialNum, date, time]
file = open("C:/Users/myname/test.txt", "a+")
file.write(' '.join(lines))
file.write(" DC voltage: "+ str(fbytesDC))
file.write(" Resistance: "+ str(fbytesRes))
file.write("\n")
file.close()


text:
Q: Learning algebra and harmonic analysis I've revised my question a bit in response to the (very helpful) advice so far--
I have an engineering background but am interested in learning abstract harmonic analysis. My interest is rather unstructured; the Fourier transform sparked my interest in mathematics, and I've been following since I first learned of it as a sort of guide through mathematics. I've decided it's time I delved into the abstract, and from my readings so far it's become clear to me that this will require a sojourn into a swathe of unfamiliar mathematics. My background in classical analysis, linear algebra, and probability is rather good (probably the rough equivalent of a 1st year american grad student), and so I'm familiar as well with point-set topology. I'm also familiar with measure theory (via probability, and some real analysis). I have essentially no abstract algebra.
I would be interested in three bits of advice:

*

*What algebra is essential for the canon of harmonic analysis? Perhaps this is a vacuous question (i.e., that an answer is as simple "just google" or "open a book")? It strikes me that techniques or background might work their way in unnamed. I'm hoping to prevent the sinking feeling that I don't know something I should.

*Specific examples (theorems, objects, counterexamples) which illustrate important applications of harmonic analysis, especially in relation to algebra. I'm not looking for explanations, just statements of what's thought to be important. I'm hoping that this information will help me sift through the different branches of harmonic analysis, especially where I am most unfamiliar with the language.

*Canonical/important texts which I might find useful. I'm especially interested in those good for self study (well-edited with many examples and end-of-chapter exercises, and ideally a conversational tone with lengthy remarks and some historical content).

A: Let me suggest that you look at the book "An introduction to topology and modern analysis", by Simmons.  It covers concepts of point set topology that you presumably already know, but also gives a fairly concise, but quite readable, introduction to abstract algebra.  It then brings these together in its final sections into a discussion of Banach algebras and related topics, culminating in a proof of the Gelfand--Naimark theorem.  [See below for a brief remark about this theorem, and the other theorems mentioned in the subsequent paragraphs.]
Since you say that you are interested in abstract harmonic analysis, the Gelfand--Naimark theorem is a good place to start.  (For example, it is not so far to go from there to the abstact form of Wiener's Tauberian theorem.)
Note: I am interpreting abstract harmonic analysis to mean something like harmonic analysis on locally compact abelian groups (and related topics).
Simmons also has exercises, I think.
When I was studying this stuff, the next place I went to after Simmons was Naimark's tome Normed rings.  (There are various editions, and some of the later ones might be called Normed algebras instead, if I'm not misremembering.  They are translated from Russian, so the slighly unusual, and changing, name may be an artefact of this; I'm not sure.  In any case, they are basically about the theory of Banach algebras and its applications to abstract harmonic analysis.)
This is a place where one can read about various group rings of topological groups, Haar measure, the general form of Wiener's Tauberian theorem, and other concepts of abstract harmonic analysis.  It is essentially too long to read from
start to finish, but in my experience one can dip into it in bits and pieces, and having a firm understanding of the material from Simmons helps a lot.
Naimark's book is a monograph, not a textbook as such, and although it has many historical comments and illustrative examples (although the examples are often at a theoretically fairly high level), I don't remember it as having exercises.  But in any case, I am not suggesting it as a first point of call, but as somewhere to go after you have some basics under your belt.
There is also a book by Loomis, An introduction to abstract harmonic analysis,
which also treats Haar measure, various group rings, and so on.  If I remember correctly it is  less condensed than Naimark and also less comprehensive.  My memory is that I preferred Naimark, but probably for idiosyncratic reasons.  I don't remember whether Loomis's book has exercises.
All the books I'm mentioning are probably out of print, so I'm also assuming that you have access to a university library or something similar.  (Any decent such library should have them.)
Finally, some fundamental results that I would recommend aiming for, which combine algebra
and analysis nicely:

*

*Gelfand's generalization of Wiener's theorem (that if $f$ is a nowhere zero continuous periodic function whose Fourier series is absolutely convergent, than
the Fourier series of $1/f$ is also absolutely convergent).

*the Gelfand--Naimark theorem (identifying certain commutative Banach algebras with extra
structure as being algebras of continuous functions on compact topological space; it is a beautiful generalization of the classical spectral theorems for matrices).

*The generalization of Wiener's Tauberian theorem to arbitrary commutative locally compact groups.  (Wiener's original theorem says that if $f$ is an $L^1$-function on the real line whose Fourier transform is nowhere zero, then
the translates of $f$ span a dense subspace of $L^1$.)

*More abstract, but basic to the previous example and lots of other things, is
the existence of Haar measure for any locally compact group.
As already mentioned,
the first two results are in Simmons, and are easier, but already involve a very nice interplay between analysis and algebra.  (The general framework is that of Banach algebras, which combine the analysis of Banach spaces with the
algebra of rings, ideals, and so on.)
The second two results are in Naimark, and Haar measure is also in Loomis (and many other places) (and the general form of Wiener may be in Loomis too; I forget now).

A: Harmonic analysis is a very broad field. A nice introduction to harmonic analysis at the level of a beginning graduate student would be Grafakos' Classical and Modern Fourier analysis (two books).
Elias Stein also has many nice books, but they are quite hard as he leaves out a lot of details.
The books require at least knowledge in measure and integration theory (and so real analysis), some basic functional analysis and for Grafakos you might want to know what a group is.
So, maybe you should also state what kind of harmonic analysis you want to do. The contents of the first book of Grafakos (Classical Fourier Analysis) is at least something you should know if you want to do harmonic analysis (as I have been told).

A: Worth having a look at is "Harmonic analysis on finite groups" for applications to probability theory (one of your stated strengths). That way you'll be going from what you already know to the new stuff. Here is the Google Books link.


text:
Q: inserting html control values into sql server using c# I want to insert the values into sql server and display into the form again.  I am having my controls in html only.
Since I am using more javascript, I can't change this to asp.net controls.  Now I want to insert html dropdown, text controls into Sql Server database.  After that, I want to display it into the form.

A: you cant send html tag's to server ...
to do this yo must changhe this attribute in your page Directive in html Source
AutoEventWireup="true"=====>AutoEventWireup="false"

then you can save your html string in sql

A: i found as;
Html controls can be used in csharp as;
in the tag u should define runat attribue
so that we can get the id's in c#
string a=erp.value;


text:
Q: StaTaskScheduler and STA thread message pumping TL;DR: A deadlock inside a task run by StaTaskScheduler. Long version:
I'm using StaTaskScheduler from ParallelExtensionsExtras by Parallel Team, to host some legacy STA COM objects supplied by a third party. The description of the StaTaskScheduler implementation details says the following:

The good news is that TPL's implementation is able to run on either
  MTA or STA threads, and takes into account relevant differences around
  underlying APIs like WaitHandle.WaitAll (which only supports MTA
  threads when the method is provided multiple wait handles).

I thought that would mean the blocking parts of TPL would use a wait API which pumps messages, like CoWaitForMultipleHandles, to avoid deadlock situations when called on an STA thread.
In my situation, I believe the following is happening: in-proc STA COM object A makes a call to out-of-proc object B, then expects a callback from B via as a part of the outgoing call.
In a simplified form:
var result = await Task.Factory.StartNew(() =>
{
    // in-proc object A
    var a = new A();
    // out-of-proc object B
    var b = new B();
    // A calls B and B calls back A during the Method call
    return a.Method(b);
}, CancellationToken.None, TaskCreationOptions.None, staTaskScheduler);

The problem is, a.Method(b) never returns. As far as I can tell, this happens because a blocking wait somewhere inside BlockingCollection<Task> does not pump messages, so my assumption about the quoted statement is probably wrong.
EDITED The same code works when is executed on the UI thread of the test WinForms application (that is, providing TaskScheduler.FromCurrentSynchronizationContext() instead of staTaskScheduler to Task.Factory.StartNew).
What is the right way to solve this? Should I implemented a custom synchronization context, which would explicitly pump messages with CoWaitForMultipleHandles, and install it on each STA thread started by StaTaskScheduler?
If so, will the underlying implementation of BlockingCollection be calling my SynchronizationContext.Wait method? Can I use SynchronizationContext.WaitHelper to implement SynchronizationContext.Wait?

EDITED with some code showing that a managed STA thread doesn't pump when doing a blocking wait. The code is a complete console app ready for copy/paste/run:

using System;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleTestApp
{
    class Program
    {
        // start and run an STA thread
        static void RunStaThread(bool pump)
        {
            // test a blocking wait with BlockingCollection.Take
            var tasks = new BlockingCollection<Task>();

            var thread = new Thread(() =>
            {
                // Create a simple Win32 window
                var hwndStatic = NativeMethods.CreateWindowEx(0, "Static", String.Empty, NativeMethods.WS_POPUP,
                    0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

                // subclass it with a custom WndProc
                IntPtr prevWndProc = IntPtr.Zero;

                var newWndProc = new NativeMethods.WndProc((hwnd, msg, wParam, lParam) =>
                {
                    if (msg == NativeMethods.WM_TEST)
                        Console.WriteLine("WM_TEST processed");
                    return NativeMethods.CallWindowProc(prevWndProc, hwnd, msg, wParam, lParam);
                });

                prevWndProc = NativeMethods.SetWindowLong(hwndStatic, NativeMethods.GWL_WNDPROC, newWndProc);
                if (prevWndProc == IntPtr.Zero)
                    throw new ApplicationException();

                // post a test WM_TEST message to it
                NativeMethods.PostMessage(hwndStatic, NativeMethods.WM_TEST, IntPtr.Zero, IntPtr.Zero);

                // BlockingCollection blocks without pumping, NativeMethods.WM_TEST never arrives
                try { var task = tasks.Take(); }
                catch (Exception e) { Console.WriteLine(e.Message); }

                if (pump)
                {
                    // NativeMethods.WM_TEST will arrive, because Win32 MessageBox pumps
                    Console.WriteLine("Now start pumping...");
                    NativeMethods.MessageBox(IntPtr.Zero, "Pumping messages, press OK to stop...", String.Empty, 0);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            Thread.Sleep(2000);

            // this causes the STA thread to end
            tasks.CompleteAdding();

            thread.Join();
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Testing without pumping...");
            RunStaThread(false);

            Console.WriteLine("\nTest with pumping...");
            RunStaThread(true);

            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }
    }

    // Interop
    static class NativeMethods
    {
        [DllImport("user32")]
        public static extern IntPtr SetWindowLong(IntPtr hwnd, int nIndex, WndProc newProc);

        [DllImport("user32")]
        public static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hwnd, int msg, int wParam, int lParam);

        [DllImport("user32.dll")]
        public static extern IntPtr CreateWindowEx(int dwExStyle, string lpClassName, string lpWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);

        [DllImport("user32.dll")]
        public static extern bool PostMessage(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        public static extern int MessageBox(IntPtr hwnd, string text, String caption, int options);

        public delegate IntPtr WndProc(IntPtr hwnd, int msg, int wParam, int lParam);

        public const int GWL_WNDPROC = -4;
        public const int WS_POPUP = unchecked((int)0x80000000);
        public const int WM_USER = 0x0400;

        public const int WM_TEST = WM_USER + 1;
    }
}

This produces the output:

Testing without pumping...
The collection argument is empty and has been marked as complete with regards to additions.

Test with pumping...
The collection argument is empty and has been marked as complete with regards to additions.
Now start pumping...
WM_TEST processed
Press Enter to exit

A: My understanding of your problem: you are using StaTaskScheduler only to organize the classic COM STA apartment for your legacy COM objects. You're not running a WinForms or WPF core message loop on the STA thread of StaTaskScheduler. That is, you're not using anything like Application.Run, Application.DoEvents or Dispatcher.PushFrame inside that thread. Correct me if this is a wrong assumption.
By itself, StaTaskScheduler doesn't install any synchronization context on the STA threads it creates. Thus, you're relying upon the CLR to pump messages for you. I've only found an implicit confirmation that the CLR pumps on STA threads, in Apartments and Pumping in the CLR by Chris Brumme:

I keep saying that managed blocking will perform "some pumping" when
called on an STA thread.  Wouldn't it be great to know exactly what
will get pumped?  Unfortunately, pumping is a black art which is
beyond mortal comprehension.  On Win2000 and up, we simply delegate to
OLE32's CoWaitForMultipleHandles service.

This indicates the CLR uses CoWaitForMultipleHandles internally for STA threads. Further, the MSDN docs for COWAIT_DISPATCH_WINDOW_MESSAGES flag mention this:

... in STA is only a small set of special-cased messages dispatched.

I did some research on that, but could not get to pump the WM_TEST from your sample code with CoWaitForMultipleHandles, we discussed that in the comments to your question. My understanding is, the aforementioned small set of special-cased messages is really limited to some COM marshaller-specific messages, and doesn't include any regular general-purpose messages like your WM_TEST.
So, to answer your question:

... Should I implemented a custom synchronization context, which would
explicitly pump messages with CoWaitForMultipleHandles, and install it
on each STA thread started by StaTaskScheduler?

Yes, I believe that creating a custom synchronization context and overriding SynchronizationContext.Wait is indeed the right solution.
However, you should avoid using CoWaitForMultipleHandles, and use MsgWaitForMultipleObjectsEx instead. If MsgWaitForMultipleObjectsEx indicates there's a pending message in the queue, you should manually pump it with PeekMessage(PM_REMOVE) and DispatchMessage. Then you should continue waiting for the handles, all inside the same SynchronizationContext.Wait call.
Note there's a subtle but important difference between MsgWaitForMultipleObjectsEx and MsgWaitForMultipleObjects. The latter doesn't return and keeps blocking, if there's a message already seen in the queue (e.g., with PeekMessage(PM_NOREMOVE) or GetQueueStatus), but not removed. That's not good for pumping, because your COM objects might be using something like PeekMessage to inspect the message queue. That might later cause MsgWaitForMultipleObjects to block when not expected.
OTOH, MsgWaitForMultipleObjectsEx with MWMO_INPUTAVAILABLE flag doesn't have such shortcoming, and would return in this case.
A while ago I created a custom version of StaTaskScheduler (available here as ThreadAffinityTaskScheduler) in attempt to solve a different problem: maintaining a pool of threads with thread affinity for subsequent await continuations. The thread affinity is vital if you use STA COM objects across multiple awaits. The original StaTaskScheduler exhibits this behavior only when its pool is limited to 1 thread.
So I went ahead and did some more experimenting with your WM_TEST case. Originally, I installed an instance of the standard SynchronizationContext class on the STA thread. The WM_TEST message didn't get pumped, which was expected.
Then I overridden SynchronizationContext.Wait to just forward it to SynchronizationContext.WaitHelper. It did get called, but still didn't pump.
Finally, I implemented a full-featured message pump loop, here's the core part of it:
// the core loop
var msg = new NativeMethods.MSG();
while (true)
{
    // MsgWaitForMultipleObjectsEx with MWMO_INPUTAVAILABLE returns,
    // even if there's a message already seen but not removed in the message queue
    nativeResult = NativeMethods.MsgWaitForMultipleObjectsEx(
        count, waitHandles,
        (uint)remainingTimeout,
        QS_MASK,
        NativeMethods.MWMO_INPUTAVAILABLE);

    if (IsNativeWaitSuccessful(count, nativeResult, out managedResult) || WaitHandle.WaitTimeout == managedResult)
        return managedResult;

    // there is a message, pump and dispatch it
    if (NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, NativeMethods.PM_REMOVE))
    {
        NativeMethods.TranslateMessage(ref msg);
        NativeMethods.DispatchMessage(ref msg);
    }
    if (hasTimedOut())
        return WaitHandle.WaitTimeout;
}

This does work, WM_TEST gets pumped. Below is an adapted version of your test:
public static async Task RunAsync()
{
    using (var staThread = new Noseratio.ThreadAffinity.ThreadWithAffinityContext(staThread: true, pumpMessages: true))
    {
        Console.WriteLine("Initial thread #" + Thread.CurrentThread.ManagedThreadId);
        await staThread.Run(async () =>
        {
            Console.WriteLine("On STA thread #" + Thread.CurrentThread.ManagedThreadId);
            // create a simple Win32 window
            IntPtr hwnd = CreateTestWindow();

            // Post some WM_TEST messages
            Console.WriteLine("Post some WM_TEST messages...");
            NativeMethods.PostMessage(hwnd, NativeMethods.WM_TEST, new IntPtr(1), IntPtr.Zero);
            NativeMethods.PostMessage(hwnd, NativeMethods.WM_TEST, new IntPtr(2), IntPtr.Zero);
            NativeMethods.PostMessage(hwnd, NativeMethods.WM_TEST, new IntPtr(3), IntPtr.Zero);
            Console.WriteLine("Press Enter to continue...");
            await ReadLineAsync();

            Console.WriteLine("After await, thread #" + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Pending messages in the queue: " + (NativeMethods.GetQueueStatus(0x1FF) >> 16 != 0));

            Console.WriteLine("Exiting STA thread #" + Thread.CurrentThread.ManagedThreadId);
        }, CancellationToken.None);
    }
    Console.WriteLine("Current thread #" + Thread.CurrentThread.ManagedThreadId);
}

The output:

Initial thread #9
On STA thread #10
Post some WM_TEST messages...
Press Enter to continue...
WM_TEST processed: 1
WM_TEST processed: 2
WM_TEST processed: 3

After await, thread #10
Pending messages in the queue: False
Exiting STA thread #10
Current thread #12
Press any key to exit
Note this implementation supports both the thread affinity (it stays on the thread #10 after await) and the message pumping. The full source code contains re-usable parts (ThreadAffinityTaskScheduler and ThreadWithAffinityContext) and is available here as self-contained console app. It hasn't been thoroughly tested, so use it at your own risk.

A: The subject of STA thread pumping is a large one with very few programmers having an enjoyable time solving deadlock.  The seminal paper about it was written by Chris Brumme, a principal smart guy that worked on .NET.  You'll find it in this blog post.  Unfortunately it is rather short on specifics, he doesn't go beyond noting that the CLR does a bit of pumping but without any details on the exact rules.
The code he's talking about, added in .NET 2.0, is present in an internal CLR function named MsgWaitHelper().  The source code for .NET 2.0 is available through the SSCLI20 distribution.  Very complete, but the source for MsgWaitHelper() is not included.  Quite unusual.  Decompiling it is rather a lost cause, it is very large.
The one thing to take away from his blog post is the danger of re-entrancy.  Pumping in an STA thread is dangerous for its ability to dispatch Windows messages and get arbitrary code to execute when your program isn't in the correct state to allow such code to execute.  Something that most any VB6 programmer knows when he used DoEvents() to get a modal loop in his code to stop freezing the UI.  I wrote a post about its most typical dangers.  MsgWaitHelper() does this exact kind of pumping itself, it however is very selective about exactly what kind of code it allows to run.
You can get some insight in what it does inside your test program by running the program without a debugger attached and then attaching an unmanaged debugger.  You'll see it blocking on NtWaitForMultipleObjects().  I took it one step further and set a breakpoint on PeekMessageW(), to get this stack trace:
user32.dll!PeekMessageW()   Unknown
combase.dll!CCliModalLoop::MyPeekMessage(tagMSG * pMsg, HWND__ * hwnd, unsigned int min, unsigned int max, unsigned short wFlag) Line 2305  C++
combase.dll!CCliModalLoop::PeekRPCAndDDEMessage() Line 2008 C++
combase.dll!CCliModalLoop::FindMessage(unsigned long dwStatus) Line 2087    C++
combase.dll!CCliModalLoop::HandleWakeForMsg() Line 1707 C++
combase.dll!CCliModalLoop::BlockFn(void * * ahEvent, unsigned long cEvents, unsigned long * lpdwSignaled) Line 1645 C++
combase.dll!ClassicSTAThreadWaitForHandles(unsigned long dwFlags, unsigned long dwTimeout, unsigned long cHandles, void * * pHandles, unsigned long * pdwIndex) Line 46 C++
combase.dll!CoWaitForMultipleHandles(unsigned long dwFlags, unsigned long dwTimeout, unsigned long cHandles, void * * pHandles, unsigned long * lpdwindex) Line 120 C++
clr.dll!MsgWaitHelper(int,void * *,int,unsigned long,int)   Unknown
clr.dll!Thread::DoAppropriateWaitWorker(int,void * *,int,unsigned long,enum WaitMode)   Unknown
clr.dll!Thread::DoAppropriateWait(int,void * *,int,unsigned long,enum WaitMode,struct PendingSync *)    Unknown
clr.dll!CLREventBase::WaitEx(unsigned long,enum WaitMode,struct PendingSync *)  Unknown
clr.dll!CLREventBase::Wait(unsigned long,int,struct PendingSync *)  Unknown
clr.dll!Thread::Block(int,struct PendingSync *) Unknown
clr.dll!SyncBlock::Wait(int,int)    Unknown
clr.dll!ObjectNative::WaitTimeout(bool,int,class Object *)  Unknown

Beware that I recorded this stack trace on Windows 8.1, it will look pretty different on older Windows versions.  The COM modal loop has been heavily tinkered with in Windows 8, it is also a very big deal to WinRT programs.  Don't know that much about it, but it appears to have another STA threading model named ASTA that does a more restrictive kind of pumping, enshrined in the added CoWaitForMultipleObjects()
ObjectNative::WaitTimeout() is where the SemaphoreSlim.Wait() inside the BlockingCollection.Take() method starts executing CLR code.  You see it plowing through the levels of internal CLR code to arrive at the mythical MsgWaitHelper() function, then switching to the infamous COM modal dispatcher loop.
The bat signal sign of it doing the "wrong" kind of pumping in your program is the call to CliModalLoop::PeekRPCAndDDEMessage() method.  In other words, it is only considering the kind of interop messages that get posted to a specific internal window that dispatches the COM calls that cross an apartment boundary.  It will not pump the messages that are in the message queue for your own window.
This is understandable behavior, Windows can only be absolutely sure that re-entrancy won't kill your program when it can see that your UI thread is idle.  It is idle when it pumps the message loop itself, a call to PeekMessage() or GetMessage() indicates that state.  Problem is, you don't pump yourself.  You violated the core contract of an STA thread, it must pump the message loop.  Hoping that the COM modal loop will do the pumping for you is thus idle hope.
You can actually fix this, even though I don't recommend you do.  The CLR will leave it to the application itself to perform the wait by a properly constructed SynchronizationContext.Current object.  You can create one by deriving your own class and override the Wait() method.  Call the SetWaitNotificationRequired() method to convince the CLR that it should leave it up to you.  An incomplete version that demonstrates the approach:
class MySynchronizationProvider : System.Threading.SynchronizationContext {
    public MySynchronizationProvider() {
        base.SetWaitNotificationRequired();
    }
    public override int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) {
        for (; ; ) {
            int result = MsgWaitForMultipleObjects(waitHandles.Length, waitHandles, waitAll, millisecondsTimeout, 8);
            if (result == waitHandles.Length) System.Windows.Forms.Application.DoEvents();
            else return result;
        }
    }
    [DllImport("user32.dll")]
    private static extern int MsgWaitForMultipleObjects(int cnt, IntPtr[] waitHandles, bool waitAll,
        int millisecondTimeout, int mask);
}

And install it at the start of your thread:
    System.ComponentModel.AsyncOperationManager.SynchronizationContext =
        new MySynchronizationProvider();

You'll now see your WM_TEST message getting dispatched.  It the call to Application.DoEvents() that dispatched it.  I could have covered it up by using PeekMessage + DispatchMessage but that would obfuscate the danger of this code, best to not stick DoEvents() under the table.  You really are playing a very dangerous re-entrancy game here.  Don't use this code.
Long story short, the only hope of using StaThreadScheduler correctly is when it is used in code that already implemented the STA contract and pumps like an STA thread should do.  It was really meant as a band-aid for old code where you don't have to luxury to control the thread state.  Like any code that started life in a VB6 program or Office add-in.  Experimenting a bit with it, I don't think it actually can work.  Notable too is that the need for it ought the be completely eliminated with the availability of asych/await.