text:
Q: Trouble loading CSV files import xlrd
import pandas as pd
data = pd.read_csv("/Milk_Papers_Estimated_Class.csv")
path ='/Milk_Papers_Estimated_Class.csv'

I experience an error in the following code while trying to run the .csv file.:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 504: invalid continuation byte.

I do not know why I am facing this error.Can anyone help me out with this?

A: By default the read_csv takes utf-8 as the encoder.
data = pd.read_csv("/Milk_Papers_Estimated_Class.csv", encoding='latin-1')

Try giving the encoding as latin-1
Might work:")


text:
Q: Why can't I call function from inside chrome.downloads.onChanged? I'm creating an extension in chrome for the first time (I'm not a web, or javascript developer).  I'm adding onto a codebase that is in an older version of javascript that I've never used (Once I'm at a computer with that codebase, I'll tag which version it is, but I can't remember).
I have a class called DownloadManager, and inside of it I am calling chrome.downloads.onChanged, and within it, I call another function inside of the class, but it can't recognize the class (I think that's the issue).
// Class named DownloadManager
function DownloadManager(someData) {

    this._myData = someData;

    // function that does a thing, and tests run successfully
    this.doAThing = function(someData) {
        // Code in here that we assume works, and there's no issues.
    }

    if(chrome.downloads) {
        chrome.downloads.onChanged.addListener(function(delta) {
            // Error here
            this.doAThing(delta.data);
        }
    }
}

The error I'm getting is on the this.doAThing(this._myData); line.  The error is Error in event handler for downloads.onChanged: TypeError: Cannot read property 'doAThing' of null at <URL>.
I'm assuming it's a scoping issue, and this. doesn't mean anything there, and it can't access doAThing there.  I'm certain that the argument taken in is of the same type as the function declared above.
I'll add more data when I'm back in that environment.

A: Inside your event handler for chrome.downloads.onChanged the this keyword now has a different context than this inside the DownloadManager. It might make sense that since you defined the event handler within the downloadManager that you could share the variable, but that just happens to be a coincidence of "where the code was defined vs where the code is invoked from".
You could probably get away with assigning this to a variable in the main scope:
function DownloadManager(someData) {
    this.doAThing = function(someData) {
        // Code in here that we assume works, and there's no issues.
    }

    window.myScope = this;

    if(chrome.downloads) {
        chrome.downloads.onChanged.addListener(function(delta) {
            // Error here
            window.myScope.doAThing(delta.data);
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tagging foreign text using isascii in python I would like to create a very simple non-English word identification script which replaces every word in a text with a <FOREIGN> tag if that word contains any specific non-English character. For this I used the .isascii() method.
I have the following sample string:
s = "abc def déf äëü المزيد 한글  - 1 2 3 4 5"

And the following is the expected output:
s_exp = "abc def <FOREIGN> <FOREIGN> <FOREIGN> <FOREIGN> - 1 2 3 4 5"

My current working implementation is:
import re
for word in s.split():
    if not word.isascii():
        s = re.sub(word, "<FOREIGN>", s)

While this works perfectly for small amount of data, I am worried about its performance on 100,000s of rows of textual data organized in a pandas dataframe. I was wondering if there is any solution that might be better performing than this for loop. At the moment, I am using
df['Text'].apply(lambda x: replace_nonenglish(x)) where replace_nonenglish is:
def replace_nonenglish(s):
    for word in s.split():
        if not word.isascii():
            s = re.sub(word, "<FOREIGN>", s)
    return s

Note:
I am fully aware that this will provide a bunch of false negatives, i.e. non-English words not tagged as <FOREIGN> such as the French "bien" or the German "gut" but that is acceptable for now.

A: You can also use
import re
s = "abc def déf äëü المزيد 한글  - 1 2 3 4 5"
print( re.sub(r"\b[a-zA-Z]*[^\W\d_a-zA-Z][^\W\d_]*\b", "<FOREIGN>", s) )
# => abc def <FOREIGN> <FOREIGN> <FOREIGN> <FOREIGN>  - 1 2 3 4 5

See the Python demo and a regex demo.
Details:

*

*\b - a word boundary (it is Unicode aware in Python by default)

*[a-zA-Z]* - zero or more ASCII letters

*[^\W\d_a-zA-Z] - any Unicode letter but an ASCII letter

*[^\W\d_]* - zero or more Unicode letters

*\b - a word boundary.

With the PyPi regex library (install with pip install regex in your terminal/console window) it would look a bit cleaner:
import regex
s = "abc def déf äëü المزيد 한글  - 1 2 3 4 5"
print( regex.sub(r"\b[a-zA-Z]*[^\P{L}a-zA-Z]\p{L}*\b", "<FOREIGN>", s) )

See this Python demo. Here, \p{L} matches any Unicode letter and \P{L} matches any char other than a Unicode letter.


text:
Q: Magento 2 How to Remove a Top Link Using Layout ifconfig In Magento 2 how can I remove a link from top.links via layout? I am assuming you can do this because every link is block in the top.links node is a its own block.

This is was a question I had earlier today. Because there is little
  information on this I will answer my own question and hopefully this
  will be of help for other people.

A: Lets say if you want to remove the sign in link. You first need to find out the parent block, then create a conditional action (using the ifconfig attribute) to unset a child block and then pass the alias/name of the child block as an argument.
<referenceBlock name="top.links">
    <action method="unsetChild" ifconfig="section_id/group/enabled">
        <argument name="alias" xsi:type="string">authorization-link</argument>
    </action>
</referenceBlock>

Note: ifconfig only accepts true or false (1/0) and will only unset the child if the value is true.


text:
Q: Celery worker variable sharing issues I am using Python and celery in a project. In the project, I have two files:
celeryconfig.py
BROKER_URL = "amqp://guest:guest@localhost:5672//"
CELERY_RESULT_BACKEND = "amqp"
CELERY_IMPORTS = ("example",)
CELERYD_CONCURRENCY = 2

and example.py
from celery.task import task
import hashlib

md5 = hashlib.md5()

@task
def getDigest(text):
    print 'Using md5 - ',md5
    md5.update(text)
    return md5.digest()

In celeryconfig.py, I set the CELERYD_CONCURRENCY to 2, which means that it will distribute the tasks in my task queue to 2 different processes.
From a Python console, I run:
from example import getDigest
getDigest.delay('foo');getDigest.delay('bar')

This creates two tasks that are simultaneously executed by the two workers.
The problem is, as both of the worker processes run their task functions [getDigest()], they seem to be using the same hash object (md5). The output of celeryd confirms this as you can see below.
[PoolWorker-2] Using md5 -
[PoolWorker-2] <md5 HASH object @ 0x23e6870>
[PoolWorker-1] Using md5 -
[PoolWorker-1] <md5 HASH object @ 0x23e6870>

For the sake of simplicity, I am using the md5 object of hashlib, but in my actual project, I am using an object that cannot be accessed and modified by more than one process. This  expectedly makes the workers crash.
That brings up the question: How can I modify my code to make the worker processes initialize and use their very own (md5) object? Right now, they are sharing the same object - causing my application to crash. Is this possible?

A: They're using the same object because you're explicitly telling them to in your code. By creating the object outside the scope of the task and using it within the task, you are giving all workers access to the shared object. This is a concurrency issue, not necessarily a Celery issue. You could use a copy of the object if it's small, or use your own locking strategy. In general, though, if an object is going to be updated by more than one process at a time, it needs to employ some sort of synchronization, which is outside of the scope of Celery.


text:
Q: Meteor Mongo find does not work for _id: 0 I have a template named qa and inside it I am using a helper named question, which will get the text field of my document, based on the _id property.
Template.qa.helpers({
    question: function () {
        return Questions.find({_id: 24}).fetch()[0].text;
    }
});

This works fine for all _id values unless I use _id: 0, then nothing is returned. I run db.questions.find({_id: 0}) on the minimongo console, and it does return a document.
{ "_id" : 0, "author" : 0, "create" : "2014-12-22T13:26:23.038Z", "liked" : [ ], "range" : "", "text" : "I want to get this text", "update" : "2014-12-22T13:26:23.038Z", "version" : 1 }

Can I not use _id: 0 in collection.find() for Meteor?
Clarification: I do not want to return all fields except _id, I want to find/select based on the _id value. But it does not work if the _id is 0.

A: I think you want to avoid falsy _id values.  Meteor replaces a falsy _id with a random number to prevent it ever going to the database.  The comments on the code explain it:
// protect against dangerous selectors.  falsey and {_id: falsey} are both
// likely programmer error, and not what you want, particularly for destructive
// operations.  JS regexps don't serialize over DDP but can be trivially
// replaced by $regex.


text:
Q: Removing noise generated by a servo from an audio signal Background
I'm working on an Arduino-based audio visualisation project where I run an audio signal into the Arduino, using an FFT to calculate the intensities at different frequencies and then using that to power various servo motors depending on the intensities.
When I just had audio running into the Arduino everything worked well and the FFT calcuated the expected values.
When I connected the servo motor, however, I got large amounts of noise in the audio signal cable and the resultant values from the FFT were all over the place.
Fixing the Issue
From doing research on the internet I found that I most likely need to use a filter to remove this noise. I have a few questions:

*

*Would I need to use a high-pass filter or a low-pass filter?

*How would I know what capacitance to use?

*Would I need to apply the filter on the signal cable or on the cables to the servo (in case of the servo would I be filtering the power cable or the PWM control cable)?

If there is a another method for removing noise that I have not considered, please let me know :)

A: I had a special-effects project which included both servos and audio (via a 40W amplifier), with the same problem you describe.
Originally, power was ran from a battery via one cable to a PCB which then distributed power to various devices including the servos, RF receiver, and audio amplifier. Noise from servos was unacceptably high on the audio output.
The solution that worked was to bring power from the battery separately to the audio amplifier. This effectively meant adding another ~2 meter length of wires from the battery. Electrically, it may seem identical, but in fact moving the junction for power and ground further from the servo motors cut the noise to a usable level.
One of the comments mentions star earthing which is akin to this suggestion - instead of having ground shared by different systems on a perfboard, running separate lengths of cable introduced enough impedance that it effectively filtered out the noise without adding additional components. You may, however, still want to add filtering components.


text:
Q: Lazy loading thumbnail images I am trying to lazily load a dynamic thumbnail view.
I have to put images in thumbnail view one by one and until images are not available I have to display temporary image like placeholder. Any guidelines please?

A: See the accepted answer in this thread. You wouldn't need the last-in first-out stack, but it shows how to load images asynchronously using grand central dispatch, which is quite straightforward. You don't need to think about complicated thread management. :)

A: You could go about like this -

*

*Create a UIImageView with a default placeholder image.

*Fetch your image in a background thread. You want to do it like this
because, fetching image in the main UI thread blocks it till the
image is fetched, which severely hampers UI responsiveness. There
are several libraries available which do this for you. They even
cache the images. SDWebImage is great!

*See if you get a valid HTTP 200 response back i.e. a valid image. If yes, then replace the new image with placeholder image. Else let the placeholder image be.

Hope this helps...


text:
Q: Show that $\Sigma_{n=1}^\infty |z_n| $ converges. Assume $z_k = |z_k|e^{i\alpha_k}$ are complex numbers
and that exists $0<\alpha<\pi/2$ s.t $\forall k -\alpha < \alpha_k<\alpha$
assume that $\Sigma_{n=1}^\infty z_n $ converges.
we need to show that $\Sigma_{n=1}^\infty |z_n| $ converges.
I kind of have no idea how to approach this one, its from a test I attended and I'm going for a second go at it and I want to understand the first one, first.

A: Hint: compare the real part of $z_n$ to $|z_n|$.

A: Hint:  Two parts:
1) $\sum z_n$ converges iff $\sum Re(z_n)$ and $\sum Im(z_n)$ converge
2) $Re(z_n) = |z_n|\cos(\alpha_n) \geq |z_n|\cos(\alpha)$
Can you do the rest?


text:
Q: Prove that $\tau \sigma \tau ^{-1}$ depends only on the lateral class of $\tau$ with respect to $Z(\sigma)$ I want to prove that, given $\sigma, \tau, \tau  ' \in S_n$, we have that:

$\tau ' \in \tau H \Longleftrightarrow \tau \sigma \tau ^{-1}= \tau ' \sigma (\tau ')^{-1}$

Where $H=Z(\sigma)$ is the centralizer of $\sigma$. I proved $(\Longrightarrow)$:
If $\tau ' \in \tau H$, then $\tau '=\tau \rho$ where $\rho \in H$. This means that $\tau ' \sigma (\tau ')^{-1}=\tau \rho \sigma \rho ^{-1} \tau ^{-1}=\tau \sigma \tau ^{-1}$.
I don't know what to do for ($\Longleftarrow$).

A: If $\tau\sigma\tau^{-1} = \tau'\sigma(\tau')^{-1}$, then premultiplying both sides by $(\tau')^{-1}$ and postmultiplying by $\tau$ gives
$$(\tau')^{-1}\tau\sigma = \sigma(\tau')^{-1}\tau.$$
Thus $(\tau')^{-1}\tau\in H = Z(\sigma)$.


text:
Q: Please help me to answer this conditional probability question Question:

So, for part (a), my answer is:
$$ {10 \choose 8} (0.6)^8 (0.4)^2 + {10 \choose 9}(0.6)^9 (0.4)^1 + {10 \choose 10 } (0.6)^10 (0.4)^0 = 0.1673$$
I am not sure how to answer part (b).
What I thought of:
Let $X$ = number of correct answers
    $Y$ = number of answers known
Therefore:
$P(X\ge 9|Y\ge 8) = \frac{P\left(X\ge9, Y=8 \right) + P\left(X\ge9, Y=9 \right) + P\left( X\ge 9 , Y=10 \right)}{P\left( Y\ge 8 \right)}$
In this case, the denominator is the answer to part (a).
I am not sure if I got the numerator right. I think I enumerated all the possible cases but now when I want to compute the first term in the numerator, I need to (I think) compute:
Probability know any 8 correct answers and guess any 1 answer correctly and any 1 answer wrong + Probability know any 8 correct answer and guess 2 correctly.
I am not sure how to compute the above and I am not even sure if this is the way to proceed

A: Hint:
$$P(X≥9, Y≥8) = P(X=9, Y=8) + P(X=10, Y=8) + P(X=9, Y=9) + P(X=10, Y=9) + P(X=10, Y=10)$$

How to calculate $P(X=9, Y=8)$?

*

*I knew 8 answers: the probability for that is $\left(\frac{3}{5}\right)^8$

*I guessed one answer correct: the probability for that is $\frac{2}{5}\frac{1}{3}=\frac{2}{15}$

*I guessed one answer incorrect and didn't knew it: the probability
for that is $1-\frac{3}{5}-\frac{2}{5}\frac{1}{3}=\frac{4}{15}$.

There are $\frac{10!}{8!\cdot 1!\cdot 1!}$ ways to order  these answers, so:
$$P(X=9, Y=8) = \frac{10!}{8!\cdot 1!\cdot 1!}\cdot \left(\frac{3}{5}\right)^8 \cdot \frac{2}{15} \cdot \frac{4}{15}$$


text:
Q: Capturing a program window with BitBlt always returns the same image I wrote the following code (C++ Win32) to capture a game window screen and get pixel color array from the image. Function autoB() does the job.
Then I draw the result array into my window to visually check what I got.
The problem is that this program works only once after I start the computer, after the first time it "caches" the first screenshot taken from the game and I always get the same array of pixels. Even if I close and restart the program I get the same screenshot.
The game is not using DirectX to draw on the screen and I'm always able to take screenshots using Alt+PrtSc.
Any help in understanding why it's happening this way is appreciated.
int getPixels(HDC *eClientHdcMem, HBITMAP *eClientBmp, unsigned char **lp) {

BITMAP bmpScreen;
    BITMAPINFOHEADER bi;

GetObject(*eClientBmp, sizeof(BITMAP), &bmpScreen);

LONG bW = bmpScreen.bmWidth, bH = bmpScreen.bmHeight;

bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bW;
bi.biHeight = -bH;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;

DWORD dw = ((bW * bi.biBitCount + 31) / 32) * 4 * bH;
*lp = new unsigned char[dw];

return GetDIBits(*eClientHdcMem, *eClientBmp, 0, (UINT)bH, *lp, (BITMAPINFO *)&bi, DIB_RGB_COLORS);

}

void autoB() {
HWND hwnd;
HDC hDC0 = NULL, eClientHdcMem = NULL;
HBITMAP eClientBmp = NULL;
BITMAP bmp = {0};
unsigned char *lp = NULL, *sp = NULL;
WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
RECT vp;
int vpW, vpH;
long iW, iH;

if (!(hwnd = FindWindow(NULL,TEXT("Client")))) return;
if (!(hDC0 = GetDC(hwnd))) return;

GetWindowInfo(hwnd,&wi);
vp = wi.rcClient;
vpW = vp.right - vp.left;
vpH = vp.bottom - vp.top;

if (!(eClientBmp = CreateCompatibleBitmap(hDC0, vpW, vpH))) return;
if (!(eClientHdcMem = CreateCompatibleDC(hDC0))) return;
SelectObject(eClientHdcMem, eClientBmp);

BitBlt(eClientHdcMem, 0, 0, vpW, vpH, hDC0, 0, 0, SRCCOPY);

int res = getPixels(&eClientHdcMem, &eClientBmp, &lp);

DeleteObject(eClientBmp);
DeleteObject(eClientHdcMem);

    // begin testing
HDC sts = GetDC(hStats);
HBITMAP stsBmp = CreateCompatibleBitmap(sts, vpW, vpH);
HBITMAP stsBmpOld = (HBITMAP)SelectObject(sts, stsBmp);
unsigned char r,g,b;
for(unsigned int i=0;i<vpW;i++) {
    for(unsigned int j=0;j<vpH;j++) {
        r = lp[(vpW*j+i) * 4 + 2];
        g = lp[(vpW*j+i) * 4 + 1];
        b = lp[(vpW*j+i) * 4 + 0];
        SetPixel(sts,i,j,RGB(r,g,b));
    }
}
SelectObject(sts, stsBmpOld);
DeleteObject(stsBmp);
DeleteObject(stsBmpOld);
ReleaseDC(hStats,sts);
    // end testing

DeleteDC(eClientHdcMem);
ReleaseDC(hwnd,hDC0);

delete [] lp;
lp = NULL;
delete [] sp;
sp = NULL;

}

The only way to change the screenshot is to restart the game. Then again, the first screenshot is captured and will be displayed over and over again regardless of what's happening in the game window.

A: Are you sure you're getting back the same pixels, or are you just seeing the same image on your screen in your debug window? The original image copy code looks OK, but in your "debug" code, even though you are calling SetPixel() directly, you still need to call InvalidateRect() to cause Windows to send a new WM_PAINT message. If you're not doing that, you're probably just looking at the old image, even though the new bits have indeed been captured (but not drawn).

A: I came across the same problem and I noticed that the HDC variable (hDC0 in your case) used to call CreateCompatibleDC and in turn BitBlt makes the difference. If you use GetDC(NULL) you will get the iamge of the whole screen and in this case the image is updated every time, while using GetDC(myWindowHwnd) gives the problem you were mentioning that is always the same image is returned without any refresh.
The window I want to capture is a full screen, topmost window which has been created like this:
    hwnd = CreateWindowExA(0, "myWindow", "myWindow", WS_POPUP, x, y, w, h, NULL, NULL, wc.hInstance, NULL);

    SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED | WS_EX_TRANSPARENT);
    SetLayeredWindowAttributes(hwnd, 0, 0xFF, LWA_ALPHA);
    ShowWindow(hwnd, SW_SHOW);
    SetWindowPos(hwnd, HWND_TOPMOST, x, y, w, h, SWP_NOACTIVATE);

Even if the windows is displayed and is above all other windows the BitBlt function fails to capture the updated frames of the window while this is updated by another thread.


text:
Q: Close All Popups with Leaflet.js I'm working on a map using Leaflet.js that uses a number of markers (eventually there will be ~40 markers). Each marker has a related popup with details. The default behaviour of Leaflet.js seems to be to automatically open at least one marker's popup (the last listed marker, I believe).
I'd like all the popups to be closed on the initial loading of the map page so users have to click the markers to open the popups. Does anyone know how to do this?

A: There is a clean method from your map object to close all open popups
map.closePopup();

A: Just remove your calls to .openPopup().
Instead of
L.marker([57.70887, 11.97456]).addTo(map).bindPopup("Ideal Festival
2004").openPopup();

Use
L.marker([57.70887, 11.97456]).addTo(map).bindPopup("Ideal Festival
2004");

The click behavior will still be there (when users click on those markers, the popups will still appear), but the popups won't be visible when the page loads.

A:   map.closePopup();

did not work for me as well and did not close the most recent popup.
So, I used the approach that was mentioned earlier with some modifications. Here is what worked for me.
Generalization of what  user2304819  suggested:
  var ButtonremoveNotidfications = L.easyButton({
                id: 'ButtonremoveNotidfications',
                states: [{
                    stateName: 'Show',
                    icon: 'Clear notifications',
                    title: 'Show',
                    onClick: function (btn) { //Below is the closing module
                        var aa = $(".leaflet-popup-close-button").length
                        if (aa > 0) {
                            for (var i = 0; i < aa; i++) {
                                $(".leaflet-popup-close-button")[i].click();
                            }
                        }
                    }
                }]
            });
            ButtonremoveNotidfications.button.style.width = widthbuttonstyle;
            ButtonremoveNotidfications.button.style.height = heightbuttonstyle;
            ButtonremoveNotidfications.button.style.color = 'blue';
            ButtonremoveNotidfications.addTo(map);

A: I managed to solve my problem by this piece of code:
$(".leaflet-popup-close-button")[0].click();

Hope it helps someone in future.

A: $(".leaflet-popup-close-button").click()

try this after your map load completes.

A: popup.removeFrom(map)
Is what worked for me.

A: If you haven't created layers for the popups, use:
 map.eachLayer(function (layer) {
      layer.closePopup();
 });

A: @florian-boudot's https://stackoverflow.com/a/36940867/2095317 answer is right but there is a cache
If you see the documentation closely, closePopup method works only in 2 cases

*

*It closes the last popup opened using openPopup method

*If a popup object is passed as an argument, it closes only that popup

Here is an example
// initiate your popup
let popup = L.popup()
          .setLatLng([lat,lang])
          .setContent("text")

// use the leaflet map object
map.openPopup(popup);

// close the popup after 5s

// Case 1: closes popup as it was the last popup object opened with map object
setInterval(() => map.closePopup(), 5000);

// Case 2: If you want to be more accurate/specific which popup to close
// and have the popup object in a variable pass the popup object
setInterval(() => map.closePopup(popup), 5000);


text:
Q: Daily/weekly average usage frequency should be used as a ratio scale or a ordinal scale I measured the usage frequency using a 6-point method. (1=rarely used; 2=1–3 times a week; 3=4–6 times a week; 4=1–3 times a day; 5=4–6 times a day; and 6=more than 7 times per day).
Next, I do a regression analysis using usage frequency as the independent variable. I re-coded it to average daily usage as below: ( rarely used=1/10; 1–3 times a week=2/7; 4–6 times a week=5/7; 1–3 times a day=2;4–6 times a day=5; more than 7 times per day=8).
but it seems to become a ratio scale, however, the distance between each scale point is not equal, is this correct? Should this variable be calculated as an ordinal scale?


text:
Q: How can I add a description to show when clicked on an image? When I click on an image it opens up in a bigger image box. I want to add a description to each image that opens up under the image box when I open that particular image. As shown in the picture I want to display the description to that particular image under the larger image box when the image is clicked.

$(document).ready(function() {
  $(".Thumbnail a").click(function(e) {
    e.preventDefault();
    $(".imgBox img ").attr("src", $(this).attr("href"));
  });
});

document.addEventListener("mousemove", showImage);
document.addEventListener("mouseleave", showImage);
document.addEventListener("scroll", showImage);

function showImage() {
  var items = document.getElementById("thumbnail").getElementsByTagName("li");
  Array.from(items).forEach(function(e) {
    if (e.getElementsByTagName("img")[0].matches(":hover")) {
      //put whatever you want in here
      e.style.backgroundColor = "blue";
    } else {
      //likewise put whatever you want in here
      e.style.backgroundColor = "red";
    }
  });
}

A: I would be inclined to use figure for this as it makes a neat wrapper for both an image and a caption.

// Cache a container, and add a listener to it
const container = document.querySelector('div');
container.addEventListener('click', handleClick, false);

function handleClick(e) {

  // If the clicked element is an image
  if (e.target.matches('img')) {

    // Get its parentNode (figure)
    const parent = e.target.parentNode;

    // Get the `figcaption`
    const caption = parent.querySelector('figcaption');

    // Toggle its `showcaption` class
    caption.classList.toggle('showcaption');
  }
}
figure { display: inline-block; }
figure img:hover { cursor: pointer; }
figcaption { visibility: hidden; }
.showcaption { visibility: visible; }

Dummy image

Dummy image 2


text:
Q: jquery remove/hide list option not containg string value from other list I have a problem updating select options.
<select id="all">
    <option value="Volvo_A">Volvo_A</option>
    <option value="Volvo_B">Volvo_B</option>
    <option value="Volvo_C">Volvo_C</option>
    <option value="Saab_A">Saab_A</option>
    <option value="Saab_B">Saab_B</option>
    <option value="Saab_C">Saab_C</option>
    <option value="Saab">Saab</option>
    <option value="Mercedes_A">Mercedes_A</option>
    <option value="Mercedes_B">Mercedes_B</option>
    <option value="Mercedes_C">Mercedes_C</option>
    <option value="Mercedes">Mercedes</option>
    <option value="Audi_A">Audi_A</option>
    <option value="Audi_B">Audi_B</option>
    <option value="Audi_C">Audi_C</option>
</select>

<select id="type">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>
<button type="button" id="Filter">Filter</button>

I want to update select list with id all based on value from select list with id type using Jquery. For example if volvo is selected from select with id type, then all option which do not contain volvo in select list with id all should be hidden temporarily.
How can I achieve this.
I tried the following code but did not work.
$( "#Filter" ).click(function( event ) {
  var filter = $("#type").val();
  $("#all > option[value != filter]").remove();
});

A: $(function(){
   $('#type').change(function(){
       var val_type = $(this).val().toLowerCase();
       $('option', '#all').each(function(){
           if( $(this).val().toLowerCase().indexOf(val_type) === -1 ){
               // Not right type
               $(this).prop('disabled', true).hide();
           } else {
               // Is right type
               $(this).prop('disabled', false).show();
           }
       });
       // If the selected option is not longer possible then choose the first possible option
       if( $('option', '#all').filter(':selected').is(':disabled') ){
           $('#all').val($('option', '#all').not(':disabled').first().val());
       }
   }).change();
});

Note: I have amde the comparision case-insenitive via toLowerCase() since otherwise nothing is selected.  See it working here.
However, a better option performance-wise would be to add a class to each option in the #all select with which to match the allowed values.
Edit: just seen the filter button.  Had read it initially as wanting it on a change event so that is the way I have done it.  But not difficult to convert the code the run on the button click instead.
Edit: Here is a version using classes which will be more efficient if the lists get big.

A: http://jsfiddle.net/H2eCw/
$( "#Filter" ).click(function( event ) {
  var filter = $("#type").val();
    console.log($("#all > option:not([value^=\"Volvo\"])"));
            console.log(filter);
    $("#all > option").show();
    $("#all > option:not([value^=\""+filter+"\"])").hide();
    $("#all").val($('#all>option:visible:first').val());
           //$("#all > option:not[value ^= "+filter+"]").remove();
});

Hide/Show instead of Remove..

A: Heres a jsfiddle
of it working.
function Test(val){

    $("#all > option").each(function() {
        if(this.value.indexOf(val)== -1){
            $(this).remove();
        }
});
}


text:
Q: django prefetch when listing objects in admin I have following models:
class UserProfile(models.Model):
  name = models.CharField()
  info = models.OneToOneField(UserInfo, related_name='user')

class UserInfo(models.Model):
  def __unicode__(self):
    return self.user.__unicode__() + self.age
  age = models.IntegerField()

class Ticket(models.Model):
  userinfo = models.ForeignKey(UserInfo)

The problem is now in the Ticket admin interface. Ticket's userinfo field is rendered as dropdown. If there is lots of UserInfo in the database, every one of them makes a single call to the database (UserProfile) to generate its name.
How can I tell the admin (or any widget) to prefetch related UserProfiles when it is rendering the UserInfo dropdown?
I am looking for something like
info = models.OneToOneField(UserInfo, related_name='user', prefetch_in_bulk=True)

A: I figured out one way to do this:
class TicketAdminForm(forms.ModelForm):
  class Meta:
    model = Ticket
  userinfo = forms.ModelChoiceField(queryset=UserInfo.objects.prefetch_related('user').all())

class TicketAdmin(admin.ModelAdmin):
  form = TicketAdminForm

admin.site.register(Ticket, TicketAdmin)

Now the needed models are prefetched as a one sql query rather than many queries.


text:
Q: tkinter get selected element from combobox without button I'm trying to find a way to get the tkinter combobox selected element without using a button, or to get the value from command in button, however so far nothing is working for me.
here's an example code (that's not working):
def show_frame(frame, prev_frame):

    selected_elem = combobox.get()

    if selected_elem == "choose element":
        label = Label(frame1, text="please choose an element!")
        label.grid(row=4, column=0)

    else:
        prev_frame.grid_forget()
        frame.grid(row=0, column=0, sticky='nsew')

    return selected_elem

elem= ""
button = Button(frame1, text="enter", command=lambda: elem==show_frame(frame3, frame1))
button.grid(row=2, column=1, padx=10, pady=10)

Is there a way to get it also outside of this function? this was just an idea that I had but as I mentioned, it's not working...

A: You need the bind method to watch for a selected element:
import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.title("Combobox")

selected_elem = tk.StringVar(value='value1')
combobox = ttk.Combobox(root, textvariable=selected_elem)
combobox['values'] = ('value1', 'value2', 'value3')
combobox.pack(fill=tk.X, padx=20, pady=20)

myLabel = tk.Label(root, text=selected_elem.get())
myLabel.pack()

# prevent typing a value
combobox['state'] = 'readonly'

# place the widget
combobox.pack(fill=tk.X, padx=5, pady=5)

# bind the selected value changes
def value_changed(event):
    """ handle the value changed event """
    myLabel.configure(text=selected_elem.get())
    myLabel.pack()

combobox.bind('<<ComboboxSelected>>', value_changed)

root.mainloop()

more info here:
https://www.pythontutorial.net/tkinter/tkinter-combobox/


text:
Q: Regex to match any number of repititions except k I'm trying to find all text which doesn't match the following pattern ^([^\.]*\.){3}[^\.]*$ - i.e. any text seperated by 3 periods (.) for example XXX.XXX.XXX.XXX does match,  XX.XX or XX.XX.XX.XX.XX does not.
Any character except the period can be used in place of X, i.e. I want essentially want to count the number of periods in the string and filter by the count <> 3 (the expression above does the opposite, i.e. matches when the count == 3)
How do you say match 1,2 or 4+ times?

A: You could use Negative Lookahead with what you don't want and if the condition satisfied capture anything:
The general idea:
(?!^not_this_pattern$)^[\s\S]*$

[\s\S] capture anything, including new line (in contrast to .)
And for this example:
(?!^([^\.]*\.){3}[^\.]*$)^[\s\S]*$

Demo
Or alternatively use condition operator | for the pattern to repeat (2 or less) or (4 or more):
^((?:[^\.]*\.[^\.]*){,2}|(?:[^\.]*\.[^\.]*){4,})$

Demo

A: First, I'm going to simplify your question down to the core piece: how to match any number of repetitions except k.  To that end, I'll simplify the expression down to x.  After all, this should work with any expression, so might as well start off simple.
Regex provides two useful constructs for us:

*

*The "n or more" construct {n,}

*

*This specifies that you want this expression to repeat n or more times.

*The "range" construct {n,m}

*

*This specifies that you want this expression to repeat any number of times between n and m, inclusive.

We can put these together using regex's OR notation (|) to match "between 1 and k - 1 times" ({1,k-1}) and "k + 1 or more times" ({k+1,}), separately.  We are using k - 1 and k + 1 as bounds because both of these functions are inclusive, and we want to exclude k.  If we wanted k to be, say, 3, we would end up with the following expression:
^(x{1,2}|x{4,})$

Now, this could be a problem if you happen to have a really long expression, since you would have to type the expression out twice.  This could get really long!  Luckily, we can refer back to a capturing group we made earlier.  The syntax is (?n), where n denotes which capturing group you are referring to.  In this case, we'll put our pattern in the first capturing group, and we'll refer to it using (?1).  This gives us:
^(x)((?1){0,1}|(?1){3,})$

Notice that I used 0 to 1 and 3+ as my quantifiers because we already matched the expression once at the beginning of our pattern.  One caveat here is that not all flavors of regex support this syntax.  PCRE (and PCRE2) supports it, but Python, Golang, Java, and ECMAScript do not.
Now all we've got left is to plug in your pattern.  Super easy, we can just drop it in where x is in our previous patterns:
Using the first method, if you aren't using PCRE or you have a short expression:
^(([^\.]*\.){1,2}|([^\.]*\.){4,})[^\.]*$

And using the second method, if you're using PCRE and you have a long expression:
^([^\.]*\.)((?1){0,1}|(?1){3,})[^\.]*$


text:
Q: Are epimorphisms in the category of magmas surjective? The question says it all, but let me recall the definitions.

*

*A magma $(X, \cdot)$ is a set $X$ with a binary operation $\cdot \colon X \times X \to X$ (without any further assumptions like associativity).

*A morphism between two magmas $X$ and $Y$ is a map $f \colon X \to Y$ with $f(a \cdot b) = f(a) \cdot f(b)$ for all $a, b\in X$.

*A morphism $f$ is epi, respectively mono, if one can cancel it from the right, respectively left: $g \circ f = h \circ f \implies g=h$, respectively $f \circ g = f \circ h \implies g = h$.

Using free magmas with one generator shows that monomorphisms are injective.
The question is whether epimorphisms are always surjective (in many other categories this fails, e.g., in the category of monoids).

A: Yes. Suppose $f:X\to Y$ is not surjective, and let $Z$ be the complement of $f(X)$ in $Y$. Then the disjoint union $f(X)\cup Z\cup Z'$ of $f(X)$ and two copies of $Z$ can be given a magma structure so that the two obvious embeddings of $Y$ (as $f(X)\cup Z$ and $f(X)\cup Z'$) are inclusions of submagmas, and have the same composition with $f$. Products of elements of $Z$ with elements of $Z'$ can be defined arbitrarily.

A: Given an algebraic category in which every monomorphism is regular, then every epimorphism is surjective. In fact, if $X \to Y$ is an epimorphism and $X \to Q \to Y$ is its image factorization, then $Q \to Y$ is a monomorphism, hence regular, but also an epimorphism, and hence an isomorphism. This result is usually used to show that epimorphisms of groups are surjective. But it can also be used to show that epimorphisms of magmas are surjective (and this is precisely what Jeremy Rickard's answer does): Let $(X,\cdot)$ be a submagma of $(Y,\cdot)$, let $Z$ be the complement of $X \subseteq Y$. Consider $Q = X \sqcup Z \sqcup Z$. Make it into a magma in such a way that the two inclusion maps $Y \to Q$ become magma morphisms $(Y,\cdot) \rightrightarrows (Q,\cdot)$  and the products between elements of the copies of $Z$ can be defined arbitrarily. Then $(X,\cdot) \to (Y,\cdot) \rightrightarrows (Q,\cdot)$ is an equalizer.


text:
Q: Single series of data on an excel chart (line) is reversing its order I am creating a simple line chart in excel, using 4 data series against date (in the form of YYYY).
Three of these series are financial, and displayed against the primary axis.
One is non-financial, and displayed against the secondary axis.
The non-financial series is displaying with it's order reversed (i.e. the value for 1993 is occuring in 2020, the value for 2020 is occuring in 1993, etc.)
I have tried creating the graph both by selecting all data at once, and by individually adding each data series to the graph separately - but still the same problem.
Any help gratefully received, I am sure I am missing something painfully obvious!

EDIT #1 - to include data, unsure of how to upload file, so example given:

Year
Number of Units
Unit 1
Unit 2
Unit 3

2020
3
£10
£15
£7

2019
3
£8
£13
£7

2018
2
£7

£6

2017
1
£7

2016
1
£4

2015
1
£3

On producing graph, the individual unit prices are displaying correctly correlated to the relevant date. The Number of units series however is displaying on the line chart as follows:
2020 - 1
2019 - 1
2018 - 1
2017 - 2
2016 - 3
2015 - 3

A: Answered in comments above, many thanks to @Isolated.

Right-Click on your secondary axis (whatever axis has your nbr_of_units) and select format axis. Under Axis Option , make sure the checkbox for "values in reverse order" is NOT selected.

Unfortunately, as his answer was merely a comment I'm not able to properly thank him by formally accepting his advice.


text:
Q: As Per customer requirement i need to change the View and Edit page of My Account in Drupal7 My Account
I want to add the Two fields in that Name and Mobile Number.
With that if customer wants to change his name or mobile number he has to enter the OTP as generated by us.
In Drupal core module i try create and edit i am confused.
By using hook_form_alter i can be show disabled field and all. But how to be fix with OTP functionality confusing.
With that i want to show the fields data in masked view
Please suggest me some ideas.

A: In drupal password field is required if you are changing email address or updating password.  as you can see under current password field description is "Enter your current password to change the E-mail address or Password."
In your case User will able to update Name and Mobile Number field without entering OTP.
If you want to no current password field use this contributed module https://www.drupal.org/project/nocurrent_pass


text:
Q: NoClassDefFoundError: org/json/JSONArray I'm trying to call a web service. When http://localhost:8080/getauthors is visited this exception is fired that says NoClassDefFoundError: org/json/JSONArray while i have included this dependency in my pom.xml. War is deployed via tomcat 8.0.36 which is set in Tomcat run configuration of intellij. What i have tried so far:

*

*Clean/install pom.xml with different versions of org.json

*Clean maven cache from /Users/cemalonder/Library/Caches/IntelliJIdea2016.3/tomcat/

*Delete all versions of org.json from /Users/cemalonder/.m2/ and reinstall them

exception

javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

java.lang.NoClassDefFoundError: org/json/JSONArray
    rest.service.GetAuthorsService.doGet(GetAuthorsService.java:53)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>MyBookHistory</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0-b01</version>
        </dependency>

        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>

    </dependencies>

</project>

package rest.service;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * Created by cemalonder on 09/01/2017.
 */
@WebServlet("/getauthors")
public class GetAuthorsService extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // objects that will be used for response
        PrintWriter out = resp.getWriter();

        // request - response configurations
        resp.setContentType("applictaion/json; charset=UTF-8");
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

        // data configuration
        Integer authorSize = 6;

        String[] authorImages = { "http://www.hayalperdesi.net/images/haberler/1168.jpg",
                                  "https://farzimuhaldotcom.files.wordpress.com/2012/01/nfk.jpg",
                                  "http://kitaplikkedisi.com/wp-content/uploads/2014/11/William-Burroughs-014.jpg",
                                  "http://www.fakirelma.com/files/uploads/news/default/orhan-pamuk-yazarlar-af9a1b2321937079ac42.jpg",
                                  "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRp8gM20DyWSr489aVssuXyVrRbYLf5HO8PTaWyD1EZ7iCdFaVD4w",
                                  "http://hepsi10numara.com/wp-content/uploads/2013/02/iyi-yazarlar.jpg"};

        String[] authorNames = {"name1", "name2", "name3", "name4", "name5", "name6", "name7"};

        String[] authorBio = {"randomString1",
                              "randomString2",
                              "randomString3",
                              "randomString4",
                              "randomString5",
                              "randomString6",
                              "randomString7"};

        /* create JSONArray for multiple author information. Than for each author
           create a JSONObject. */

        JSONArray authors = new JSONArray();
        for (int i = 0; i < authorSize; i++) {
            JSONObject author = new JSONObject();
            author.put("authorImage", authorImages[new Random().nextInt(authorImages.length)]);
            author.put("authorName", authorNames[new Random().nextInt(authorNames.length)]);
            author.put("authorBio", authorBio[new Random().nextInt(authorBio.length)]);
            authors.put(author);
        }

        out.print(authors);

        if (out != null) try {
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Tomcat is deploying
/Users/cemalonder/Development/Libraries/apache-tomcat-8.0.36/bin/catalina.sh run
[2017-01-10 09:56:28,048] Artifact MyBookHistory:war exploded: Server is not connected. Deploy is not available.
10-Jan-2017 21:56:30.100 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.0.36
10-Jan-2017 21:56:30.102 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Jun 9 2016 13:55:50 UTC
10-Jan-2017 21:56:30.103 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.0.36.0
10-Jan-2017 21:56:30.103 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Mac OS X
10-Jan-2017 21:56:30.103 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            10.12
10-Jan-2017 21:56:30.103 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          x86_64
10-Jan-2017 21:56:30.103 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_74.jdk/Contents/Home/jre
10-Jan-2017 21:56:30.103 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.8.0_74-b02
10-Jan-2017 21:56:30.104 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
10-Jan-2017 21:56:30.104 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         /Users/cemalonder/Library/Caches/IntelliJIdea2016.3/tomcat/Tomcat_MyBookHistory
10-Jan-2017 21:56:30.104 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         /Users/cemalonder/Development/Libraries/apache-tomcat-8.0.36
10-Jan-2017 21:56:30.105 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/Users/cemalonder/Library/Caches/IntelliJIdea2016.3/tomcat/Tomcat_MyBookHistory/conf/logging.properties
10-Jan-2017 21:56:30.105 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
10-Jan-2017 21:56:30.108 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote=
10-Jan-2017 21:56:30.108 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.port=1099
10-Jan-2017 21:56:30.108 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.ssl=false
10-Jan-2017 21:56:30.109 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.authenticate=false
10-Jan-2017 21:56:30.109 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.rmi.server.hostname=127.0.0.1
10-Jan-2017 21:56:30.110 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
10-Jan-2017 21:56:30.110 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.endorsed.dirs=/Users/cemalonder/Development/Libraries/apache-tomcat-8.0.36/endorsed
10-Jan-2017 21:56:30.110 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/Users/cemalonder/Library/Caches/IntelliJIdea2016.3/tomcat/Tomcat_MyBookHistory
10-Jan-2017 21:56:30.110 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/Users/cemalonder/Development/Libraries/apache-tomcat-8.0.36
10-Jan-2017 21:56:30.111 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/Users/cemalonder/Development/Libraries/apache-tomcat-8.0.36/temp
10-Jan-2017 21:56:30.112 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/cemalonder/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
10-Jan-2017 21:56:30.594 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
10-Jan-2017 21:56:30.716 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
10-Jan-2017 21:56:30.723 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
10-Jan-2017 21:56:30.725 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
10-Jan-2017 21:56:30.725 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 1788 ms
10-Jan-2017 21:56:30.774 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service Catalina
10-Jan-2017 21:56:30.774 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.0.36
10-Jan-2017 21:56:30.784 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
10-Jan-2017 21:56:30.792 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
10-Jan-2017 21:56:30.794 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 68 ms
Connected to server
[2017-01-10 09:56:31,273] Artifact MyBookHistory:war exploded: Artifact is being deployed, please wait...
[2017-01-10 09:56:31,946] Artifact MyBookHistory:war exploded: Artifact is deployed successfully
[2017-01-10 09:56:31,946] Artifact MyBookHistory:war exploded: Deploy took 673 milliseconds
10-Jan-2017 21:56:40.794 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /Users/cemalonder/Development/Libraries/apache-tomcat-8.0.36/webapps/manager
10-Jan-2017 21:56:40.857 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /Users/cemalonder/Development/Libraries/apache-tomcat-8.0.36/webapps/manager has finished in 63 ms

A: Okay I got it. It seems there is a problem with Intellij's maven configuration. I changed catalina base directory to catalina home and it works now.
Add this (which points same direction as Dcatalina.home)

-Dcatalina.base=/Users/cemalonder/Development/Libraries/apache-tomcat-8.0.36

to Run/Debug Configuration as a parameter


text:
Q: Iterate through each item in accordion block with Selenium & Python I've got an accordion block which I'd like to click each item & take a screenshot. Each item shares a class so I thought a for loop would work but I can't get it to select the items.
HTML Structure:

Click This

Click This

Python:
detailsAccordion = browser.find_elements_by_class_name('accordion')
index = 1
for option in detailsAccordion:
    option.click()
    try:
        element = ui.WebDriverWait(ff, 10).until(lambda driver : driver.find_element_by_xpath("//div[@class='accordion'][" + str(index) + "]/div[@class='accordionContent']").text != "" )
    except:
        print "Can't do it"
        browser.quit()
    index = index + 1
    n = nextNumber(n)
    browser.save_screenshot('{0}\{1}.png'.format(imagesPath, n))
    option.click()

This is causing a timeout with the following error. I've looked at this error & people have had trouble with internet options/proxy settings - I don't have a proxy so no sure why this has started;
 [exec] Can't do it
 [exec] Traceback (most recent call last):
 [exec]   File "viewEmployeeUseCase.py", line 82, in <module>
 [exec]     ff.save_screenshot('{0}\{1}.png'.format(imagesPath, n))
 [exec]   File "C:\Python26\lib\site-packages\selenium-2.20.0-py2.6.egg\selenium\webdriver\firefox\webdriver.py", line 75, in save_screenshot
 [exec]     png = RemoteWebDriver.execute(self, Command.SCREENSHOT)['value']

 [exec]   File "C:\Python26\lib\site-packages\selenium-2.20.0-py2.6.egg\selenium\webdriver\remote\webdriver.py", line 151, in execute
 [exec]     response = self.command_executor.execute(driver_command, params)

 [exec]   File "C:\Python26\lib\site-packages\selenium-2.20.0-py2.6.egg\selenium\webdriver\remote\remote_connection.py", line 280, in execute
 [exec]     return self._request(url, method=command_info[0], data=data)
 [exec]   File "C:\Python26\lib\site-packages\selenium-2.20.0-py2.6.egg\selenium\webdriver\remote\remote_connection.py", line 321, in _request
 [exec]     response = opener.open(request)
 [exec]   File "C:\Python26\lib\urllib2.py", line 391, in open
 [exec]     response = self._open(req, data)
 [exec]   File "C:\Python26\lib\urllib2.py", line 409, in _open
 [exec]     '_open', req)
 [exec]   File "C:\Python26\lib\urllib2.py", line 369, in _call_chain
 [exec]     result = func(*args)
 [exec]   File "C:\Python26\lib\urllib2.py", line 1170, in http_open
 [exec]     return self.do_open(httplib.HTTPConnection, req)
 [exec]   File "C:\Python26\lib\urllib2.py", line 1145, in do_open
 [exec]     raise URLError(err)
 [exec] urllib2.URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>

Making things simple & not waiting for content to populate works fine & does all I want it to with the following;
for option in detailsAccordion:
    #print option
    option.click()
    WebDriverWait(ff, 2)
    n = nextNumber(n)
    ff.save_screenshot('{0}\{1}.png'.format(imagesPath, n))
    option.click()

A: I do not think the implicit wait is what you want and I do not believe it is doing anything in your code. "An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance." - Webdriver
What you really want is an explicit wait that waits for the accordian content to appear and then takes the screenshot.
Sorry, not a Python programmer, so I am guessing at the exact code. But I think you want something like:
detailsAccordion = browser.find_elements_by_class_name('accordion')
for option in detailsAccordion:
    option.click() # open div
    #Wait until the accordionContent div has text
    try:
        element = WebDriverWait(browser, 10).until(lambda option : option.find_element_by_class_name("accordionContent").text != "" )
    finally:
        #Throw error cause the div didn't populate
        browser.quit
    n = nextNumber(n)
    browser.save_screenshot('{0}\{1}.png'.format(imagesPath, n))
    option.click() #close div

UPDATE: Sorry, I think there are two major issues with the solution I originally suggested. (1) It should be except: instead of finally: since finally: always executes rather than just if there's a timeout error. (2) Unlike Watir-Webdriver, it seems that Selenium-Webdriver does not allow checking the accordionContent with respect to the current accordion element. The originally proposed solution is always checking the first accordionContent on the page (bad). The only way I could find the element with respect to another element is using xpath (or css-selector).
The following has been updated with these two concepts:
detailsAccordion = browser.find_elements_by_class_name('accordion')
index = 1
for option in detailsAccordion:
    print option
    option.click()
    try:
        element = ui.WebDriverWait(browser, 10).until(lambda driver : driver.find_element_by_xpath("//div[@class='accordion'][" + str(index) + "]/div[@class='accordionContent']").text != "" )
    except:
        # Error if div didn't populate
        print "Can't do it"
        browser.quit()
    index = index + 1
    n = nextNumber(n)
    browser.save_screenshot('{0}\{1}.png'.format(imagesPath, n))
    option.click()


text:
Q: Python function to find # of unique words/total words not working...why? Why is this code not working?
def hapax_legomana_ratio(text):
''' Return the hapax_legomana ratio for this text.
This ratio is the number of words that occur exactly once divided
by the total number of words.
text is a list of strings each ending in \n.
At least one line in text contains a word.'''

uniquewords=dict()
words=0
for line in text:
    line=line.strip().split()
    for word in line:
        words+=1
        if word in words:
            uniquewords[word]-=1
        else:
            uniquewords[word]=1
HLR=len(uniquewords)/words

print (HLR)

When I test it, it gives me the wrong answer. For example, when there are 3 unique words in a string of 9, it gives me 0.20454545454545456 instead of .33333.

A: To find the ratio: number of unique words to total number of words in a text:
from collections import Counter

def hapax_legomana_ratio(text):
    words = text.split() # a word is anything separated by a whitespace
    return sum(count == 1 for count in Counter(words).values()) / len(words)

It assumes that text is a string. If instead you have a list of lines then you could get the words list as follows:
words = [word for line in all_lines for word in line.split()]

A: There are a lot of fallacies in your code. I think there is a typo in the line if word in words because it should be uniquewords (dict) instead of just words (which is the count).
More on, your text that is being supplied should be split into lines & should be list of such lines. I would rather recommend to do this
for line in text.splitlines():

So that you don't have to worry for the text being passed to be a list.
Also, you are doing len(uniquewords) which is wrong since you store all the words in the dict irrespective of being unique. The word's uniqueness is given by the value obtained from the dict by passing the word as the key, i.e. 1 or -1. Thus, you should iterate over the dict's items & count the keys with value as 1.
Also, you are not taking care of punctuation characters! Suppose this is the text
This is a test,
yes it is a test.
Notice how the test, & the test. would be differently stored in the words dict?
The slightly corrected code is as follows.
def hapax_legomana_ratio(text):
    ''' Return the hapax_legomana ratio for this text.
    This ratio is the number of words that occur exactly once divided
    by the total number of words.
    text is a list of strings each ending in \n.
    At least one line in text contains a word.'''

    uniquewords = dict()
    words = 0
    for line in text:
        line = line.strip().split()
        for word in line:
            words += 1
            word = word.replace(',', '').strip()
            if word in uniquewords:
                uniquewords[word] -= 1
            else:
                uniquewords[word] = 1

    unique_count = 0
    for each in uniquewords:
        if uniquewords[each] == 1:
            unique_count += 1
    HLR = unique_count/words

    print (HLR)

Finally, if this is a really big project &/or you would require this in the future too, I would rather recommend using the collection.Counter library to do all this instead of doing all this.


text:
Q: How to get Quickbooks online data in my webapp without the user logging in I'm creating an ecomerce app for a local store and they use Quickbooks Online.  I can see the Quickbooks Online API requires a "Connect to Quickbooks" button where the user then logs in, but that's not what I'm looking for.  What I'm looking for is something when they look at the products page, the app queries (or sends a REST/SOAP call) and gets back product data for my store.  Our customers will have no idea that we're using quickbooks online, and definitely won't have a login.  The flow would be like:
Customer clicks Products
ProductsAction will execute a service call to QuickBooks to get the products we sell (select * from products)
ProductsAction will return Success passing in the list of products to the page to be rendered.
mycompany/Products renders the items returned from QuickBooks Online.
Is there any possible way to do this?  Everything I've read requires O'Auth authentication (meaning the user would have to login to QBO).
Feel free to ask any questions an thanks in advance!

A:
I can see the Quickbooks Online API requires a "Connect to Quickbooks" button where the user then logs in, but that's not what I'm looking for.

Yes, it is.
You only have to log in ONCE. Exactly ONCE, and then you never, ever have to log in ever again. So, your QuickBooks admin logs in ONCE using the "Connect to QuickBooks" button, and then NEVER LOGS IN AGAIN.
Instead, you store the OAuth tokens, and use the stored tokens to do you queries from there on out.

What I'm looking for is something when they look at the products page, the app queries (or sends a REST/SOAP call) and gets back product data for my store.

This is all perfectly do-able. The reason you can't do it right now is because you're not storing the OAuth tokens like you should be.

Our customers will have no idea that we're using quickbooks online, and definitely won't have a login.

They don't need to have any idea about this. Store the OAuth tokens after you connect ONCE, and then everything can be unattended, no login, you just query away whenever you want to.

Is there any possible way to do this?

Yes!

Everything I've read requires O'Auth authentication (meaning the user would have to login to QBO).

The QuickBooks admin logs in ONCE and then never again. Store the OAuth tokens after that one and only login, and then use those to do all of your queries in the future.
This is how OAuth works for every single application that uses OAuth on the entire planet. Log in and authenticate once, store the tokens you get for future queries.
...
...
Did I mention you should be storing the OAuth tokens that you get back after that one single time your QuickBooks admin logs in?   :-P

A: Yes, you can do this:

*

*Create an account on https://developer.intuit.com using your accounts QBO login.

*Make an app

*Grab OAuth creds from the API Explorer.

See my tutorial for help on the first two steps: http://minimul.com/integrating-rails-and-quickbooks-online-via-the-version-3-api-part-1.html
You still need OAuth creds but since you only desire to interact with your company/personal QBO account you don't need to do anything formal, just get the OAuth credentials somehow. Once you have the credentials you can start building your integration code.


text:
Q: JPA can't find table I'm using JPA 2.0, Eclipselink 2.0, maven and weblogic 10.3.6. Here's my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="certifications" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/com/ni/ds_edata_soa_nontx</jta-data-source>
        <class>com.ni.apps.engineering.certification.entities.NicdsCliCertificationStg</class>
        <class>com.ni.apps.engineering.certification.entities.NicdsCliCertificationStgPK</class>
        <class>com.ni.apps.engineering.certification.entities.NicdsCliUpMapping</class>
        <properties>
            <property name="javax.persistence.jdbc.password" value="ni"/>
            <property name="javax.persistence.jdbc.user" value="NI"/>
            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
            <property name="eclipselink.logging.level.sql" value="FINE"/>
        </properties>
    </persistence-unit>
</persistence>

This is my facade
    package com.ni.apps.engineering.certification.controller;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;
import com.ni.apps.engineering.certification.entities.NicdsCliCertificationStg;
import com.ni.apps.engineering.certification.exception.CertificationException;
import com.ni.apps.engineering.certification.utils.CertificationConstants;

public class CertificationFacade {

    @PersistenceUnit(unitName = "certifications")
    private EntityManagerFactory emf;

    public List<NicdsCliCertificationStg> getCertificationsByUpId(String upId)
            throws CertificationException {
        String stringQuery = new StringBuilder(
                "select c from NicdsCliCertificationStg c where c.id.contactsId = 1234").toString();
                //.append(upId).toString();
        try {
            emf = Persistence.createEntityManagerFactory("certifications");
            EntityManager em = emf.createEntityManager();
            TypedQuery<NicdsCliCertificationStg> query = em
                    .createQuery(stringQuery, NicdsCliCertificationStg.class);
            return query.getResultList();
        } catch (Exception e) {
            throw new CertificationException(
                    CertificationConstants.INTERNAL_ERROR_MESSAGE, e);
        }
    }
}

When I try to run the app, this is the error I'm getting
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.1.v20111018-r10243): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist

Error Code: 942
Call: SELECT CONTACTS_ID, PROFILE_ID FROM NI.NICDS_CLI_UP_MAPPING WHERE (PROFILE_ID = ?)
    bind => [1 parameter bound]
Query: ReadAllQuery(referenceClass=NicdsCliUpMapping sql="SELECT CONTACTS_ID, PROFILE_ID FROM NI.NICDS_CLI_UP_MAPPING WHERE (PROFILE_ID = ?)")

Any ideas why it can't find the table?
-EDIT-
Adding the entity
package com.ni.apps.engineering.certification.entities;

import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;

/**
 * The persistent class for the NICDS_CLI_CERTIFICATION_STG database table.
 *
 */
@Entity
@Table(name="NICDS_CLI_CERTIFICATION_STG", schema="NI")
public class NicdsCliCertificationStg implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private NicdsCliCertificationStgPK id;

    @Column(name="ALTERNATE_EMAIL")
    private String alternateEmail;

    @Temporal(TemporalType.DATE)
    @Column(name="CERT_EXPIRATION_DATE")
    private Date certExpirationDate;

    @Temporal(TemporalType.DATE)
    @Column(name="CERT_ISSUE_DATE")
    private Date certIssueDate;

    @Column(name="CERT_STATUS")
    private String certStatus;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @Column(name="PRIMARY_EMAIL")
    private String primaryEmail;

    //bi-directional one-to-one association to NicdsCliUpMapping
    @OneToOne
    @JoinColumn(name="CONTACTS_ID")
    private NicdsCliUpMapping nicdsCliUpMapping;

    public NicdsCliCertificationStg() {
    }

    public NicdsCliCertificationStgPK getId() {
        return this.id;
    }

    public void setId(NicdsCliCertificationStgPK id) {
        this.id = id;
    }

    public String getAlternateEmail() {
        return this.alternateEmail;
    }

    public void setAlternateEmail(String alternateEmail) {
        this.alternateEmail = alternateEmail;
    }

    public Date getCertExpirationDate() {
        return this.certExpirationDate;
    }

    public void setCertExpirationDate(Date certExpirationDate) {
        this.certExpirationDate = certExpirationDate;
    }

    public Date getCertIssueDate() {
        return this.certIssueDate;
    }

    public void setCertIssueDate(Date certIssueDate) {
        this.certIssueDate = certIssueDate;
    }

    public String getCertStatus() {
        return this.certStatus;
    }

    public void setCertStatus(String certStatus) {
        this.certStatus = certStatus;
    }

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPrimaryEmail() {
        return this.primaryEmail;
    }

    public void setPrimaryEmail(String primaryEmail) {
        this.primaryEmail = primaryEmail;
    }

    public NicdsCliUpMapping getNicdsCliUpMapping() {
        return this.nicdsCliUpMapping;
    }

    public void setNicdsCliUpMapping(NicdsCliUpMapping nicdsCliUpMapping) {
        this.nicdsCliUpMapping = nicdsCliUpMapping;
    }

}

