text:
Q: How can I avoid blocking of selects if there is a transaction ongoing? I have some InnoDB tables and a script that starts a transaction. Within this transaction different rows of one table gets updated, other rows will be inserted into another table and many selects are performed. This must happen reliably so I use a default transaction with REPEATABLE READ as the isolation level. This transaction may take some time.
Now, when other scripts (web page requests) get executed at the same time they do some selects at the database. Unfortunately, those selects wait until the transaction has ended since they read from the same tables. The selected data can be the updated data of the transaction but can also be other data.
This blocking is what I'd like to avoid. I'd like to show the web page to the user immediately and cannot wait for the transaction (one or two seconds would be acceptable, but the transaction sometimes is much longer).
So how can I do selects? I guess that the data may not always be accurate then. But this is better then let the user wait for 20 seconds.
Should I

*

*use 'FOR UPDATE' or 'LOCK IN SHARE MODE' with the selects in the transaction?

*use another isolation level?

*put the reading selects also in a transaction?

*do something different?

I think this is a very common requirement, but I couldn't find a simple answer yet.
Note: next thing would be to secure concurrent write transactions. But for now I just want to make sure that at least parallel reads don't get blocked during the transaction.

A: Okay, this is not a real answer but I thought I should tell what I have found out:
It did not have anything to do with the MySQL actions, I guess. It actually was hanging PHP requests. That is, when the first PHP call started the long ongoing transaction, further PHP calls to other pages have hanged. And the reason why they hanged was that the session was locked by the first request! session_start() did not work anymore. Just when the first request has completed (or timed out), further requests were going to work again.
Since the PHP call with long transaction did not need to write anything into the session I just close the session with session_write_close() in this call. Now, further requests do not hang anymore.
This was the hint for me.
Conclusion: the database selects were not blocked.


text:
Q: API/Middleware Authenticated Communication - Request Integrity Check My team and I are working on an API/Middleware system that will require all requests made to the middleware layer to sign the request with a public and private key for security.  Most of these requests are going to be made server to server with the exception of mobile applications such as iPhone and Android apps that will directly query data from the middleware.
We have implemented our signature libraries very closely mirroring the way the Amazon Market API works using sorted query strings and doing HMAC 256 hashing with public and private keys to generate a signature that is compared upon receipt using the same algorithm.
Unfortunately, we just learned (a little late in the game) that in order to release iPhone apps through the app store you have to meet certain government criteria in order to implement the crypto libraries (read as export restrictions).  Now we are being forced to decide if we should re-write our signing algorithms to use a much more simple method such as appending a private key to the query string and SHA1() hashing it for comparison.
I HATE taking a highly secure method and reducing it to just hashing in a private key, but I'm not familiar enough with security and crypto to know what I am losing in the long run by dropping HMAC 256.  (Note: the query string already includes the public key)
For example, we currently order our query string and perform an operation like this to sign it:
$signature = base64_encode( hash_hmac( 'sha256', $querystring, $private_key, TRUE ) );

If we are forced to not use the crypto class in our apps then our signatures would look like this:
$signature = base64_encode( sha1( $querystring . $private_key ) );

Technically we may meet the criteria to use the library in our app, but I don't know if I want to risk the legal ramifications if the US Gov'ment decides that what we are doing doesn't exactly meet their legal description of 'authentication'.
Any and all advice from you security gurus out there is much appreciated!  What am I losing by using the second code example, does it make hacking our middleware any easier?

A: In case anyone else ends up in a similar situation, at least in our circumstance, the encryption method we are using (described above) does fit within the legal requirements and works with Apples ToS.  We basically implemented an Amazon AWS style authentication, though in hindsight OAuth 1.0 would have been just a little stronger method with pre-built libraries to help along the way.
IF you were to do this type of authentication in an app today I would definitely suggest looking to OAuth.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extract the line from the file, concatenate it with a certain string problem I have a problem, in the text file I have the form "User:Username Password,Real name Real Surname Email" and so on several lines, how can I add the word "(suspended)" to the beginning of a specific line?
My code does this:
"U(suspended)ser:Username Password,Real name Real Surname Email"

How to fix it,to get?
"(suspended)User:Username Password,Real name Real Surname Email"

Here's code:
    char username_to_suspend[50];
    scanf("%s",username_to_suspend);
    char line[100];
    char new_line[sizeof(line)]="(suspended) ";
    FILE *fp = fopen("users.txt", "r+");
    while(fgets(line,sizeof(line),fp)!=NULL)
    {
        if(strstr(line,username_to_suspend)!=NULL)
        {
            strcat(new_line,&line[1]);
            fseek(fp, -strlen(line), SEEK_CUR);
            fputs(new_line, fp);
        }
        else
        {
            continue;
        }
       break;

    }

    fclose(fp);

Thanks in advance!
Best regards!


text:
Q: Size and Size on disk of a .txt file Opened up a new file in Notepad and inserted the sentence without the quotes, "Four score and seven years ago" in it.
Four              4 characters
score             5 characters
and               3 characters
seven             5 characters
years             5 characters
ago               3 characters

TOTAL : 25 + 5 spaces = 30 characters.
You will find that the file has a size of 30 bytes on disk: 1 byte for each character.
Saved the file to disk under the name gettingSize.txt.
Then look at the size of the file.
As a rule, Each character consumes a byte.
Size : 30 bytes
Size on Disk : 4.00 KB (4,096 bytes)
The below paragraphs are copy pasted from a pdf.
If you were to look at the file as a computer looks at it, you would find that each byte contains not a letter but a number -- the number is the ASCII code corresponding to the character (see below). So on disk, the numbers for the file look like this:
F   o   u   r     a   n   d      s   e   v   e   n
70 111 117 114 32 97 110 100 32 115 101 118 101 110
By looking in the ASCII table, you can see a one-to-one correspondence between each character and the ASCII code used. Note the use of 32 for a space -- 32 is the ASCII code for a space. We could expand these decimal numbers out to binary numbers (so 32 = 00100000) if we wanted to be technically correct -- that is how the computer really deals with things.
1) i know that every thing is stored in the form of bits and bytes, so what generally this means - "you would find that each byte contains not a letter but a number -- the number is the ASCII code corresponding to the character". A byte is 8 bits. So how does "each byte a number -- the number is the ASCII code". How can a byte contains a ASCII number(eg. 49 for '1') other than 0 and 1?
2) What exactly is the difference between Size and Size on Disk? And How does ASCII and Unicode fit into it?
3)In Java, Strings are objects. Can I say it be a multiple characters concated together?
String str = "Four score and seven years ago"
So how does a str stored in memory. Is it in the same manner as saving in the notepad file?

A: Files are stored in blocks. If file size is smaller than block size (in your case, 4KB) the file will take all block but most of its space is unused. I think this question was answered on SuperUser, i'll find the link.
UPDATE: https://superuser.com/questions/704218/why-is-there-such-a-big-difference-between-size-and-size-on-disk

A: To make a few short points:

*

*"How can a byte contain an ASCII number (eg. 49 for '1') other than 0 and 1?

A Byte is 8 bits. Thus you can store numbers between 0 and 255 in it.

*What is the difference between filesize and size on disk:

See MJafar Mash's answer: "size" is the actual size in bytes and "size on disk" is the number of bytes you need to allocate as blocks for the file to be placed in.

*In Java Strings are Objects. Can I say that a String is multiple characters concatenated together?

Yes, but It's actually more complicated than that:
  Taken from this answer:

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

A: 1) i know that every thing is stored in the form of bits and bytes, so what generally this means - "you would find that each byte contains not a letter but a number -- the number is the ASCII code corresponding to the character". A byte is 8 bits. So how does "each byte a number -- the number is the ASCII code". How can a byte contains a ASCII number(eg. 49 for '1') other than 0 and 1?
Each ASCII character occupies 1 byte. Internally, each character is stored as its ASCII number. So, you can store 8-bits of data max i.e, 2^8 -1 = 255. So the range would be 0-255.
2) What exactly is the difference between Size and Size on Disk? And How does ASCII and Unicode fit into it?
Each ASCII character is 1 byte. So, 30 bytes is the actual size of the data in the file. Next, the 4KB is the size of the segment/block in which the file is stored. In your case it is the minimum "new" space given to any file on the disk.
3)In Java, Strings are objects. Can I say it be a multiple characters concated together? String str = "Four score and seven years ago" So how does a str stored in memory. Is it in the same manner as saving in the notepad file?
Yes. Strings are indeed (internally) multiple characters concatenated together. But the characters cannot be changed.String is an object, so , they are stored as an array of characters (in java each character is 2 bytes). Java uses UTF-8 (it could be different based on various factors)  as default Charset. You can also change it.


text:
Q: C++ Functions, what im doing wrong Im new to this page and a beginner in c++.I can get my code to work, basically my code looks like this,
#include <iostream>
#include <cmath>

using namespace std;

double result(double num1,double num2) {
    return num1 + num2;
}
void addition() {
    double num1{};
    cout << "Enter first number: ";
    cin >> num1;
    double num2{};
    cout << "Enter second number: ";
    cin >> num2;
    cout << "The result is: " << result << endl;
}
int main() {
    addition();
    return 0;
}

Say for example the user inputs 25 as his first and second number so the result should be 50, but it's not. It looks something like this
Enter first number: 25
Enter second number: 25
The result is: 006911F9

I tried changing from double to int thinking it would help but sadly it didnt. What im a missing?

A: You are printing the address of the function result.
If you want to call the function result, use () operator.
In other words, change this line
    cout << "The result is: " << result << endl;

to
    cout << "The result is: " << result(num1, num2) << endl;


text:
Q: Write Mac OS X apps with Visual Studio I just came upon this article here which can turn your day to day visual basic app to run on mac os x. Here is the link: http://mac.sillydog.org/dev/visual_studio.php The thing I don't get is that the author doesn't tell us specifically what to download, and where to get all the files. He's a bit vague... Can anyone make this clearer to me?
BTW: I am using VB.NET although the author uses C#. I think it  will still work though.

A: The important part is the mono framework. It looks like you need this release.

A: *

*.NET Framework

*Microsoft Visual Studio Express

*Mono Framework for Mac OS X

*wx.NET
The Mac OSX build of wx.NET is called Carbon. The readme says:

This package is a contribution of wx.NET user Matthias Fuchs, who wrote:
Hi,
as i didn't find a binary package for Mac OS X I created my own ;-)
I've built wx.NET for Mac OS 10.5.7. I used wxWidgets 2.8.10 and created a Mac OS X Framework Bundle.
The zip file includes a "wxWidgets.framework" folder, which must be installed into /Library/Frameworks/ on the root partition of MacOS X. I also tried to copy the wx.NET.dll to Mono's GAC, but mono can't find the wx-c.dylib. But I think it is ok, that users can just put the wx.NET files into their bin/debug/release folders.

