text:
Q: JMeter JDBC manual commit I'm using JMeter to do some load testing, and need to run a test which inserts a few thousand records. Part of the requirement is that it should not commit each individual update, but only commit every thousand records. Seems pretty straightforward, but I cannot find any examples or documentation explaining how to do a manual commit in JMeter, and I can't get it to work.
I've got it set up to read a few entries from a csv file, plus a counter variable for an incrementing ID field. If auto commit is enabled, that works fine.
When I disable auto commit, nothing gets committed -- as you'd expect. But how DO I get it committed? I can't even get it to commit every update without auto commit, let alone a specified rate.

*

*I tried adding a JDBC post processor with a commit statement and/or
commit query type, on the same DB connection pool, only one thread on
that pool and in the test, but that doesn't work.

*Tried doing the same as a separate JDBC request, that didn't work either.

*Tried adding the commit to my update statement itself, no luck.

*Tried changing transaction isolation, but none of those values seem to make
a difference.

*Tried opening a transaction with a pre-processor or a
request or within the existing request, but that also hasn't helped.

I assume my problem might be that the commit is going into a separate transaction from the actual update statements...but I can't find any way to change that...

A: Try doing the following:

*

*Add a JDBC Request with Query Type set to AutoCommit(false)

*Put your JDBC Requests as you want

*Add a JDBC Request with Query Type set to Commit

Your plan should look like this:

Fist set autocommit to false:

Then call your update queries:

Finally commit:

Reset autocommit to true:

If this does not work, I suggest you report an issue to JMeter.


text:
Q: Interesting Eclipse JavaDoc commenter error So when I was working on a lab for my class, I used the ALT+SHIFT+J Eclipse shortcut to auto generate Javadoc comments for my functions. Here are some examples where I had no problem:
// ----------------------------------------------------------
 /**
 * Mutator method for setting processorSpeed.
 *
 * @param newProcessorSpeed Updated processor speed value
 */
 public void setProcessorSpeed(double newProcessorSpeed)
 {
 processorSpeed = newProcessorSpeed;
 }

 // ----------------------------------------------------------
 /**
 * Returns value of computer power
 *
 * @return numcores * processorSpeed
 */
 public double computePower()
 {
 double temp = numcores * processorSpeed;
 return temp;
 }

However, when I tried to do the same shortcut for this function:
public String toString()
 {
 String temp =
 processor + ", " + String.valueOf(numcores) + " cores at "
 + String.valueOf(processorSpeed) + "GHz";
 return temp;
 }

All I get is:
// ----------------------------------------------------------
 public String toString()
 {
 String temp =
 processor + ", " + String.valueOf(numcores) + " cores at "
 + String.valueOf(processorSpeed) + "GHz";
 return temp;
 }

Just thought it was an interesting error. Curious as to what makes Eclipse treat the toString function differently.

A: That's not the behavior I get. Instead, I get a block comment that starts /* (non-Javadoc). This is because toString() is an inherited function and that's the behavior that the auto-doc shortcut invokes in my setup. Yours is obviously set up differently.
You can set up any template you like for various contexts by going to Window -> Settings and then navigating to Java -> Code Style -> Code Templates. The docs for the variables you can use in a template can be found here. The template for comments to overriding methods in my setup is:
/* (non-Javadoc)
 * ${see_to_overridden}
 */

A: Because you are overwriting the method a non-javadoc comment is generated. Every Java object inherits from Object and Object defines a toString() method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: meaning of scheme theoretic - defining equation In algebraic geometry, an algebraic set $X$ is the common zero set of polynomials.
In this case, these polynomials is called the defining equation of $X$.
I know that any algebraic set regards as scheme by Hartshorne book (II.2.6).
My question is simple... what is the meaning of scheme theoretic - defining equation??

A: It means that you keep track of the actual polynomials in the defining ideal, as opposed to just the reduced portion (the radical of the ideal).  For example, $x$ and $x^2$ define the same zero set in $k[x,y]$, but scheme-theoretically, the schemes corresponding to $k[x,y]/(x)$ and $k[x,y]/(x^2)$ are not the same.


text:
Q: Are there any alternatives to using List.Single to get an element with a primary key? I have a List of User objects from my data store.
Now once it is already in memory the only way to get a user by his ID is to use the Single extension method. This is really performance degrading.
I know I could have used a dictionary instead of a list but this would be redundant. I would have to store the Primary Key 2 times. So is there another way to do what i want?
BTW I am making a custom class that can do something like this, but i was hoping for something out of the box.