package com.ni.apps.engineering.certification.entities;

import java.io.Serializable;
import javax.persistence.*;

/**
 * The primary key class for the NICDS_CLI_CERTIFICATION_STG database table.
 *
 */
@Embeddable
public class NicdsCliCertificationStgPK implements Serializable {
    //default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;

    @Column(name="CONTACTS_ID")
    private long contactsId;

    @Column(name="CERT_NAME")
    private String certName;

    public NicdsCliCertificationStgPK() {
    }
    public long getContactsId() {
        return this.contactsId;
    }
    public void setContactsId(long contactsId) {
        this.contactsId = contactsId;
    }
    public String getCertName() {
        return this.certName;
    }
    public void setCertName(String certName) {
        this.certName = certName;
    }

    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (!(other instanceof NicdsCliCertificationStgPK)) {
            return false;
        }
        NicdsCliCertificationStgPK castOther = (NicdsCliCertificationStgPK)other;
        return
            (this.contactsId == castOther.contactsId)
            && this.certName.equals(castOther.certName);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + ((int) (this.contactsId ^ (this.contactsId >>> 32)));
        hash = hash * prime + this.certName.hashCode();

        return hash;
    }
}

package com.ni.apps.engineering.certification.entities;

import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;

/**
 * The persistent class for the NICDS_CLI_UP_MAPPING database table.
 *
 */