Follow those instructions and use the Windows Mono build of wx.NET when testing on the same machine as Visual Studio and the Mac OSX build when you deploy it.


text:
Q: prime divisibility:v what is the formula? I know how to divide certain numbers, like $$\frac{x}{2}$$ whereas $x$ ends in 2, 4, 6, 8, or 0. and my idea to represent $x$ is $$a+10b+100c+1000d...$$ and it is divisible by 3 if $$\frac{a+b+c+d...}{3}$$ is a whole number.
$\frac{x}{5}$ is possible if the number ends in 0 or 5.
$\frac{x}{6}$ is possible if $\frac {x}{3}$ and $\frac{x}{2}$ are both possible. this is the same for all composite numbers.
my big question is: what about larger $$\frac{x}{p}$$ where p is any prime number and x is any number you are trying to test? is there any formula that can be directly applied to any prime-regular number combination to find the divisibility?

A: You have asked about two different kinds of divisibility tests.
The tests for divisibility by $2$ and $5$ work so nicely because we write our numbers in base $10$ and those are the prime factors of $10$. If we wrote using a different base $b$ we could test for divisibility by a prime factor of $b$ by checking just the last (units) digit.
In base $10$ there are digit tests for other numbers too. You show that you know that to test for divisibility by $3$ or $9$ you use the sum of the digits. For $11$ you look at the alternating sum and difference of the digits. For $4$ you look at the last two digits. There's a test for $7$ too, but it's really ugly.
The second kind of test you're thinking about is the one you quote for $6$. If a number is divisible by each of two primes $p$ and $q$ then it will be divisible by their product $pq$. That's a fact about numbers and doesn't depend on the base you use to write them. (It can also be generalized a bit.)
See https://en.wikipedia.org/wiki/Divisibility_rule (and other web links for "divisibility test").

A: I know the following about the general case for base $b$;
If $p|b$, then you can check divisibility by $p^k$ by checking the last $k$ digits of the number in question.
If $b \equiv 1 \pmod{p}$, then the sum of digits test applies.
If $p-1=b$, then the alternating sum of digits test works.
I am under the impression (possibly mistaken) that is is always possible to construct a digit test, however in the majority of cases it is rather absurd and not worth doing.


text:
Q: Quero fazer um código javascript que execute um arquivo ao invés de fazer download Preciso de algum código JavaScript que ao clicar em um botão na página HTML ele execute um arquivo.
Por exemplo: tenho um arquivo .bat, e quero que ao clicar em um botão na pagina HTML ele execute esse arquivo.
Meu problema é que todas tentativas que eu fiz o código faz download do arquivo, e oque eu preciso é executar.