A: Assuming the primary key is a reference type, you'd only be storing a reference to the primary key twice.
Have you tried using Dictionary<,> and found it doesn't work well enough? It's certainly the most natural solution. KeyedCollection<,> (suggested by Mark) would certainly work too, but requires you to derive from the class - and I wouldn't like to guarantee it'll actually save any memory. (You'd need to know the implementation details - it could easily just use a Dictionary internally, for example.)

A: You could save your in-memory users in a KeyedCollection.


text:
Q: Javascript not rendering inline in HTML with Rich Text Publisher I am trying to print the below HTML code with embedded Javascript on the Jenkins (2.241) project page using the Rich Text Publisher plugin but the Javascript table loads at the very bottom of the page instead of on the right-hand side below the 'Recent Changes' link and above the "Hello World" where I need it. How can I fix this?

<html>
<body>

<script language="javascript" type="text/javascript">
function tableCreate(){
    var body = document.body,
        tbl  = document.createElement('table');
    tbl.style.width  = '500px';
    tbl.style.border = '1px solid black';

    for(var i = 0; i < 5; i++){
        var tr = tbl.insertRow();
        for(var j = 0; j < 5; j++){
            var td = tr.insertCell();
            td.appendChild(document.createTextNode('ABC'));
            td.style.border = '1px solid black';
        }
    }
    body.appendChild(tbl);
}
tableCreate();
</script>

<p style="font-size:40px">
Hello World.
</p>

</body>
</html>


text:
Q: execute filter chain before admin generator symfony I need to call a filter added to the filter chain before calling an action build with the admin generator.
But it seems that the filter chain is not executed before the admin generator.
Is there any workaround?
Edit: I am using apostrophe sandbox. I need to change the database connection at runtime because I have one database per client and I am doing that in a filter. but for the pages that use admin generator the filter is not called and I get the following error.
at Doctrine_Manager->getCurrentConnection()
in SF_ROOT_DIR\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Manager.php line 558 ...
at Doctrine_Manager->getConnectionForComponent('Tag')
in SF_ROOT_DIR\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Core.php line 1090 ...
at Doctrine_Core::getTable('Tag')
in SF_ROOT_DIR\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\generator\sfDoctrineGenerator.class.php line 41 ...
at sfDoctrineGenerator->configure()
in SF_ROOT_DIR\lib\vendor\symfony\lib\generator\sfModelGenerator.class.php line 56 ...
at sfModelGenerator->generate(array('model_class' => 'Tag', 'theme' => 'aAdmin', 'non_verbose_templates' => 1, 'with_show' => , 'singular' => null, 'plural' => null, 'route_prefix' => 'a_tag_admin', 'with_doctrine_route' => 1, 'config' => array('list' => array('sort' => array('name', 'asc'), 'title' => 'Tags Admin', 'display' => array('=name', 'tag_aBlogPost', 'tag_aEvent', 'tag_aMediaItem', 'tag_aPage'), 'fields' => array('name' => array('label' => 'Tag'), 'tag_aPage' => array('label' => 'Pages'), 'tag_aMediaItem' => array('label' => 'Media'), 'tag_aEvent' => array('label' => 'Events'), 'tag_aBlogPost' => array('label' => 'Blog'), 'tab_aEvent' => array('label' => 'aEvent')), 'object_actions' => array(), 'actions' => array('new' => array('label' => ' New Tag', 'action' => 'new', 'params' => array('class' => 'a-btn big icon a-add')), 'clean' => array('label' => ' Clean Tags', 'action' => 'clean', 'params' => array('class' => 'a-btn big a-show-busy')))), 'form' => array('class' => 'aTagForm'), 'filter' => null, 'edit' => array('title' => 'Edit Tag'), 'new' => array('title' => 'New Tag')), 'moduleName' => 'aTagAdmin'))
in SF_ROOT_DIR\lib\vendor\symfony\lib\generator\sfGeneratorManager.class.php line 113 ...
at sfGeneratorManager->generate('aTagAdminGenerator', array('model_class' => 'Tag', 'theme' => 'aAdmin', 'non_verbose_templates' => 1, 'with_show' => , 'singular' => null, 'plural' => null, 'route_prefix' => 'a_tag_admin', 'with_doctrine_route' => 1, 'config' => array('list' => array('sort' => array('name', 'asc'), 'title' => 'Tags Admin', 'display' => array('=name', 'tag_aBlogPost', 'tag_aEvent', 'tag_aMediaItem', 'tag_aPage'), 'fields' => array('name' => array('label' => 'Tag'), 'tag_aPage' => array('label' => 'Pages'), 'tag_aMediaItem' => array('label' => 'Media'), 'tag_aEvent' => array('label' => 'Events'), 'tag_aBlogPost' => array('label' => 'Blog'), 'tab_aEvent' => array('label' => 'aEvent')), 'object_actions' => array(), 'actions' => array('new' => array('label' => ' New Tag', 'action' => 'new', 'params' => array('class' => 'a-btn big icon a-add')), 'clean' => array('label' => ' Clean Tags', 'action' => 'clean', 'params' => array('class' => 'a-btn big a-show-busy')))), 'form' => array('class' => 'aTagForm'), 'filter' => null, 'edit' => array('title' => 'Edit Tag'), 'new' => array('title' => 'New Tag')), 'moduleName' => 'aTagAdmin'))
in SF_ROOT_DIR\lib\vendor\symfony\lib\config\sfGeneratorConfigHandler.class.php line 82 ...
at sfGeneratorConfigHandler::getContent(object('sfGeneratorManager'), 'aTagAdminGenerator', array('model_class' => 'Tag', 'theme' => 'aAdmin', 'non_verbose_templates' => 1, 'with_show' => , 'singular' => null, 'plural' => null, 'route_prefix' => 'a_tag_admin', 'with_doctrine_route' => 1, 'config' => array('list' => array('sort' => array('name', 'asc'), 'title' => 'Tags Admin', 'display' => array('=name', 'tag_aBlogPost', 'tag_aEvent', 'tag_aMediaItem', 'tag_aPage'), 'fields' => array('name' => array('label' => 'Tag'), 'tag_aPage' => array('label' => 'Pages'), 'tag_aMediaItem' => array('label' => 'Media'), 'tag_aEvent' => array('label' => 'Events'), 'tag_aBlogPost' => array('label' => 'Blog'), 'tab_aEvent' => array('label' => 'aEvent')), 'object_actions' => array(), 'actions' => array('new' => array('label' => ' New Tag', 'action' => 'new', 'params' => array('class' => 'a-btn big icon a-add')), 'clean' => array('label' => ' Clean Tags', 'action' => 'clean', 'params' => array('class' => 'a-btn big a-show-busy')))), 'form' => array('class' => 'aTagForm'), 'filter' => null, 'edit' => array('title' => 'Edit Tag'), 'new' => array('title' => 'New Tag')), 'moduleName' => 'aTagAdmin'))
in SF_ROOT_DIR\lib\vendor\symfony\lib\config\sfGeneratorConfigHandler.class.php line 75 ...
at sfGeneratorConfigHandler->execute(array('C:/wamp/www/sfprojects/asandbox/plugins/apostrophePlugin/modules/aTagAdmin/config/generator.yml', 'C:\wamp\www\sfprojects\asandbox\apps\frontend/modules/aTagAdmin/config/generator.yml'))
in SF_ROOT_DIR\lib\vendor\symfony\lib\config\sfConfigCache.class.php line 108 ...
at sfConfigCache->callHandler('modules/aTagAdmin/config/generator.yml', array('C:/wamp/www/sfprojects/asandbox/plugins/apostrophePlugin/modules/aTagAdmin/config/generator.yml', 'C:\wamp\www\sfprojects\asandbox\apps\frontend/modules/aTagAdmin/config/generator.yml'), 'C:\wamp\www\sfprojects\asandbox\cache\frontend\dev\config/modules_aTagAdmin_config_generator.yml.php')
in SF_ROOT_DIR\lib\vendor\symfony\lib\config\sfConfigCache.class.php line 197 ...
at sfConfigCache->checkConfig('modules/aTagAdmin/config/generator.yml', 1)
in SF_ROOT_DIR\lib\vendor\symfony\lib\config\sfConfigCache.class.php line 249 ...
at sfConfigCache->import('modules/aTagAdmin/config/generator.yml', , 1)
in SF_ROOT_DIR\lib\vendor\symfony\lib\controller\sfController.class.php line 186 ...
at sfController->forward('aTagAdmin', 'index')
in SF_ROOT_DIR\lib\vendor\symfony\lib\controller\sfFrontWebController.class.php line 48 ...
at sfFrontWebController->dispatch()
in SF_ROOT_DIR\lib\vendor\symfony\lib\util\sfContext.class.php line 170 ...
at sfContext->dispatch()
in SF_ROOT_DIR\web\index.php line 10 ...


text:
Q: create custom JOptionPane input dialog that will be either closed in 5 seconds or closed by user's action. Details below I would like to have a customized InputDialog so that following code could work. I am creating an old fashion application. The InputDialog will be created once users click a button on a view. I am wondering if we could create a customized input dialog to have the feature that my title says. Just let me know if anything is unclear.
String s = MyCustomInputDialog("my question");
// show the input dialog that will be either closed in 5 seconds or closed by the user's action
System.out.println(s) // print null or print user's input

A: Check answers over in Closing A JOptionPane Programmatically , which has a really interesting hack to loop through all Windows to find the JOptionPane and kill it.


text:
Q: Converting infix expressions to postfix expressions I have a problem i can't find the wrong in this function it sometimes do well with any input but it cached when there is parentheses in the input {i want to know where is the wrong in this code and how to fix it , and Is there another better  way instead this way}
    public static String Converting_infix_expressions_to_postfix_expressions(String infix) throws Exception{
    StringTokenizer st = new StringTokenizer(infix);
    int numOF_tokens = st.countTokens();
    String postfix = "" ;
    for (int i = 1; i <= numOF_tokens; i++) {
        String term = st.nextToken();
        try {  // if it is an Float there is no problem will happen
            float x =  Float.parseFloat(term);
            postfix += x +" " ;
            System.out.println("term is number " + term);
        } catch (Exception e) {
            System.out.println("term is symbol " + term);
            if(stack.isEmpty())
                stack.push(term);
            else if(term == "(")
                stack.push(term);
            else if(term == ")"){
                while((String)stack.peek() != "(")
                    postfix += stack.pop() +" ";
                stack.pop();
            }

            else{
                int x = 0,y = 0;
                switch(term){
                case "+": x = 1; break;
                case "-": x = 1; break;
                case "*": x = 2; break;
                case "/": x = 2; break;
                }
                switch((String)stack.peek()){
                case "+": y = 1; break;
                case "-": y = 1; break;
                case "*": y = 2; break;
                case "/": y = 2; break;
                }
                if(x > y)
                    stack.push(term);
                else {
                    int x1 = x , y1 = y;
                    boolean puchedBefore = false;
                    while(x1 <= y1){
                        postfix += stack.pop() +" ";
                        if(stack.isEmpty() || stack.peek() == "(" ){
                            stack.push(term);
                            puchedBefore = true;
                            break;
                        }
                        else{
                            switch(term){
                            case "+": x1 = 1; break;
                            case "-": x1 = 1; break;
                            case "*": x1 = 2; break;
                            case "/": x1 = 2; break;
                            }
                            switch((String)stack.peek()){
                            case "+": y1 = 1; break;
                            case "-": y1 = 1; break;
                            case "*": y1 = 2; break;
                            case "/": y1 = 2; break;
                            }
                        }
                    }
                    if(!puchedBefore)
                        stack.push(term);
                }
            }
        }
    }
    while(!stack.isEmpty()){
        postfix += stack.pop() +" ";
    }
    System.out.println("The postfix expression is : " + postfix);
    return postfix;
}

A: You have a couple of problems with your code.

*

*You should make a custom string tokenizer since there may not be a space between a parenthesis and a number. Ex: (5 + 6)

*The try-catch block is not being used properly. Consider, first checking if the field is symbol then moving on to parsing it as a Float. This way you can avoid having most of your code appear in the catch block.

*The bug you are referring to can be fixed with the follow change to line 18.
while(!stack.isEmpty() && (String)stack.peek() != "(")


text:
Q: How do I combine the float values of two columns and put it in an another column of my dataframe? I am using the dataset- Meteorite Landings which can be found here- https://www.kaggle.com/nasa/meteorite-landings#meteorite-landings.csv
The dataset has a lot of missing values, after filling in the values of the columns- reclat and reclong, I tried to combine those in the form of strings and put them into the GeoLocation column.
reclat col:       reclong col:

0    50.77500     0      6.08333
1    56.18333     1     10.23333
2    54.21667     2   -113.00000
3    16.88333     3    -99.90000
4   -33.16667     4    -64.95000

The problem is that the combined value does not show up in the desired coordinate format as I want.
I am trying to combine the values of reclat and reclong, preferably in a coordinate format.
Combining the two values in string form and inserting it into the GeoLocation column
data['GeoLocation']=str(data['reclat'])+str(data['reclong'])

I expected the column of GeoLocation to have values of reclat and reclong appended together, but it's in a different format as shown below.
0    0        50.77500\n1        56.18333\n2       ...
1    0        50.77500\n1        56.18333\n2       ...
2    0        50.77500\n1        56.18333\n2       ...
3    0        50.77500\n1        56.18333\n2       ...
4    0        50.77500\n1        56.18333\n2       ...
Name: GeoLocation, dtype:object

A: Firstly, typecast all the float values to string:
data['reclat'] = data['reclat'].astype(str)
data['reclong'] = data['reclong'].astype(str)

Then, just add the value of two columns to produce output string. It will be appended.
data['GeoLocation'] = data['reclat'] + data['reclong']

I hope this is what you wanted. If not let me know accordingly.

A: data['GeoLocation'] = data['reclat'].astype(str) + ' ' + data['reclong'].astype(str)

Please try the above code.
Type cast the columns and you can concatenate into a single column.


text:
Q: Include a single jsp file multiple times Ok, so basically I have a jspf template file with a backing FragmentBean that I want to include multiple times in the same request page scope. When I include this template I pass it a different parameter value so I can identify which instance I'm dealing with inside the template and store the data correctly in a session map. The problem I'm having is any action I perform on one included instance of this template applies to all the other ones. So for example when I click a button to hide or unhide panels inside the template all of the included instances also hide and unhide their corresponding hidden panels. This lead me to realize that it is not creating new backing bean instances. It seems like I'm probably misusing jsp:include but how do I get the desired code-reuse of including a single jsp file multiple times?
I'm limited to JSF 1.2, JSTL 1.1 and JBoss 4.0.4. So no RichFaces ajax trickery. And yes I realize we need to upgrade. Another battle for another time.

A: You are right, in that it is using the same instance multiple times, so any event or action updates that specific managed bean and the same information is reflected everywhere you have included your page.
When you include multiple times, it does not mean a new instance every time.
What you can do is pass parameters to identify from where you are including and then do some functionality.
Another trick, is to declare multiple  declarations with a different session variable.


text:
Q: phpMyAdmin: "Choose Field to display" doesn't show off I want to display more columns in phpmyadmin's drop-down boxes when inserting records in related tables (by foreign key constraints).
I created two tables:

*

*tab1 with columns id (int), name (char).

*tab2 with columns id (int), idTab1 (int, FK).

tab2.idTab1 is related to tab1.id.
The problem is when visualizing the drop-down box in insert tab it displays only the available tab1.id records like 1 -, 2 -, ...
I'd like to know how to show tab1.name next each tab1.id record in drop-down box.
Someone told me to use "Choose Field to display", but this option doesn't show.

A: It's really the "Choose column to display" (phpMyAdmin 4+, for sure) that you want. It can be found by two ways:

*

*"Designer" page (main menu). The option it's in one of the top icons;

*"Relation View" page, that can be accessed by the "Structure" page (main menu). The link to the relation view is right below from the fields of the table.

A: You can do this with phpmyadmin's designer. After you created the Foreign key relation in the visual designer you can choose which column to display when inserting values into the table with the foreign key (Icon "Choose column to display").
Here is a nice little tutorial which also contains the solution to your problem.

A: You can lower the ForeignKeyMaxLimit to 0 to always display the popup for foreign key selection. This setting can be changed on a per-session-basis directly within phpMyAdmin (Homepage -> More settings -> Main frame [Tab] -> Edit mode [Tab] -> Foreign key limit) or in the config files of your installation.

A: May you can try Show/Hide table list
Go to phpmyadmin -> Designer -> Left Bar(Show/Hide table list) -> So you can check/uncheck table that you want to display


text:
Q: Does JScript Provide a Ternary Operator? Do we have a ternary operator in Jscript (as opposed to JavaScript)? If so, what is the syntax?

A: It's
expression ? expression : expression

just like C. It's a little looser, actually, because JavaScript is not strongly-typed. Thus the two possible "forks" of the operator can result in different types of values.
Thus:
alert(document.all ? "Hello from IE!" : "Hello from a non-IE browser!");

Most of the time, the differences between Microsoft's ECMAScript and those found in other browsers (or other server-side environments) aren't really that great, and for ordinary non-DOM code it's pretty rare to have to deal with such things.

A: yes it does.
test ? expression1 : expression2

A: Example:
var result = 5 > 10 ? '5 is greater than 10' : '5 is not greater than 10';

A: You can always use google to find language syntax, too.
The first result I got was, http://msdn.microsoft.com/en-us/library/be21c7hw%28v=vs.85%29.aspx.  It has examples like
var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");


text:
Q: Display some text in vertical order I am using HTML5 and want to display an string in vertical format:
For example: WELCOME can be displayed as:
W
E
L
C
O
M
E
Is it possible to achieve? If yes, how can I do this?
Note: In the example, there are two line break. Please avoid one line break.

A: You can use word-break with some small width:
p{
    width:10px;
    word-break: break-all;
}

JSFiddle

A: You could rotate text using. But for your case this might be better: http://www.youtube.com/watch?v=DcqmT8D_kzA#t=235
.rotate {
  -webkit-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  -o-transform: rotate(-90deg);
  transform: rotate(-90deg);

  /* also accepts left, right, top, bottom coordinates; not required, but a good idea for styling */
  -webkit-transform-origin: 50% 50%;
  -moz-transform-origin: 50% 50%;
  -ms-transform-origin: 50% 50%;
  -o-transform-origin: 50% 50%;
  transform-origin: 50% 50%;

  /* Should be unset in IE9+ I think. */
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

EXAMPLE: http://jsfiddle.net/cbDEK/

A: If you do not want to rotate the text, you can also use a big letter-spacing like so:
.text{
    letter-spacing: 999em;
    word-break: break-all;
}


text:
Q: How to prove that operator is not compact in $L_2 (\mathbb{R})$ I have the operator
$(Af)(x) = \int _{\mathbb{R}} e^{{-(x-t)^2}/2} f(t) dt$. It seems to me that it isn't compact and I'm looking for some general <=> criterion for integral operators to be compact on $L_2 (\mathbb{R})$.

A: Recall that if $g$ is $L^1$, then
$$
T_g:f\longmapsto f\ast g
$$
is bounded from $L^p$ to $L^p$ since $\|f\ast g\|_p\leq \|f\|_p\|g\|_1$. So with the $L^1$ function $g(t)=e^{-\frac{t^2}{2}}$, in particular, $T_gf(x)=\int e^{-\frac{(x-t)^2}{2}}f(t)dt=(f\ast g)(x)$ is bounded from $L^2$ to $L^2$.
Note that $T_g$ is unitarily equivalent to the multiplication operator by $\hat{g}$ via the Fourier transform. So $T_g$ is compact if and only if
$$
h\longmapsto \hat{g}h
$$
is compact from $L^2$ to $L^2$. As is well-known, a multiplication operator by $\theta\in L^\infty$ on $L^2(\mathbb{R})$ is compact if and only $\theta=0$ a.e. Since $\hat{g}\neq 0$ a.e., it follows that $T_g$ is not compact.

A: Do you mean
\begin{equation}
A:L^2(\mathbb{R}) \rightarrow L^2(\mathbb{R}), \ \ \ (Af)(x) = \int_{\mathbb{R}} e^{-(x-t)^2/2} f(t) dt \ ?
\end{equation}
An operator is compact if it maps bounded sets to relatively compact sets, that is, to sets whose closure is compact. A set is compact if every bounded sequence in it contains converging subsequence. I have the feeling that $A$ is compact, because the Fourier transform is $L^2$-isometry up to a constant and $A$ is mapped to the form $\hat{A}f(\omega) = g(\omega)f(\omega)$, where $g(\omega) = \int_{-\infty}^\infty e^{-x^2/2} e^{-i\omega x} dx$. An orthogonal moving box sequence $f_n(\omega) = \chi_{[n,n+1)}(\omega)$ in the Fourier domain is mapped to a sequence that converges to $0$ in $L^2$.

However, there is another orthogonal moving impulse sequence $f_k(t) = \textrm{sinc}(t-k)$, where $\textrm{sinc}(x) = \frac{\sin(\pi x)}{\pi x}$ for $x \neq 0$ and $1$ for $x = 0$. This time we will show that for any subsequence $f_{k_n}$ there is lower limit estimate for $||Af_{k_n} - Af_{k_m}||_2$, when $k_n$ and $k_m$ are far from each other. Hence $Af_{k_n}$ cannot be a Cauchy-sequence and hence cannot converge. We have
\begin{eqnarray}
|(\mathcal{F}Af_{k_n}-\mathcal{F}Af_{k_m})(\omega)|^2 & = & |\mathcal{F}Af_{k_n}(\omega) - \mathcal{F}Af_{k_m}(\omega)|^2 = |g(\omega)\mathcal{F}f_{k_n}(\omega) - g(\omega) \mathcal{F}f_{k_m}(\omega)|^2 \\
& = & |g(\omega) e^{-i k_n \omega} \mathcal{F}f_0(\omega) - g(\omega) e^{-i k_m \omega} \mathcal{F}f_0(\omega)|^2 \\
& = & |e^{-i \frac{1}{2} (k_m + k_n) \omega} (e^{i \frac{1}{2} (k_m - k_n)} - e^{-i \frac{1}{2}(k_m - k_n)\omega})g(\omega) \mathcal{F}f_0(\omega)|^2 \\
& = & |2ie^{-i\frac{1}{2} (k_m + k_n)\omega}\sin(\frac{1}{2}(k_m-k_n)\omega)g(\omega)\mathcal{F}f_0(\omega)|^2 \\
& = & 2 \sin^2(\frac{1}{2}(k_m-k_n)\omega)|g(\omega)\mathcal{F}f_0(\omega)|^2 \\
& = & 2 \frac{1}{2} (1-\cos((k_m-k_n)\omega)|g(\omega)\mathcal{F}f_0(\omega)|^2 \\
& = & |g(\omega) \mathcal{F}f_0(\omega)|^2 - \cos((k_m-k_n)\omega)|g(\omega)\mathcal{F}f_0(\omega)|^2
\end{eqnarray}
Hence
\begin{eqnarray}
||Af_{k_n}-Af_{k_m}||_2^2 & = & 2\pi||\mathcal{F}Af_{k_n}-\mathcal{F}Af_{k_m}||_2^2
\\
& = & 2\pi||g\mathcal{F}f_0||_2^2 - 2\pi \int_{-\pi}^\pi |g\mathcal{F}f_0(\omega)|^2 \cos((k_m-k_n)\omega) d\omega \ .
\end{eqnarray}
Now for sufficiently large differences $k_n-k_m$ we have
\begin{equation}
||Af_{k_n}-Af_{k_m}||_2^2 \geq \pi ||g\mathcal{F}f_0||_2^2
\end{equation}
because coefficients of Fourier series tend to $0$. This follows from the Riemann-Lebesgue lemma. Now $g$ is everywhere nonzero and $\mathcal{F}f_0$ = $\frac{1}{2\pi} \chi_{[-\pi,\pi]}$ hence the product is nonzero on the interval $[-\pi,\pi]$ and we have a lower limit. The result can be generalized to other convolution operators as follows. There has to be an interval $[a,b]$ s.t. $\neg(g=0 \ \textrm{a.e.})$. Otherwise $g=0\in L^2(\mathbb{R})$. Choose $f_0$ s.t. $\mathcal{F}f_0 = \chi_{[a,b]}$. Then the product $g\mathcal{F}f_0 \neq 0 \in L^2(\mathbb{R})$. Estimate now implies divergence.


text:
Q: How to disable any log for a thread I am using org.apache.log4j.Logger for logging and I am developing a jsp just for monitoring purposes.
This jsp is using classes that write logs (INFO level) not interesting for this monitoring, but annoying, as long as I want to execute this jsp very often.
So, my question is the next:
Is there any way to disable these INFO logs just for the thread where my jsp is running?
If there is not, maybe this approach might pay the bill:
Is there any way to tell log4j level for one given class is FATAL just for a few milliseconds?

A: There's no easy way to do this using simple log4j config.
However, you can have your code install a custom filter on the appropriate logger.  See the interface reference here:
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html

*

*Construct an object that implements
the filter you want.

*Find the logger using LogManager.getLogger("loggername")

*Insert the filter.

A: Is the thread-id being logged? If so, can't you just use grep -v to remove the annoying lines that are for that thread and INFO level?


text:
Q: Cross-platform solution for Arial font In my Swing application I use Arial font. Unfortunately it is rendered differently on different platforms:
Windows:

Mac OS X:

Linux:

Windows and Mac OS X variants look almost the same. Linux is quite different and seems to be not an Arial at all. Main problem is the different width of letters...
What would be the best solution that would render text similar to Windows variant on Linux? Probably some alternative fonts like for example Nimbus Sans L?
Some limitations: JRE cannot be supplied with the application and it should be very close to Arial.
Thanks!

A: Embrace platform variety. Given that different platforms have similar fonts with different metrics, let each component do the work of calculating its own preferred size by not interfering and by using layouts correctly. Here's a nice example with screenshots.

A: One solution may be load the font file using Font.createFont(). Here's a sample.

A: Did you try antialiasing, like this article
http://docs.oracle.com/javase/tutorial/2d/text/renderinghints.html

A: You can install Microsoft's free fonts on Linux and use them in Java. This includes an Arial font. This blog post shows you how: How to Install Windows Fonts in Java on Linux


text:
Q: Before update trigger is not working I have two objects, which is used to populate the field value from product object to quote lineitem object. Both the objects have unique field name (CPQQuoteLineItem__c  --> Product_Code__c, product --> name) both the objects have same values in the field
for update trigger is not working
trigger updateproductcode on CPQQuoteLineItem__c(after insert, before update) {
    if (trigger.isInsert) {
        list < CPQQuoteLineItem__c > quotelineitemrecords = [select id, ProductCode__c, Product_Code__c from CPQQuoteLineItem__c where id IN: trigger.new];
        for (CPQQuoteLineItem__c singlerecord: quotelineitemrecords) {
            list < Product2 > testproduct = [select id, Name from Product2 where Name =: singlerecord.Product_Code__c];
            for (Product2 testpro: testproduct)
                singlerecord.ProductCode__c = testpro.id;
            update singlerecord;

        }
    }

    if (trigger.isUpdate) {
        list < CPQQuoteLineItem__c > quotelineitemrecords = [select id, ProductCode__c, Program_TF__c, Product_Code__c from CPQQuoteLineItem__c where id IN: trigger.new]; {

            for (CPQQuoteLineItem__c singlerecord: quotelineitemrecords) {
                list < Product2 > testproduct = [select id, Name from Product2 where Name =: singlerecord.Product_Code__c];
                for (Product2 testpro: testproduct)
                    singlerecord.ProductCode__c = testpro.id;
                system.debug('testproduct' + singlerecord);
            }
        }
    }
}

A: You don't need to query the line item records, nor perform a recursive update, because you can modify the records in Trigger.new to save changes to the database. You should be querying all the product codes at the same time so you don't run in to bulk DML errors ("too many SOQL queries: 101"). There's no need to distinguish between a before insert and before update, even, since the logic should be identical.
Here's the revised code:
trigger updateproductcode on CPQQuoteLineItem__c(before insert, before update) {
  Map<String, Id> products = new Map<String, Id>();
  // Aggregate values to query
  for(CPQQuoteLineItem__c record: Trigger.new) {
    products.put(record.Product_Code__c, null);
  }
  // Query for record Ids
  for(Product2 record: [SELECT Name FROM Product2 WHERE Name = :products.keySet()]) {
    products.put(record.Name, record.Id);
  }
  // Update Trigger.new with queried values
  for(CPQQuoteLineItem__c record: Trigger.new) {
    record.ProductCode__c = products.get(record.Product_Code__c);
  }
}

This is just another example of the Aggregate Query Update pattern. It's very simple, yet one of the most commonly used patterns for bulkifying code.


text:
Q: System.Data.Entity.Core.EntityCommandExecutionException Occurred in MVC app Using EF I am about to create an Application Form with UUID as its unique key (not primary key).
I got the error:

An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
  Additional information: An error occurred while executing the command definition. See the inner exception for details.

Connection String To DB:
 connectionString="Data Source=(localdb)\v11.0;
                   Initial Catalog=FormsContext;
                   Integrated Security=True;
                   MultipleActiveResultSets=True;
                   AttachDbFilename=|DataDirectory|Forms.mdf"
 providerName="System.Data.SqlClient"

FormsContext.cs:
namespace ApplicationForm.Models
{
    public class FormsContext : DbContext
    {
        public FormsContext() : base("name=FormsContext")
        {
        }

        public System.Data.Entity.DbSet<ApplicationForm.Models.Form> Forms { get; set; }
...

The database is like this:
 FormsContext->Forms->{id,uuid,first,last...}

I am not so sure what happened this time. Would anyone help me to go through this?
Edit/Resolution
I wasn't sure how to check Inner Exception and I did some research on this. So when I read the error message in the Inner Exception, I could solve my problem.
I found out what the bug was. The query field is 'firstname' but my table column name is 'first'. They did not match. Once I changed the DB column name, it was working again.

A: In my case helped next:
1) press View Detail.. button:

2) Check your actual error:

Hope it helps for someone.

A:
found out what the bug was. The query field is 'firstname' but my table column name is 'first'. They did not match. Once I changed the DB column name, it was working again.

One must be diligent to keep each in sync if the database is always in flux.
Why?
EF is simply a set of mappings, a snapshot in time, and whether those mappings are to tables or stored procedures, it does not matter.
For any subtle change(s) to column names or foreign key constraints can have ripple effects to any old mappings and they need to be remapped/scaffolded into new structure(s); otherwise hence weird behaviors from old mappings.
At times, those effects can create obvious errors like you found or even more insidious non obvious logical errors which can provide working (compiled) software with subtle logic bugs. I have seen the logic bugs by experience and they do happen.
So always be wary to keep the EF mappings in sync.

I answered to a different EF question but in a similar vein.
I had run into a situation where in EF a mapped stored proc at runtime failed because an internal change in the stored proc saw that a sql cast had stripped out a column name from the result, and EF (mapped before the changed) failed. I have a screen shot in my answer which shows that EF/db changes can have a deleterious effect:
The data reader is incompatible . A member does not have a corresponding column in the data reader with the same name

A: Just in case this helps someone - I saw this error message. It turned out that I had changed the database associated with my EF model and hadn't set the connection string up properly.


text:
Q: Charge in dielectric material I'm trying to find a simple way to draw this but can't find a solution

A: I simplify the code and calculations of @Juan Castano by creating a pic named atom, then putting pics along paths (see option [sloped], no atan2 or angle calculation needed) from the origin to integer points inside a loop.

\documentclass[tikz,border=5mm]{standalone}
\begin{document}
\begin{tikzpicture}
\tikzset{pics/atom/.style args={major #1 minor #2}{code={%
\fill[red] (0,#2) arc (90:-90:#1 and #2);
\fill[green!50] (0,#2) arc (90:270:#1 and #2);
\draw (0,0) ellipse(#1 and #2);
}}}

\def\atompath{(0,0)--(\x,\y) pic{atom=major .4 minor \bb} node[right,scale=.6]{$+$} node[left,scale=.6]{$-$}}

\foreach \x in {-4,...,4}
\foreach \y in {-3,...,3}
{%
\pgfmathtruncatemacro\b{\x*\x+\y*\y}
\ifnum \b>0
\pgfmathsetmacro{\bb}{.08*sqrt(\b)}
\ifnum \x<0
\path[nodes={sloped,pos=1,xscale=-1}] \atompath;
\else
\path[nodes={sloped,pos=1}] \atompath;
\fi
\fi
}

% central charge
\draw[fill=red] (0,0) circle(.18) node[scale=0.6]{$+$} + (-135:.4) node[red]{$q$};
\end{tikzpicture}
\end{document}

A: This is a solution following John Kormylo's comment. I use a \foreach command to draw all the ellipses, but I rotate each one and change its minor axis according to its position.
\documentclass[border=2mm]{standalone}
\usepackage{tikz}

\definecolor{positive}{HTML}{FADDB9}
\definecolor{negative}{HTML}{7BC192}

\begin{document}
\begin{tikzpicture}
\foreach\y in {-3,...,3} \foreach\x in {-4,...,4} % row, column
{%
  % atan2 implementation
  \ifnum\x = 0
    \ifnum\y > 0
      \def\a{90}
    \else
      \def\a{-90}
    \fi
  \else\ifnum\x > 0
    \pgfmathsetmacro\a{atan(\y/\x)}     % angle in quadrants  I and IV
  \else
    \pgfmathsetmacro\a{atan(\y/\x)+180} % angle in quadrants II and III
  \fi\fi
  % dipoles
  \pgfmathtruncatemacro\b{\x*\x+\y*\y}
  \ifnum\b > 0
    \pgfmathsetmacro\bb{0.08*sqrt(\b)} % semi-axis b = distance to the origin (scaled)
    \begin{scope}[shift={(\x,\y)},rotate=\a]
      \fill[positive] (0,\bb) arc (90:-90:0.4 and \bb);
      \fill[negative] (0,\bb) arc (90:270:0.4 and \bb);
      \draw (0,0) ellipse (0.4 and \bb);
      \node[transform shape,scale=0.6] at ( 0.2,0) {$+$};
      \node[transform shape,scale=0.6] at (-0.2,0) {$-$};
    \end{scope}
  \fi
}
% central charge
\draw[fill=red] (0,0) circle (0.15) node[scale=0.6] {$+$} node [red,below left] {$q$};
\end{tikzpicture}
\end{document}

Edit: Two changes:

*

*Following Sebastiano's suggestion I adapted the code for positive and negative charges. I added a parameter q that should takes values +1,-1 and that changes accordingly the x-axis. Then I needed an \ifnum for display the central charge.

*atan2. Why not use the built-in function? You'll be thinking. Me too...

The new (and shortest) code:
\documentclass[border=2mm]{standalone}
\usepackage{tikz}

\definecolor{positive}{HTML}{FADDB9}
\definecolor{negative}{HTML}{7BC192}

\def\q{-1} % central charge: +1,-1 we only need the sign

\begin{document}
\begin{tikzpicture}
\foreach\y in {-3,...,3} \foreach\x in {-4,...,4} % row, column
{%
  % dipoles
  \pgfmathsetmacro\a{atan2(\y,\x)}
  \pgfmathtruncatemacro\b{\x*\x+\y*\y}
  \ifnum\b > 0
    \pgfmathsetmacro\bb{0.08*sqrt(\b)} % semi-axis b = distance to the origin (scaled)
    \begin{scope}[shift={(\x,\y)},rotate=\a,x=\q cm]
      \fill[positive] (0,\bb) arc (90:-90:0.4 and \bb);
      \fill[negative] (0,\bb) arc (90:270:0.4 and \bb);
      \draw (0,0) ellipse (0.4 and \bb);
      \node[transform shape,scale=0.6] at ( 0.2,0) {$+$};
      \node[transform shape,scale=0.6] at (-0.2,0) {$-$};
    \end{scope}
  \fi
}
% central charge
\draw[fill=red] (0,0) circle (0.15) node [red,below left] {$q$};
\ifnum\q = 1
  \node[scale=0.6] at (0,0) {$+$};
\else
  \node[scale=0.6] at (0,0) {$-$};
\fi
\end{tikzpicture}
\end{document}

And the same picture with a negative central charge:


text:
Q: Android play video from url problem I have .mp4 file. If I placed it in the memory card, android's default video player can play it normally. But If I upload it to the web server and try to play it through the web browser of Android, it is giving mag saying, "Sorry, the video is not valid for seaming to this device."
The same is happening is I want to play it through my App. I used the following code:
private SurfaceHolder holder;
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource("http://www.languagehostess.com/videos/aka1.mp4");
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

It is giving the follwing error:
Command PLAYER_INIT completed with an error or info PVMFFailure

What is the problem related the that video or code?

A: You need to check the Android Video Encoding Recommandations . Make sure that your video is encoded with the supported code, and your video respects the resolutions. I had the exact same issues and after the video were properly encoded the streamming worked.
Also if you didn't noticed yet, usually the emulator does not play them, and you'll have to test on a real device.


text:
Q: Spring JPA returns data for wrong column Something as simple as a MySQL native query like this:
SELECT image_filename FROM article

using this entity
@Entity
@Table(name = "article")
public class Article {
    @Id
    @Column(name = "id")
    private String id;

    @Column(name = "title")
    private String title;

    @Column(name = "summary")
    private String summary;

    @Column(name = "content")
    private String content;

    @Column(name = "image_filename")
    private String imageFilename;
}

returns the data from a different field called summary.  I've checked the SQL table and it does not have this issue.
The issue occurs in all sorts of other queries.  What would cause this?

A: I was able to solve this problem by making sure the columns in my create table statement, entity, result set mapping, and native query were all in alphabetical order (except for the primary key, which is first).
It seems very strange to me that JPA would require this, and will jumble up the columns if you don't do this.


text:
Q: How do you pass a JavaScript variable into an HTML input field for this particular case? There is a function that calculates and displays the difference of 2 time variables the user selects in separate drop down lists. The display is invoked when the paragraph tags are used in the form. Function below:
<script type='text/javascript'>//<![CDATA[
        $(window).load(function () {
            $(document).ready(function () {
                function calculateTime() {
                    //get values
                    var valuestart = $("select[name='timestart']").val();
                    var valuestop = $("select[name='timestop']").val();

                    //create date format
                    var timeStart = new Date("01/01/2007 " + valuestart).getHours();
                    var timeEnd = new Date("01/01/2007 " + valuestop).getHours();

                    var hourDiff = timeEnd - timeStart;

                    $('p').html("Total Hours: " + hourDiff)

                }

                $("select").change(calculateTime);
                calculateTime();

            });
        });//]]>

    </script>

The function works. However, I'm needing the "difference in time" value to be passed to an HTML input tag and displayed instead of simply being displayed when paragraph tags are used.
Is there be a way to do this?

A: Yes:
$("input").val(hourDiff);


text:
Q: HTTP Error when trying to connect to a channel in Pubnub I am trying to connect to a channel in Pubnub using an application in Android Studio. How do I fix this?
SUBSCRIBE : ERROR on channel my_channel : [Error: 103-1] : HTTP Error. Please check network connectivity. Please contact support with error details if issue persists.

A: Its too late to answer , but might help someone else.
Pub Nub uses internet and adding internet permissions to manifest solved my problem . This is not mentioned in pub nub documentation .
<uses-permission android:name="android.permission.INTERNET" />


text:
Q: What is meant by "vacuum polarization"? When we talk about vacuum polarization in effects like the Lamb Shift, what is actually being polarized? What effects does it have?

A: In quantum field theory particles like electrons are not the fundamental objects. Instead the fundamental objects are the quantum fields. These fields have quantum states, just like all quantum objects, and some of these states appear to us as particles. So when we observe an electron we are actually observing a particular state of the quantum field that looks to us like an electron.
Like all quantum objects the quantum fields have a ground state i.e. a lowest energy state. If a field was completely non-interacting, i.e. if the particles the field described did not interact with each other or with anything else, then the field would be zero in the ground state and would have zero energy. However the particles in the Standard Model all interact with each other and as a result all the fields interact and become entangled, and the result is that the ground state is hideously complicated and far too complicated for us to calculate it. Instead we have to approximate its properties using perturbation theory, and this leads us to the popular science description of the vacuum as a roiling mass of virtual particles (though this is a metaphor and not actually true).
So far so good, but if we introduce an electron then we no longer have a vacuum and the vacuum near the electron changes as a result of the perturbation introduced by the presence of the electron. In popular science terms the electron interacts with all the virtual particles present in the vacuum state, and this slightly changes the properties of the electron. In the case of the Lamb shift we have an electron bound into a hydrogen atom, and the interaction with the vacuum slightly changes the energy of the hydrogen atom. It is a very small change, but it is measurable because the shifts in the energy levels of the hydrogen atom can be detected in its absorption and emission spectra.
So the vacuum polarisation is the change in the quantum field ground state caused by the presence of a charged particle like an electron. If you look at the Wikipedia article you linked it says:

In quantum field theory, and specifically quantum electrodynamics, vacuum polarization describes a process in which a background electromagnetic field produces virtual electron–positron pairs that change the distribution of charges and currents that generated the original electromagnetic field.

Though we should emphasise that the virtual electron–positron pairs are just a computational device for calculating the quantum field ground state.


text:
Q: How do I get the forecolor of an control? How do you get the color of a control, such as a label or rectangle? I need to do something like this:
if (label.foreground == #FFFFFF)
    Messagebox.Show("Branco!").

For awhile, I resolved my case with this:
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromRgb(255, 255, 255);
if (rec.Fill == mySolidColorBrush)
    MessageBox.Show("Branco!");

Here are the errors I'm getting when I try the answers already posted:

A: Now that I know you're using WPF, here's how to set the color on your label. Use the Foreground property and set it to a valid Brushes value.
if (label.Foreground = Brushes.White)
    MessageBox.Show("Branco!");

Same with the rectangle:
var rect = new Rectangle();
rect.Fill = Brushes.Green;

A: if (label.ForeColor == System.Drawing.Color.Black)
{
    // Do something here
}

A: according to MSDN the Type of ForeColor is System.Drawing.Color, which mean you need to compare your element color with a predefined color in System.Drawing.SystemColors
EDIT
kindly check these question
Changing background color of the form with hexadecimal code
convert hex code to color name
try something like this
if (label.ForeColor == Color.FromArgb(0xFFFFFF)) Messagebox.Show("Branco!");


text:
Q: test if two strings are different in rake file In a rake task, I want to execute a commande conditionally, but the string comparison does not work as expected. Here is what I have in my rake task:
puts "compare ('#{fetch(:stage)}' != 'production')"
if fetch(:stage) != 'production' then
  puts 'they are different'
end

I expect that puts 'they are different' is skipped, since the two strings are equal. But the statement is executed nonetheless, as the output proves:
compare ('production' != 'production')
they are different

I guess this is because the first is a variable of type sting while the second is a constant ? Obviously string comparisons work differently in ruby. What is the 'ruby way' to do it ?


text:
Q: Converting int to string with a specific format I'm trying to convert an classical integer value like:
2000

into a format like this:
2.000,00

I have tried the following methods:
String.valueOf(input.format());

And this method:
private String getCents(Decimal x){
    String y = String.valueOf(x);
    String z = '.';
    if(y.contains(',')) z = ',';
    y = y.substring(0, y.indexOf(z));
    if(x - Decimal.valueOf(y) == 0)
        return String.valueOf(x.format()) + z + '00';
    else return String.valueOf(x.format());
}

But the string class doesn't contains the valueOf method for some reason. Is there any other way to do this ?

A: The class String does not contain the method valueOf, because this ain't Java, you know.
The method you are searching for is ToString, which allows a format-provider as an argument. The simplest way is another string which defines the format.
    int i = 2000;
    Console.WriteLine(i.ToString("#,##0.00"));
    Console.ReadLine();

This will do what you want to do.
Read more about format-providers in the docs of the ToStringmethod.

A: given en-US culture
this will do:
string.Format(CultureInfo.GetCultureInfo("en-US"), "{0:N}", 2000)


text:
Q: What is this Weierstrass' proof of uniqueness of $\mathbb{R}$ and $\mathbb{C}$ algebras? I'm reading Derbyshire's Unknown Quantity.

It's an interesting exercise to enumerate and classify all possible algebras. Your results will depend on what you are willing to allow. The narrowest case is that of commutative, associative, finite-dimensional algebras over (that is, having their scalars taken from) the field of real numbers $\mathbb{R}$ and with no divisors of zero. There are just two such algebras: $\mathbb{R}$ and $\mathbb{C}$, a thing proved by Weierstrass in 1864.

What is this proof? I've googled Weierstrass algebra proof but found mainly the Stone-Weierstrass Theorem, which I'm not sure if this is the proof.

A: I think the author meant Frobenius clasiffication of real division algebras (see for example Why are the only division algebras over the real numbers the real numbers, the complex numbers, and the quaternions?) that its an stronger result, so if you want to add commutativity you loose the quaternions.


text:
Q: How to wait until an array of tasks has finished? I have an array of Task<T> objects and would like to block until all have returned.  How would I do this? (This is in a debugging view so performance is not an issue).
Basically, what is the task library equivalent of jquery's $.when?

A: If you want to block, you can use Task.WaitAll(yourTasks);. If you want to use a continuation that fires when they're all done (and are either using .NET 4.5 or the AsyncTargetingPack for .NET 4.0), you can use Task.WhenAll(yourTasks).ContinueWith(t => ...);

A:  Task.WaitAll(arrayOfTasks); ///.....


text:
Q: Dr. Java: Static Error: This class does not have a static void main method accepting String[] when running program I am taking my second Java class ever, and was told by my professor to use Dr. Java. We have started learning GUI, and he has given us some sample code as examples:
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.stage.*;
import javafx.collections.*;

public class HelloWorldMain extends Application{
 public void start(Stage primaryStage){
  FlowPane pane = new FlowPane();

  // put all controls on 'pane'
  Label lblHello = new Label("Hello");
  pane.getChildren().add(lblHello);

  Button btnHello = new Button("Hello World");
  pane.getChildren().add(btnHello);

  TextField txtHello = new TextField("Hello");
  pane.getChildren().add(txtHello);

  PasswordField pass = new PasswordField();
  pane.getChildren().add(pass);

  CheckBox cbHello = new CheckBox("Hello");
  pane.getChildren().add(cbHello);

  RadioButton rbMale= new RadioButton("Male");
  RadioButton rbFemale = new RadioButton("Female");
      pane.getChildren().add(rbMale);
      pane.getChildren().add(rbFemale);

  ToggleGroup group = new ToggleGroup();
  rbMale.setToggleGroup(group);
  rbFemale.setToggleGroup(group);

  ChoiceBox cbColors = new ChoiceBox();
  cbColors.setItems(FXCollections.observableArrayList("Red", "Green", "Blue"));

  pane.getChildren().add(cbColors);

  Scene scene = new Scene(pane, 300, 200);
  primaryStage.setScene(scene);
  primaryStage.show();
 }
}

However, when I try to run this in Java, I get the following error:
Static Error: This class does not have a static void main method accepting String[].
Professor is not able to help me, and I don't see an answer to this exact question. Any help is appreciated!


text:
Q: Removing NaNs from imported lists I have imported data for basket analysis, where each row of my data represents a shopping basket. I want to import this into a list of tuples, but when I do this I get lots of NaN values, as each list is the length of the maximum basket.
How can I remove these NaN values so I can see each basket correctly?
[['ItemA', 'ItemB', 'ItemC', 'ItemD', nan, nan, ...],

Here is my code so far:
import pandas as pd
data = pd.read_csv('basket_analysis_sample_2_small.csv')
data = data.values.tolist()


text:
Q: Clicking button within span with no ID using Selenium I'm trying to have click a button in the browser with Selenium and Python.
The button is within the following

            Download Slides

Chrome's dev console tells me the button is within  but I have no idea how to reference the button for a .click().

A: Well, if you just want to click on an element without an id or name, I'd suggest three ways to do it:

*

*use xpath:
driver.find_element_by_xpath('//*[@id="generate"]/span')

*use CSS selector:
driver.find_element_by_css_selector('#generate > span')

*Just try .find_element_by_tag_name() like:
driver.find_element_by_id('generate').find_elements_by_tag_name('span')[0]

Note that this way first try to get the generate
 element by it's id, and then finds all the  elements under that
.
Finally, gets the first  element use [0].


text:
Q: PHP Excel return false to string with special chars I have several strings from a form ($_POST var), some of them with special chars (ñ, á, é, etc.). When I create the Excel file with these $_POST vars, all cells print the right information but the ones with special chars prints FALSE.
Here's a piece of  code:
for ($j=1; $j<$_POST["z"]; $j++) {
$fila_despacho = $j+1;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$fila_despacho, '03')
->setCellValue('B'.$fila_despacho, $_POST["servicio".$j])
->setCellValue('C'.$fila_despacho, trim ($_POST["comuna".$j]))
->setCellValue('D'.$fila_despacho, 1)
->setCellValue('E'.$fila_despacho, trim($_POST["nombre".$j]))
->setCellValue('F'.$fila_despacho, trim($_POST["direccion".$j]))
        ->setCellValue('G'.$fila_despacho, trim($_POST["num".$j]));
}//endfor

About UTF-8, I don't know how to check that, I'm new at this. Can you tell me how?

A: Change to UTF-8 before setting the cell value. Use utf8_encode(). Example:
$objPHPExcel->getActiveSheet()->setCellValue('A1', utf8_encode($descripcion));

Later on you can save the file, for example with:
header('Content-Type: application/vnd.ms-excel;  charset=UTF-8');
header("Content-Disposition: attachment;filename='$archivo'");


text:
Q: Set maximum width for UITableViewCell I have a UITableViewController with system and custom cells.

Problem 1) Top two cells with Default style.
titleLabel have a name, accessoryView have a UITextField.
On iPad, if textfield contains long text - it overlaps label.
How can I limit maximum width for textfield? VFL?
Problem 2) Bottom custom cells have some elements (labels, buttons) contained in cell's contentView.
Sizes and position of elements inside contentView are controlled by VFL.
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
    super.init(style: .Default, reuseIdentifier: reuseIdentifier)

    let img = UIImageView()
    contentView.addSubview(img)

    let label = UILabel()
    contentView.addSubview(label)

    let button = UIButton()
    contentView.addSubview(button)

    contentView.vfls([ // just adds NSLayoutConstraint
        "H:|-15-[type(20)]-[label]-10-[delete(30)]-7-|",
        "V:|-15-[type(20)]->=0-|",
        "V:|[label]|",
        "V:|-10-[delete(30)]->=0-|"
    ], views: [
        "type": img,
        "label": label,
        "delete": button,
    ])
}

How can I limit maximum width of cell (like top two system cells) and hold it at center of cell.
I tried to place all elements in new container view and control it size and position via VFL too - but no luck.


text:
Q: pip3 install not working invald syntax? (windows) I've tried using the pip3 install function multiple times on Python 3.9 but it never worked. I first tried it with JupyterNotebook and ended up using Anaconda to install Jupyter. I am currently trying to install Twint and InstagramOSINT but every time I use pip3 install I get an error message saying SyntaxError: Invalid Syntax. I checked to see if I have pip3 installed on my PC and I do.

A: you need to run powershell as admin otherwise you will get this error.


text:
Q: How to continue if grunt-contrib-csslint throws error and how to exclude some files?
   I tried specifying force: true for grunt-contrib-csslint to continue even if error occurs as follows, but it does not seem to work, kindly help.
module.exports = function (grunt) {
    grunt.initConfig({

    // define source files and their destinations
    csslint:{
       options: {
           force: true,
           absoluteFilePathsForFormatters: true,
           formatters: [
               {id: 'compact', dest: 'quality/report/css/compact.xml'}
           ]
       },
       strict:{
           options:{
               force: true,
               import:2,
               "box-model":false,
           },
           src:['src/main/webapp/public/css/*.css'],
       },
       lax: {
            options: {
                import: false
            },
       src: ['src/main/webapp/public/css/ng-grid.css']
      }
   }
   });
   // load plugins
   grunt.loadNpmTasks('grunt-contrib-csslint');

       // register at least this one task
       grunt.registerTask('default', [ 'csslint' ]);
       };
       }};

The 'lax' property also does not seem to work and it still picks the files specified there? Kindly point out the problem with this also.
Thanks,
Paddy

A: To insert the following code in registerTask.
You cannot set force option for csslint but you can set force option for grunt.
// set the grunt force option
grunt.option("force", true);

// register at least this one task
grunt.registerTask('default', [ 'csslint' ]);

A: To just run the lax option try:
grunt.registerTask('default', [ 'csslint:lax' ]);

If you want Grunt to continue on errors, run:
grunt --force

A: You can exclude certain files using  "!" in the csslint:check:src array as follows:
    csslint: {
        options: {
            csslintrc: '.csslintrc'
        },
        check: {
            src: [
                '<%= yeoman.app %>/css/**/*.css',
                '!<%= yeoman.app %>/_scss/**/*.scss'
            ]
        }
    },

In the case above (from the Grunfile.js file) we're telling grunt to process .css files, but to ignore .scss files.

A: There is a npm package for running a specific task with force mode, so you don't have to use the force option globally.
It's called 'grunt-force-task' and can be found here:
https://github.com/floriangosse/grunt-force-task
A solution for the csslint-question would look like this:
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.registerTask('default', [ 'force:csslint' ]);

Besides that running a specific task with force flag is in discussion in the grunt main repository atm. Maybe there will be some changes to grunt itself in the future. See:
https://github.com/gruntjs/grunt/issues/810


text:
Q: Usage of TILDE inside a complex jQuery/CSS3 selector I am struggling to understand a jQuery selector that I found inside a jsFiddle (http://jsfiddle.net/Pm3cj/3/). The selector is:
'~.container, ~:has(.container)'

What is the meaning of the tilde?

*

*is it a kind of :not ?

*is it some sort of the partial match ~= operator ?

*is it some variation of the "next siblings" selector?

I have searched a lot on the jQuery and the W3C sites, without finding such an usage of tilde. At least I did not recognize it.
Anybody could tell me where such usage of tilde is explained?

A: Remember jQuery selector syntax is based on CSS selector syntax, and in CSS the tilde denotes "any of the following siblings." So
`~:has(.container)`

...finds any proceeding siblings that have the class container.

A: This would be an awkward comment, so here goes:
Here's an example;
[att~=val]

and from the docs;

Represents an element with the att attribute whose value is a white
  space-separated list of words, one of which is exactly "val". If "val"
  contains white space, it will never represent anything (since the
  words are separated by spaces). If "val" is the empty string, it will
  never represent anything either.

The following selectors illustrate the differences between "=" and
  "~=". The first selector will match, for example, the value "copyright
  copyleft copyeditor" for the "rel" attribute. The second selector will
  only match when the "href" attribute has the value
  "http://www.w3.org/".

a[rel~="copyright"]
a[href="http://www.w3.org/"]

From reading this, I hope you could possibly understand the physical use for this. It allows you to select an 'includes' as such. Since there isn't really an ':includes' selector, a '~' can be used, quite commonly with a :contains.

I believe in your example,
'~.container, ~:has(.container)'

Is testing if you can 'find' a class container anywhere after this, or an element that 'includes' this container anywhere after your 'button clicked' element.


text:
Q: Using Excel to create calculation sheets with a 5mm grid In my office we have calculation pads for hand writing calculations. I also have some spreadsheets I use and would like to make them look the same. I have a few problems.

*

*Setting a 5mm grid. I found that you can't set a grid to exactly 5mm. Using Excel to make a grid in millimeters.
I can work around this by setting 2 columns slightly wider than 5mm, and the 3rd column slightly under 5mm, to get an approximate average. (I found that it doesn't actually print the size is says anyway, 5.03 was coming out slightly larger than this). I have printed with a grey grid successfully.

*The problem I'm having is that when I have a number with 3 digits or more, it doesn't fit within the cell and turns into a #.
What I would like is for it to continue over the top of the next cell, as happens with text.

*When I insert our company logo (as a picture), I can't see the gridlines.
Can this be changed?

*Perhaps I could scan our calculation pad and set it as a watermark?
I haven't figured out how to do this.

A: I am able to get a 5.01 mm by 5.01 mm grid by adjusting the print scaling settings.
Under Page Setup | Scaling, change the value to 10%. Then adjust the row height and the column width to 5 mm and Excel will round it to 5.01 mm.
Keep in mind that a font size of 60 points at 10% scaling will print at 6 points. A 3-digit number of 6-point Calibri will display in a cell with width 5.01 mm.

A: Instead of messing with points and "character widths" that vary by font, switch to "Page Layout" view.
In "Page Layout" view, one can use real measurements like "mm" and "in" for BOTH height and width. So not only are you directly specifying the measurement you desire, you are working in the same units for both height and width which is essential for square boxes such as a graph-like grid has.


text:
Q: Specific solution to the $1D$ wave equation So my current solution to the $1D$ wave equation is (with my given boundary and initial conditions):
$$y(x,t) = \sum_{n=1}^\infty C_n\cdot \sin\frac{n \pi x}{2 l}\cdot\cos\frac{n \pi c t}{2 l}$$
However there is one final initial condition that is piecewise, I'm unsure of how to apply this and the solutions expected are of a infinite series (fourier series).
The last initial condition is:
$$y(x,0)= \begin{cases}
     R\cdot\frac{x}{l} & \quad 0\le x\le 1 \\
    R\cdot\left(2 - \frac{x}{l}\right) & \quad l\le x\le 2 l
\end{cases}$$
Any help or advice on solving is much appreciated.

A: Assuming all of our changes are correct, you can get all the $C_n$ by using the formula of the Fourier sine series coefficients:
The solution tells you that $y(x,0)=\sum_{n=1}^\infty C_n\sin\left(\frac{n\pi x}{2l}\right)$, and the condition tells you that this series must equal that piecewise function.
Thus $$C_n=\frac{1}{l}\int_0^{2l}y(x,0)\sin\left(\frac{n\pi x}{2l}\right)dx.$$
Since the function is given piecewise you have to break it up into two integrals:
$$C_n=\frac{1}{l}\int_0^l R\cdot\frac{x}{l}\sin\left(\frac{n\pi x}{2l}\right)dx+\frac{1}{l}\int_l^{2l}R\left(2-\frac{x}{l}\right)\sin\left(\frac{n\pi x}{2l}\right)dx$$
It is kind of tedious to make sure you don't lose any of these constants while integrating, but you should be able to solve it from here (look up $\int x\sin(ax)dx$ in a table to make it go quicker if you want).


text:
Q: How to create bmp file from hex data in python? The hex data array only contains the gray color value, do not have any bmp file information.
But I know the resolution(width & height in pixels), the image is gray color, which means each pixel is 8 bit.
Any tools(online or offline) or code to generate bmp file from the data?
For example , the following code not work, the resulution is 8*33
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

s = "FFFFFFFF B0A7FFFF FFFFFFB3 807D8EFF FFFFFF94 707783CC FFFFFF89 7A8988A4 FFFFFFAD 929298BE FFFFFFAD 979AA8E2 FFFFFFAF 8991A9FF FFFFFF9F 808BA6FF FFFFFFAB 8694AFFF FFFFFFB2 8A96A0FF FFFFFFA8 859496FF FFFFFFB3 88809ADA FFFFFFA6 7B728DD7 FFFFFF85 6F7084D4 FFFFFF86 66647BDA FFFFFF8D 606482DD FFFFFF8B 666788DC FFFFFF7B 616282CE FFFFFF86 63657AC2 FFFFFFA1 72697FCB FFFFFF9B 75636FC6 FFFFFF88 6B596EC1 FFFFFF8B 675A80D5 FFFFFFA0 6D5E79DE FFFFFF8F 6B5C73FF FFFFD67F 605E8FFF FFFFDA7F 665B96FF FFFFD384 645A86FF FFFFFF84 6F6E86FF FFFFFFBE 979DC0FF FFFFFFFF C2CCFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFCBB9 9EB7FFFF FFBEA17C 677A99FF FFC59F66 565972C5 BACC9D70 595A76CA 9E997665 5E699EE0 977B6A6B 7F94B0FF FFBDA5A4 C4D9FFFF"

data = s.replace(" ", "").decode('hex')
plt.imsave('filename.bmp', np.array(data).reshape(8,33), cmap=cm.gray)

A: I was looking for an answer to a similar question and was unable to locate a 'quick' understandable solution in 'pure' python.
So I wrote some code to create a bitmap (from character array data which is converted to RGB values in the example). Please read comments after MIT license of code example below. They describe the information one needs to create a bitmap from any data.
I incorporated information from http://blog.paphus.com/blog/2012/08/14/write-your-own-bitmaps/ and enter link description here
My output was:

#!/usr/bin/python
# ----------------------- START MIT LICENSE -----------------------
# Copyright (c) 2018 Benjamin Spiegl

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ----------------------- END MIT LICENSE -----------------------

# The pixel data has to be written with some minor modifications.
# First, the bottom row of the image appears first in the data.
# If you forget this step your image will be vertically flipped.
# Second, the pixes are written in BGR (blue - green - red) format, which is the opposite of the normal RGB.
# Finally, at the end of each row you must pad it with bytes till it is a multiple of 4.
# All numbers in the headers must be LITTLE-ENDIAN.
# For instance, when representing 54 as four bytes, those four bytes must be 54, 0, 0, 0.
# To represent 24 as two bytes, the two bytes must be 24, 0.

from numpy import array
from math import floor

def make_hex_list(int_val=None, force_byte_len=None, little_endian=True):
    if int_val is None:
        return []
    raw_pix_hex = hex(int_val)[2:]
    first_hex_str = ''  # is falsy
    if len(raw_pix_hex) % 2:  # odd number of hex vals
        first_hex_str = '0x0' + raw_pix_hex[0]
        raw_pix_hex = raw_pix_hex[1:]
    if first_hex_str:
        raw_pix_hex_list = [first_hex_str] + ['0x' + raw_pix_hex[lit_pair_idx * 2:lit_pair_idx * 2 + 2]
                                              for lit_pair_idx in range(int(floor(len(raw_pix_hex) / 2)))]
    else:
        raw_pix_hex_list = ['0x' + raw_pix_hex[lit_pair_idx * 2:lit_pair_idx * 2 + 2]
                            for lit_pair_idx in
                            range(int(floor(len(raw_pix_hex) / 2)))]  # max 4 bytes (32 bit) -> should be ok
    if force_byte_len and len(raw_pix_hex_list) != force_byte_len:  # force 4 bytes
        raw_pix_hex_list = ['0x00'] * (force_byte_len - len(raw_pix_hex_list)) + raw_pix_hex_list
    elif len(raw_pix_hex_list) > 4:
        raise OverflowError('base matrix too large for 32 bit bitmap.')
    if little_endian:
        return list(reversed([int(hx, 16) for hx in raw_pix_hex_list]))
    else:
        return [int(hx, 16) for hx in raw_pix_hex_list]

# A=yellow, T=red, C=green, G=blue, D=grey, N=black
bmp_BGR_colors = {'A': (0, 255, 255), 'T': (0, 0, 255), 'C': (0, 255, 0), 'G': (255, 0, 0),
                  'N': (0, 0, 0), 'D': (150, 150, 150)}

bmp_name = 'bitmap_test.bmp'
magnify = 16
mybase_arr = array([['G', 'A', 'G', 'A', 'D', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['G', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N'],
                    ['N', 'A', 'G', 'A', 'A', 'D', 'T', 'T', 'A', 'N']])
arr_height, arr_width = mybase_arr.shape
# prepare header information
pixel_width = arr_width * magnify  # force 4 bytes
pixel_height = arr_height * magnify  # force 4 bytes
linepad = pixel_width * 3 % 4  # ensure valid row bytes (3 bytes per pixel; 1 per color channel)
total_pad = pixel_height * linepad
pix_offset = [0x36, 0x00, 0x00, 0x00]  # force 4 byte
raw_pix_data_size = pixel_width * pixel_height * 3 + total_pad
raw_pix_data_size_hex_list = make_hex_list(int_val=raw_pix_data_size, force_byte_len=4)
file_size = 0x36 + raw_pix_data_size  # force 4 byte
# create header values for byte conversion
header_vals = [0x42, 0x4d] + make_hex_list(int_val=file_size, force_byte_len=4) + [0x00]*4 + pix_offset + \
              [0x28, 0x00, 0x00, 0x00] + make_hex_list(int_val=pixel_width, force_byte_len=4) + \
              make_hex_list(int_val=pixel_height, force_byte_len=4) + \
              make_hex_list(int_val=1, force_byte_len=2) + \
              make_hex_list(int_val=24, force_byte_len=2) + make_hex_list(int_val=0, force_byte_len=4) + \
              raw_pix_data_size_hex_list + [0x13, 0x0b, 0x00, 0x00]*2 + [0x00, 0x00, 0x00, 0x00]*2
assert(len(header_vals) == pix_offset[0])
# create pixel values for byte conversion
if linepad:  # need to 0-pad lines to a multiple of 4 bytes per line
    pixel_vals = list()
    for reverse_row in list(reversed(mybase_arr)):
        for cpy in range(magnify):  # repeat line 16 times (magnify)
            pixel_vals.extend([val for pix in reverse_row for val in bmp_BGR_colors[pix] * magnify] + [0x00] * linepad)
else:  # no padding needed
    pixel_vals = [val for reverse_row in list(reversed(mybase_arr))
                  for cpy in range(magnify) for pix in reverse_row
                  for val in bmp_BGR_colors[pix]*magnify]  # last for to unpack tuples
assert(len(pixel_vals) == raw_pix_data_size)
with open(bmp_name, 'wb') as bmp_file:
    bmp_file.write(bytearray(header_vals + pixel_vals))  # convert values to bytes


text:
Q: "two other methods" vs "other two methods"? for example,

*

*I want two other methods.

*I want other two methods.

Which one above is correct ?
If both are correct, what is the difference? What is the target noun of "two" and "other" assuming they are both adjective?
If only one is correct, is it due to adjective-order-restriction?

A: The grammatically correct one is

I want two other methods.

This implies that the two other methods, combined with the original method, are not the only appropriate methods. The asker is thinking that the methods you already told him/her about aren't adequate enough, and wants two more methods.
"other" should have some modifier or quantifier or the definite article preceding it, so your second sentence is ungrammatical.

I want the other two methods.

This means two (contradictory!) things:

*

*that the person wants the other two methods out of some total amount.

*that the person doesn't want your currently selected method, but rather he/she wants the other two methods out of those total.
You'll have to tell which is which by context.
To go off-topic:

I want every other thing.
Come back some other time.
I hate that other car.


text:
Q: IIS 7 Application Pool Private Memory Usage For IIS 7,
Help for Recycling Conditions for Application Pool says that Private Memory Usage is ...privately allocated system physical memory ...
(The property is named Maximum Used Memory in IIS 6.)
And, Event Log entry when application pool recycles;
"A worker process with process id of '4824' serving application pool '(thepool)' has requested a recycle because it reached its private bytes memory limit."
Thus, if its private bytes then it must be the committed memory which physical memory + page file. But, help says its physical memory(in that case property must be named private working set.)

ASP.NET Performance Monitoring, and When to Alert Administrators
Private Bytes. The current size, in bytes, of the committed memory owned by this process.
http://msdn.microsoft.com/en-us/library/ms972959.aspx#monitor_perf_topic12

i don't find any correction to this documentation, or am i missing something?


text:
Q: Permissions required for a local user to query services I'm trying to write an application, that is running as a local user on the server, and needs access to enumerate services, and potentially even control them (start/stop).
Is being a part of the administrators group the only way this user would be able to get access to this functionality (being used via the ServiceController class)? If easier, I'd be ok with even just being able to enumerate the list of services (the interactive starting/stopping isn't a show-stopper). Would adding the user to the power user's group work?
Thanks!
edit: http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx#access_rights_for_the_service_control_manager

A: The Power Users group is never the answer. It's an old legacy thing. Best to just consider it non-existent.
If you want to set permissions on individual Windows services in a granular way, you can, but it's nowhere near as easy/intuitive as setting permissions on a file
To view the current permissions of a Windows service:
C:\Users\Ryan>sc sdshow netlogon

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCR
RC;;;IU)(A;;CCLCSWLOCRRC;;;SU)

To set the permissions on a single Windows service, for example, so that a non-admin user can start and stop a particular service:
sc sdset netlogon "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"
[SC] SetServiceObjectSecurity SUCCESS

That looks awful, doesn't it?  That goo is called SDDL - Security Descriptor Definition Language.
This article is a pretty good primer on how to interpret SDDL and do what you're trying to do.
You can also use Security Templates and Group Policies to accomplish the same thing:

A: Another friendly option for doing the same thing is the subinacl command line tool included in the Windows 2003 Resource Kit. It is a wonderful little bag of tricks.
Here is the syntax for setting user permissions on services:
SUBINACL /SERVICE \\MachineName\ServiceName /GRANT=[DomainName\]UserName[=Access]

These are the Access-options available:
F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
L : Read controL
Q : Query Service Configuration
S : Query Service Status
E : Enumerate Dependent Services
C : Service Change Configuration
T : Start Service
O : Stop Service
P : Pause/Continue Service
I : Interrogate Service
U : Service User-Defined Control Commands

So to give the members of the group DOMAIN\GroupName permission to start and stop the service 'ServiceName' one would:
subinacl /service ServiceName /GRANT=DOMAIN\GroupName=TO

To view permissions set on the service 'ServiceName' (before and after running the above) one would:
subinacl.exe /service /verbose=1 ServiceName

Here is an official HOWTO for setting service permissions using subinacl:
http://support.microsoft.com/kb/288129
And here is the subinacl download link:
http://www.microsoft.com/en-us/download/details.aspx?id=23510

A: To enumerate services, your process needs the SC_MANAGER_ENUMERATE_SERVICE right, in the old days every authenticated user had this right, but since Vista this is no longer the case.
Interactive users have it, that's why a normal user can do a net start or Get-Service
You can change the permissions on the Service Control Manager to allow your process to enumerate services. You also need to change permissions on any service you want to access.
I just wrote a blog post about how to do this, it includes a PowerShell script to do this for all services on the local machine.

A: Hm, that all depends on the language you're using to query processes, but the required user role will be determined by a set of privileges that your code will need on the target machine.
Some of those privileges are associated with normal user accounts whereas others will require admin role.


text:
Q: how to write parametric-typed function where the parameter class declares some method(s) in scala? I deal with Scala problem which I can't properly name, so maybe there is already answer somewhere here (please be patient).
Assuming this code:
class A {def foo() = 5}
class B {def foo() = 6}
def fooer[T](x:T) = x.foo()

I get error:
<console>:7: error: value foo is not a member of type parameter T
    def fooer[T](x:T) = x.foo

This perfectly makes sense as compiler can't possibly know what type T will be passed. So finally the question - how can I implement typed function so it accepts only types with foo method declared?
Please note that I don't seek enum alternitives (see doc) as I don't know how many classes are there (external library). Also the classes have no common predecessor class or trait and they can't be modified.
Is this even possible? C++ language support this behavior using templates. I prefer solution which doesn't use reflection API.
Thanks :)
I tried some more definitions of fooer such as
def fooer[T <: {def foo(): Integer}](x:T) = x.foo()
fooer[A](new A)
<console>:10: error: type arguments [A] do not conform to method fooer's type parameter bounds [T <: AnyRef{def foo(): Integer}]
          fooer[A](new A)
               ^

but with no success

A: The problem is that A.foo returns an Int not an Integer. If you change your method to:
def fooer[T <: {def foo(): Int}](x:T) = x.foo()

then it will work.


text:
Q: Pinescript Draw horizontal line with dynamic color? reposting with correct code markup
hi, i want draw a horizontal line that changes color dynamically.
If cumulative volume delta above 0, white, else red.
I'm using fill right now as I haven't been able to get it to work with hline, but the problem is that on HTF the line is barely visible as -50 to 50 pixels is very small.
On HTF line is very small
But on LTF it's huge and unsightly. Is there any way to have the line render colors dynamically while also being consistent width no matter the time frame?
On LTF line is unsightly
This is what I have that's causing the inconsistent line sizing
lineColor = cumulative_volume_delta > 0 ? color.new(color.white, 40) : color.new(color.red, 5)

lineTop = plot(50 , title = 'Line Top', transp = 100, display=display.none)
lineBottom = plot(-50, title = 'Line Bottom', transp = 100, display=display.none)
fill(lineTop, lineBottom, title = 'Line Color', color = lineColor, transp = 0)

This is what I tried initially that didn't work as hline wont accept dynamic variables
if cumulative_volume_delta > 0
hline(0, "Line", color=color.white, linestyle=hline.style_solid, linewidth=1)
else
hline(0, "Line", color=color.red, linestyle=hline.style_solid, linewidth=1)

Would appreciate any help!


text:
Q: Convert Integer to 4 byte ungisned char vector (in Big endian byte order) Suppose, I wanted to write decimal 31 in a binary file (which is already loaded into vector) in 4 bytes so I have to write as 00 00 00 1f, but I don't know how to convert decimal number in hex string (of 4 bytes)
So, expected hex in vector of unsigned char is:
0x00 0x00 0x00 0x1f // int value of this is 31

To do this I tried following:
std::stringstream stream;
stream << std::setfill('0') << std::setw(sizeof(int) * 2) << std::hex << 31;
cout << stream.str();

Output:
0000001f

Above line of code gives output in string format but I want it into vector of unsigned char in format of '0x', so my output vector should have elements after conversion as 0x00 0x00 0x00 0x1F.

A: Without bothering with endianness you could copy the int value into a character buffer of the appropriate size. This buffer could be the vector itself.
Perhaps something like this:
std::vector<uint8_t> int_to_vector(unsigned value)
{
    // Create a vector of unsigned characters (bytes on a byte-oriented platform)
    // The size will be set to the same size as the value type
    std::vector<uint8_t> buffer(sizeof value);

    // Do a byte-wise copy of the value into the vector data
    std::memcpy(buffer.data(), &value, sizeof value);

    return buffer;
}

The order of bytes in the vector will always in the host native order. If a specific order is mandated then each byte of the multi-byte value needs to be copied into a specific element of the array using bitwise operations (std::memcpy can't be used).
Also note that this function will break strict aliasing if uint8_t isn't an alias of unsigned char. And that uint8_t is an optional type, there are platforms which doesn't have 8-bit entities (though they are not common).

For an endianness-specific variant, where each value of a byte is extracted one by one and added to the vector, perhaps something like this:
std::vector<uint8_t> int_to_be_vector(unsigned value)
{
    // Create a vector of unsigned characters (bytes on a byte-oriented platform)
    // The size will be set to the same size as the value type
    std::vector<uint8_t> buffer(sizeof value);

    // For each byte in the multi-byte value, copy it to the "correct" place in the vector
    for (size_t i = buffer.size(); i > 0; --i)
    {
        // The cast truncates the value, dropping all but the lowest eight bits
        buffer[i - 1] = static_cast<uint8_t>(value);
        value >>= 8;
    }

    return buffer;
}

Example of it working

A: You could use a loop to extract one byte at a time of the original number and store that in a vector.
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>

using u8 = std::uint8_t;
using u32 = std::uint32_t;

std::vector<u8> GetBytes(const u32 number) {
    const u32 mask{0xFF};
    u32 remaining{number};

    std::vector<u8> result{};
    while (remaining != 0u) {
        const u32 bits{remaining & mask};
        const u8 res{static_cast<u8>(bits)};
        result.push_back(res);
        remaining >>= 8u;
    }
    std::reverse(std::begin(result), std::end(result));
    return result;
}

int main() {
    const u32 myNumber{0xABC123};
    const auto bytes{GetBytes(myNumber)};
    std::cout << std::hex << std::showbase;
    for (const auto b : bytes) {
        std::cout << static_cast<u32>(b) << ' ';
    }
    std::cout << std::endl;
    return 0;
}

The output of this program is:
0xab 0xc1 0x23


text:
Q: Using Winston in typescript I can't figure how to use the logging module Winston in typescript. I have an error when I try to set the logger level, and another one when I try to log an error:
import * as logger from "winston";

logger.level = 'debug';
// [ts] Cannot assign to 'level' because it is a constant or a read-only property.

logger.error(new Error('test'));
// [ts] Argument of type 'Error' is not assignable to parameter of type 'string'.

I have added both winston and @types/winston to my project.

Edit: to complete Joshua answer, it seem that by default winston logs to... nowhere. You have to add a transport to make it work:
import * as logger from "winston";

logger.configure({
    level: 'debug',
    transports: [
        new logger.transports.Console({
            colorize: true
        })
    ]
});

A: Here are the type definitions for Winston:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/winston/index.d.ts
If you look at the bottom of the file, the default export is declared as const, so when you try to modify the level property, it complains at you because you are trying to modify a const object. Here are the relevant lines:
declare const winston: winston.Winston;
export = winston;

Instead of trying to set that property directly, try using the configure method (note that your logger import is of type Winston:
logger.configure({
    level: 'verbose',
    ...
})

If this doesn't work (I'm not sure exactly what else the configure call expects), you might try creating a new LoggerInstance, which you will be able to modify.
Your second error is because you're passing an Error object where a string is expected. The declaration of Winston.info is here:
info: LeveledLogMethod;

And here is the LeveledLogMethod interface:
interface LeveledLogMethod {
    (msg: string, callback: LogCallback): LoggerInstance;
    (msg: string, meta: any, callback: LogCallback): LoggerInstance;
    (msg: string, ...meta: any[]): LoggerInstance;
}


text:
Q: HTTP and HTTPS iframe I am creating a small widget and I want to allow others to use it. The iframe is loaded via HTTP - but I want to allow users to login via HTTPS. i.e. Send a request for login via SSL.
Is this allowed within the same-origin policy? i.e. The scenario is that a user can integrate my JavaScript to their website, the widget opens and I want to allow them to login via HTTPS?

A: @Bruno - I agree, but I would like to point out that even checking the source - as demanding as that is - of the page might not be enough to ensure security or proper/intended destination, since that is often the originally served source text. Unless I'm seriously mistaken, that can be changed easily with in-page or even off-page javascript code (which itself can be obfuscated, if someone really wants to make it next to impossible to find). That said, IF a user has an appropriate browser, I think that they  might be able - if they are suspicious to begin with - to check the source of the iframe to determine the source of that code, then determine whether they trust the source... not really a reasonable expectation.
Though all of this could be determined with appropriate debuggers and/or software/DOM inspectors and a good helping of digital elbow grease, the OP cannot reasonably expect everyone to do this (if anyone at all)

A: It is generally bad practice to embed an iframe with content served over HTTPS within a page served over plain HTTP (or mix content). The reason for this is that there's no good way for the user to check they're using the HTTPS site they intend (unless the user really wants to check the source of the page).
An attacker could very well replace the content you serve like this:
<iframe src="https://your.legitimate.example/loginframe" />

with:
<iframe src="https://rogue.site.example/badloginframe" />

or even:
<iframe src="http://rogue.site.example/badloginframe" />

This is very hard to detect for the user, and defeats the security measure you're trying to put in place by enabling login via HTTPS.

A: I have done some tests. If you are linking from an https page to another domain with https they need a valid SSL certificate.


text:
Q: Post base64String of image with other parameters to server swift Here I have an image which I am converting in base64String (†he resulted base64String is too large) and try to post on server with some other parameters but in return I am getting failure. I am having an done action button on tap it started converting and post to server. I used Alamofire for http request. Below is my code which I used but not getting result.
@IBAction func doneBtn(_ sender: Any) {

    if (itemNameTF.text?.characters.count)! > 0 && (itemPriceTF.text?.characters.count)! > 0 && (itemUnits.text?.characters.count)! > 0 {

    let productName = "\(itemNameTF.text!)_\(itemUnits.text!)"

        let productPrice = itemPriceTF.text!

        let productImage:UIImage = itemImage.image!
        if let dataImage = UIImageJPEGRepresentation(productImage, 0.5)?.base64EncodedString() {

            let url = "someURl"
            let parameter = ["product_name": productName, "product_price": productPrice, "product_img": "\(dataImage)"]

            headers = ["Content-Type": "application/json","Authorization" : "Token \(token!)"]
            Alamofire.request(url, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
                print(response.request)
                print(response.response)
                print(response.result)
                print(response.result.value)
            }
        }
    }
}

In result it gives me an response of

Please help me if anyone could find problem. Thank You!

A: Just add this line into your code:
let fullBase64String = "data:image/png;base64,\(dataImage))"

and then add "fullBase64String"
let parameter = ["product_name": productName,"product_price":productPrice,product_img": "\(fullBase64String)"]


text:
Q: CTAD doesn't work with defaulted template arguments? Compare the following case when I have a class object that takes a vector. The non-deduced parameter T can be substituted fine with the default template argument:
#include <vector>

template <typename T = int>
struct container
{
    container(std::vector<T> vec) {}
};

int main()
{
    container C = std::vector{1,2,3,4,5};
}

This is not the case for my class which is a bit more complicated (CompilerExplorer):
#include <cstdio>
#include <initializer_list>
#include <variant>

template <size_t> struct obj;

template<size_t Vs>
using val = std::variant<std::monostate, int, struct obj<Vs>>;

template <size_t Vs = 0>
struct obj
{
    obj() = default;
    obj(std::initializer_list<val<Vs>> init) {
        printf("initializer of object called, Vs = %d\n", Vs);
    }
};

template <size_t Vs = 0>
struct container : public obj<Vs>
{
    container(obj<0> init) {}
};

int main()
{
    container<5> some_container = obj{1,2,5,2,obj{1,2,33},2,2};
}

This fails with the following error:
<source>: In function 'int main()':
<source>:29:57: error: class template argument deduction failed:
   29 |     container<5> some_container = obj{1,2,5,2,obj{1,2,33},2,2};
      |                                                         ^
<source>:29:57: error: no matching function for call to 'obj(int, int, int)'
<source>:14:5: note: candidate: 'template<long unsigned int Vs> obj(std::initializer_list<std::variant<std::monostate, int, obj<Vs> > >)-> obj<<anonymous> >'
   14 |     obj(std::initializer_list<val<Vs>> init) {
      |     ^~~

But it works when I supplement the template specialization obj<0> in the instantiation of the container (in main). Any ideas why this doesn't work for my class and how I can fix it? I don't want to force the user to specify the template each time.

A: This problem already exists in the simpler case of just
auto o = obj{1,2,33};

which yields this error:
<source>:29:24: error: class template argument deduction failed:
   29 |     auto o = obj{1,2,33};
      |                        ^
<source>:29:24: error: no matching function for call to 'obj(int, int, int)'
<source>:14:5: note: candidate: 'template<long unsigned int Vs> obj(std::initializer_list<std::variant<std::monostate, int, obj<Vs> > >)-> obj<<anonymous> >'
   14 |     obj(std::initializer_list<val<Vs>> init) {
      |     ^~~
<source>:14:5: note:   template argument deduction/substitution failed:
<source>:29:24: note:   mismatched types 'std::initializer_list<std::variant<std::monostate, int, obj<Vs> > >' and 'int'
   29 |     auto o = obj{1,2,33};

So, the compiler is unable to deduce, that the three ints should be an initializer list. If you add extra braces around them, the compiler recognizes that this should actually be a single list argument instead of three separate ones and it works:
auto o = obj{{1,2,33}};

This also carries over to the more complicated case:
container some_container = obj{{1,2,5,2,obj{{1,2,33}},2,2}};