@Entity
@Table(name="NICDS_CLI_UP_MAPPING", schema="NI")
public class NicdsCliUpMapping implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name="NICDS_CLI_UP_MAPPING_CONTACTSID_GENERATOR" )
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="NICDS_CLI_UP_MAPPING_CONTACTSID_GENERATOR")
    @Column(name="CONTACTS_ID")
    private long contactsId;

    @Column(name="PROFILE_ID")
    private BigDecimal profileId;

    //bi-directional one-to-one association to NicdsCliCertificationStg
    @OneToOne(mappedBy="nicdsCliUpMapping")
    private NicdsCliCertificationStg nicdsCliCertificationStg;

    public NicdsCliUpMapping() {
    }

    public long getContactsId() {
        return this.contactsId;
    }

    public void setContactsId(long contactsId) {
        this.contactsId = contactsId;
    }

    public BigDecimal getProfileId() {
        return this.profileId;
    }

    public void setProfileId(BigDecimal profileId) {
        this.profileId = profileId;
    }

    public NicdsCliCertificationStg getNicdsCliCertificationStg() {
        return this.nicdsCliCertificationStg;
    }

    public void setNicdsCliCertificationStg(NicdsCliCertificationStg nicdsCliCertificationStg) {
        this.nicdsCliCertificationStg = nicdsCliCertificationStg;
    }

}