text:
Q: Flask redirect entering route twice I would like to be able to pass messages from a POST redirect to other templates. See the edit for the specific blueprint structure and routes / views.
After POSTing to the _update_test route, it prints >> about to redirect
Then, I can see with my debugger that the browse_tests route is entered and the message content is as expected (what was provided from Flask's redirect() function. I see >> about to render template is printed to the console
Problem is, before the page base_browse_test.html is rendered, the browse_tests route is entered a second time and the message component is gone from the request, so the template renders with an empty message (message = ''). I see >> about to render template is printed a second time before the page renders.
What am I missing here?
EDIT: here is the blueprint structure
root/webapp/__init__.py: (the entirety of this file can be found at this pastebin)
def create_app('development'):
    webapp = Flask(__name__)
    ...
    from .mod_tests import tests as tests_blueprint
    webapp.register_blueprint(tests_blueprint, url_prefix='/tests')
    return webapp

root/webapp/mod_tests/__init__.py:
from flask import Blueprint
tests = Blueprint('tests', __name__)
from . import manage_tests_views

root/webapp/mod_tests/manage_tests_views.py:
@tests.route('/_update_test', methods=['POST'])
    def update_test():
        ...
        print 'about to redirect'
        return redirect(url_for('tests.browse_tests', message={"main":"foo message content"}))

@tests.route('/browse_tests', methods=['GET'])
@login_required
def browse_tests():
    if request.args.get('message'):
        message = request.args['message']
    else:
        message = ''
    print 'about to render template'
    return render_template('tests/base_browse_tests.html',
                           message=message)

*

*Running with or without the debugger makes no difference.

*request.accept_mimetypes is equal to a MIMEAccept dict containing ('*/*', 1) on the first request (message intact, query string included in request) and contains ('text/html', 1), ('image/webp', 1), ('application/xhtml+xml', 1), ('application/xml', 0.9), ('*/*', 0.8) on the second, empty query string request. Is this any kind of clue?

*the request.cookies['session'] string value does not change, although the dubugger seems to think it does (by turning it blue in my IDE)

*request.fullpath is equal to u'/tests/browse_tests?notification=<encoded json>' on the first, notification-intact request. request.fullpath equals u'/tests/browse_tests?' on the second, notification-absent request

*request.is_xhr == True on the first, notification-intact request. It is False on the second, notification-absent request

*request.environ['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' first, and it is absent on the second request.

*request.environ['HTTP_UPGRADE_INSECURE_REQUESTS'] is absent from the first request, and equals'1'` on the second request

A: There must be something wrong with your Blueprint structure or it usage
I tried reproducing your code on my machine without blueprint and it worked !
In your code  modify this line and run, it may work.
I made the POST request using this
return redirect(url_for('tests.browse_tests', message={"main":"foo message content"}))

TO
return redirect(url_for('.browse_tests', message={"main":"foo message content"}))

This is what i did on my machine
Test/
----hello.py
----templates/
--------base_browse_tests.html
hello.py
from flask import Flask, redirect, url_for, request, render_template
from flask.ext.login import login_required
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

@app.route('/_update_test', methods=['POST'])
def update_test():

    print '>>>>>>>>>>>>>>about to redirect'
    message={"main":"foo message content"}
    return redirect(url_for('browse_tests', message=message ))

@app.route('/browse_tests', methods=['GET'])
def browse_tests():

    if request.args.get('message'):
    message = request.args['message']
    else:
    message = ''

    print '##################about to render template'

    return render_template('base_browse_tests.html',
                       message=message)

if __name__ == "__main__":
    app.run(debug=True)

base_browse_tests.html

Message: {{message}}

peace

A: Sorry everyone, there was an errant redirect left in the javascript that executes on that page. Let this serve as a reminder to be careful.
This question may be closed as the solution was not at all related to the problem.


text:
Q: R: MTP in multtest creates different estimates from glm for test="lm.YvsXZ" I apologize if I am completely missing something fundamental about what I am trying to do here.
I am trying to use MTP to estimate adjusted p-values for a much more complex regression, and I keep getting parameter estimates that differ wildly from those that I get from glm.
To demonstrate my thinking, here is an example using the mtcars data:
library(multtest)
data(mtcars)
g <- glm(mpg ~ cyl + disp + hp + vs, data=mtcars)
summary(g)
mtcars$Intercept <- 1
m <- MTP(X=t(mtcars[c("Intercept","cyl","disp","hp","vs")]),
    Y=mtcars["mpg"],test="lm.YvsXZ", robust=FALSE, typeone="fwer",
    method="sd.maxT", keep.nulldist=FALSE, B=2000)
md <- as.data.frame(cbind(m@estimate, m@statistic, m@rawp, m@adjp))
names(md) <- c("Estimate","t-value","Raw p","Adj p")
md
As you can see, the estimates and their t-values are very different. This carries over if you do not add the Intercept term to the MTP call (which I am not sure about).
I'm sure that I am not understanding something fundamental about what's going on here, but I am just learning about R and MTP/multtest. I am assuming that bootstrapping would not change the estimates SO much, but maybe I am wrong?
Thanks for any help that you can give.

A: I talked with the very helpful Dr. Pollard, and I was confused about 2 points:
   1) Using "lm.YvsXZ" requires that something be in the Z matrix as well as the X matrix, and
   2) MTP was designed to adjust one predictor at a time. If you have more than one predictor that needs adjustment put them, one at a time and serially, in X, and the rest in Z for as many rounds as you have predictors.
So, I need to use multcomp.


text:
Q: How can I determine all ajax requests are resolved? Here is my code:
function ajaxRequest(value, path, website){
    var status = false;
    return new Promise(function (resolve, reject) {
        window[website] = $.ajax({
            url :  path,
            type : 'GET',
            data: { "name": value,
                    "_token": $('meta[name="_token"]').attr('content')
            },

            beforeSend: function(){
                if(window[website] != null) {
                    window[website].abort();
                }
            },
            success: function (people) {
                status = true;
                resolve([status, people]);
            },

            error: function (jqXHR, textStatus, errorThrown) {
                reject([status, textStatus]);

            },

            timeout: 20000

        });
    });
}

And I call the function like this:
ajaxRequest('Jack', 'search/twitter', 'twitter').then(function(res) { console.log(res)}, function(err){console.log(err)});
ajaxRequest('Jack', 'search/instagram', 'instagram').then(function(res) { console.log(res)}, function(err){console.log(err)});

Now I need to know those two ajax requests are done. How can I do that?
Noted that I think I have to use promise.all(), but not sure how can I use it in my case.

A: You are right, promise.all() is invented to solve exactly that problem.
All it does is to return a new Promise that will resolved when all the given Promises are resolved.
In your case, you can wrap your 2 ajax calls with Promise.all something like that:
promise.all([
   ajaxRequest('Jack', 'search/twitter', 'twitter').then(function(res) { console.log(res)}, function(err){console.log(err)}),
   ajaxRequest('Jack', 'search/instagram', 'instagram').then(function(res) { console.log(res)}, function(err){console.log(err)})
]).then(([response1, response2]) => {
   // Here you execute your logic when both of the promises are resolved.
})

A: You can pass function calls to $.when(). Note, jQuery.ajax() returns a jQuery promise object, using Promise constructor is not necessary
$.when(ajaxRequest(), ajaxRequest())
.then(function(...results) {
  // do stuff with `results` array
})
.fail(function(jqxhr, textStatus, errorThrown) {
  console.error(errorThrown)
})


text:
Q: Evaluate a variable to use as a variable name?
Possible Duplicate:
Javascript Objects: Dynamic variable names?

I have a json string passed in from a cgi script. This json string has a list of id's. In javascript
var informationObj = jQuery.parseJSON(information);
tid = informationObj.idList[0].id;

tid is now an ID and I want to use it to access objects within the json string itself like so:
alert (informationObj.tid.rpath);

However this does not seem to work. I have also tried:
alert (informationObj.eval(tid).rpath);

Is there a way around this?
Thanks.

A: You need this form:
informationObj[tid].rpath

They are equivalent:
var a = 'something';
b[a] === b.something

A: Use bracket notation:
alert(informationObj[tid].rpath);


text:
Q: Deriving the average and variance of number of runs in runs test NIST states that the average and variance of a number of runs in the "runs above and below median" test as
$$
\overline{R} = \frac{2n_a n_b}{n_a + n_b} + 1 \\
s^2 = \frac{2n_a n_b(2n_a n_b - n_a - n_b)}{(n_a+n_b)^2 (n_a+n_b-1)}
$$
where $n_a$ is the number of values above the median and $n_b$ is the number of values below the median.
How is this result proved? Actually, more importantly, how do I begin to think about this problem?
It seems to me that this result might actually be valid more generally for "runs above/below threshold", since most likely $n_a = n_b$ for runs above median.


text:
Q: Non-zero rows give the basis of null space? Q. Find the nullity and basis of null space of linear transformation $A:R^4\rightarrow R^4$ given by the matrix
$$\begin{bmatrix} 0 & 1 & -3 & -1 \\ 1 & 0 & 1 & 1 \\ 3 & 1 & 0 & 2 \\ 1 & 1 &-2&0
\end{bmatrix}$$
Its given that if we reduce this matrix to echlon form then the non-zero rows gives the basis of null space. I do not understand why this works.

A: The basic principal is that elementary row options do not change the rowspace of a matrix. To prove that, you could demonstrate that the processes of scaling a basis element, interchanging two basis elements, and adding multiples of one basis element to another, all result in a new basis.
So, if you perform elementary row operations and change it entirely to row-echelon form, you are left with a matrix that has some zero rows and some nonzero rows. The row-echelon shape makes it obvious that the nonzero rows are linearly independent. Can you see why?
Since this is the case, the remaining rows are a basis for the rowspace of the matrix.
Basic row operations do not change the (right) nullspace either, so you can use the new matrix to work with the nullspace. Using that matrix instead of the original matrix, it will be particularly easy to solve the equation $A'x=0$ with back substitution to discover what is in the nullspace.

A: Basic operations on rows do not change the null space. When you add for example two rows, it's like adding two equations in the system obtained when writing Ax=b.
Edit : the first answer is more complete, didn't see it when writing mine.


text:
Q: ValueError: Input contains NaN, infinity or a value too large for dtype('float32') even though there is none that is like it I was trying to fit my dataset into the CART model, but I keep on getting
ValueError: Input contains NaN, infinity or a value too large for dtype('float32').
as an error.
error problem
I had already double, even triple checked the dataset and I have seen that it does not contain any NaN, infinity, or anything that counts as that. I have also double checked if there were any blanks, and there weren't. I tried everything including the most famous thread here, but to no avail. What could I be doing wrong?
Edit:
flood_tr=df.sample(frac=0.75,random_state=42)

flood_test=df.drop(flood_tr.index)

y = flood_tr['flood_height']

mar_np = np.array(flood_tr['precipitation'])  (mar_cat, mar_cat_dict) = stattools.categorical(mar_np, drop=True, dictnames=True)

mar_cat_pd = pd.DataFrame(mar_cat)
X = pd.concat((flood_tr[['elev']], mar_cat_pd), axis = 1)

rfy = np.ravel(y)

rf01 = RandomForestClassifier(n_estimators = 100,
criterion="gini").fit(X,rfy) #<--- this is where i got the error

here is the data set I used https://www.kaggle.com/datasets/giologicx/aegisdataset

A: Your dataset has values larger than float32 (single-precision). I would recommend doing the following.

X.round(dec)

where dec == decimal precision in between something like (2~5)


text:
Q: What are non-Abelian plasmas? I know what a non-Abelian group is: a group whose operation does not obey commutativity.  Does this have anything to do with a non-Abelian plasma?  I'm not really looking at a specific paper, but I'll give an example here: http://arxiv.org/abs/1211.0343

A: In Quantum Field Theory certain particles/fields are actually different `components' of the same field. Examples would be the electron and the neutrino or the three different colored quarks. Such a multiplet is often called a Yang-Mills multiplet as Yang and Mills originally thought the positron and neutron were two components of the same field (an idea that turned out to be wrong, but the mathematical approach was gold).
$$ \begin{pmatrix} e^{-}\\ \nu_e \end{pmatrix}, \begin{pmatrix} q_r\\ q_g \\q_b \end{pmatrix}$$
In quantum mechanics, when we have the Dirac equation, we would expect the wavefunction of the electron to be invariant under a phase rotation$\psi \rightarrow \psi e^{i\phi} $. These phase rotations are unitary complex numbers $e^{i\phi}$ and form the group $U(1)$. This property of the Dirac equation being invariant under a phase transformation is called global phase invariance.
$$ i \hbar \gamma^\mu \partial_\mu \psi - mc \psi = 0$$
Note furthermore that the Dirac equation is NOT invariant under a phase shift that varies from point to point $\psi \rightarrow \psi e^{i\phi(x^\mu)}$. Using the product rule on the first term we find that inserting $\psi \rightarrow \psi e^{i\phi(x^\mu)}$ in the Dirac equation gives us no longer zero:
$$ \left[ i \hbar \gamma^\mu \partial_\mu - mc \right] \psi e^{i\phi(x^\mu)} =  e^{\phi(x^\mu)}\left[ i\hbar \gamma^\mu \partial_\mu \psi - \psi \hbar \gamma^\mu \partial_\mu \phi(x^\mu) - mc \psi \right] \neq 0$$
However, we can make the Dirac invariant under such a 'local' phase transformation by introducing some additional term that 'absorbs' the extra term we get. Note that this extra term $\partial_\mu \phi(x^\mu)$ is the gradient of a scalar field $\phi(x^\mu)$ and thus behaves like a vector field. We could thus hope to make the Dirac equation invariant under local phase transformations by inserting some sort of vector field. However, since we wish to be able to cancel an arbitrary phase transformation this should be a vector field which has a certain gauge freedom of the following form
$$i \hbar \gamma^\mu \partial_\mu \psi - \frac{e}{c}\gamma^\mu A_\mu - mc \psi = 0 $$
$$A_\mu \rightarrow A_\mu - \frac{\hbar c}{e} \partial_\mu \phi(x^\mu) $$
Notice how miraculous! We found that if we wish the electron wavefunction to be completely invarient under an arbitrary phase transformation $\psi(x^\mu)$ this is only possible when we introduce a field that behaves exactly like the EM-field! Any arbitrary $U(1)$ phase-transformation of the electron field can now be compensated by a corresponding gauge transformation of the EM-field! \ \
In Quantum Field Theory the $(e^-, \nu)$ and quark multiplets are not only invariant under phase transformations, but they are also invariant under certain groups of (unitary) matrices (with determinant 1) that mix the components of the fields in a specific way.
The $(e^-, \nu)$ multiplet is (at high energies) also invariant under the non-Abelian group $SU(2)$ while the quark multiplet in also invariant under the non-Abelian group $SU(3)$. Hence the name non-Abelian gauge fields / non-Abelian Yang-Mills theory.
Just as we had to introduce a gauge field (the Electromagnetic field) to make the Dirac equation truely invariant under these phase transformations we need to introduce other gauge fields (the $W^\pm$ and $Z$ gauge fields in the case of the $SU(2)$ transformations of the $(e^-, \nu)$ to make this multiplet truely invariant under these $SU(2)$ transformations. The gluons (which are actually 8 different gauge fields) are the fields that make the quarks invariant under these $SU(3)$ transformations.
So to give a simple answer to your question: the quark-gluon plasma is typically a non-Abelian plasma (I hope you can put some more terms in context now). The paper you mentioned studies more general supersymmetric versions of these non-Abelian gauge theories with larger multiplets and larger gauge groups.


text:
Q: Adding NON duplicate elements to an expandable array I am trying to add elements of type ENTRY in this array. But before adding I want want to make sure its not a duplicate as I don't want duplicate entries. Tried a lot but it keeps doesn't add entries :/ I tried BREAK from the IF clause as well didn't seem to work. Is there something really silly I'm missing  ? Would really appreciate if someone could help me. Cheers
import java.util.Arrays;

public class PhoneDirectory {
    private Entry[] ar;
    static int index = 0;

    public PhoneDirectory() {
        ar = new Entry[0];
    }

    public PhoneDirectory(Entry[] ent) {
        ar = ent;
    }

    public boolean addEntry(Entry ent) throws NullPointerException {

        boolean newEntry = true;
        for (int i = 0; i < ar.length; i++) {

            if (ar[i] == ent) {
                newEntry = false;

            else
                newEntry = true;
        }

        int length = ar.length;
        Entry[] temp = new Entry[length];

        for (int x = 0; x <= length - 1; x++) {

            temp[x] = ar[x];
        }

        length++;
        ar = new Entry[length];

        // add the new entry in the last index
        for (int i = length - 1; i >= 0; i--) {

            if (newEntry == true) {

                ar[i] = ent;
                newEntry = false;
                // return true;
            } else {

                // ar[i] = temp[i];
                return false;
            }
        }

        return true;

    }
}

A: You could use Set , dynamically add the data and maintain uniqueness
Set<Entry> entries = new HashSet<Entry>();
//note you will have to implment `equals()` & `hashcode()` in `Entry` class
//and then simply
entries.add(entry1);
entries.add(entry2);
entries.add(entry3);

It grows by it self you don't need to handle it + it maintains uniqueness,
If you want to preserve the order in set then you need to use LinkedHashSet
In your code
for (int i = 0; i < ar.length; i++) {

        if (ar[i] == ent) {
            newEntry = false;

        else
            newEntry = true;
    }

you are comparing two objects so you need to override equals() in your Entry class and then you need to use ar[i].equals(ent) to check (and not the ==)
also ,
For example ent matches with value at index 2 and array is of size 4 then at last index newEntry would be set to true and so it will allow this entry,  Use break; when you find the already existing entry

A: In the addEntry function you created the temp array with all the previous entries in the PhoneBook. Then you reassigned ar as a new array. However, you never repopulated the new ar with the previous entries you stored in temp.
length++;
ar = new Entry[length];

//copy the temp entries back into the new ar
for (int i=0; i<= temp.length-1; i++){
  ar[i] = temp[i];
}

Also you need to add a break in your newEntry loop:
boolean newEntry = true;
for (int i = 0; i < ar.length; i++) {

    //comparing object should use equals
    if (ar[i].equals(ent)) {
        newEntry = false;
        //add break;
        break;
    }
    else
        newEntry = true;
}

I don't think you need a for loop to add the lastest entry
Instead of :
   for (int i = length - 1; i >= 0; i--) {

        if (newEntry == true) {

            ar[i] = ent;
            newEntry = false;
            // return true;
        } else {

            // ar[i] = temp[i];
            return false;
        }
    }

Try this
int i = length-1;

if (newEntry == true) {
  ar[i] = ent;
  newEntry = false;
  return true;
} else {
   return false;
}

A: This is your problem:
    if (ar[i] == ent) {
        newEntry = false;

    else
        newEntry = true;

You really want:
if (ar[i].equals(ent)) {

It is unlikely your entries will be == to each, which means the same instance, not just an equivalent object.

A: Make sure you have overridden the equals method on the Class ENTRY
for (int i = 0; i < ar.length; i++) {

    if (ar[i].equals(ent)) {
        newEntry = false;
        break;
    }
    else
        newEntry = true;
}


text:
Q: Not able to deploy python script to heroku I can't able deploy my script to Heroku because of below error
-----> Python app detected
-----> Installing "python-3.6.0"
-----> Installing pip
-----> Installing requirements with pip
   /app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/bin/steps/pip-install: line 7: /app/.heroku/python/bin/pip: No such file or directory
!     Push rejected, failed to compile Python app.
!     Push failed

I have setup virtualenv in that folder which is shown below
env  Procfile  namaztimesms.py  requirements.txt  runtime.txt

Now my Procfile contain
web: python namaztimesms.py

requirements.txt file contains
beautifulsoup4==4.5.3
requests==2.13.0

runtime.txt contains
"python-3.6.0"

I don't know what I do next??Is something wrong with virtualenv or it has not installed properly??


text:
Q: C++ templates with specialization and inlining in header vs source files First, I am aware of those SO posts, but they do not answer my question (or if they do, I do not understand):
What is template<> inline bla bla
C++ template and inline
My question is the following: what is the reason why some of those cases work, and one fails with regards to template specialization? What are the mechanisms at stake? (this code was used on Arduino 1.8, but I guess it is general C++ features?).

Case 1: this works fine, including template specialization:
serial output:
specialized template bla!!
general template: 10

in main.ino:
#include "template.h"

const int i = 10;

void setup(){
  Serial.begin(115200);
  delay(10);
  Serial.println("booted");
}

void loop(){
  template_print("bla!!");
  template_print(i);

  Serial.println();

  delay(5000);
}

in template.h:
#ifndef TEMPLATE
#define TEMPLATE

template <typename T>
inline void template_print(T data){
    Serial.print("general template: ");
    Serial.println(data);
}

template <>
inline void template_print(const char * data){
    Serial.print("specialized template ");
    Serial.println(data);
}

#endif

Case 2: this works fine, including template specialization.
in main.ino: the same.
in template.h:
#ifndef TEMPLATE
#define TEMPLATE

template <typename T>
void template_print(T data){
    Serial.print("general template: ");
    Serial.println(data);
}

template <>
void template_print(const char * data){
    Serial.print("specialized template ");
    Serial.println(data);
}

#endif

Case 3: this works fine
in main.ino: the same
in template.h:
#ifndef TEMPLATE
#define TEMPLATE

template <typename T>
void template_print(T data){
    Serial.print("general template: ");
    Serial.println(data);
}
#endif

in template .cpp:
#include <Arduino.h>
#include "template.h"

template <>
void template_print(const char * data){
    Serial.print("specialized template ");
    Serial.println(data);
}

Case 4: this compiles, but the template specialization does not work:
Serial output:
general template: bla!!
general template: 10

main.ino: the same as case 1
template.h: the same as case 3
template.cpp:
#include <Arduino.h>
#include "template.h"

template <>
inline void template_print(const char * data){
    Serial.print("specialized template ");
    Serial.println(data);
}

Edit
I had made a mistake, actually case 2 works.


text:
Q: Can't switch to number keyboard iOS My app won't allow users to switch keyboards to the number/character keyboard.
I don't have anything in my UI Inspector showing over the bottom of the screen.

I am truly stumped as to what could be causing this issue. Whatever it is blocks the number/symbol switcher, the keyboard language (or Emoji) selector, and the speech to text button. The space bar and return key on the same row continue to operate fine.
The affected UITextField's are subclassed, the keyboard works as expected on the other 5 views in which they are contained, but here is their code:
JCTextField.h
#import <UIKit/UIKit.h>

IB_DESIGNABLE
@interface JCTextField : UITextField

@property (nonatomic, retain) IBInspectable UIColor *underlineColor;
@property (nonatomic) IBInspectable CGFloat underlineWidth;
@property (nonatomic, retain) IBInspectable UIImage *sideImage;
@property (nonatomic) IBInspectable CGFloat internalOffset;
@property (nonatomic) IBInspectable CGFloat borderOffset;

@end

JCTextField.m
#import "JCTextField.h"

@implementation JCTextField

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self != nil) {
        self.underlineColor = [UIColor blackColor];
        self.underlineWidth = 1;
        self.internalOffset = 0;
        self.borderOffset = 0;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CALayer *border = [CALayer layer];
    border.borderColor = _underlineColor.CGColor;
    border.frame = CGRectMake(_borderOffset, self.frame.size.height - _underlineWidth, self.frame.size.width - (_borderOffset * 2), self.frame.size.height);
    border.borderWidth = _underlineWidth;
    [self.layer addSublayer:border];
    self.layer.masksToBounds = YES;

    [self setValue:[UIColor lightTextColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self setTextColor:[UIColor whiteColor]];
    [self setFont:[UIFont fontWithName:@"Montserrat-Regular" size:16.0]];

    if (self.sideImage) {
        UIImageView *sideImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width - 30, 0, 30, 30)];
        sideImageView.contentMode = UIViewContentModeCenter;
        sideImageView.image = self.sideImage;
        [self addSubview:sideImageView];
    }

    [self setTintColor:[UIColor whiteColor]];

    [self setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];

}

- (CGRect)textRectForBounds:(CGRect)bounds {
    if (self.sideImage) {
        UIEdgeInsets insets = UIEdgeInsetsMake(0, _internalOffset, 0, 18);
        return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)];
    }
    UIEdgeInsets insets = UIEdgeInsetsMake(0, _internalOffset, 0, 0);
    return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)];
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    if (self.sideImage) {
        UIEdgeInsets insets = UIEdgeInsetsMake(0, _internalOffset, 0, 18);
        return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)];
    }
    UIEdgeInsets insets = UIEdgeInsetsMake(0, _internalOffset, 0, 0);
    return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)];
}