A: The error was that the weblogic's datasource had a different combination of user and password than the one I need for the application's schema. If I find a way to force JPA to use a specific schema/user/password combination without changing the user in the datasource, I'll update this answer.

A: If you are using different user to test, then the user that is configured in the datasource
In the datasource Connection Pool config, go to advanced section
Type this in the "Init SQL" section (see the SQL word before the instruction, its needed)
SQL ALTER SESSION SET CURRENT_SCHEMA=DEVLPMT
See http://docs.oracle.com/middleware/1212/wls/JDBCA/jdbc_datasources.htm#CJAFCBBD


text:
Q: A combinatorics problem involving geometry Find the number of triangles that can be formed in a regular polygon of $2n+1$ sides such that the center of polygon lies inside the triangle. (The triangles are to be  formed using the vertices of the polygon).

A: First, pick any starting point $A$. (Suppose it is at the bottom of the circle.) This can be done in $(2n+1)$ ways. Number the points starting at $A=0$. Let the second point $B$ be at position $i\leq n$. (We know that at least one of $B$ and $C$ has to be at the left side of the line $AO$.) Now, for $C$ we know that $n+1\leq C< 2n+1$, because it has to be at the right of $AO$. It also has to be above $BO$, which implies $C\leq i+n<2n+1$. Now, $n+1\leq C\leq i+n$, thus the number of possibilities for $C$ is $i+n-(n+1)+1=i$. Summing over all possible $i$ gives the total number of possibilities for $B$ and $C$:
$$
\sum_{i=1}^n i=\binom {n+1}2
$$
Now, let $A$ be a random point on the circle. This creates $2n+1$ as many solutions, but since  we count each triangle three times now (with $A$ once at each corner), we have to divide by three, resulting in:
$$
\frac{2n+1}3\binom{n+1}2
$$


text:
Q: Differing behaviors for ParseFiles functions in html/template I don't understand why the behaviors of func (t *Template) Parsefiles(... differs from func ParseFiles(....  Both functions are from the "html/template" package.
package example

import (
    "html/template"
    "io/ioutil"
    "testing"
)

func MakeTemplate1(path string) *template.Template {
    return template.Must(template.ParseFiles(path))
}

func MakeTemplate2(path string) *template.Template {
    return template.Must(template.New("test").ParseFiles(path))
}

func TestExecute1(t *testing.T) {
    tmpl := MakeTemplate1("template.html")

    err := tmpl.Execute(ioutil.Discard, "content")
    if err != nil {
        t.Error(err)
    }
}

func TestExecute2(t *testing.T) {
    tmpl := MakeTemplate2("template.html")

    err := tmpl.Execute(ioutil.Discard, "content")
    if err != nil {
        t.Error(err)
    }
}

This exits with the error:
--- FAIL: TestExecute2 (0.00 seconds)
    parse_test.go:34: html/template:test: "test" is an incomplete or empty template
FAIL
exit status 1

Note that TestExecute1 passed fine so this not a problem with template.html.
What's going on here?
What am I missing in MakeTemplate2?

A: It's because of the template names. Template objects can hold multiple teplates, each has a name. When using template.New("test"), and then Executing it, it will try to execute a template called "test" inside that template. However, tmpl.ParseFiles stores the template to the name of the file. That explains the error message.
How to fix it:
a) Give the template the correct name:
Use
return template.Must(template.New("template.html").ParseFiles(path))