@end


text:
Q: Restoring Virtualmin backup fails: "Cannot change ownership" I'm attempting to restore my DNS settings from a virtualmin backup after reinstalling bind9.  I've selected only the DNS to be restored, as per the advice in this link, regarding duplication of directories exceeding capacity.  However, when I go for it, I'm confronted with the following:
Starting restore of 1 domains from local file /home/name/2013-12-04_12.00/mysite.com.tar.gz ..

Extracting backup archive file ..
.. extraction of /home/name/2013-12-04_12.00/mysite.com.tar.gz failed :

/bin/tar: ./.backup/upsmart.com_web_alog: Cannot change ownership to uid 1003, gid 33: Disk quota exceeded
/bin/tar: ./.backup/upsmart.com_web_elog: Cannot change ownership to uid 1003, gid 33: Disk quota exceeded
/bin/tar: Exiting with failure status due to previous errors

.. failed! See the progress output above for the reason why.

Any ideas as to what might be going wrong?
Any input would be greatly appreciated.

A: Disk quota exceeded <-- that would be a good starting point for your investigation.
Someone (the user with UID 1003) is over their disk quota.
Your system won't let that user have any more disk space, so you can't extract the backup data to restore it.
Either adjust the user's disk quota (see your operating system's manual, or the Virtualmin documentation for instructions), or delete some of their files so they have enough room within their disk quota to extract the backup.


text:
Q: Can't reference css stylesheet in template being loaded by python I'm new to using Python and have came across a problem when trying to reference my style-sheet from a .tpl document.
My python, template and css documents are all in the same directory however when I load the page using the CMD to "localhost:8080" it shows the template without the style being applied.
In my template document index.tpl i have referenceed three stylesheets:
<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="animate-custom.css" />

And my python file outputs the template: index.py:
from bottle import route,template,debug,run
import sqlite3

@route('/')
def player():
    return template('index.tpl')

debug(True)
run(reloader=True)

A: I haven't used bottle, but most web frameworks require you to put your css/js/images in a particular directory (that you set via configuration). Usually it's called "static" or something similar.
I bet if you tried to load those CSS files directly in your browser:
http://localhost:8080/demo.css

you'd get a 404.
The way you have it currently set up is what you'd do for traditional PHP/CGI stuff - your web server is looking for files on disk and serving them. Frameworks don't (generally) work like that - you set up routing rules.
You did that with the @route('/') decorator - by setting that up, you told bottle "any requests to http:// localhost:8080/ should run the player function and return whatever it generates."  Notice you haven't set up any rules for your css files.
The other possibility is you're not referring to the CSS files correctly in your HTML. If you don't get a 404 when you load the CSS files directly, post the HTML and we can take a look at that.
Edit: Found this in the bottle doc:
http://bottlepy.org/docs/dev/tutorial.html#routing-static-files
Static files such as images or CSS files are not served automatically. You have to add a route and a callback to control which files get served and where to find them:
from bottle import static_file
@route('/static/<filename>')
def server_static(filename):
  return static_file(filename, root='/path/to/your/static/files')


text:
Q: Ruby Factory method can not find attribute? The following Ruby code almost works. In the Mage and Warrior class, I gave it an attribute toon and want to print out the value, but it gives me this error.
C:/rails/11.rb:37:in <main>': undefined methodtoon' for # (NoMethodError)
What is wrong?
class Party
    attr_reader :member

    def initialize(occupation)
        member = create(occupation)
    end
end

class PartyFactory < Party
    def create(occupation)
        if occupation == :warrior
            Warrior.new
        elsif occupation == :mage
            Mage.new
        else
            raise "Unknown hero"
        end
    end
end

class Mage
    attr_accessor :toon
    def initialize
        @toon = "woor"
    end
end

class Warrior
    attr_accessor :toon
    def initialize
        @toon = "WAR"
    end
end

party = PartyFactory.new(:warrior)

puts party.toon

A: You created a party object. Within that Party object you created a warrior object, but you didn't save it to the object so it isn't accessible outside of the class.
For example if you do this:
@warrior = Warrior.new

Now you can access that warrior like so:
party.warrior.toon

EDIT: Make sure to add warrior as an attr_reader

A: There are a few problems with your PartyFactory class. If this class is in fact a factory, it should not inherit from the Party class. It should be an entirely different class that is responsible for creating parties.
I would change the Party constructor to take its member directly.
class Party
  attr_reader :member

  def initialize(member)
    @member = member
  end
end

I would change the PartyFactory class so that it doesn't inherit from the Party class.
class PartyFactory
  def create(occupation)
    if occupation == :warrior
      Warrior.new
    elsif occupation == :mage
      Mage.new
    else
      raise "Unknown hero"
    end
  end
end

To call the toon method you first need to create the party with the factory and then call the toon method on the party's member.
factory = PartyFactory.new
party = factory.create(:warrior)
party.member.toon