instead of
return template.Must(template.New("test").ParseFiles(path))

b) Specify, which template you want to execute in you Template object:
Use
err := tmpl.ExecuteTemplate(ioutil.Discard, "template.html", "content")

instead of
err := tmpl.Execute(ioutil.Discard, "content")

Read more about this in http://golang.org/pkg/text/template/


text:
Q: Understanding benefits of PKCE vs. Authorization Code Grant I am new to the OAuth world and I am trying to understand the benefits of using PKCE over traditional Authorization code grant. (Many of my assumptions could be wrong, so I would thank for your corrections.)
I am a mobile app developer and according to OAuth documentation, client secrets can't be hardcoded in public clients' app code. The reason to avoid hardcoding the client secret is that a hacker could decompile my app and get my client secret.
The hacker with my client secret and my redirect_url, could develop a fake application. If a final user (User1) downloads the real application and the hacker's application (both), the fake application could listen to the real application callback and get the authorization code from it. With the authorization code (from the callback) and the client secret (stolen by decompiling my app), the hacker could get the authorization token and the refresh token and be able to get for example User1's data.
If other users download the real and the fake application, their data would also be in danger. Am I right? Would the hacker need both or could he/she do an attack only with the authorization code? Does the fifth step of the image requires the client secret and authorization code?
The attack is called interception attack.