text:
Q: Overwritting border for active li doesn't work when fixed menu has overflow-y So, I want to have a simple menu with a border-right of 1 px black. And then, I want the active li to override the border-right to 1px white. My code works, except when I add an overflow-y: scroll to my fixed menu.
Here you can see what I mean, there's a fixed menu that's scrollable but the active styling doesn't take effect. If you comment the overflow-y line, you'll see the active styling does work then.
https://jsfiddle.net/6bd4b6ty/2/

.menu{
  border-right: 1px solid black;
  box-sizing: border-box;
  width: 100px;
  height: 200px;
  left: 0;
  top: 0;
  position: fixed;
  overflow-y: scroll; /* comment this line */
}

ul{
  list-style: none;
  width: 100px;
  margin: 0;
  padding: 0;
}

li{
  height: 40px;
  border-bottom: 1px solid black;
  width: 100px;
}

a{
  height: 40px;
  width: 100px;
  display: block;
  box-sizing: border-box;
}

a.active{
  border-right: 1px solid white;
}

potato

cheese

tomato

cucumber

carrot

garlic

Any ideas on how to solve this, obviously I want the menu to be scrollable at the same time that the active border works :P Thanks!

A: Don't fix width for the menu, set it to auto
See it working, I changed the active border-color to red for visiblility

.menu{
    box-sizing: border-box;
    width:auto;
    height: 200px;
    left: 0;
    top: 0;
    position: fixed;
    /* overflow:visible; */
    overflow-y: scroll; /* comment this line */
}

ul{
  list-style: none;
  width: 100px;
  margin: 0;
  padding: 0;
}

li{
  height: 40px;
  border-bottom: 1px solid black;
  width: 100px;
}

a{
  height: 40px;
  width: 100px;
  display: block;
  box-sizing: border-box;
  border-right: 1px solid black;
}

a.active{
  border-right: 1px solid red;
}

potato

cheese

tomato

cucumber

carrot

garlic

A: Using :after selector you can achieve this

.menu{
  box-sizing: border-box;
  width: auto;
  height: 200px;
  left: 0;
  top: 0;
  position: fixed;
  overflow-y: scroll; /* comment this line */
}
.menu:after{
  content:"";
  position:absolute;
  width:1px;
  height:123%;
  background:#000;
  right: 0;
  top: 0;
  z-index: 0;
}
ul{
  list-style: none;
  width: 100px;
  margin: 0;
  padding: 0;
  position: relative;
  z-index:1;
}

li{
  height: 40px;
  border-bottom: 1px solid black;
  width: 100px;

}

a{
  height: 40px;
  width: 100px;
  display: block;
  box-sizing: border-box;
  // border-right: 1px solid black;
}

a.active{
  border-right: 1px solid red;
}

potato

cheese

tomato

cucumber

carrot

garlic

A: Please change the code as shown below. My edits are commented. The explanation is below the code snippet.

.menu{
  /*border-right: 1px solid black;*/ /* I deleted this line*/
  box-sizing: border-box;
  width: 100px;
  height: 200px;
  left: 0;
  top: 0;
  position: fixed;
  overflow-y: scroll;
}

ul{
  list-style: none;
  width: 100%; /* Changed from px to % */
  margin: 0;
  padding: 0;
}

li{
  height: 40px;
  border-bottom: 1px solid black;
  width: 100%; /* Changed from px to % */
}

a{
  border-right: 1px solid black; /* I added this*/
  height: 40px;
  width: 100%; /* Changed from px to % */
  display: block;
  box-sizing: border-box;
}

a.active{
  border-right: 1px solid white;
}

potato

cheese

tomato

cucumber

carrot

garlic

CHANGES
First Change
Remove the border-right from .menu class. And add the same border-right to a tag.
Second Change
In three places, the px is changed to %.
EXPLANATION
For First Change
The .main has width of 100px. When the horizontal scrollbar appears the width of .main will be 100px including the scrollbar. That is the reason the border-right comes after the scrollbar.
To eliminate this, remove the border-right from .main and add the border-right to a tag.
For Second Change
The reason for the appearing of vertical scrollbar, even though the width of all the child element is same, is as follows:
Since the horizontal scrollbar is appeared some content of the child is gone under that horizontal scrollbar. To view these contents, a vertical scrollbar is required.
By making the px to %, the remaining width (i.e. width of .main minus horizontal scrollbar width) will be considered as 100%, thus we can eliminate this problem.

A: The border appearing after scrollbar is a strange behavior.
But if you want a work-around to get the final output. Check the shared code snippet below.

* {
  box-sizing: border-box;
  /* browser reset code */
}
.menu {
  width: 100px;
  height: calc(40px * 6);
  /* actual height of UL */
  padding: 0;
  border-right: 1px solid red;
  margin: 0;
  list-style: none;
}
.grand-parent {
  width: 100px;
  overflow: hidden;
  height: 200px;
  position: fixed;
  left: 0;
  top: 0;
}
.parent {
  overflow-y: scroll;
  height: 200px;
  width: 125px;
  /* width + approx scrollbar width */
}
li {
  height: 40px;
  border-bottom: 1px solid black;
  width: 100px;
}
a {
  height: 40px;
  width: 100px;
  display: block;
  box-sizing: border-box;
}
a.active {
  border-right: 1px solid white;
}

potato

cheese

tomato

cucumber

carrot

garlic

A: Working Demo !!!
Remove border style in menu and add into li elements.
li{
  border-right: 2px solid blue;
  height: 40px;
  border-bottom: 1px solid white;
  width: 100px;
}
li .active{
  border-right: 2px solid white!important;
  /* border-right: 2px inset #fff!important; */
}


text:
Q: Question with PIL.putdata() and For loop to append the modified images to a new list I have an image that I want to make 5 copies.
import PIL
from PIL import Image

image=Image.open("image.gif")
image=image.convert('RGB')
images=[]
for i in range(1, 6):
    images.append(image)

After making some changes to the intensity of each color in the RGB band, I want to load this data onto these 5 pictures (each item in the "RGB_band" list is a tuple containing different pixel modifications, and each tuple is unique from one another).
RGB_band= [modification_1,modification_2,modification_3, modification_4, modification_5]

new_images=[] #loop to load new pixel information onto the pictures and append to a new list.
for i in range(len(images)):
    images[i].putdata(RGB_band[i])
    new_images.append(images[i])

I was expecting each image in the "new_images" list to have different color intensity (i.e. first image should show the pixel data from modification_1, second image shows pixel data from modification_2, etc), but instead all 5 images in "new_images" list are the original image from the list "images" (unmodified). However, during the "For" loop, if I have it this way:
for i in range(len(images)):
    images[i].putdata(RGB_band[i])
    new_images.append(images[i])
    new_images[i].show()

Then the image shown during each iteration has the correct color (i.e. 5 images shown with 5 different colors)
Could anyone please tell me what the problem is? I tried different thing in the "For" loop but the images in "new_images" list still came out the same.

A: I don't know what you are trying to do, but I think you have failed to realise that Python objects need to be copied in order to be unique objects with their own allocated memory.
Compare this, where each image in the list is sharing memory with the other items:
image=Image.open("image.png").convert('RGB')
images=[]
for i in range(1, 6):
    images.append(image)

If you now look at the list - specifically the addresses on the right you can see they are all the same thing:
print(images)

[<PIL.Image.Image image mode=RGB size=1000x300 at 0x1084C3C10>,
 <PIL.Image.Image image mode=RGB size=1000x300 at 0x1084C3C10>,
 <PIL.Image.Image image mode=RGB size=1000x300 at 0x1084C3C10>,
 <PIL.Image.Image image mode=RGB size=1000x300 at 0x1084C3C10>,
 <PIL.Image.Image image mode=RGB size=1000x300 at 0x1084C3C10>]

And if we check whether they share memory:
print(images[0] is images[4])
True

Now look at this when I copy each image so that it is a unique copy with its own data:
Uimages=[]
for i in range(1, 6):
    Uimages.append(image.copy())

Now look at the list and see the addresses are different:
print(Images)
[<PIL.Image.Image image mode=RGB size=1000x300 at 0x108797790>,
 <PIL.Image.Image image mode=RGB size=1000x300 at 0x108797F50>,
 <PIL.Image.Image image mode=RGB size=1000x300 at 0x1087973D0>,
 <PIL.Image.Image image mode=RGB size=1000x300 at 0x108797510>,
 <PIL.Image.Image image mode=RGB size=1000x300 at 0x1084DB450>]

And check if they are the same object:
print(Uimages[0] is Uimages[4])
False

In general, if you start treating images as lists of pixels, you have probably already gone wrong. It is inefficient and slow. Consider using Numpy or OpenCV and using vectorised code.


text:
Q: Linear regression least square method Right now, I'm studying linear regression using the least squares method. So, if $f(x)=ax+b$, I have to find
$$\min\sum(y-ax-b)^2.$$ But why does this minimum exist, and is there only one minimum or multiple of them?

A: We are minimizing
$$Q(a,b) = \sum (y_i -a x_i-b)^2.$$
Since $Q$ is a differentiable function in $\mathbb{R}^2$, any minimiser must be a stationary point, hence a solution of
$$
\frac{\partial Q}{\partial a} = \sum 2 (-x_i)(y_i-ax_i-b) = 0
$$
$$
\frac{\partial Q}{\partial b} = \sum 2 (-1)(y_i-ax_i-b) = 0
$$
i.e.
$$
\begin{cases} 1\cdot b + \bar x \cdot a =& \bar y\\
\bar x \cdot b + \overline{x^2} \cdot a =& \overline{xy}
\end{cases}
$$
This is the so-called normal system. When $\overline{x^2}-\bar x^2\ne 0$, that is, when the variance is not zero, the system has one and only one solution. This solution must in fact be a global minimum, due to the convexity of $Q$. As it was pointed out, the Hessian matrix, given by
$$
\begin{pmatrix}
2n & \sum x_i^2\\
2 \sum x_i &  2\sum x_i^2,
\end{pmatrix}
$$
is positive definite when the variance of $x$ is positive (just compute the minors' determinants).
Finally, you can try to figure out what happens when the variance is zero (all x's are the same).


text:
Q: Как изменить свойство primaryStage.setTitle Необходимо при нажатии кнопки на форме изменять значение primaryStage.setTitle();
Main.java
package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("view.fxml"));
        primaryStage.setTitle("Исходная форма");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
        primaryStage.setResizable(false);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Controller.java
package sample;

import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Controller {
    @FXML
    public Button btnRed = new Button();
    @FXML
    public Button btnYellow = new Button();
    @FXML
    public Button btnGreen = new Button();
    @FXML
    public Pane PaneM = new Pane();

    Tooltip tooltipRed = new Tooltip();
    Tooltip tooltipYellow = new Tooltip();
    Tooltip tooltipGreen = new Tooltip();

    public void tooltipsValues() {
        tooltipRed.setText("RED");
        tooltipGreen.setText("GREEN");
        tooltipYellow.setText("YELLOW");
    }

    public void initialize(){
        btnRed.setTooltip(tooltipRed);
        btnYellow.setTooltip(tooltipYellow);
        btnGreen.setTooltip(tooltipGreen);
    }

    public void onClickRed() {
        PaneM.setStyle("-fx-background-color: #7e1300");
        btnRed.setDisable(true);
        btnGreen.setDisable(true);
        btnYellow.setDisable(false);
    }

    public void onClickYellow(){
        PaneM.setStyle("-fx-background-color: #7e7d10");
        btnYellow.setDisable(true);
        btnRed.setDisable(true);
        btnGreen.setDisable(false);
    }

    public void onClickGreen(){
        PaneM.setStyle("-fx-background-color: #2d8e26");
        btnGreen.setDisable(true);
        btnYellow.setDisable(true);
        btnRed.setDisable(false);
    }
}

A: Вы должны передать в контроллер ссылку на stage и потом можно будет поменять заголовок.
public void start(Stage primaryStage) throws Exception{
   FXMLLoader loader = new FXMLLoader(getClass().getResource("/view.fxml"));
   Parent root = loader.load();
   // получить ссылку на контроллер
   Controller controller = loader.getController();
   // передать stage в контроллер
   controller.setStage(primaryStage);

   primaryStage.setTitle("Исходная форма");
   primaryStage.setScene(new Scene(root));
   primaryStage.show();
   primaryStage.setResizable(false);
}

Кусок контроллера
private Stage stage;

public void setStage(Stage stage) {
    this.stage = stage;
}

public void onClickRed() {
    paneM.setStyle("-fx-background-color: #7e1300");
    btnRed.setDisable(true);
    btnGreen.setDisable(true);
    btnYellow.setDisable(false);
    // меняем заголовок окна
    stage.setTitle("RED");
}


text:
Q: What is the purpose of Object.create() in this piece of code? EDIT:
I understand the purpose of Object.create() in general. But i need to know why it is used in the below code as it makes no difference at all.
I found the below code in this article. I can understand that fruits.call(this); will essentially inherit the properties from fruits to any instance of apple that gets created. Then why do we need to do apple.prototype = Object.create(fruits.prototype); Can anyone explain the purpose of this line? I tried executing the code without the that line and it still runs with no issues.
function fruits() {
    this.name = 'fruit 1';
}

function apple() {
    fruits.call(this);
}

apple.prototype = Object.create(fruits.prototype);
const app = new apple();
console.log(app.name);

// Output: fruit 1


text:
Q: How to make dividers in navbar like breadcrumb? I want to make "dividers" between links in navbar automatically.

before: Home Library Logout
  after: Home / Library  / Logout

How can I do this?

A: Try this.
and check example at CODEPEN
HTML:

HOME

ABOUT US

SERVICES

WORK

BUSINESS

CONTACT

CSS:
div.navbar a {
  display: inline-block;
}

ul li:after {
  content: "/";
}

ul li:last-child:after {
  content: "";
}

I hope it helps you


text:
Q: Is it possible to paint without using a Frame of any sort in Java? I am wondering whether I am able to use the paint method of Java's graphics class on something other than a JFrame--that is, no JFrames allowed. Is it possible?
Thanks in advance!

A: Graphics represents a graphic context, i.e. something you can draw on. In addition to GUI components like JFrame, JPanel etc. providing getGraphics() to access the visible gfx context, another common class that allows access to a gfx context is BufferedImage (or Image classes in general).
While painting on a visible GUI element immediately shows the results of the painting, using a BufferedImage allows you to perform the painting off screen into a buffer, and then painting the whole image at once (on a JFrame as you still need something visible) when you're ready to display the image. This is often used in animation and games when you need to avoid flickering for example.


text:
Q: Check if the number is round, if not then round it I have a little python project. Just for fun. There you can add when you want to shutdown your pc. At the beginning you can choose seconds/minutes/hours, and if you choose minutes than the input number* 60 will be in the "shutdown.exe /s /t ...). (It's only working with round numbers, even than 1.5*60 will be round at the end.) I want to check if the ...*60 will be a round number or not. And if it isn't than round it and run with the round number. There is the code part what i am talking about:
minutes = input(":")
if minutes >= "1":
    minutes = int(minutes)
    minsec = (minutes*60)
    minsec = str(minsec)
    os.system("shutdown.exe /s /t " + minsec)

 You can see the full code here.
(I just started learning python and that's my first question, sorry if something isn't understandable.)

A: regardless if the value is round or not, just cast it to integer aka round it using int(yourvalue) the value will always be round.

A: I used eval(), this worked:
minutes = input(":")
if minutes >= "1":
    #Minutes Calculation
    minsec = str(int(eval(minutes) * 60))
    #Shutdown with time
    os.system("shutdown.exe /s /t " + minsec)


text:
Q: WPF: font (size) renders differently on XP and Vista/7 The code is pretty much straightforward:
<TextBlock TextAlignment="Center" Text="{Binding TimeAgo}" Foreground="White" FontSize="12" FontFamily="Calibri" Background="Transparent"/>

As far as I know, WPF has native support for Calibri font. However, the font renders differently on XP and on Vista/7:
XP:

Vista:

My main issue is with the font's size (It renders bigger on XP) since I have dedicated, limited space for the text.
I am currently using UseLayoutRounding="True" but removing it didn't make any difference. I'm also using:
<ResourceDictionary Source="/PresentationFramework.Aero, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />

But removing it also didn't make any difference (In terms of the font's size).

A: WPF does not have native support for any font, it can only use the fonts installed on the machine.
The bigger text is not Calibri (it looks like Arial or Tahoma to me), you can look at the shape of the "g" to see those are not the same font.
You can only use Calibri on XP if you or another software (like Office 2007 or later) installed it first.