To solve the the problem of hardcoding client secrets in the public client app and make it impossible for hackers to get the client secret and steal tokens, PKCE was invented. With PKCE, the client app code doesn't need to have the client secret hardcoded as PKCE doesn't need that information to get the tokens of the final users.
The PKCE flow creates a random string, transforms it to a SHA-256 hash value and to Base64. In the second point of the image, that encoded string is sent to the authentication server with the client id. Then the authorization code is sent in the callback and if any malicious app intercepts the code, it wouldn't be able to get the tokens as the fifth point of the image needs the original random string that was created by the legitimate app.
That is great, but if the client secret isn't need any more to get the tokens to access User1 data, how can I avoid a hacker developing a fake app which use PKCE flow with my client id and getting the tokens of the users who think that app is the legitimate one?
As the fifth step of the image don't need any more the client secret to get the tokens, anyone could develop fake apps using my public client id, and if any user downloads the fake app and do the OAuth flow, the hacker could get its tokens and access that users data!
Am I right?

A:
if the client secret isn't need anymore to get the tokens to access User1 data, how can I avoid a hacker developing a fake App which use PKCE flow with my client id and getting the tokens of the users who think that app is the legitimate one?

OAuth 2.0 or PKCE does not protect against "fake apps".
The PKCE does protect against having a malicious app on the device to steal a token that is intended for another app. E.g. think of a Bank app, it is not good if another app on the device can get the token that the Bank app is using. That is the case illustrated in your picture and that PKCE mitigates against.

As the 5th step of the image don't need anymore the client secret to get the tokens, anyone could develop fake apps using my public client id.

A mobile app cannot protect a client secret, similarly to JavaScript Single Page Applications. Therefore these clients are Public Clients rather than Confidential Clients according to OAuth 2.0. Only Confidential Clients can protect a client secret in a secure way, only those should use client secrets. PKCE is a good technique for Public Clients but might be used for Confidential Clients as well.

if any user downloads the fake app and do the oauth flow, the hacker could get it's tokens and access that users data!

Contact Apple Store or Google Play store for "fake apps", or use e.g. Anti-malware applications. That is the mitigations against "fake apps". PKCE only mitigates the case when another app on the same device try to steal the token that is issued for another app (e.g. a bank app).


text:
Q: Why is this difference between order and setorder(v) by data.table? I would like to order a data.table. With setorder(v) I receive different result as with base::order. How could I receive the same result, order?
I already have tried to solve with 1 column, but I should order by more columns.
1: (test = data.table(V1 = c("TeilA1_a", "TeilA_a", "TeilC1_a", "TeilA_a"),
                      V2 = c("4", "3", "2", "1")))
 2:   test[order(V1)]
 3:   sort(test[[1]])
 4:   c(order(test[[1]]))
 5:   order(test[[1]])
 6:   test[c(order(test[[1]]))]
 7:   test[order(test[[1]])]
 8:   (setorderv(test, c("V1"), c(1)))
 9:   test[order(V1)]
10:  test[order(V1, V2)]

Why are results of lines c(4,5) identical, but c(6,7) not? I expect the same output of line 8 as line 6.

A: From ?setorder (data.table_1.12.2):

Also note that data.table always reorders in "C-locale" (see Details). To sort by session locale, use x[base::order(.)].

Further in Details

data.table always reorders in "C-locale". As a consequence, the ordering may be different to that obtained by base::order. In English locales, for example, sorting is case-sensitive in C-locale. Thus, sorting c("c", "a", "B") returns c("B", "a", "c") in data.table but c("a", "B", "c") in base::order. Note this makes no difference in most cases of data; both return identical results on ids where only upper-case or lower-case letters are present ("AB123" < "AC234" is true in both), or on country names and other proper nouns which are consistently capitalized. For example, neither "America" < "Brazil" nor "america" < "brazil" are affected since the first letter is consistently capitalized.

Thanks to Frank, it is noted when order optimization is on, order is substituted internally with data.table:::forder whereas test[(order(V1))]; test[c(order(V1))]; test[base::order(V1)] does not and is instead retrieved from scope outside of [.
Thanks also to MichaelChirico, test[c(order(V1))]; test[(order(V1))] will default to data.table:::forder from data.table_1.12.4 onwards. Please kindly check out the NEWS for updates.
Hence, test[order(V1), verbose=TRUE] sorts by C-locale (just like test[data.table::chorder(V1)]) giving
#data.table_1.12.2
order optimisation is on, i changed from 'order(...)' to 'forder(DT, ...)'.
   rn       V1 V2
1:  1 TeilA1_a  4
2:  2  TeilA_a  3
3:  4  TeilA_a  1
4:  3 TeilC1_a  2

while test[base::order(V1)]; test[(order(V1)), verbose=TRUE]; test[c(order(V1)), verbose=TRUE] gives
   rn       V1 V2
1:  2  TeilA_a  3
2:  4  TeilA_a  1
3:  1 TeilA1_a  4
4:  3 TeilC1_a  2

data:
library(data.table)
test = data.table(rn=1:4, V1 = c("TeilA1_a", "TeilA_a", "TeilC1_a", "TeilA_a"), V2 = c("4", "3", "2", "1"))


text:
Q: When using a search field on a website, is there a way to open the search result in a new tab in Firefox? For example, I go to http://en.wikipedia.org, I enter something into the search field, and I would like to see the search result in a new tab.

A: Consider using the search box next to the address bar in Firefox to search on Wikipedia directly without explicitly having to go to the search box within a Wikipedia page. Within the Firefox search box, change the provider to Wikipedia

For subsequent searches, click Alt+Enter after you enter a keyword within the search box instead of just Enter, to view results in a new tab.


text:
Q: How to disable JavaScript in browser using Selenium (Java)? In my feature automation, I need to disable JavaScript in browser and run the flow. How to disable JavaScript?
Tried DesiredCapabilities for firefox and Chrome.
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, false)

And
DesiredCapabilities dc = new DesiredCapabilities();
dc.setJavascriptEnabled(false);

For firefox, tried
1) Setting up profile for firefox
2) Adding add-on - noScript.xpi
3) profile.setPreference("javascript.enabled", false);
4) Through UI, tried changing the flag - "javascript.enabled" in "about:config" to false. Here, opened firefox and gave "about:config" getting a warning - "This might void your warranty!". There is a button - "I'll be careful, I promise!" with id - warningButton. This button should be clicked to proceed further. To click this button, used driver.findElement(By.id("warningButton")).click(); but it not work.
All the above options are not working. Any advice will be helpful.

A: I don't know Java, but maybe a solution for Python 3 will help you.
in Python, you can use Options() instead of FirefoxProfile() to deactivate JavaScript:
from selenium.webdriver.firefox.options import Options
options = Options()
options.preferences.update({"javascript.enabled": False})
driver = webdriver.Firefox(options=options)
driver.get('about:config')

Maybe Java this:
FirefoxOptions options = new FirefoxOptions();
options.preferences.update({"javascript.enabled": False});
WebDriver driver = new FirefoxDriver(options);
driver.get('about:config')

A: You change the preference value using profile with lots of options:
DesiredCapabilities capabilities = new DesiredCapabilities();
// setCapability(SUPPORTS_JAVASCRIPT, javascriptEnabled);
capabilities.setJavascriptEnabled(false);