text:
Q: how to update image stored on folder I have a grid-view that displays a projects table with both update and delete options. My problem is with updating the project images. When I update the project and UploadPhoto.HasFile=false, this means I am not choosing image. In the else statement, I want to get the project image as the default or get the project image. This is my code :
 int projectid = Convert.ToInt32(e.CommandArgument);

  if (UploadPhoto.HasFile)
                {

                    try
                    {
                        if (UploadPhoto.PostedFile.ContentType == "image/jpeg" ||
                            UploadPhoto.PostedFile.ContentType == "image/.jpg" ||
                            UploadPhoto.PostedFile.ContentType == "image/.psd" ||
                            UploadPhoto.PostedFile.ContentType == "image/.png" ||
                            UploadPhoto.PostedFile.ContentType == "image/.gif")
                        {
                            if (UploadPhoto.PostedFile.ContentLength < 8729744)
                            {
                                string filename = Path.GetFileName(UploadPhoto.FileName);
                                UploadPhoto.SaveAs(Server.MapPath
                                    ("~/ProjectsImages/" +
                                      projectid + filename));

                            }

                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else
                {

                    string relativePath = "/ProjectsImages/";
                    var path = Server.MapPath(relativePath);
                    string[] filePaths = Directory.GetFiles(path, projectid + "*");
                    UploadPhoto.FileName = filePaths; //here what i want to do

                }
// At this line I update the project and UploadPhoto.FileName = null
// This overrides the project image

                context.Update_Project_Detail(txtProjectName.Text,
                    txtAreas.Text,
                    DateTime.Parse(txtEditDate.Text),
                    txtClassification.Value,
                    UploadPhoto.FileName, projectid);

What I want in the else statement, is to get the projectimage name and assign it to UploadPhoto.filename.


text:
Q: Use current repo's user.email for commits in VS Code I use Git with two different emails / profiles, resulting in:
git config user.email >> myRepoEmail@address.com
git config --global user.email >> myGenericEmail@address.com

If I use VS Code and open a terminal, my commits use the repo email address; this makes sense because I am effectively using Git (not VSCode). However, if I use the Source Control Git sidebar and type a commit message, Ctrl+Enter to commit, etc., then it commits using the global email (myGenericEmail@address.com), even though I am working in a repo which has a different setup.
Is there a way to tell VS Code to use the repo's settings for commits, rather than invoking --global for commits?
[EDIT in info from comments]
I suppose I should mention I have in my gitconfig the command
[includeIf "gitdir:C:/Users/myname/privateRepoFolder"]
    path = ~/gitconfig-private

and in that alternate gitconfig-private, I have
[user]
    email = myRepoEmail@address.com

A: With Git 2.8 or more, I would actually recommend:
git config --global user.useConfigOnly true

And then launch VSCode.
That way, VSCode could not default to a generic email if, for any reason, it does not find your user.name/user.email configured in any local repo: it would have to ask you who you are in that repo.

A: I finally had a chance to check on Windows.
From your comments:

I suppose I should mention I have in my gitconfig the command
  [includeIf "gitdir:C:/Users/myname/privateRepoFolder"] path =
~/gitconfig-private, and in that alternate gitconfig-private, I have
  [user] email = myRepoEmail@address.com.

On Windows, the includeIf conditional include is a little particular about the path.
First, make sure to end the path with a / to specify a directory, like in their example:
; include for all repositories inside /path/to/group
[includeIf "gitdir:/path/to/group/"]
    path = /path/to/foo.inc

So you should use:
[includeIf "gitdir:C:/Users/myname/privateRepoFolder/"]
    path = ~/gitconfig-private

I found that it also works by ending the path with the .git file (to be more explicit).
[includeIf "gitdir:C:/Users/myname/privateRepoFolder/.git"]
    path = ~/gitconfig-private

Second, for VSCode, it only works if you use case-insensitive path matching (gitdir/i):
[includeIf "gitdir/i:C:/Users/myname/privateRepoFolder/"]
    path = ~/gitconfig-private

This case-insensitive behavior is a known behavior of VSCode.
See the reported issue Git integration does not correctly support includeIf directive:

I tried to commit from VSCode, which failed to pick up the includeIf
  config. Then I ran the wrapper from the command line, and it did pick
  up the includeIf. I then checked the log:
In VSCode:
config --get-all user.name in c:\Users\zhuowei\Documents\repos\includeIf
Outside:
config --get-all user.name in C:\Users\zhuowei\Documents\repos\includeIf
Note the difference in the case letter.


text:
Q: intento simular el comando tail y head con python en windows estoy intentando crear un software que simule ser la terminal de linux (bash)
#-*- coding: utf-8 -*-
import subprocess
import os

def clear():
    subprocess.call(["cmd.exe","/c","cls"])

def ls():
    dirlist = os.listdir('.')
    for file in dirlist:
        print(file)

def mkdir():
    try:
        os.mkdir(cmd[6:])
    except Exception as e:
        print("ese directorio ya existe")

def cd(cdir):
    try:
        os.chdir(cdir)
    except Exception as e:
        print("el sistema no puede encontrar la ruta")
def rm(delfd):
    try:
        os.remove(cmd[2:])
    except Exception as e:
        print("no se ha encontrado la carpeta o directorio{}".format(delfd))

if __name__ == '__main__':
    wt = True
    while wt:
        cmd = str(raw_input("{}>".format(os.getcwd())))
        if cmd == "help":
            print('''de momento no pondré este comando porque el output eslargo y hace dificil leer el codigo''')
        elif cmd == "clear":
            clear()
        elif cmd [:2] == "ls" and cmd[2:] == "":
            ls()
        elif cmd[:6] == "mkdir ":
            mkdir()
        elif cmd[:2] == "cd":
            cd(cmd[3:])
        elif cmd[:2] == "rm":
            rm(cmd[2:])
        elif cmd[:4] == "echo":
            print(cmd[5:])
        elif cmd[:5] == "touch":
            open(cmd[5:], "w")
        elif cmd[:3] == "pwd":
            print(os.getcwd())

¿como puedo implementar los comandos head y tail?

A: Si entendemos por head, el mostrar las primeras 10 líneas de un archivo y tail las últimas 10. Puedes implementarlo de esta forma:
import os

def tail(filename, count=10, offset=1024):
    """
    A more efficent way of getting the last few lines of a file.
    Depending on the length of your lines, you will want to modify offset
    to get better performance.
    """
    f_size = os.stat(filename).st_size
    if f_size == 0:
        return []
    with open(filename, 'r') as f:
        if f_size <= offset:
            offset = int(f_size / 2)
        while True:
            seek_to = min(f_size - offset, 0)
            f.seek(seek_to)
            lines = f.readlines()
            # Empty file
            if seek_to <= 0 and len(lines) == 0:
                return ""
            # count is larger than lines in file
            if seek_to == 0 and len(lines) < count:
                return "".join(lines)
            # Standard case
            if len(lines) >= (count + 1):
                return "".join(lines[count * -1:])

def head(filename, count=10):
    """
    This one is fairly trivial to implement but it is here for completeness.
    """
    with open(filename, 'r') as f:
        lines = [f.readline() for line in xrange(1, count+1)]
        return "".join([l for l in filter(len, lines)])

Ligeramente adaptado de este código, lo que tiene de interesante, es que el tail muchas veces se plantea como la lectura completa del archivo para mostrar solo las últimas líneas, lo cual es muy poco performante con archivos realmente grandes, en este caso no se hace esto, sino leer en un buffer los últimos bytes y recuperar las líneas desde dicho buffer.
Para ejecutarlo, algo como esto:
print head(file)
print tail(file)

A: Estas son las dos funciones que tienes que implementar en tu código. Obviamente tienes que agregar el llamado a las funciones desde tu código principal y enviarle el nombre del archivo. Se incluye la captura de errores por si el archivo no existe o no se puede leer. Se usó el modulo itertools para mayor eficiencia con archivos grandes
import itertools

def head(textfile):
    try:
        with open(textfile) as data:
            text_iterator = itertools.islice(data, 0, 10)
            for element in text_iterator:
                print(element, end = '')
    except:
        print("[ERROR] El archivo no existe o no puede ser abierto")

def tail(textfile):
    try:
        with open(textfile) as data:
            all_lines = itertools.islice(data, 0, None)
            num_lines = sum(1 for _ in all_lines)
            data.seek(0)
            line_begin = 0 if (num_lines < 10) else num_lines - 10
            text_iterator = itertools.islice(data, line_begin, None)
            for element in text_iterator:
                print(element, end = '')
    except:
        print("[ERROR] El archivo no existe o no puede ser abierto")


text:
Q: Transparent triangle over an iframe or div I've got one problem. I need to include to my page one iframe with maps.
And I need one (or two) triangles over this iframe with a transparent background.

I've tried this solution, but it didn't work.
How can I realize it?

A: What you are trying to achieve is done by cropping the image in the shape of the arrow and giving it a negative margin so the element below overlaps the header image.
Proof of concept:

.example {
  -webkit-clip-path: polygon(0 0, 100% 0, 100% calc(100% - 20px), calc(50% + 20px) calc(100% - 20px), 50% 100%, calc(50% - 20px) calc(100% - 20px), 0 calc(100% - 20px));
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 20px), calc(50% + 20px) calc(100% - 20px), 50% 100%, calc(50% - 20px) calc(100% - 20px), 0 calc(100% - 20px));
  background: #fff url(https://source.unsplash.com/random/800x120) no-repeat 50% 50% /cover;
  pointer-events: none;

 /* the rest is only relevant for this snippet */

  height: 120px;
  margin-bottom: -20px;

}
.example > * {
  /* in case you place anything inside the header div */
  pointer-events: all;

}
.test {
  background-color: #777;
  min-height: 80px;
}

Considering the second element is a map, I assume you want the clicks on the overlapping area to go to the map, not to the header, so I added pointer-events:none to the header, reverting the property for its immediate children, so they respond to pointer actions.


text:
Q: Convert TXT file to CSV using Python I have the txt output, which I am willing to convert into CSV
Output(data.txt)

apache_web,/my_storage/nfs/indexes,18452
apache_web,/my_storage/nfs/indexes,0

OR
name_of_bucket:apache_web,bucket_id:/mystorage/nfs/indexes,size:18452
name_of_bucket:apache_web,bucket_id:/mystorage/nfs/indexes,size:0

Expecting
name_of_bucket,bucket_id,size
apache_web,/my_storage/nfs/indexes,18452
apache_web,/my_storage/nfs/indexes,0

A: file = open("data.txt", "r")

String = ""
for line in file:
    String += line

file.close()

file = open("data.csv", "a")
file.write(String)
file.close()

A: A .csv file is a plaintext format that is interpreted by Excel into cells, so you can just write that output into a ".csv" file extension like so:
with open("data.txt", "r") as f:
    content = f.readlines()

with open("data.csv", "w+") as csvfile:
    csvfile.write("name_of_bucket,bucket_id,size\n")
    csvfile.writelines(content)

A: So assuming you had a input file called data.txt that contained the following four lines, namely in both of your possible formats:
apache_web,/my_storage/nfs/indexes,18452
apache_web,/my_storage/nfs/indexes,0
name_of_bucket:apache_web,bucket_id:/mystorage/nfs/indexes,size:18452
name_of_bucket:apache_web,bucket_id:/mystorage/nfs/indexes,size:0

The following script can read each line, and remove the prefixes from each column and write the amended values back to an output.csv file:
import csv

header = ['name_of_bucket', 'bucket_id', 'size']

with open('data.txt', 'rb') as f_data, open('output.csv', 'wb') as f_output:
    csv_data = csv.reader(f_data)
    csv_output = csv.writer(f_output)
    csv_output.writerow(header)

    for row in csv_data:
        row = [cell.replace(r + ':', '') for cell, r in zip(row, header)]
        csv_output.writerow(row)

Giving you an output.csv file containing:
name_of_bucket,bucket_id,size
apache_web,/my_storage/nfs/indexes,18452
apache_web,/my_storage/nfs/indexes,0
apache_web,/mystorage/nfs/indexes,18452
apache_web,/mystorage/nfs/indexes,0

Firstly it makes use of Python csv library to automatically split entries in each row and make a list of values. Next it uses a list comprehension to remove the corresponding header value (with : appended) if present. Next it writes the modified list of entries to a new output file.
zip() is used to allow you to read one value at a time from multiple lists, in this case it takes one entry from the row (cell), and the corresponding header value (r) which it uses to do a string replace() to replace the text with an empty string, i.e. delete it if present.
Tested using Python 2.7.12


text:
Q: Nav bar links not working I am making a website using bootstrap. I have made a nav bar where I want the menu items to link to the different sites. However it is not working at all - it is usually never a problem getting links to work, but I am new in using Bootstrap and i feel like I'm missing something - do you need to have a js code to get your links to work? Normally I just write something like  I have put all the sites in the same folder and I have tried so many things now. I have also tried giving the items and ID and then adding a js code, but nothing happens.

$(document).ready(function() {
  $('#aboutus').on('click', function() {
    location.href = "About kopi.html";
  });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

    Name
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

          </button>

          Home (current)

          Portfolio

          About

A: Hi Maria and welcome to Stack Overflow.
The syntax for your a tag is correct. And thus it should work.
Saying that your link doesn't work, is extremely vague. What you could try:

*

*Make sure all your styles and scripts from Bootstrap are loaded. (This includes dependencies such as jQuery and Popper.js)

*Make sure the pages you're referring actually exist. (Does this file: Portfolio.html exist?)

A: It looks like you're using some classes that are specific to Bootstrap 4 in your markup, but including the Bootstrap 3 JS and CSS.
Try using the Bootstrap 4 files instead:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"/>


text:
Q: Widget update frequency I know this is easy, but how can i make my widget update every 24 hours this what am presently trying,
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:autoAdvanceViewId="@id/stack_view"
android:initialLayout="@layout/cepf_appwidget_layout"
android:minHeight="100dp"
android:minWidth="180dp"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="3600000" >
</appwidget-provider>

A: 24 hours = 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 86400000 milliseconds. Put this value to the android:updatePeriodMillis
P.S. Your current frequency is 3600000 milliseconds. This is: 3600000 / 1000 = 3600 seconds / 60 = 60 minutes = 1 hour.
Well, it's basic convertion. 1 hour is 60 minutes, 1 minute is 60 seconds, 1 second is 1000 milliseconds.


text:
Q: Magento removing item options in checkout order review section In my website i have enable one page checkout.Also there are only downloadable products.
I need to remove Item options in Checkout Order Review section (Please refer below image. I need to remove highlighted parts.)

Can anyone let me know how to do this please.
Thank You.

A: I think you want to remove custom option in checkout.
The custom options are displayed in the default template (in \app\design\frontend\base\default\template\checkout\cart\item\default.phtml) with the following snippet:
<?php if ($_options = $this->getOptionList()):?>

    <?php foreach ($_options as $_option) : ?>
    <?php $_formatedOptionValue = $this->getFormatedOptionValue($_option) ?>

<?php echo $this->escapeHtml($_option['label']) ?>

    <dd<?php if (isset($_formatedOptionValue['full_view'])): ?> class="truncated"<?php endif; ?>><?php echo $_formatedOptionValue['value'] ?>
        <?php if (isset($_formatedOptionValue['full_view'])): ?>

<?php echo $this->escapeHtml($_option['label']) ?>

<?php echo $_formatedOptionValue['full_view'] ?>

        <?php endif; ?>

    <?php endforeach; ?>

<?php endif;?>

So, you comment this or remove as per your convenience.
But in your case you are using onepage checkout So, you have to check this code in extensions phtml file.

A: You need to go in app\design\frontend\rwd\default\template\downloadable\checkout\onepage\review\item.phtml
Open item.phtml file
And in this file here is code what is displaying that
<?php if ($links = $this->getLinks()): ?>

<?php echo $this->getLinksTitle() ?>

            <?php foreach ($links as $link): ?>

<?php echo $this->escapeHtml($link->getTitle()); ?>

            <?php endforeach; ?>

<?php endif; ?>

So you can remove or just comment this  and you will get you want.
And yes go to your theme folder if your is not rwd.


text:
Q: Parse Phone Number into component parts I need a well tested Regular Expression (.net style preferred), or some other simple bit of code that will parse a USA/CA phone number into component parts, so:

*

*3035551234122

*1-303-555-1234x122

*(303)555-1234-122

*1 (303) 555 -1234-122

etc...
all parse into:

*

*AreaCode: 303

*Exchange: 555

*Suffix: 1234

*Extension: 122

A: This is the one I use:
^(?:(?:[\+]?(?<CountryCode>[\d]{1,3}(?:[ ]+|[\-.])))?[(]?(?<AreaCode>[\d]{3})[\-/)]?(?:[ ]+)?)?(?<Number>[a-zA-Z2-9][a-zA-Z0-9 \-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?<Ext>[\d]{1,5}))?$

I got it from RegexLib I believe.

A: None of the answers given so far was robust enough for me, so I continued looking for something better, and I found it:
Google's library for dealing with phone numbers
I hope it is also useful for you.

A: Strip out anything that's not a digit first.  Then all your examples reduce to:
/^1?(\d{3})(\d{3})(\d{4})(\d*)$/
To support all country codes is a little more complicated, but the same general rule applies.

A: This regex works exactly as you want with your examples:
Regex regexObj = new Regex(@"\(?(?<AreaCode>[0-9]{3})\)?[-. ]?(?<Exchange>[0-9]{3})[-. ]*?(?<Suffix>[0-9]{4})[-. x]?(?<Extension>[0-9]{3})");
Match matchResult = regexObj.Match("1 (303) 555 -1234-122");

// Now you have the results in groups
matchResult.Groups["AreaCode"];
matchResult.Groups["Exchange"];
matchResult.Groups["Suffix"];
matchResult.Groups["Extension"];

A: Here is a well-written library used with GeoIP for instance:
http://highway.to/geoip/numberparser.inc

A: here's a method easier on the eyes provided by the Z Directory (vettrasoft.com),
geared towards American phone numbers:
string_o s2, s1 = "888/872.7676";
z_fix_phone_number (s1, s2);
cout << s2.print();      // prints "+1 (888) 872-7676"
phone_number_o pho = s2;
pho.store_save();

the last line stores the number to database table "phone_number".
column values: country_code = "1", area_code = "888", exchange = "872",
etc.


text:
Q: VBA: Return multiple value in a single cell if the ID match Updated: I found the solution, that attached code will actually work. Still please put effort to read others comments as well
I am using find function to match ID in Report Worksheet with the ID in Master worksheet and return the data corresponding to the ID in Report Worksheet if there is a match. The code is only returning the ID data which every comes first in the search range in Master worksheet. It does not go till the end of the search range in Master Worksheet.
How do I make the ID search till the end of ID Column in Master Worksheet? If the ID has multiple match then return the multiple corresponding data in single-cell with a new line.
Master and report worksheet example:

Sub Match_Control()

    Dim firstMatchRow As Long
    Dim wshM As Worksheet
    Dim wshR As Worksheet
    Dim i As Long ' To start Counter
    Dim LastRow As Long 'To check for last used row in ID columns
    Dim rngMatch As Range ' To define range where the match has to be found
    Dim xreturn As String 'To store the string for single cell

    Set wshM = Worksheets("Sheet1") 'Worksheet where the data is coming from,it is a source worksheet
    Set wshR = Worksheets("Sheet2") 'Worksheet where the information will be paste if the condition is satisfied
    LastRow = wshR.Range("A" & wshR.Rows.Count).End(xlUp).Row 'Check for the last row in column A in SRDS ID worksheet. It will check from bottom and which is the first used row
    For i = 2 To LastRow 'counter from i=2 to last used row
        Set rngMatch = wshM.Range("A:A").Find( _
            What:=wshR.Range("A" & i).Value, _
            LookAt:=xlPart) 'Range (J:J) is where the data will be looked in SRDS to Control worksheet, Find is what we are looking for from the SRDS ID and jump to next row with IngRow counter,
                            'xlPart is what it will be looking at, instead of xlWhole I have used xlpart.

        If Not rngMatch Is Nothing Then
            firstMatchRow = rngMatch.Row

            Do

                wshR.Range("B" & i).Value = xreturn & rngMatch.Offset(0, 1).Value
                Set rngMatch = wshM.Range("A:A").FindNext(rngMatch)
                xreturn = wshR.Range("B" & i).Value & ", "
            Loop Until firstMatchRow = rngMatch.Row

        Else
            wshR.Range("C" & i).Value = "NOT FOUND"

        End If 'When the condition is executed and finished,
        xreturn = Empty 'To clear the xreturn value for next do loop
    Next i 'Increase the counter by 1 and go to search function again
End Sub

A: Edited to adapt to the updated question and written generically:
Option Explicit
Sub GroupByID()
    Dim dKey As Long
    Dim dItem As String
    Dim dict As Object
    Dim cell as Range
    Set dict = CreateObject("Scripting.Dictionary")
    For Each cell In Sheet1.Range("A2:A" & Sheet1.UsedRange.Rows.Count
        dKey = cell.Value
        If Len(dKey)>0 Then
            If Not dict.Exists(dKey) Then
                dict.Add dKey, cell.Offset(0,1).Value
            Else
                dict.Item(dKey) = dict.Item(dKey) & vbCr & cell.Offset(0,1).Value
            End If
        End If
    Next
    Sheet2.Cells(2, 1).Resize(dict.Count) = Application.Transpose(dict.Keys)
    Sheet2.Cells(2, 2).Resize(dict.Count) = Application.Transpose(dict.Items)
End Sub

Answer to previous version of question:
When usingFind on a single column, I store the row number from the first match in a variable before entering a Do loop that repeatedly calls FindNext.  FindNext doesn't remember where it has been and will happily  find cells it has already found and continue finding them until the heat death of the universe.   The infinite loop is avoided by comparing that variable to the row number of every subsequent match and then exiting the loop if they are equal.   Or put another way, the loop starts by trying to find the second match so the only way a row number can equal the first match is if the last match was found and the loop restarted.
It might look something like this...
    For lngRow = 2 To lngLastRow
         Set rngMatch = wshM.Range("A:A").Find( _
             What:=wshR.Range("D" & lngRow).Value, _
             LookAt:=xlPart)
         If Not rngMatch Is Nothing Then
             firstMatchRow = rngMatch.Row
             Do
                 wshR.Range("E" & rngMatch.Row).Value = rngMatch.Offset(0, 1).Value
                 Set rngMatch = wshM.Range("A:A").FindNext(wshR.Range("D" & lngRow).Val)
             Loop Until firstMatchRow = rngMatch.Row
         Else
             wshR.Range("F" & lngRow).Value = "NOT FOUND"
         End If
     Next lngRow

Some things to watch out for:
The new variable firstMatchRow is not declared.  It should beLong
I did not presume to know the importance of your For loop so I kept it intact; but it is unlikely that you wanted to to write all matches to the same cell. So I took the liberty of changing the ouput row.
For and FindNext don't always compliment each other very well. You may want to reconsider your looping strategy depending on your requirements.
This is one keystroke away from an infinite loop, consider adding Do Events as a precaution against a locked Excel session.
Look into Application.ScreenUpdating


text:
Q: Does the IETF publish versions RFCs that include errata? When reading an RFC published by the IETF, it's hard to know what content has been corrected without explicitly checking the errata. For example, in RFC 7049 Section 2.4.2, the following correction exists in the errata:
diff --git a/rfc7049.txt b/rfc7049.txt
index 5d29907..c7c20e6 100644
--- a/rfc7049.txt
+++ b/rfc7049.txt
@@ -886,7 +886,7 @@ RFC 7049                          CBOR                      October 2013
    and eight bytes 0x00).  In hexadecimal:

    C2                        -- Tag 2
-      29                     -- Byte string of length 9
+      49                     -- Byte string of length 9
          010000000000000000  -- Bytes content

But to realize this particular section was corrected, I'd have to go through the errata beforehand and write down all the sections that have corrections. Then, if I come across a section that was corrected, I'd have to look back at the errata and find what that particular correction was.
So, to simplify this process, does the IETF publish versions RFCs that include errata?

A: From what I understand, a standards track IETF RFC is a reference, and therefore, should not change. This is why errata are published separately. However, the IETF does indeed provide RFCs with the errata included with the following caveat:

This is a purely informative rendering of an RFC that includes verified errata. This rendering may not be used as a reference.

For this particular RFC, one may find the version with errata included at the following location:
https://www.rfc-editor.org/rfc/beta/errata/RFC7049.html, which was navigated to from https://datatracker.ietf.org/doc/rfc7049/ by clicking the with errata button in the Document > Formats section.


text:
Q: how to covert regular expression in simplest form?
I have made this expression from nfa (NFA to regular expression) :
   (a+ab+aab)(a+aa) but at book answers it is written like this : (a+aab)(aa)
I am thinking that the my answer is same as book but they have converted it into it just like quadratic equation as we do. SO any one who can help me or book answer is wrong or mine is wrong BUT IF BOTH ARE SAME THEN TELL ME HOW TO CONVERT INTO BOOK FORM?


text:
Q: Flask configuration handling from external file I have set all configurations inside Configure class belonging to settings.py module
import os, secrets
basedir = os.path.abspath(os.path.dirname(__file__))

class Config():
    SECRET_KEY = secrets.token_hex(16)
    SQLALCHEMY_DATABASE_URI ='sqlite:///' + os.path.join(basedir, 'sqlitedb/data.sqlite')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    MAIL_SERVER = 'smtp.gmail.com'
    MAIL_PORT = 587
    MAIL_USE_TLS = True
    ...........

Which is initialized by main app.py
from flask import Flask
from MyProject.extensions import db, mail, bootstrap, migrate
**from MyProject.settings import Config**
from werkzeug.security import generate_password_hash, check_password_hash

def create_app():
    app = Flask(__name__.split('.')[0])
    app.url_map.strict_slashes = False
    **app.config.from_object(Config)**
    register_extensions(app)
    register_blueprints(app)
    return app

My task is to handover the SECRET_KEY value as an argument to the function which is inside other (mail.py) module
from itsdangerous import URLSafeTimedSerializer
from Myproject.app import mail
from Myproject import app
def send_congrats_email(user):
    confirm_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
    confirm_url = url_for(
        'confirm_email',
        token=confirm_serializer.dumps(user, salt='email-confirmation-salt'),
        _external=True)

    send_email('[Congrats] You are registered',
               sender= "NICOLAS",
               recipients=[user.email],
               html_body=render_template('users/email_confirmation.html',
                                         user=user))

Please, advice what is the right/proper way of doing this task?

A: Solution to such problem is the following:
from flask import current_app

and then modify:
confirm_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])

to
confirm_serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])