FirefoxBinary binary = new FirefoxBinary( new File( binaryPath ) );
FirefoxProfile profile = new FirefoxProfile();

//profile.setPreference("preferenceName", "Value");
profile.setPreference("javascript.enabled", false);

RemoteWebDriver driver = new FirefoxDriver(binary, profile, capabilities);

To view the preferences, you can visit the URL about:config

@See

*

*Chrome driver to disable JavaScript issue

*chromium-command-line-switches

A: As per Selenium 3.6 Java Client Release, the easiest way to disable Javascript in the browser would be to set the setJavascriptEnabled argument through an instance of DesiredCapabilities to False and merge it through an instance of FirefoxOptions as follows:
package demo;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Q46883024_setJavascriptEnabled
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
        DesiredCapabilities dc = new DesiredCapabilities();
        dc.setJavascriptEnabled(false);
        FirefoxOptions op = new FirefoxOptions();
        op.merge(dc);
        WebDriver driver = new FirefoxDriver(op);
        driver.get("https://google.com");
        driver.quit();
    }
}

While execution, the browser you are using may override the setJavascriptEnabled settings.

A: Truse me this was random trial but works perfectly for me
from selenium import webdriver

options= webdriver.ChromeOptions()

chrome_prefs = {}
options.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"javascript": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"javascript": 2}
driver = webdriver.Chrome("your chromedriver path here",options=options)

driver.get('https://google.com/search?q=welcome to python world')

Example image here:-https://i.stack.imgur.com/DdKZQ.png

A: this works:
FirefoxOptions options = new FirefoxOptions();
options.addPreference("javascript.enabled", false);

A: This is how you can do it for Chrome in Java.
// import org.openqa.selenium.chrome.ChromeOptions;

ChromeOptions options = new ChromeOptions();
options.addArguments("user-agent=\"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\"");
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_setting_values.javascript", 2);
options.setExperimentalOption("prefs", chromePrefs);
new ChromeDriver(options);

And it worked for me with ChromeDriver 2.41.578706. As a bonus I am also setting Googlebot as user-agent.
In case you need to do something with DesiredCapabilities you can also convert the options above to capabilities:
// import static org.openqa.selenium.chrome.ChromeOptions.CAPABILITY;

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CAPABILITY, options);
new ChromeDriver(capabilities);


text:
Q: Gnome in Ubuntu Server I have installed GUI in Ubuntu server using
sudo apt-get ubuntu-desktop --no installrecommends

I have started it using
startx

I have accessed the home folder using(since there is no icons)
nautilus

Is there any other way to open the home folder?
If I restart my server will it automatically go to the GUI or the to the login prompt at the command line?

A: Open terminal and edit your system wide crontab.
sudo nano /etc/crontab

After last hash-tag enter and save the following line.
@reboot root lightdm

After several reboots, system seems to have no problems. And hopefully never will. Can't say for sure that this is the best solution...


text:
Q: How can Tomcat's cookies with quoted values be read correctly in ASP? We have a site which integrates Java web apps under Tomcat with ASP pages, including sharing information in cookies in the traditional ASP key/value format:
Cookie: foo=a=b&c=d; ...

As of Tomcat 5.5.26, cookie handling has been altered slightly, with the effect that our cookie value is now enclosed in quotes, which wasn't the case before:
Cookie: foo="a=b&c=d"; ...

However, we have ASP code that also reads this cookie, and which expects the values in it to be parseable thus:
Response.Write("["+Request.Cookies("foo")("c")+"]");

This now fails to return the expected result:
[d"]

I have read about the use of:
javax.servlet.http.Cookie#setVersion(int)

to modify this behaviour but it doesn't seem to be what is needed here. I am aware that the quoted value is more "correct", but try telling ASP that... Is there any trick I have missed about getting ASP (or Tomcat) to play nice? TIA as always.

A: Quoted cookies correnspond to cookie version > 1 or 2
Non-quoted cookies are valid for cookie version 0
If you have a look at the very interesting discussion over at tomcats bugzilla: https://issues.apache.org/bugzilla/show_bug.cgi?id=44679 there seem to be multiple ways to tune tomcats cookie behaviour.
If you have control about tomcat setting the cookies then this would be the way to switch to non quoted cookies:
Cookie cookie = new Cookie(COOKIENAME,COOKIEVALUE);
cookie.setVersion(0);

This cookie will be be saved unquoted but will also restrict you to a smaller char-set and additional rules like not having any leading/trailing spaces.


text:
Q: Storyboard issue with Xcode 6 and 7 Why my Main Storyboard appears like shown at Above? I made a copy of the project but now both of them have the same problem with the storyboard! I can run the app using the simulator and it works fine, but I can't see any labels or the buttons.

A: The problem is with your device layout....
Actually it makes on other layout like wAny hAny and now you show it on other layouts like wCompact hRegular....thats why the problem occurs...
Here is the visual site of it....

To prevent this type of things...you need to give constraints to your objects..after making correct constraints, the size classes won't matter that much except adaptive layout

A: Its because of Auto Layout Stuff. Set proper auto layout to you label object.
For eg.
Set Leading,Trailing,Top & Bottom layout to your label & then run your application. You will be able to see it on your screen.


text:
Q: Using Roadkill wiki on authenticated website for help system Posted this on google groups for Roadkill wiki, but there seems to be not much activity. Stackoverflow was mentioned, but there's only 2 posts per year...  Bitbucket account is closed... Seems wrong to add an issue in github to just ask questions... https://github.com/roadkillwiki/roadkill/issues
I want to create a help wiki for a password protected website (asp.net, c#, iis...). This website is using Form Authentication. Only users logged onto the site will be able to see the help pages. They will be able to READ the pages, not add or edit or register new users or anything like that.
1) admin access
There will be 1 (or 2 or 3) admin users who can add/edit/delete pages. They can use a special URL to get to the admin pages if required.
- They use their own credentials from the real website somehow mapped as admin in Roadkill, or
- have special Roadkil user+pwd, defined in Roadkill rather than the real website.
2) For the read only requirement, I see it's work in progress for v3.
https://github.com/roadkillwiki/roadkill#viewer-role
http://roadkillwiki.userecho.com/topics/27-viewer-role/
I know it says "no ETA", but are we talking 1 month, 6 months, 1 year? I might have to do my own as I need this within a month or two!
3) For authentication of my readonly users... I thought I would have to write my own "User Manager", using the technique described here:
http://www.roadkillwiki.net/wiki/12/users-and-permissions
But then I thought... If I just install Roadkill in a protected folder in the root of my website, doesn't this give me Form Authentication for free? I don't care who the users are, all pages will be readonly for them... a kind of anonymous access... but I saw anonymous access doesn't exist.
Then I saw this question:
http://roadkillwiki.userecho.com/topics/10-port-it-to-aspnet-identity/
and the answer is no, "asp.net identity doesn't support groups". But it supports roles, so you could have admins, editors (and viewers), am I missing something?
Any tips regarding the 3 points above? It's borderline off topic by stackoverflow standards, I know. So let's make it a real question: how to configure Roadkill in a Form authenticated asp.net website so that all users have readonly access, to create a series of help pages?
There aren't that many .net wikis out there! It's all php!


text:
Q: If $\int f \mathrm d \mu$ exists and $\int g \mathrm d \mu$ is finite, then $\int (f+g) \mathrm d \mu = \int f \mathrm d \mu + \int g \mathrm d \mu$ Let $(X, \mathcal X, \mu)$ be a $\sigma$-finite measure space and $f, g:X \to \mathbb R \cup \{\pm \infty\}$ $\mu$-measurable.

*

*We say that $\int f \mathrm d \mu$ exists if at least $\int f^+ \mathrm d \mu < +\infty$ or $\int f^- \mathrm d \mu < +\infty$. In this case,
$$
\int f \mathrm d \mu := \int f^+ \mathrm d \mu - \int f^- \mathrm d \mu \in \mathbb R \cup \{\pm \infty\}.
$$

*We say that $\int f \mathrm d \mu$ is finite if $\int f^+ \mathrm d \mu < +\infty$ and $\int f^- \mathrm d \mu < +\infty$. In this case, $\int f \mathrm d \mu \in \mathbb R$.

We adopt the convention that $a + (\pm\infty) = (\pm\infty)$ for all $a \in \mathbb R$. I'm trying to prove the following statement, i.e.,

Theorem If $\int f \mathrm d \mu$ exists and $\int g \mathrm d \mu$ is finite, then $\int (f+g) \mathrm d \mu$ exists and
$$
\int (f+g) \mathrm d \mu = \int f \mathrm d \mu + \int g \mathrm d \mu.
$$

In below attempt, I'm stuck at proving $\int (f+g)^- \mathrm d \mu = +\infty$. Could you elaborate on my difficulty?

Proof: WLOG, we assume $\int f^+ \mathrm d \mu < \infty$. We have $(f+g)^+ \le f^+ + g^+$, so
$$
\int (f+g)^+ \mathrm d \mu \le \int (f^+ + g^+) \mathrm d \mu = \int f^+ \mathrm d \mu + \int g^+ \mathrm d \mu < +\infty.
$$
As such, $\int (f+g) \mathrm d \mu$ exists. If $\int f^- \mathrm d \mu <+ \infty$, the claim follows from the linearity of integral. Now we consider the case $\int f^- \mathrm d \mu =+ \infty$. Then $\int f \mathrm d \mu =- \infty$. It suffices to prove that $\int (f+g)^- \mathrm d \mu = +\infty$.

A: Below is my proof that $\int (f+g)^- \mathrm d \mu = +\infty$.

We have
$$
f^-=(-f)^+ = ((-f-g)+g)^+ \le (-f-g)^+ + g^+=(f+g)^-+g^+.
$$
It follows that
$$
\begin{align}
\int f^- \mathrm d \mu &\le \int ((f+g)^- + g^+) \mathrm d \mu \\
&\overset{(\star)}{=} \int (f+g)^- \mathrm d \mu + \int g^+ \mathrm d \mu.
\end{align}
$$
Here $(\star)$ is because $(f+g)^-$ and  $g^+$ are non-negative. Because $\int g^+ \mathrm d \mu <+\infty$, we can subtract it from both sides of  $\int f^- \mathrm d \mu \le \int (f+g)^- \mathrm d \mu + \int g^+ \mathrm d \mu$. Then we  get
$$
\int (f+g)^- \mathrm d \mu \ge \int f^- \mathrm d \mu - \int g^+ \mathrm d \mu = +\infty -\int g^+ \mathrm d \mu = +\infty.
$$
This completes the proof.