text:
Q: How to let the c++ output in the vc code terminal When I run a C++ program in vs code, it alway pops up a new window. Are there any ways to let the program output to the inner terminal (or output window) of vs code, instead of the annoying pop up window?

A: In VS-Code you configure the build/run in the tasks.json, and the debug in the launch.json (all configuration files go under ${workspaceFolder}/.vscode/).
You can set a keyboard shortcut for each task or for debug. For example my default build task is run with Ctrl+Shift+Band debug starts with F5. More info on how to set build/run/debug in VS-Code:
https://code.visualstudio.com/docs/languages/cpp
And as shingo mentioned depending on the externalConsole flag you can control if a new terminal window pops up or not.


text:
Q: Bijection and image Let $f: A → B$ be a bijection, so $f^{-1}: B → A$ is a function. Let $X$ be a subset of $A$. How do I prove that $\text{Im}(f)(X)  = \text{Preim}(f^{-1})(X)$?
Thank you.

A: See Bijection :

A function $f : A → B$ is bijective if and only if it is invertible, that is, there is a function $g: B → A$ such that $(g \circ f)$ = identity function on $A$ and $(f \circ g)$ = identity function on $B$. This function maps each image to its unique preimage.

In your case, consider for example the function $f(x) = x^2$; let $A = \mathbb Z$ (the set of  integers) and let $X = \mathbb N$ (the set of natural number).
Clearly : $X \subseteq A$, but $f$ is not bijective.
In this case the inverse image of $\{ 4 \}$ would be $\{ -2, 2 \}$ and we have that $4 \in \mathbb N$ but $-2 \notin \mathbb N$, i.e. $-2 \notin Preim(f^{-1})(X)$.

A: Because $f$ is a bijection, we know an inverse $f^{-1}$ exists.
Let $ y \in \text{Im}_f(X) $ be arbitrary.
    \begin{align*}
        \exists x \in X. \; f(x) = y. \;\;\;\;\; &&\text{(Definition of Image)} \\
        f^{-1}(y) = x \;\;\;\;\; &&\text{(Definition of Inverse)} \\
        f^{-1}(y) \in X \;\;\;\;\; &&(x \in X)  \\
        y \in \text{PreIm}_{f^{-1}}(X) \;\;\;\;\; &&\text{(Definition of Pre-Image)}
    \end{align*}
    Since $ y \in \text{Im}_f(X) $ was arbitrary, $ \text{Im}_f(X) \subseteq \text{PreIm}_{f^{-1}}(X). \\ \\ $
Let $ y \in \text{PreIm}_{f^{-1}}(X) $ be arbitrary.
    \begin{align*}
        \exists x \in X. \; f^{-1}(y) = x. \;\;\;\;\; &&\text{(Definition of Pre-Image)} \\
        f(x) = y \;\;\;\;\; &&\text{(Definition of Inverse)} \\
        y \in \text{Im}_f(X) \;\;\;\;\; &&\text{(Definition of Image)}
    \end{align*}
    Since $ y \in \text{PreIm}_{f^{-1}}(X) $ was arbitrary, $ \text{PreIm}_{f^{-1}}(X) \subseteq \text{Im}_f(X). \\ $
By double containment, $$ \text{Im}_f(X) = \text{PreIm}_{f^{-1}}(X)  \;\;\;\;\; \blacksquare $$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Discord.js blacklist code doesn't do anything So I'm making this code for blacklisted words and it doesn't work. It doesn't give any errors but doesn't work. How to fix?
let blacklisted = ['blacklisted', 'right'];
    let foundInText = false;//
    for(const i in blacklisted) {
        if (message.content.toLowerCase().includes(blacklisted[i])) foundInText = true;
    }
    if (foundInText === true) {
        message.delete();
        message.channel.send('no just no');
    }

That is the code so as I have said it doesn't give any errors but just doesn't do anything if I send a blacklisted word

A: Your for ... in logic returns the actual value of the current blacklisted object it's iterating over, not the array index of the current value. Because of this, your code is trying to find the value of blacklisted["blacklisted"] or blacklisted["right"], which will be undefined and always return false.
To make this work with your current code, you can instead just check whether the message content contains the value of i.
if (message.content.toLowerCase().includes(i)) foundInText = true;

However, even if it does find a blacklisted word somewhere towards the start of the list, your code will still iterate over the entire list, due to lacking a break keyword when the text is found (you don't need to iterate the list any further if you've already found a match). You can massively simplify your code by using the some array function, which checks if any of the elements of an array satisfies a given condition, immediately returns true once it finds any element that satisfies the condition, or false if it doesn't find anything.
let blacklisted = ["blacklisted", "right"]

let foundInText = blacklisted.some(blacklistWord => message.content.toLowerCase().includes(blacklistWord))

if (foundInText) { // No need for === true on boolean variables
    message.delete();
    message.channel.send('no just no');
}


text:
Q: JQuery cycle plugin with different effect on next and previous Using JQuery cycle, is it possible to have different effects on the next and previous buttons? For example, have the next button scroll left and previous button fade?
I know about the scrollHorz effect for left and right scrolling.
Thanks

A: It is not possible to specify separate individual effects for the next and prev buttons without modifying the source code of the plug-in.
The closest you can come is specifying multiple effects in the fx options. These will be used in sequence. Example:
$('#slideDiv').cycle({
    fx:     'fade,scrollHorz',
    prev:   '#prev1',
    next:   '#next1',
    timeout: 0
});

So, the first time you click the next or prev buttons, it will use "fade", the next time you click either button, it will use "scrollHorz", then "fade" and so on.

A: Out of the box, this only works with the transitions which provide a "reverse" animation such as scrollHorz, scrollVert, shuffle.
The nice thing about jQuery Cycle is that you can write your own (or modify) any transition to include your own forward and reverse logic.  Check out the Cycle Source and do a search for "scrollHorz".  You will see how easy it is to provide logic depending on the direction of the transition (take note of the fwd variable).  You can then modify any existing transition to suit your needs.
NOTE: some javascript and math skills required.


text:
Q: Prevent 2 forms from being submitted? I have two forms on the same page and I'm preventing each from being submitted multiple times with this:
onclick="this.form.submit(); this.disabled=true;"

Using javascript, can I similarly prevent form #2 from being submitted if form #1 has already been submitted, and vice-versa?

A: You could use a global variable to save state of the forms
 var disabled=false;

and
  onclick="if(!disabled){this.form.submit(); disabled=true;}"


text:
Q: Can't mount data DVD using 12.04 I cannot mount a data DVD using Ubuntu 12.04.
I can read the DVD using a different OS, so the DVD is not the problem.
I can read other CDs using Ubuntu.
The error I get is:
$ sudo mount /dev/dvd /cdrom
mount: no medium found on /dev/sr0

The relevant output from lshw is:
   *-cdrom
        description: DVD reader
        product: DVD/CDRW UJDA775
        vendor: MATSHITA
        physical id: 0.0.0
        bus info: scsi@4:0.0.0
        logical name: /dev/cdrom
        logical name: /dev/cdrw
        logical name: /dev/dvd
        logical name: /dev/sr0
        version: CB03
        capabilities: removable audio cd-r cd-rw dvd
        configuration: ansiversion=5 status=nodisc

I have installed ubuntu-restricted-extras and run /usr/share/doc/libdvdread4/install-css.sh.


text:
Q: How to extend convoy volume? Environment:

*

*CentOS 7.4.1708

*Docker 17.09.0-ce, build afdb6d4

*convoy v0.5.0 (docker-convoy: Docker volume plugin) with devicemapper

Phase 1: Created convoy volume
sudo convoy create data-test --size 100M

Phase 2: Tried to extend convoy volume

*

*Backup original convoy volume

*Restore volume with --size option
Then, I got an error that Volume must be same size.
Is there way to extend convoy volume?

A: Docker-convoy uses devicemapper(default) that user could visible to block-device(try lsblk).

*

*Create new volume with --size option:
sudo convoy create new-volume-name --size 1000G

*Transfer data from volume-name to new-volume-name:
sudo dd if=/dev/mapper/volume-name of=/dev/mapper/new-volume-name

*Resize new-volume-name:
sudo resize2fs /dev/mapper/new-volume-name
If it warn need to check by e2fsck, run sudo e2fsck /dev/mapper/new-volume-name

*Check volume that it is readable:
sudo convoy mount new-volume-name
sudo ls -l /var/lib/rancher/convoy/devicemapper/mounts/new-volume-name
sudo convoy umount new-volume-name

*Remove original volume:
sudo convoy delete volume-name

*Switch from volume-name to new-volume-name at the container.
Note:
This process is for offline migration. I could not find out incremental backup in this time. Before you run this, the docker containers should be stopped.
And, there is no way to rename volume name.


text:
Q: assigning index number to row in table I want to add an index number to each row in a table automatically, like the one in the screenshot that I got from bootstrap's site here, I have tried multiple solutions but kept getting an index of -1 for all the rows, I would really appreciate the help, thank.

A: Does this work for you?
// tbl is the table
var rows = tbl.rows; n = 1;
for (i=0; i<rows.length; i++) {
  row = rows[i];
  f = row.firstElementChild;
  if (f) {
    el = document.createElement(f.tagName);
    el.innerHTML = (f.tagName == "TH") ? "#" : n;
    row.insertBefore(el, f);
    if (f.tagName != "TH") n++;
  }
}


text:
Q: Expected conv2d_19_input to have 4 dimensions Error in CNN via Python I have a problem about solving dimension in prediction method of CNN.
Before defining train and test data based on image , I posed a CNN model.
After the process has been done, I fitted the model.
When I predict the value by using model, It throws an error here.
How can I fix it ?
Here are my code blocks shown below.
My Keras Libraries
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator

Here is my CNN Model
classifier = Sequential()
classifier.add(Convolution2D(filters = 32,
                             kernel_size=(3,3),
                             data_format= "channels_last",
                             input_shape=(64, 64, 3),
                             activation="relu")
              )

classifier.add(MaxPooling2D(pool_size = (2,2)))

classifier.add(Convolution2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

classifier.add(Convolution2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

classifier.add(Flatten())

classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

Fitting CNN to Images
train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory(train_path,
                                                 target_size=(64, 64),
                                                 batch_size=32,
                                                 class_mode='binary')

test_set = test_datagen.flow_from_directory(
        test_path,
        target_size=(64, 64),
        batch_size=32,
        class_mode='binary')

Fit Model
classifier.fit_generator(
        training_set,
        steps_per_epoch=50,
        epochs=30,
        validation_data=test_set,
        validation_steps=200)

Prediction
S = 64

directory = os.listdir(test_forged_path)
print(directory[3])

print("Path : ", test_forged_path + "/" + directory[3])

imgForged = cv2.imread(test_forged_path + "/" + directory[3])
plt.imshow(imgForged)

pred = classifier.predict(imgForged) # ERROR
print("Probability of Forged Signature : ", "%.2f".format(pred))

The Error :
ValueError: Error when checking input: expected conv2d_19_input to have 4 dimensions, but got array with shape (270, 660, 3)

A: The predict method is missing the batch dimension from your input. Modify your prediction like so:
import numpy as np <--- import numpy

S = 64

directory = os.listdir(test_forged_path)
print(directory[3])

print("Path : ", test_forged_path + "/" + directory[3])

imgForged = cv2.imread(test_forged_path + "/" + directory[3])
plt.imshow(imgForged)

pred = classifier.predict(np.expand_dims(imgForged,0)) # <-- add new axis to the front, shape will be (1, 270, 660, 3)
print("Probability of Forged Signature : ", "%.2f".format(pred))


text:
Q: Sleeping for certain numbers lasts forever in Linux bash I'm writing a bash script in Ubuntu 13.04 that requires to sleep a specific number of seconds passed by parameter.
I've made sure that sleep allows floating point numbers looking in the documentation:

Unlike most  implementations  that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number.

Indeed it works for certain values. For example it's ok for "0.1", "0.01", "0.02", "0.03" or "0.4" but it lasts forever for others values like "0.04" or "0.05".
I mean,
this will work:
sleep 0.03

... but this will last forever:
sleep 0.04

Anybody knows why?
Thank you!

A: It is probably a bug with sleep command...
You can alternatively use bash implementation until that bug is fixed, create this alias on your script, but see sleep --help if you want to simulate all features.
alias sleep='read -t'

now try it:
date +"%S.%N"; sleep 0.04; date +"%S.%N";

this works on ubuntu 12.10 already.
EDIT: this is less precise but works too if you dont need the extra functionalities of sleep command:
function FUNCsleep() {
  local delay=$1;
  local beginAt=`date +"%s.%N"`;
  while true; do
    local now=`date +"%s.%N"`;
    if((`echo "($now-$beginAt)>=$delay" |bc -l`==1));then
      break;
    fi;
  done;
}
alias sleep='FUNCsleep'


text:
Q: Printning document or string using ASP.NET MVC 2 and C# How do I print current document or any string through printer using ASP.NET MVC 2 and C#?

A: How to trigger windows Print dialog from server side (asp.net)?
How can I pop-up a print dialog box using Javascript?
javascript print without print dialog box
How can Print Preview be called from Javascript?


text:
Q: Javascript Execution Through Python I am attempting to create an html document parser with Python. I am very familiar with jQuery and I would like to use its traversing functionality to parse these html files and return the data gathered with jQuery back to my Python program.
Is there any way to use javascript scripts through Python? Or is this just a pipe dream?

A: You might not need to do this. There is a Python module called PyQuery that directly emulates the API for jQuery. It works exactly as you would expect it to in almost every way.  Give it a shot!

A: jQuery itself does not contain an HTML/XML parser at all. It uses the browser to do all its parsing. Thus, even if you figure out how to run Javascript from Python, it won't do you any good.

A: jQuery doesn't parse HTML - it traverses the DOM. You'd need an entire rendering engine (e.g. WebKit) if you wanted to use jQuery to work on the HTML.

A: Well from your question it seems you will require python-javascript bridge like
Pyjamas http://pyjs.org/ , PyPy http://codespeak.net/pypy/dist/pypy/doc/ , skulpt http://www.skulpt.org/ . Or my personal favorite PyXPCOM http://pyxpcomext.mozdev.org/ it installs a python backend directly into the firefox browser and using xpi stubs one can make bidirectioal calls ( mind you very complicated )


text:
Q: RabbitMQ - best practice I am trying to synchronize three microservices I have.
In order to do so I've implemented RabbitMQ.
It seems as if things currently work but I am not sure if I'm following best practice and I couldn't find a reference to look it up, maybe someone could help me with that?
Brief of what I am trying to do:
I have one service who should update the two others,
each of the services should receive the message sent.
I have two types of messages (save and delete resource).
* In case of fault the queue should recover and resend the messages.
What I am currently doing:
I've set up an exchange and each of my consumers connect to two different queues, one for each type of message (save/delete).
I've used a direct exchange in order to filter the messages later on, even though currently I don't need to filter them.
Each of the queues are named, and the exchange as well as the messages are durable and I'am acking the messages I've consumed.
The question
Should I set a different queue for each type of event or should I send the messages on the same queue and filter them?
Is the use of RabbitMQ described above is the correct solution for the problem.
What is the best practice?

A: Your setup is correct.
One common rule when designing queues in rabbit is, one queue for one type (type here means different handling logic) of consumers. So, since you have two types of consumers. They have different logic for different types of events (save/delete), one queue for each is exactly correct.
If you want to have only one type of consumer, which could handle both save and delete events, then to use one queue is also OK.
But two types of consumers and one shared queue will not work. Coz when multiple consumers subscribing to one queue, events are dispatched to consumers in kind of round-robin way, so either of your consumers could only receive half of the events.


text:
Q: The kernel of homomorphism of a local ring into a field is its maximal ideal? I have a question about the proof of Theorem 3.2. of Algebra by Serge Lang.
In the theorem $A$ is a subring of a field $K$ and $\phi:A \rightarrow L$ is a homomorphism of $A$ into an algebraically closed field $L$.
In the beginning of the proof

We may first extend $\phi$ to a homomorphism of the local ring $A_\mathfrak{p}$, where $\mathfrak{p}$ is the kernel of $\phi$. Thus without loss of generality, we may assum that $A$ is a local ring with maximal ideal $\mathfrak{m}$.

Then, later

Since $\phi$ and the canonical map $A \rightarrow A/\mathfrak{m}$ have the same kernel,

I understand that $\mathfrak{m}$ is the kernel of the extension of $\phi$ to $A_\mathfrak{p}$. But in the proof, $\mathfrak{m}$ seems to be assumed to be the kernel of $\phi$ even if $A$ itself is a local ring.
In general, is the kernel of homomorphism of a local ring to a field its maximal ideal? If so, why is that ?

A: I believe, Lang meant that one can consider only the case of a local ring and the kernel being $\mathfrak{m}$ (i.e. $A:=A_{\mathfrak{p}}$). For the kernel: let $R$ be a ring of germs of infintely-differentiable functions, and take a homomorphism of $R$ to formal power series. That is embeddeble into the field of Laurent series, but the kernel is obviously not maximal ideal.

A: No, in general it is not true that a homomorphism from a local ring into a field has the maximal ideal as kernel. Just consider the inclusion ${\mathbb Z}_{(p)} \to {\mathbb Q}$ for some prime number $p$.
What is happening here is the following. Suppose you start out with a ring $A$ that is already local with maximal ideal ${\frak m}$ and a homomorphism $\phi \colon A \to L$. The kernel ${\frak p}$ of $\phi$ doesn't have to be ${\frak m}$, but you can still localize at ${\frak p}$, obtaining an other local ring $A_{\frak p}$.
So the claim by Lang that "$\phi$ and the canonical map $A \to A/{\frak m}$ have the same kernel" is true, but that's because earlier he localized exactly at the kernel. (It might have been clearer if Lang had written "we may assume that $A$ is a local ring with maximal ideal ${\frak p}$" (or "with maximal ideal ${\frak m} = {\frak p}$")).

A: We can only infer $\mathfrak m=\ker\varphi$ when $\mathfrak m$ is the only prime ideal of $A$. In this case $A/\ker\varphi$ is a subring of $L$, which is necessarily an integral domain.
However, $A$ is assumed to be a subring of a field! So, $(0)\subset A$ is prime, and we can always consider the case of $\varphi$ being the canonical embedding of $A$ in the algebraic closure of its field of fractions. With this choice of $\varphi$ if $A$ is not a field, then $\ker\varphi$ is not the maximal ideal $\mathfrak m$.


text:
Q: How to create a list of arbitrarily sized lists I'm trying to create a container that has 3 lists within it, where each list is an arbitrarily sized list of arbitrarily sized lists.  Here is my train of thought on what I would be doing (not very experienced in Matlab, so there's probably a more elegant way of doing this)
my_data = [[] [] []];

for m = 1 : M
   list1 = [];
   list2 = [];
   list3 = [];

   for n = 1 : N
      if something holds
         list1 = [list1 ftn(n)];
         list2 = [list2 ftn2(n)];
         list3 = [list3 ftn3(n)];
      end
   end

   if something else holds
      my_data(1) = [my_data(1) list1];
      my_data(2) = [my_data(2) list2];
      my_data(3) = [my_data(3) list3];
   end
end

This code doesn't actually run though... How do I do something like this in Matlab?

A: This is what cell arrays are for. Matlab doesn't let you do non-rectangular regular arrays (as you've discovered), but cell arrays let you do arrays of general objects, including standard arrays.
my_data = {{} {} {}};

for m = 1 : M
    list1 = [];
    list2 = [];
    list3 = [];
    for n = 1 : N
        if something
            list1 = [list1 something];
            list2 = [list2 something];
            list3 = [list3 something];
         end
    end

    if something
        my_data{1}{end+1} = list1;
        my_data{2}{end+1} = list2;
        my_data{3}{end+1} = list3;
    end
end


text:
Q: Cache related issues codenameone I have few issues on caching...
1)I use URLImage as follows
URLImage.createToStorage(profileImg, photoUrl + "__c", photoUrl, URLImage.RESIZE_SCALE_TO_FILL)

But if the image is edited(old one is replaced with new one) in the server,it shows the old img instead of updating to the new image. what should i do to reupdate the cached image.
2)We are developing an news app. Here news are updated daily. The recent ten news are saved in the storage as follows:
    //write the storage object
     do {
          Storage.getInstance().writeObject("newsListingStorage", fetchresponses);
        } while (fetchLastId < 10);

    //read the storage
    public Vector newsListOfflineStorage() {
        Vector newsListingRead = (Vector)Storage.getInstance().readObject("newsListingStorage");
        return fetchresponses;
       }

i am concerned that if a user stores 10 items each day, it'll store much more in a month or a year and the cache items goes on... How can i replace the cache stored every time to the latest 10 items so that there are only ten recent cached items every time one runs the app.

A: I don't know if cache expiration is already introduced in codenameone but how I handled this... is caching the images with unique id coming from your database
URLImage.createToStorage(profileImg, "largeImage_" + newsUniqueId + ".jpg", photoUrl, URLImage.RESIZE_SCALE_TO_FILL);

Let's say you stored 10 news earlier, it doesn't matter what ids they have and in your database you have 100 news and you need only the top news with unique ids from 91 to 100. Loop from 0 to 90 and delete those images from storage if they exist.
private void deleteImageFromStorage(String imageName) {
    FileSystemStorage fss = FileSystemStorage.getInstance();
    fss.deleteRetry(fss.getAppHomePath() + imageName, 2);
}

for (int i = 0; i < myTop10NewsLowestId; i++) {
    deleteImageFromStorage("largeImage_" + i + ".jpg");
}


text:
Q: Error regarding DNS - "... must be able to resolve names ..." (Windows Server 2008 R2 installation) I'm trying to replace our old Windows 2000 Server by a Windows Server 2008 R2. I followed the guide at MSDN. Coming to the step "Install Active Directory Domain Services..." the option to install the DNS-Server was grayed-out. According to Microsoft Support I skipped the DNS Server Installation at this point. (Because of the single-label DNS name)
I then installed the DNS-Server role and created a forward-lookup-zone for the domain. When running the Best Practices Analyzer of the DNS-Server role I get these two messages for both domain controllers (the old win2k and the new win 2008 R2):

*

*The DNS server [IP address] on [adapter name] must be able to resolve names in the primary DNS domain zone

*The DNS server [IP address] on [adapter name] must be able to resolve names in the forest root domain name zone
The TechCenter articles suggest to use a proper DNS Server - that's pointless when I try to configure a proper DNS Server.
How do I configure the DNS Server in a way that it resolves these zones?
Or are these errors irrelevant?

dcdiag /v /test:DNS

Seems to run fine...

A: dcdiag /test:dns options tests some of the records relevant for DCs. It doesn't test all of them. However, if that works, thats a good start.
I dont know why you created a forward lookup zone for the domain. What type of zone storage were you using in Windows 2000? I would have expected that zone to replicate when you promoted the new DC.
If you can resolve records in the zone using tools like nslookup pointed against the Windows 2008 R2 DNS server, I would ignore this. However, feedback on the BPA functionality is welcomed as per http://blogs.technet.com/b/windowsserver/archive/2009/02/11/best-practices-analyzer-resolution-guidance-now-available-online.aspx
You could feedback to support engineers that monitor the official AD support blog at http://blogs.technet.com/b/askds/archive/2010/08/02/new-dns-and-ad-ds-bpa-s-released-or-the-most-accurate-list-of-dns-recommendations-you-will-ever-find-from-microsoft.aspx or at http://connect.microsoft.com/ADBPA .


text:
Q: removing the intercept from regression line equation from ggplot using stat_reg_line() function I am adding the regression line equation to my ggplot. However, I would like to remove the intercept from plot and keep only the slope and R^2.
Here is the code I am using to generate the plot and equation. Do you have any idea how can I remove the intercept?
library(ggpmisc)
df <- data.frame(x = c(1:100))
df$y <- 20 * c(0, 1) + 3 * df$x + rnorm(100, sd = 40)
df$group <- factor(rep(c("A", "B"), 50))
df <- df %>% group_by(group) %>% mutate(ymax = max(y))

df %>%
   group_by(group) %>%
   do(tidy(lm(y ~ x, data = .)))

p <- ggplot(data = df, aes(x = x, y = y, colour = group)) +
   geom_smooth(method = "lm", se=FALSE, formula = y ~ x) +
   stat_regline_equation(
   aes( x = x, y = y  , label =  paste(..eq.label..,..rr.label.., sep = "~~~~")),
   formula=y~x, size=3,
   )
p

Thanks,

A: You can use stat_fit_tidy from the ggpmisc package:
df <- data.frame(x = c(1:100))
df$y <- 20 * c(0, 1) + 3 * df$x + rnorm(100, sd = 40)
df$group <- factor(rep(c("A", "B"), 50))

library(ggpmisc)
my_formula <- y ~ x

ggplot(df, aes(x = x, y = y, colour = group)) +
  geom_point() +
  geom_smooth(method = "lm", formula = my_formula, se = FALSE) +
  stat_fit_tidy(
    method = "lm",
    method.args = list(formula = my_formula),
    mapping = aes(label = sprintf('slope~"="~%.3g',
                                  after_stat(x_estimate))),
    parse = TRUE)

EDIT
If you want the R squared as well:
ggplot(df, aes(x = x, y = y, colour = group)) +
  geom_point() +
  geom_smooth(method = "lm", formula = my_formula, se = FALSE) +
  stat_fit_tidy(
    method = "lm",
    method.args = list(formula = my_formula),
    mapping = aes(label = sprintf('slope~"="~%.3g',
                                  after_stat(x_estimate))),
    parse = TRUE) +
  stat_poly_eq(formula = my_formula,
               aes(label = ..rr.label..),
               parse = TRUE,
               label.x = 0.6)

EDIT
Another way:
myformat <- "Slope: %s --- R²: %s"
ggplot(df, aes(x, y, colour = group)) +
  geom_point() +
  geom_smooth(method = "lm", formula = my_formula, se = FALSE) +
  stat_poly_eq(
    formula = my_formula, output.type = "numeric",
    mapping = aes(label =
                    sprintf(myformat,
                            formatC(stat(coef.ls)[[1]][[2, "Estimate"]]),
                            formatC(stat(r.squared)))),
    vstep = 0.1
  )


text:
Q: Understanding a new command and editing it I'm trying to highlight some pseudocode lines, and I'm using this solution  pseudocode block. However, I've not understood the following new command:
\newcommand{\fillcol}{green!20}
\newcommand<>{\boxto}[1]{
\only#2{
    \tikz[remember picture with id=#1]
    \draw[line width=1pt,fill=\fillcol,rectangle,rounded corners]
    (pic cs:#1) ++(8.2,-.1) rectangle (-3.4,-.1);
    }
}

What's mean the symbols <> in front of \newcommand?
Moreover, I'd like to pass the color to fill the rectangle as parameter for
the \boxto command. In the posted solution, the color is defined as a command \fillcol How to do this change? Could someone help me?
Thanks!

A: Just for quickness: I did not copy over unnecessary code from the linked question, i.e. I disabled the pic coordinate system and the tikz remember picture with id=#1 style.
The beamer class adds a new version of \newcommand, making it possible to generate commands with overlay specification, with
\newcommand<>{\cmdname}[number of args]{%...

% rest of code
}

Important to know is that the overlay specification is inside and that the command in fact has one more argument than specified, i.e. in the example, there are 3 arguments. The third one is meant for the overlay, so the last argument is always 'hidden', but can be accessed.
Please note, that the pointed brackets <1> belong to the last argument, that's how \only#3 works then.
For more on this see section 9.6 of the current beamer documentation.
\documentclass{beamer}

\usepackage{tikz}

\newcommand{\fillcol}{green!20}
\newcommand<>{\boxto}[2]{
\only#3{%
  \tikz%[remember picture with id=#1]
  \draw[line width=1pt,fill=#2,rectangle,rounded corners] (1,1) rectangle (2,2);
  }%
}

\begin{document}

\begin{frame}{Foo frame}
\boxto<1>{1}{green}

\boxto<2>{1}{red}
\end{frame}

\end{document}


text:
Q: edit custom content in bigcommerce stencil As we're currently moving from Blueprint to Stencil, we would like to add some blocks of custom content to our home page.
A block of custom content would contain an image, a line of text, as well as a link to a product, a brand, or a page.

*

*Is there a way to add a text block (text input field) in the Stencil Theme Editor in order to edit a line or block of text (besides just (background) colors, image size dropdown, etc.) without having to upload a new version of the theme?

*An option would be to use the language file (en.json) to store the content. Is there a way to modify the en.json file without having to upload a new version of the theme for every update?
Or, is there another way to deal with custom content blocks in Stencil?
To give more context, the user/client should be able to replace a background image, (promotional) content, links etc. through the Theme Editor without  having to "hand-code"... to make it more like a WYSIWYG "WordPress"-style.

A: The problem we first encountered was that the option "Edit Theme Files" from within the Theme Editor didn't do anything.
The answer to the problem is to go to "Storefront Design" > "My Themes" > "Edit Theme Files".
This option opens up the editor allowing us to edit the "en.json" file that contains the actual content for the handlebars we added to the html file.


text:
Q: Use ASP.NET when creating Windows 8 App Hi i just wonder if I could use ASP.NET to create a Windows 8 App or is ASP.NET only for homepages?

A: ASP.NET is for creating web applications.
To create win 8 app you can use any language supported by Microsoft (vb.net, c++, c#, javascript and others) along with XAML (Extensible Application Markup Language) or plain HTML.
Although I think you can create a web app in asp.net and then open in inside win 8 app in browser mode (insane!).


text:
Q: Parameters are not binding the empty values when an empty value is passed from Jquery Ajax POST request in Asp.net core mvc project In the below code I am passing an empty value for "FirstName". When the Ajax POST request is made on the controller side the "FirstName" parameter value is coming as Null but if I pass any value the value is binded to the parameter. Only for the empty values, the value is showing as null in asp.Net core project
Javascript:
var dataVal = {};
dataVal["FirstName"] = "";

$.ajax({
    type: "POST",
    "url":url,
    data:dataVal,
    dataType: "json",
    async: false,
    success: function (m) {
        if(m){
            alert(m);
        }

    },
    error: function(err){

    }
});

Controller:
public IActionResult Home(string FirstName){

}

A: Do you want to receive "" instead of null in controller when ajax send request with the value of FirstName is ""?
The explation about this is as follows:
This is simply because MVC 2.0 defaults to initializing strings to null. To be more precise, if an empty string means has no value, So .NET sets the default value of its. And the default string (belonging to reference type) is null. So The ModelBinder sets the properties to their default value if no value is provided in the request.
refer to this link.
Attention: link provided above is about Asp.net MVC, There are some methods do not work in .Net Core. For example, Someone provided a method to change bindingContext.ModelMetadata.ConvertEmptyStringToNull = false; to receive "" in controller, But in asp.net core's document:

Gets a value indicating whether or not to convert an empty string
value or one containing only whitespace characters to null when
representing a model as text.
public abstract bool ConvertEmptyStringToNull { get; }

ConvertEmptyStringToNull just has a get method, So you can't change it.

A: Use the [HttpPost] attribute on the above action method and set the default value to string parameter. The below code for reference:
[HttpPost]
public IActionResult Home(string FirstName="")
{
    …
}


text:
Q: Is there a way to use values in a list to search a dictionary? I have a list of list that has values which are the same as some keys in a dictionary, like so:
list_a = [["a", "c", "e"], ["b", "f", "g"], ["b", "d", "i"]]
dict_a = {"a": "3", "b": "3", "c": "2", "d": "5", "e": "4", "f": "3", "g": "3", "h": "1", "i": "1"}

I want to use the values in list_a to access dict_a and check if the values by those keys are the same. To make myself clear: I take the first list in list_a and use those values to check if values in dict_a by keys "a", "c" and "e" share the same value. If yes (so if those three keys share the same values) do something, if not keep looking. So far I have tried different variations of this:
for i in range(len(list_a)):
check = list_a[i]
  for j in range(len(check)):
      if dict_a[check[j]] == "3":
        #do stuff

With no result other than doing the thing every time it find a correspondence. What am I missing?

A: Use the all() function to check if all the values are the same.
And use any() to test if this is true for any of the sublists in list_a.
if any((all(dict_a.get(v) == dict_a.get(check[0]) for v in check) for check in list_a):
    # do stuff

A: If you only need the first matching result you can get it in one line of code:
list_a = [['a', 'c', 'e'], ['b', 'f', 'g'], ['b', 'd', 'i']]
dict_a = {'a': '3', 'b': '3', 'c': '2', 'd': '5', 'e': '4', 'f': '3', 'g': '3', 'h': '1',
          '1': '1'}
if (result := next((sublist for sublist in list_a if len(set(dict_a.get(v, v) for v in sublist)) == 1), None)):
    # do stuff
    print(result)

The basic idea is to loop over all inner lists. Then we take each element of the inner list, get the corresponding value from the dictionary and build a set with all those values. If this set has only one element then all the values are the same. We return the element with next and provide a default value of None if no matching inner list could be found.

After your clarification that all those values must match a given value there is a different solution:
value_to_find = '3'
for sublist in list_a:
    if all(dict_a.get(value, value) == value_to_find for value in sublist):
        print(sublist)
        # your code here
        break

Remove the break if you want to perform the action on multiple inner lists if multiple inner lists match.

A: list_a = [["a", "c", "e"], ["b", "f", "g"], ["b", "d", "i"]]
dict_a = {"a": "3", "b": "3", "c": "2", "d": "5", "e": "4", "f": "3", "g": "3", "h": "1", "i": "1"}
for i in range(len(list_a)):
    check = list_a[i]
    lst = [dict_a[check[j]] for j in range(len(check))]
    if lst[:-1] == lst[1:]:
        print("All same")
    else:
        print("Not All same")


text:
Q: Cleaning a bootable USB with Powershell I'm new to PowerShell and I am trying to make an easy PS script that will clean a bootable USB when I run it. The problem is that when I run this code:
diskpart; select disk 1; clean; create partition memory;

It just stays stuck on diskpart. I have no idea how to go forward with this.

A: Write a text file that contains the commands for diskpart:
select disk 1
clean
create partition memory

You can than supply the file using the /s switch for diskpart:
diskpart /s "C:\Temp\MyCommands.txt"

A: Welcome to PowerShell. I hope you enjoy learning it.
PowerShell understands your one-line script as follows:

*

*Resolve the meaning of diskpartResolving... Found diskpart.exeRun it and wait for it to finish.

*Resolve the meaning of selectResolving... It is an alias to Select-Object cmdlet.Run Select-Object disk 1.Return error: Select-Object : A positional parameter cannot be found that accepts argument '1'.

*Resolve the meaning of cleanResolving... No such alias, cmdlet or executable file found.Generate an error.

*Resolve the meaning of createResolving... No such alias, cmdlet or executable file found. Generate an error.

Please understand that PowerShell is a programming language, not a classic CLI.

A: PowerShell has native cmdlets called Format-Volume, Initialize-Disk, and New-Partition, which should do what you want.


text:
Q: Order One Crossover in Java Genetic Algorithm So basically i am creating a genetic algorithm but i am stuck when it comes to implementing the crossover code. Can anyone lend a helping hand to let me know if my code is a step in the right direction when implementing order one crossover. Or can anyone give me pseudo code for order one crossover?
package geneticalgorithm;

import java.util.Random;

public class GeneticAlgorithm {

final static int P = 20;
final static int N = 10;
static int popFitness = 0;
int offspringFitness = 0;
static Random rand = new Random();
static int count = 0;

   static Individual[]  population = new Individual[P];
   static Individual[] offspring = new Individual[P];

public static void main(String[] args) {

    for (int i = 0; i < P; i++){

        population[i] = new Individual(); //Generates a population of P individuals and gives each one unique genes
        population[i].generateGenes();
        population[i].fitness = 0;
    }

    for (int i = 0; i < P; i++){
        for (int j = 0; j < N; j++){                //    Loops through each individual in the population and assesses their
            if (population[i].genes[j] == 1 ){       //fitness based on how many 1's are in its genes
                population[i].fitness++;

            }
        }
    }

    for (int i = 0; i < P ; i++){
     for (int j = 0; j < N; j++){
         count++;

        System.out.print(population[i].genes[j]  ); // Loops through population and each gene and outputs each individuals genes to the screen aswell as there fitness
     if ((count % N) == 0){
         System.out.print( "    " + population[i].fitness);
         System.out.println("");
     }
    }
    }

    for (int i = 0; i < P; i++){

        popFitness += population[i].fitness; // calculates the overall fitness of the population
    }

    System.out.println(popFitness);

   offspring[1] = population[rouletteSelection()];
    System.out.println(offspring[1]);

    for (int i = 0; i < P; i++){

        int p1 = rand.nextInt(P);
        int p2 = rand.nextInt(P);

        if (population[p1].fitness >= population[p2].fitness){
                offspring[i] = population[p1];
        }
            else {                                       //Randomly creates a new population called offspring by comparing two random parents
                offspring[i] = population[p2];          //and picking the one with the largest fitness value
                        }

        }

}

 public static Individual crossover1(Individual parent1, Individual parent2){
    Individual newSol = new Individual();
    parent1 = population[rouletteSelection()];
    parent2 = population[rouletteSelection()];
    int crossoverPoint = rand.nextInt(N);
    for (int j = 0; j < N; j++){
        Individual newSolution = new Individual();

    for (int i = 0; i == crossoverPoint; i++){

        newSolution.setGenes(i, parent1.getGenes(i));
        }
    for (int i = crossoverPoint; i < N; i++){
        newSolution.setGenes(i, parent2.getGenes(i));
    }
    }
return null;}

public static int rouletteSelection(){
int parent = 0;
int randNum = rand.nextInt(popFitness);
int rollingSum = 0;
for (int i = 0; i < P; i++){
    rollingSum += population[i].fitness;  //Algorithm to select a         parent based on probability and a hint of randomness
    if (rollingSum >= randNum){
         parent = i;
        break;
    }
 } System.out.println(parent);
 return parent;

}

}

A: Your crossover function looks good to me, but you just never seem to return the new individual:
public static Individual crossover1(Individual parent1, Individual parent2){
     Individual newSol = new Individual();
     parent1 = population[rouletteSelection()];
     parent2 = population[rouletteSelection()];
     int crossoverPoint = rand.nextInt(N);
     for (int j = 0; j < N; j++){

     for (int i = 0; i == crossoverPoint; i++){

         newSol.setGenes(i, parent1.getGenes(i));
      }
    for (int i = crossoverPoint; i < N; i++){
       newSol.setGenes(i, parent2.getGenes(i));
     }
    }
    return newSol;
}


text:
Q: Skip items of a specific type in foreach loop I have this code for filling datatable from excel file:
for (int rowIndex = cells.FirstRowIndex; rowIndex <= cells.LastRowIndex; rowIndex++)
{
    var values = new List<string>();
    foreach (var cell in cells.GetRow(rowIndex))
    {
        values.Add(cell.Value.StringValue);
    }
    dataTable.LoadDataRow(values.ToArray(), true);
}

I have problem when cell is not same datatype as I set in table.
How to skip cell which is wrong datatype?
I also know this, but I can't make it work in my case:
foreach //...
{
    if //if datatype is not right
    {
        continue;
    }
}

A: C# has an is operator.
For example:
foreach(var item in collection)
{
 if(item is string)
 {
   //Do something with the string.
 }
}

A: Use the is operator:
if(cell is MyType)
{
  // can work
}

is:

Checks if an object is compatible with a given type.

A: You can use LINQ OfType<IMyType>() method to filter out wrong items:
// do not forget adding using System.Linq;
var filteredItems = items.OfType<IMyType>();
var values = new List<IMyType>(filteredItems);

MSDN:

Filters the elements of an IEnumerable based on a specified type.
  The OfType(IEnumerable) method returns only those elements in
  source that can be cast to type TResult


text:
Q: Regex expression for decimal number Could somebody help me with regex? Basically, I would like a regex which matches with decimal numbers.
Allowed types:
12
1.3234
0.3423434
23423.12

Not allowed types:
0012
12.324.12
01.2332
.12
121212.

Thanks for your help in advance!
Regards!

A: This regex should do your job.
^(?:[1-9][0-9]*|0)(?:\.[0-9]+)?$

Demo

*

*^ - Start of string

*(?: - Beginning of a non-capture group

*[1-9][0-9]* - Matches a number not starting with a zero

*|0 - Or allows matching only a zero to allow numbers like 0.3423434 or 0.1

*(?:\.[0-9]+)? - Optionally allows a decimal part in the number

*$ - End of string

Edit: Based on Allan's suggestion to use \d instead of [0-9]
In case your input only contains English numbers, or when you only intend to match English numbers, then using [0-9] should be preferred for reasons like better performance and wide supported of it across regex engines.
But in case your input contains digits from other languages like Hindi १ २ etc. and you want to match any digits, then \d should be preferred instead of [0-9]

A: That would be
^[[:digit:]]+(\.[[:digit:]]+)?$

Beginning of the string, then one or more digits, then (optionally) a dot and one or more digits, then the end of the string.
If you want to cater for the sign, add [+-]? after the ^.

A: You could use an alternation
^(?:0\.\d*[1-9]\d*|[1-9]\d*(?:\.\d+)?)$

Regex demo
Explanation

*

*^ Start of string

*(?: Non capturing group

*

*0\. Match a single zero followed by a dot

*\d*[1-9]\d* Match 0+ digits, a digit 1-9 and again 0+ digits t prevent only zeroes to match

*| Or

*[1-9]\d* Match a digit 1-9 followed by 0+ digits

*(?:\.\d+)?) Optional part to match a dot and 1+ digits

*) Close non capturing group


text:
Q: Kotlin - from a list of Maps, to a map grouped by key I have a List<Map<Branch,Pair<String, Any>>> that I would like to convert in a single Map<Branch,List<Pair<String, Any>>> .
So if I have an initial list with simply 2 elements :
List
1. branch1 -> Pair(key1,value1)

   branch2 -> Pair(key2,value2)

2. branch1 -> Pair(key1a,value1a)

I want to end up with :
Map
branch1 -> Pair(key1,value1)

           Pair(key1a,value1a)

branch2 -> Pair(key2,value2)

so a kind of groupBy, using all the values of the keys in the initially nested maps..
I have tried with
list.groupBy{it-> it.keys.first()}

but obviously it doesn't work, as it uses only the first key. I want the same, but using all keys as individual values.
What is the most idiomatic way of doing this in Kotlin ? I have an ugly looking working version in Java, but I am quite sure Kotlin has a nice way of doing it.. it's just that I am not finding it so far !
Any idea ?
Thanks

A: val list: List<Map<Branch, Pair<String, Any>>> = listOf()
val map = list
    .flatMap { it.entries }
    .groupBy { it.key }
    .mapValues { entry -> entry.value.map { it.value } }

A: Everyone else is using flatMap, but you can also consider using fold, which is a common operation for reducing a larger collection into a smaller one. (For example, you can fold a list of integers into a single sum; here, a list of maps into a single map).
Perhaps others will find this easier to read than the flatMap versions above:
val listOfMaps: List<Map<Key, Value>> = ...

val mergedMaps: Map<Key, List<Value>> =
  listOfMaps
    .fold(mutableMapOf()) { acc, curr ->
      curr.forEach { entry -> acc.merge(entry.key, listOf(entry.value)) { new, old -> new + old } }
      acc
    }

What the above code is doing:

*

*Create a new, empty map. This will be acc (that is, the accumulator).

*Iterate through our list of maps.

*Work on one map (curr) at a time.

*For the current map, run over each of its key/value pairs.

*For each key/value, call merge on acc, passing in a list of size one (wrapping the value). If nothing is associated with the key yet, that list is added; otherwise, it is appended to the list already there.

*Return the accumulating map, so it's used again in the next step.

A: The following:
val result =
    listOfMaps.asSequence()
        .flatMap {
          it.asSequence()
        }.groupBy({ it.key }, { it.value })

will give you the result of type Map<Branch,List<Pair<String, Any>>> with the contents you requested.

A: I've managed to write this.
data class Branch(val name: String)
data class Key(val name: String)
data class Value(val name: String)

val sharedBranch = Branch("1")
val listOfMaps: List<Map<Branch, Pair<Key, Value>>> = listOf(
        mapOf(sharedBranch to Pair(Key("1"), Value("1")),
                Branch("2") to Pair(Key("2"), Value("2"))),
        mapOf(sharedBranch to Pair(Key("1a"), Value("1a")))
)

val mapValues: Map<Branch, List<Pair<Key, Value>>> = listOfMaps.asSequence()
        .flatMap { map -> map.entries.asSequence() }
        .groupBy(Map.Entry<Branch, Pair<Key, Value>>::key)
        .mapValues { it.value.map(Map.Entry<Branch, Pair<Key, Value>>::value) }

println(mapValues)

Is it appliable for your needs?

A: Surprised nobody has mentioned the associate function.
val listy: List<Map<String, Int>> =
listOf(mapOf("A" to 1, "B" to 2), mapOf("C" to 3, "D" to 4))

val flattened = listy
  .flatMap { it.asSequence() }
  .associate { it.key to it.value }

println(flattened)

will print out {A=1, B=2, C=3, D=4}

A: Extract it to an extension function
private fun <K, V> List<Map<K, V>>.group(): Map<K, List<V>> =
        asSequence().flatMap { it.asSequence() }.groupBy({ it.key }, { it.value })

Use it like so:
val list = yourListOfMaps
val grouped = list.group()


text:
Q: ExpressJS and Angular 1 routing Im trying to use Express to create a API and Angular for front-end of my page but  Im unable to correctly route my pages. can somebody see my code and tell me what am I missing or doing wrong ?
The error Im getting is 404 everytime I go try to go to /about it seems that it defaults to index.html
 here is my code:

//SERVER.JS

var express = require("express");
var app = express();
var PORT = process.env.PORT || 3001;
var path = require('path');
var router = express.Router();

app.use(express.static(__dirname + '/public'));

app.listen(PORT, function () {
    console.log("Server running in PORT " + PORT);
});

//MAIN.JS

var myApp = angular.module('myApp', ['ngRoute']);

console.log("in myApp module");

myApp.config(['$routeProvider','$locationProvider',function ($routeProvider,$locationProvider) {

    console.log("in app.config")

$routeProvider
    .when('/',{
       templateUrl:'../index.html',
    })
    .when('about',{
        templateUrl:"
Banana

Bananas contain around 75% water.
",
        controller:'AboutController'
    });

    console.log('after provider');
$locationProvider.html5Mode(true);

}]);
<!DOCTYPE html >

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Morand Transportation</title>
    <link href="css/reset.css" rel="stylesheet">

    <link rel="stylesheet" href="./lib/bootstrap/css/bootstrap.min.css">

    <link href="css/style.css" rel="stylesheet">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation Menu
                    </button>
                    Home

                            Services

                            About

                            Team

                            Contact

                        Morand Trasnportation

    footer

A: probably you've made 2 mistakes:
.when('/about',{ //should have a slash
    templateUrl:"
Banana

Bananas contain around 75% water.
",
    // this is not a templateUrl
    controller:'AboutController'
});

should be like this instead:
template:"
Banana

Bananas contain around 75% water.
",

i also suggest using this awesome ui-router router with angular ;)


text:
Q: jQuery ajaxForm plugin not running success function in IE6 I'm using the jQuery plugin ajaxForm to submit a file upload form via AJAX.  The script submits the form, which, upon success, runs uploadResponse() that adds a new row into a <table> on the page.  It works fine in Opera, Firefox, Safari, IE7, and IE8.
However, IE6 does not run the uploadResponse() after the form has been submitted.  The POST request from the script runs and you can see the file when you refresh the page.  However, uploadResponse() simply does not run and the DOM is not updated.
Here is the portion of the script:
/**
 * Ajaxified upload form
 */
$('form#upload').ajaxForm(
{
    url: 'ajax/upload.php',
    success: uploadResponse,
    dataType: 'xml'
});

/**
 * Upload form response
 *
 * @param responseXML Returned from the AJAX POST
 */
function uploadResponse(responseXML)
{
    var displayName = $('display_name', responseXML).text();
    var fileName = $('name', responseXML).text();
    var directoryID = $('directory_id', responseXML).text();
    var abbrTitle = $('abbr_title', responseXML).text();
    var tableRow = 'file_' + tableRowCount;

    $('table#listing tbody').prepend(row(displayName, null, '', 'delete.php?directory_id=' + directoryID + '&file=' + fileName, 'Delete', null, tableRow, 'fileName jsHide', 'rename jsHide', 'delete jsHide', abbrTitle));
    $('td.jsHide').fadeIn();

    // AJAX renaming
    $('tr#file_' + tableRowCount).find('td.fileName').click(generateRenameForm);

    // Remove "no files" notficiation
    $('p#noFiles').remove();

    alternatingRows();
    tableRowCount++;
}

The particular code in the uploadResponse() function is not under question.  It simply does not run (I tested it using alert()).
Also, IE6 displays the "this page contains secure and non-secure content" dialogue box.  All of the scripts, stylesheets, etc. are all local on the secure server, so nothing as far as I'm aware is non-secure.  I've checked over this pretty thorougly.
Thanks for any help.

A: The datatype:xml is the issue. I'm not sure where I learnt this trick (all credit to that original source). This is how this problem can most likely be solved:
replace "datatype:xml" with
datatype: ($.browser.msie) ? "text" : "xml"

and before you start using the xml response you would need to do this:
function parseXMLResult(result) {
    var xmlDoc;
    if (typeof result == 'string') {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(result);
    } else {
        xmlDoc = result;
    }
    return xmlDoc;

}

Hopefully this should solve your problem.
Reg the secure/in-secure warning, you definitely have at least one element might be an image/css/js file which is loading over http. This problem is not specific to IE6 you should see the certificate symbol in the address bar of FireFox to have a red "i" indicating there are issues in the page.
Use a tool like FireBug to figure out the offending element.

A: Have you tested it in another pc? Maybe is a security setting in your IE6.


text:
Q: AJAX does not show image on the first request but does so on consecutive requests So i am having this strange issue. I am trying to have a loding spinner icon whilst the ajax request is made. However, the spinner is not showing for the first request (since page manual refresh) however it shows for all requests made after that. This is for when i load the spinner GIF from a local folder.
Strangely, when I provide this URL (https://i.stack.imgur.com/FhHRx.gif) which I found on another SO post, it works every time, but for other URLs from the web or for local files it doesnt show the image on the first request. The ajax is getting executed as I can see the screen colour change through the style, but just the spinner doesnt show.Anyone have any ideas why? Below is the relevant code.
body

  ...

script

CSS
.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 )
    url('../images/ajax-loader.gif')
    50% 50%
    no-repeat;
}

body.loading .modal {
    overflow: hidden;
}

body.loading .modal {
    display: block;
}

A: Fixed by addin the image as an hidden image to the html. I assume the image was not loaded at the time of making the request through the css.


text:
Q: Search word and job title in database is same but not getting I have job portal website. In that when user search some work then we are matching that word with job title in database and displaying the result.
The problem is Ex. when user searches the word 'Php Developer'. we are matching that word in database with job_title and displying exact matched results. In my database job_title contains exact word 'Php Developer' but results coming as empty.
SELECT *  FROM `tbl_jobs` WHERE `job_title` = 'Php Developer' or `job_title` like 'Php Developer'.

The database contains exact title records but they do not appear when I search as in the query above.
I am getting the results for this query.
SELECT *  FROM `tbl_jobs` WHERE `job_title` like '%Php Developer%'

My intention is exact word results. But I am not getting that to work.
Please help me; where is my problem?


text:
Q: Android callscreen Intent/broadcast? When a Call is received, is there a intent of broadcast received?

A: Please check
http://developer.android.com/reference/android/telephony/PhoneStateListener.html
You need to implement onCallStateChanged(). State that you need to monitor is CALL_STATE_RINGING.
In order to use that you need to declare the READ_PHONE_STATE permission in your manifest.
UPDATE (after suggestion):
Broadcast ACTION_PHONE_STATE_CHANGED is described under
http://developer.android.com/reference/android/telephony/TelephonyManager.html


text:
Q: My laptop suddenly failed to boot. Can someone help me diagnose the problem? My laptop suddenly failed to boot. Can someone help me diagnose the problem? Below are some of the suggestions I have already tried (I'm not sure what they all mean).
I tried using the BIOS to change boot mode and specify a boot device, but these options were unavailable. Here is the info tab.

And this is the boot tab. No boot device list is present.

I also couldn't fix the issue by booting from Ubuntu live USB. GParted gives the error Input/output error during read on /dev/sda and gnome-disks showed this.

Finally I tried to use some command line tools to check disk status and these showed errors as well. This is the output of parted.
ubuntu@ubuntu:~$ sudo parted /dev/sda 'print'
Error: /dev/sda: unrecognised disk label
Model: ATA PS3111 (scsi)
Disk /dev/sda: 21.0MB
Sector size (logical/physical): 512B/512B
Partition Table: unknown
Disk Flags:

And this is the output from fsck (I tried the suggested commands in this output and they gave similar results).
fsck from util-linux 2.31.1
e2fsck 1.44.1 (24-Mar-2018)
fsck.ext2: Input/output error while trying to open /dev/sda

The superblock could not be read or does not describe a valid ext2/ext3/ext4
filesystem.  If the device is valid and it really contains an ext2/ext3/ext4
filesystem (and not swap or ufs or something else), then the superblock
is corrupt, and you might try running e2fsck with an alternate superblock:
    e2fsck -b 8193 <device>
 or
    e2fsck -b 32768 <device>

A: From your screenshots and terminal outputs, it looks like the SSD is the problem (showing only 21 MB and IO / superblock errors).
Further investigation shows that the SSD controller (Phison PS3111) has caused trouble for a number of people since its introduction. This controller is mostly used in budget SSD's.
Judging from this, it seems most likely your SSD has simply failed.


text:
Q: Is there any way to disable "idProperty" of Model in Extjs? I have a simple Model/proxy. When I create a object of model to send to server via REST, ExtJs is generating Id and putting its value in my "id" field and that is  conflicting with my data.
Is there any way to stop this behavior or to solve this issue?
I have read idProperty Sencha Docs but I am not able to solve my issue. Kindly Help.

A: Set config options: persist: false.
Ext.define('User', {
    extend: 'Ext.data.Model',
    idProperty : 'login'
    fields: [
        {name: 'login', type: 'string', persist: false},
        {name: 'username', type: 'string'},
        {name: 'password', type: 'string'}
    ]
});

A: I ran into same problem and using ajokn answer I did this.
Ext.define('ThemeApp.model.peopleModel', {
    extend: 'Ext.data.Model',

    fields: [
        {name: 'id', type: 'int', persist: false},
        {name: 'xyz', type: 'auto'}
    ]
}

I didn't set the idProperty : 'login' cause its default value is 'id', so simply set persist: false for id property in your model.

A: Set the idProperty to a non existing field. Its dirty I know, but this should do it.
Ext.define('User', {
    extend: 'Ext.data.Model',
    idProperty : 'foo'
});


text:
Q: $T_{\epsilon}f(x)=\frac{1}{\pi}\int_{-\infty}^{\infty}\frac{\epsilon}{y^2+\epsilon^2}f(x-y) dy$ I am asked to show that for an $L^1$ function $f$,
$$T_{\epsilon}f(x)=\frac{1}{\pi}\int_{-\infty}^{\infty}\frac{\epsilon}{y^2+\epsilon^2}f(x-y) dy$$
converges to $f(x)$ as $\epsilon\to 0^+$ for almost every $x$.
As this question is given in the context of a measure theory course, I was thinking of using the dominated convergence theorem for the sequence of functions $\displaystyle f_n(y)=\frac{1/n}{y^2+(1/n)^2}f(x-y)$ for a fixed $x$.
Firstly $f_n$ is dominated by $f_1\in L^1(\mathbb{R})$ (i.e. $|f_n|\leqslant |f_1|$.)
Also $f_n\to 0=:f$. But then, $$\lim_{n\to\infty}\int_{-\infty}^{\infty}f_n(y) dy=\int_{-\infty}^{\infty}\lim_{n\to\infty}f_n(y)dy=\int 0 dy= 0$$
which is not the desired result.
Could someone explain what I reasoned wrongly and what is the correct approach.
Thank you.

A: Use the convolution approach on $ L^1(\mathbb{R}) $,
$$ (f*g)(x)=\int\limits_{\mathbb{R}}f(x-t)g(t)~\text{d}t=\int\limits_{\mathbb{R}}g(x-t)f(t)~\text{d}t. $$
Then, we can write
$$ T_{\epsilon}f(x)=\dfrac{1}{\pi}\int\limits_{\mathbb{R}}f(x-y)g(y)~\text{d}y, $$
where,
$$ g(y)=\dfrac{\epsilon}{y^2+\epsilon^2}. $$


text:
Q: EF Core getting part of a string in a call I've set up a generic repository and pull data back from my database. Part of my data includes file upload information including the location where the file is stored ala:
\\RemoteLocation\Desktop\TargetFolder\MyFile.csv
What I want is to remove all of the parts before MyFile.csv but I'm struggling to do so. Currently I'm using LINQ to gather the parts of the data I need like so:
var fileData = _files.GetAll();
var latestFile = fileData.Where(x => x.FileLoadedTime != null && x.LoadStatusId == 4 && x.EngineId == 1).ToList().Last(); // most recent is at the bottom of the list

Could someone please show me how I can chop off the parts of my data that I don't need?

A: There are several ways to get file name from path, you can try below
Path.GetFileName()
    string result1 = Path.GetFileName(latestFile);
    Console.WriteLine(result1);

Or
Using Split():
    string result =  latestFile.Split('\\').Last();
    Console.WriteLine(result);

.net Fiddle

A: The method you are looking for is Path.GetFileName(yourPath)
I am assuming your file class is like the following
public class File{
    public DateTime FileLoadedTime;
    public int LoadStatusId;
    public int EngineId;
    public string Path;
}

var fileData = _files.GetAll();
var latestFile = fileData.Where(x => x.FileLoadedTime != null && x.LoadStatusId == 4
                 && x.EngineId == 1).ToList().Last(); // most recent is at the bottom of the list

var path = Path.GetFileName(latestFile.Path);


text:
Q: ignoring null value columns in python I Have a .txt file which has three columns in it.
id      ImplementationAuthority.email   AssignedEngineer.email
ALU02034116     bin.a.chen@shan.cn bin.a.chen@ell.com.cn
ALU02035113                                     Guolin.Pan@ell.com.cn
ALU02034116     bin.a.chen@ming.com.cn Guolin.Pan@ell.com.cn
ALU02022055     fria-sha-qdv@list.com
ALU02030797     fria-che-equipment-1@phoenix.com    Balagopal.Velusamy@phoenix.com

I need to create two lists which comprises of values under the column Implementation Authority.mail and Assigned Engineer.mail. It works perfectly when columns have compltete values (i.e no null values). The values got mixed when column contains null values.
aengg=[]
iauth=[]

with open('test.txt') as f:
 for i, row in enumerate(f):
  columns = row.split()
  if len(columns) == 3:
   aengg.append(columns[2])
   iauth.append(columns[1])

 print aengg
 print iauth

I tried it with this code and it is perfectly worked for complete column values.
Can anyone please tell me a solution for null values?

A: It seems you don't have a separator. I use number of spaces for your case. And fill the blank with a None.
Try this:
#!/usr/bin/env python
# -*- coding:utf-8 -*-

aengg = []
iauth = []

with open('C:\\temp\\test.txt') as f:
    for i, row in enumerate(f):
        columns = row.split()
        if len(columns) == 2:
            # when there are more than 17 spaces between two elements, I consider it as a third element in the row, then I add a None between them
            if row.index(columns[1]) > 17:
                columns.insert(1, None)
            # if there are less than 17 spaces between two elements, I consider it as the second element in the row, then I add a None to the tail
            else:
                columns.append(None)
        print columns
        aengg.append(columns[2])
        iauth.append(columns[1])

print aengg
print iauth

Here is the output.
['id', 'ImplementationAuthority.email', 'AssignedEngineer.email']
['ALU02034116', 'bin.a.chen@shan.cn', 'bin.a.chen@ell.com.cn']
['ALU02035113', None, 'Guolin.Pan@ell.com.cn']
['ALU02034116', 'bin.a.chen@ming.com.cn', 'Guolin.Pan@ell.com.cn']
['ALU02022055', 'fria-sha-qdv@list.com', None]
['ALU02030797', 'fria-che-equipment-1@phoenix.com', 'Balagopal.Velusamy@phoenix.com']
['AssignedEngineer.email', 'bin.a.chen@ell.com.cn', 'Guolin.Pan@ell.com.cn', 'Guolin.Pan@ell.com.cn', None, 'Balagopal.Velusamy@phoenix.com']
['ImplementationAuthority.email', 'bin.a.chen@shan.cn', None, 'bin.a.chen@ming.com.cn', 'fria-sha-qdv@list.com', 'fria-che-equipment-1@phoenix.com']

A: You need to place a 'null' or 0 as place holder.
The interpreter would read Guolin.Pan@ell.com.cn in second row as the second column.
Try this
id      ImplementationAuthority.email   AssignedEngineer.email
ALU02034116     bin.a.chen@shan.cn bin.a.chen@ell.com.cn
ALU02035113     null                   Guolin.Pan@ell.com.cn
ALU02034116     bin.a.chen@ming.com.cn Guolin.Pan@ell.com.cn
ALU02022055     fria-sha-qdv@list.com  null
ALU02030797     fria-che-equipment-1@phoenix.com    Balagopal.Velusamy@phoenix.com

And then append values after checking not null.
with open('test.txt') as f:
 for i, row in enumerate(f):
  columns = row.split()
  if len(columns) == 3:
   if columns[2] != "null":
    aengg.append(columns[2])
   if columns[1] != "null":
    iauth.append(columns[1])


text:
Q: decisive trees to pandas all day trying to implement decisive trees on the titanic database using TensorFlow.
fc = tf.feature_column
CATEGORICAL_COLUMNS = ['Pclass', 'Sex', 'SibSp', 'Parch', 'Embarked']
NUMERIC_COLUMNS = ['Age', 'Fare']

   def one_hot_cat_column(feature_name, vocab):
     return tf.feature_column.indicator_column(tf.feature_column.\
             categorical_column_with_vocabulary_list(feature_name,vocab))
feature_columns = []
for feature_name in CATEGORICAL_COLUMNS:
  # Need to one-hot encode categorical features.
  vocabulary = train[feature_name].unique()
  feature_columns.append(one_hot_cat_column(feature_name, vocabulary))

  for feature_name in NUMERIC_COLUMNS:
     feature_columns.append(tf.feature_column.\
                           numeric_column(feature_name,dtype=tf.float32))

everywhere only this method of implementation. this block implements the "one-hot encoder". How to convert the result after these manipulations into a Pandas table? Needed for easy viewing and better understanding of how these lines work

A: Suppose y_test is your predictions and y is the columns specified for submission, then execute:
df = pd.DataFrame(data=y_test,columns=['y'])
Columns refer to the column name and then simply do df.to_csv to convert your predictions dataframe in csv type file and submit.


text:
Q: Signal and slot for multiple widgets I have three pushbutton widgets in my class and i want to connect the clicked signals from all of the three to one slot. Here is what my syntax looks like:
QObject::connect(PtrLineedit1, SIGNAL(Clicked()), this, SLOT(myslot()));
QObject::connect(PtrLineedit2, SIGNAL(Clicked()), this, SLOT(myslot()));
QObject::connect(PtrLineedit3, SIGNAL(Clicked()), this, SLOT(myslot()));

But the above syntax is not working. And the above syntax i am using in one of my WizardPage class. this Wizard has three pages, and in one of the page(class) has three pushbuttons and in this class constructor i am trying to achieve. I have used "clicked()" too, but no luck

A: First of all, there is no signal "Clicked", but there is "clicked" - the lowercase one.
Second - it's better not to use the macros SIGNAL and SLOT - they are error prone, like in your case. If you look inside them, they are generating a string, which could not be checked by compiler. Instead better to use following syntax:
QObject::connect(PtrLineedit1, &LineEditClass::clicked, this, &ThisClass::myslot);

Cause if you will write then:
QObject::connect(PtrLineedit1, &LineEditClass::Clicked, this, &ThisClass::myslot);

It would produce the error during compilation, in case when LineEditClass::Clicked is not defined. This would protect you from typos.
UPD: As eventually I've found another your question which faces issue  relevant to this one, I've updated this answer with more details, which might be helpful for others.
In case of overloaded methods, you must explicitly tell compiler which one should be used - for example we have following:
void QComboBox::currentIndexChanged(int index)
void QComboBox::currentIndexChanged(const QString &text)

thus the &QComboBox::currentIndexChanged could be resolved ambigously, and you will get the compilation error. To fix it you need to explicitly tell what are the arguments of the function you want to connect to:
QObject::connect(comboBox, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ThisClass::myComboBoxSlotWithIntArg);

or
QObject::connect(comboBox, static_cast<void(QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged), this, &ThisClass::myComboBoxSlotWithStringArg);


text:
Q: Unable to join channel on Hyperleger Fabric I'm having trouble with the BYFN tutorial. I managed to do it without problems, and now I'm trying to change some things on the configuration files. I configured 6 orgs, and I'm trying to create a channel with two of them. When I get to the command to join a channel, I'm getting this error:
Error: proposal failed (err: rpc error: code = Unknown desc = access denied: channel [] creator org [Client1MSP])
Here are my configuration files: https://www.dropbox.com/s/tutc4pla6jlygej/my_network.zip?dl=1
The commands I'm running from start to finish are on COMMANDS.txt. Any help is appreciated.

A: I found the problem.
By using:
docker ps
 docker logs <container_id> on the peer container that was failing to join the channel, I was able to read this error on the log: expected MSP ID Org1MSP, received Client1MSP
Which led me to the docker-compose-base.yaml file, where I found some lines I forgot to change to reflect the different org names.


text:
Q: How to create TabWidget inside a Fragment in Android I need to create a TabWidget inside a Fragment. It should look like as in the attached image. The content of each Tab should be in a separate Fragment...

A: I think you just need to visit developer.android


text:
Q: Evaluating variable from postfix expression I'm trying to build a solver for single variable equations. I'm using Shunting-yard algorithm, expanded with suggestions by denver and rici. Obviously this algorithm works great to parse trough given math expression, determine its validity and evaluate the value. However, I'm having trouble to understand how to incorporate solving for a certain variable.
If I use the equation 2 * (x - 4) = 4, this can without much fuss be transformed into RPN as 2 x 4 - * 4 -. From here, it would be easy to evaluate the value for any given x. But, how to determine x? I'm looking at gab's answer, and although it's clear to me how to build a tree from the RPN form, I don't understand how to calculate the value (step 5. in his answer).
Thank you.

A: You what you would do if you solved this with pencil and paper: You move stuff to the other side of the equation until only x remains. Your tree looks like this:
        =
      /   \
    *       4
   / \
  2   −
     / \
    x   4

All branches are operators, all leaves are operands. The path from your single variable passed through the * and − nodes on the left-hand side. That means that you must get as much stuff as possible from the left-hand side to the right-hand side, ideally until there is only the x node left.
The first node on the left is a multiplication operator. You can apply the transformation
a * b == c    ⟺    b = c / a

to the tree: Remove the multiplication on the left and insert its inverse operation, division by the constant 2, on the right. Your tree now looks like this:
        =
      /   \
    −       ÷
   / \     / \
  x   4   4   2

The division operates on two constants. You can "fold" them into the result, 2:
        =
      /   \
    −       2
   / \
  x   4

(If you have only one variable, you can do that as you create the nodes, so that you don't have an intermediary step with a ÷ node that you are going to delete anyway. You should also detect any divisions by zero here.)
Now move the subtraction operator in the same way:
        =
      /   \
    x       +
           / \
          2   4

Calculate the constant expression on the right and you get x == 6.
So you basically turn the top-most left-hand operator into its inverse until there's only the variable left:
a + x == b   ⟺   x == b − a            x + a == b   ⟺   x == b − a
a − x == b   ⟺   x == a − b            x − a == b   ⟺   x == b + a
a * x == b   ⟺   x == b / a            x * a == b   ⟺   x == b / a
a / x == b   ⟺   x == a / b            x / a == b   ⟺   x == b * a

If you have only one variable and have resolved all constant expressions, your x will be the variable or an operator node; the a will be a constant number.
(But careful with division: In the example above, the division has no remainder. If the division has a remainder, integer division will not give the correct result when resolving the value of x and floating-point division will likely introduce small errors.)


text:
Q: MySQL DELETE from multiple tables I need to delete a lot of rows in multiple tables that are older than certain date.
Actually I'm doing this:
DELETE FROM trash1 WHERE deletion_date < DATE_SUB(NOW(), INTERVAL 48 HOUR);
DELETE FROM trash2 WHERE deletion_date < DATE_SUB(NOW(), INTERVAL 48 HOUR);
DELETE FROM trash3 WHERE deletion_date < DATE_SUB(NOW(), INTERVAL 48 HOUR);

Is there any approach to make it better or faster?
Is it possible to do it in only one query?
Thanks.

A: First thing I would check is the efficiency of the query WHERE deletion_date < DATE_SUB(NOW(), INTERVAL 48 HOUR) on those tables using EXPLAIN.
EXPLAIN DELETE FROM trash1 WHERE deletion_date < DATE_SUB(NOW(), INTERVAL 48 HOUR);

And so on.  You're looking to see if the query is using an indexed column or not and how many rows it has to search through.  You want to avoid searching every row in the table.
Next thing to check is whether deletion_date is indexed and the type of index.  Because this is a range query (ie. "less than") rather than a simple equality check the type of index can matter.  There's a discussion about optimizing range queries in the MySQL manual.
Start with that, see how it goes.  If you have trouble, post the output of your EXPLAINs.


text:
Q: Is it possible to install Ubuntu onto a computer where no other operating system exists? My computer is a Toshiba satellite 7675d-s7104 model, and it has no operating system on it.
Is it possible to just boot Ubuntu from a flash drive?

A: That is possible. There is no reason you should have an operating system preinstalled in order to try live media (like a live CD or a live flash drive).

A: Yes, you can do it with:
1. A USB stick that is at least 2 gb
Or
2. A CD


text:
Q: Map in Ext.Window.window show not fully I created extended Ext.Panel.panel component containing maps showing through openlayers, this component is located in Ext.Window.window.
But after load page, map showing only partly:
http://habrastorage.org/storage2/17f/1be/3bd/17f1be3bdc2a9765c1852d93a95ee1b8.png
Ext.define('MA.view.components.OpenlayersPanel',
{
    extend: 'Ext.panel.Panel',
    alias: 'widget.openlayerspanel',
    multiSelect: true,

    initComponent: function()
    {
        this.callParent(arguments);
        this.on('afterrender', this.afterRender, this);
    },

    afterRender: function()
    {
        this.map = new OpenLayers.Map(this.body.dom.id);
        this.layer = new OpenLayers.Layer.OSM('OSM Map');
        this.fromProjection = new OpenLayers.Projection("EPSG:4326");
        this.toProjection = new OpenLayers.Projection("EPSG:900913");
        this.position = new OpenLayers.LonLat(75.1, 61.15).transform(this.fromProjection, this.toProjection);
        this.zoom = 12;
        this.map.addLayer(this.layer);
        this.layer.setIsBaseLayer(true);
        this.map.setCenter(this.position, this.zoom);
    }
});

app.js:
Ext.application(
{
    requires: ['Ext.container.Viewport'],
    name: 'MA',
    appFolder: 'app',
    controllers:
        [
            'Map'
        ],
    launch: function()
    {
        Ext.create('Ext.window.Window',
            {
                layout:
                {
                    type: 'vbox'
                },
                items:
                    [
                        {
                            xtype: 'openlayerspanel'
                        },
                        {
                            xtype: 'button',
                            text: 'Load',
                        }
                    ]
            }).show();
    }
});

When i resize browser, map is refresh and show normally.
What's fix to make it work?

A: If nothing works except resize, try to resize programmatically:
//inside window listeners
show: function(){
  this.setWidth(this.getWidth() + 1); // or height
}

or use timeout for define map - create map after window is shown:
not afterrender, but show
show: function(){
  setTimeout(function(){
    // init map here
    }, 100)
}

or use this code:
function ShowMapWindow() {
    Ext.create('Ext.window.Window', {
        width: 400,
        height: 300,
        items: [{
            loader: {
                loadMask: { showMask: true },
                renderer: 'frame',
                url: 'http://www.openstreetmap.org/export/embed.html?bbox=37.314,55.568,38.031,55.927&layer=mapnik'
            }
        }],
        layout: "fit",
        listeners: {
            close: function () {
                this.remove(true);
            }
        },
        modal: true
    }).show();
}

A: I was confronting myself with the problem and the person with the first solution with the fancy screenshot is wrong. It has absolutely nothing to do with the resize because if you use Google Maps instead of OSM, it works perfectly. The problem ist the missing map attributes, like SRS, BBOX, etc.. Check the documentation for attributes of OpenLayers and it will work.

A: What if you zoomIn(), and then zoomOut().  Or set the initial zoom to 11, and then call zoomIn() after centering the map.


text:
Q: Is there a way of writing a FindElement call by passing in a string value for type I am currently writing a Selenium UI test for our new transactional website however whilst setting up the solution I am trying to find a more efficient way of creating a method to find my element without duplicate of code.
Ideally I want to create something akin to this:
    public void SearchForElement(IWebDriver driver, string elementType, string elementReference)
    {
        driver.FindElement(By.Id(elementReference));
    }

Where 'Id' is the variable value 'elementType'
In previous solutions I have done the following:
            if (elementType == "Id")
            {
                returnElement = driver.FindElement(By.Id(elementReference));
            }

            else if (elementType == "Name")
            {
                returnElement = driver.FindElement(By.Name(elementReference));
            }
            else if (elementType == "CssSelector")
            {
                returnElement = driver.FindElement(By.CssSelector(elementReference));
            }
            else if (elementType == "XPath")
            {
                returnElement = driver.FindElement(By.XPath(elementReference));
            }
            else if (elementType == "ClassName")
            {
                returnElement = driver.FindElement(By.ClassName(elementReference));
            }

However as you can see the latter is in effect the same line of code that is only differentiated by the type.
Any help/advice would be much appreciated.

A:
As the UI tests are being written in parallel to the development of our transactional site (Not ideal I know) I find it easier to maintain an array of the elements that I am using

There is nothing wrong with writing automated tests in parallel to development. In fact, this is the ideal way to do it. You actually have a much bigger problem than the question you ask. Your problem can be addressed with a different architecture for your tests. Encapsulating automation behavior in a Selenium Page Object Model allows you to partially create classes that other testers can use, but defer things like defining locators until you have a user interface to deal with.
As an example, imagine you are automating the UI for a todo list app. The UI isn't built yet, but that doesn't stop you from writing a test:
todoList = new TodoListPageModel(driver);

todoList.Add("Pay the electric bill");

CollectionAssert.Contains(todoList.GetItems().ToList(), "Pay the electric bill");

Your page model would look like:
public class TodoListPageModel
{
    private readonly IWebDriver driver;

    private IWebElement AddButton => throw new NotImplementedException();
    private IWebElement TodoTextField => throw new NotImplementedException();
    private IEnumerable<IWebElement> Items => throw new NotImplementedException();

    public TodoListPageModel(IWebDriver driver)
    {
        this.driver = driver;
    }

    public void Add(string todo)
    {
        TodoTextField.SendKeys(todo);
        AddButton.Click();
    }

    public IEnumerable<string> GetItems()
    {
        return Items.Select(item => item.Text.Trim());
    }
}

Properties that refer to elements or collections of elements can throw a NotImplementedException until you have a user interface. Then you can implement those properties using the correct locator, and run the tests.
Depending on who gets done first, you could inform the developer that the tests are written, and they just need to fill in the locators. After that the developer has tests to run during development, which is pretty nice.


text:
Q: Why does this dataframe variable take an attribute not explicity assigned to it? (dplyr-R) Curious: can someone give the explanation as to why df1 and df3 are finally assigned the same attribute even though df3 is the one explicitly modified? I would have assumed that because df1 and df3 have different memory addresses they would not be both modified. Piping issue?--How are objects being bound together?
library(lobstr)
library(dplyr)
library(data.table)

df1 <- data.frame(x = 1:3, y = letters[1:3])
df2<-data.frame(df1)

df3<-df2%>% dplyr::mutate_at(vars(ends_with("x")),
                   funs(data.table::setattr(.,"label","An x column")))

str(df1)
str(df3)

obj_addr(df1)
obj_addr(df3)

Results
 str(df1)
'data.frame':   3 obs. of  2 variables:
 $ x: int  1 2 3
 ..- attr(*, "label")= chr "An x column"
 $ y: Factor w/ 3 levels "a","b","c": 1 2 3
str(df3)
'data.frame':   3 obs. of  2 variables:
 $ x: int  1 2 3
 ..- attr(*, "label")= chr "An x column"
$ y: Factor w/ 3 levels "a","b","c": 1 2 3

obj_addr(df1)
[1] "0xafe6a98"
obj_addr(df3)
[1] "0x98deef0"

A: Per the documentation for setattr:

In data.table, all set* functions change their input by reference.
  That is, no copy is made at all, other than temporary working memory
  which is as large as one column. The only other data.table operator
  that modifies input by reference is :=. Check out the See Also section
  below for other set* function that data.table provides.

If you want to specify attributes with the normal copy-on-modify semantics you can use structure:
df3 <- df2 %>%
  dplyr::mutate_at(vars(ends_with("x")), funs(structure(., label = "An x column")))


text:
Q: Atributo de tipo clase: ¿como acceder a métodos de la clase original? Buenos días. A ver si me explico:
Tengo 2 clases creadas dentro del mismo paquete y no son padre-hija. La clase 1 tiene sus atributos y sus métodos. La clase 2 tiene sus atributos con la particularidad de que uno de estos es un atributo del tipo clase 1. Por ejemplo, clase 1:
`public class Cliente {

private int idCliente;
private String nombre;
private String direccion;
private String telefono;

}`

Clase 2:
`public abstract class Cuenta {

protected int numeroDeCuenta;
protected double saldo;
protected Cliente titular;

}`

Osea, el atributo "titular" de la clase 2, es un atribut del tipo clase. Pues bien, a la hora de probar el programa, creo un objeto del tipo clase "Cliente" y otro del tipo clase "CuentaCorriente" (esta es una clase hija de la clase "Cuenta", ya que esta es abstracta y no permite instanciar :
`Cliente usuario2 = new Cliente (0000001, "Fulanito López", "C/ Madrid 95,
3ºA", "669541985");`

`CuentaCorriente cuenta_corriente_usuario2 = new CuentaCorriente (0000001,
5000, usuario2);`

Pues aqui el problema: ¿no se supone que si pongo cuenta_corriente_usuario2. deberia de salir una lista con los metodos disponibles de ambas clases? Lo que quiero es acceder desde el objeto "cuenta_corriente_usuario2" a los métodos de la clase "Ciente". No puedo poner que sean padre-hija, ni static.

A: Para poder acceder a los métodos del objeto titular de tipo Cliente, primero tienes que acceder a el.
Lo cual lo puedes hacer obteniendo el objeto titular y después accediendo a sus métodos.
Cliente cliente = cuenta_corriente_usuario2.getTitular();
int idCliente = cliente.getIdCliente();

O puedes acceder directamente a sus métodos.
int idCliente = cuenta_corriente_usuario2.getTitular().getIdCliente();


text:
Q: Django Admin with custom form; calculate field not in form In a normal (none admin view), if one has a field that is calculated by the backend, and not in the form, one would handle it like so:
obj = form.save(commit=False)
obj.calc_me = calc_at_now()
obj.save

Now say I have an admin model for Foo
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
    exclude = ['calc_me']

How do I tell Django that when it saves Foo, to calculate the required field with obj.calc_me = calc_at_now() ?
In BaseModelAdmin I see there is a method:
    def save_model(self, request, obj, form, change):
        """
        Given a model instance save it to the database.
        """
        obj.save()

Is it not a bit hacky to override this function since its not documented?
Or how about override the models clean method?
class Foo(models.Model):
    def clean(self):
        self.calc_me = calc_at_now()
        super().clean()

What is the recommended approach. Trying to start using forms the right way.

A: I'd recommend using either a pre_save or post_save signal instead, unless your scenario only applies to the admin page.
https://docs.djangoproject.com/en/3.2/topics/signals/

A: you can do this by adding save method in your model
like
class Foo(models.Model):
    ....
    ....
    def save(self, *args, **kwargs):
        self.calc_me = calc_at_now()
        super(Collector, self).save(*args, **kwargs)

lets give it a try

A: You can override save_model() in your admin class and save any model field.
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
    ...

    def save_model(self, request, obj, form, change):

        # save any field value
        obj.calc_me = calc_at_now()

        super().save_model(request, obj, form, change)

you can also differentiate add form and change form with change flag in save_model().


text:
Q: Android Activity Killed vs App Killed My Question
I'd like to call a function leaveGame() to leave a multi device game, when my app is killed. However, the game uses several activities to work. So, I can't call it in onStop, else the player will leaveGame() every time a new activity within the game launches.
Is there a way to check if the app process itself is being killed?
Current Solution
My current solution (very clunky) is to set a Boolean isCreated in all the activities that the GameActivity calls. (MissionActivity for eg)  I then check if it has been set in my onStop.(See Coordinating Activities here)
GameActivity
@Override
public void onStop(){
    super.onStop();
    if(MissionActivity.isCreated==null) leaveGame();
}

MissionActivity
public static Boolean isCreated;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mdgame);
    isCreated = true;
    //etc
}

Thanks

A:
Is there a way to check if the app process itself is being killed?

No, sorry.
However, you can use ProcessLifecycleOwner from the Architecture Components to find out when you no longer have any activities in the foreground.


text:
Q: Find a polynomial $h(x)$ of maximum degree such that $h(x)$ is a factor of $f(x)$ and $g(x)$ Let $f(x)= x^3-x$ and $g(x)= x^4 + 3x^3 +x^2$
How can I find a polynomial $h(x)$ of maximum degree such that $h(x)$ is a factor of $f(x)$ and $g(x)$.
My thoughts:  there exist others polynomials $t_1(x)$ and $t_2(x)$ such that $g(x) = h(x)t_2(x)$ and $f(x) = h(x)t_1(x)$. I've tried factorizing the polynomials but I can't seem to get anywhere.
Thanks.

A: $$f(x)=x(x^2-1)=x(x+1)(x-1)$$
$$g(x)=x^2(x^2+3x+1)$$
Essentially we need to find the GCD of them.
If the highest powers of $(x-a)$ in $f(x),g(x)$ are $F,G$
then  the highest powers of $(x-a)$ in the GCD will be min$(F,G)$

A: If h(x) is a factor of both f and g then h is a factor of gcd(f,g) = gcd(x(x-1)(x+1), x^2(x^2 + 3x + 1)) = x. So it can only be that h(x) = x.

A: Here is one idea: find all of the roots of $f(x)$ and $g(x)$.  If $r_1,\ldots,r_n$ are the roots in common, then let $h(x)=(x-r_1)\ldots(x-r_n)$.  Notice that the roots of $f(x)$ are all rational, so we're only interested in the rational roots of $g(x)$.  Can you show that $0$ is the only such root?  It follows that $h(x)=x$ is the desired polynomial.

A: Hint $\,\ \gcd(x(x\!-\!1)(x\!+\!1),\,f(x)) = x\ $ if $\,\ \overbrace{f(0)=0}^{\large x\,\mid\, f(x)},\,\ \ \overbrace{f(\pm1)\ne 0}^{\large\ x\mp1\,\nmid\, f(x)}$
a polynomial form of $\,\gcd(pqr, n) = p\,\ $ when $\ p\mid n,\,\ \ q,r\nmid n,\ $ for distinct primes $\,p,q,r$.

A: It is easy to check that
$$
     5x = (2x^{2}+3x-5)(x^{3}-x)+(-2x+3)(x^{4}+3x^{3}+x^{2}).
$$
The two polynomials $x^{3}-x$ and $x^{4}+3x^{3}+x^{2}$ do have a common factor of $x$. Any other common factor of $x^{3}-x$ and of $x^{4}+3x^{3}+x^{2}$ would have to divide $5$ (on the left), which leaves only constant polynomial factors in common, other than $x$.


text:
Q: URL rewriting variable name I am trying to rewrite an URL so that a passed variable is replaced with a new id, for example;
wwww.domain.com/default.php?s=1&lang=en
To be rewritten to:
www.domain.com/default.php?id=1$lang=en
The s variable being replaced with id
I have tried:
RewriteEngine on
Options +FollowSymlinks
RewriteBase /
RewriteCond %{QUERY_STRING} ^s=(.+)$
RewriteRule ^s=(.+)$ id=$1 [R,NC,L]

also
RewriteRule ^s=(.+)$ id=%1 [R,NC,L]

no luck... what am I doing wrong?
Thanks for any help!!

A: This should work if even if you don't have s as the first variable. (Not sure what you really want.)
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} ^(.*&)*s=(.*)(&*)$
RewriteRule ^default.php$ default.php?%1&id=%2%3

A: Try this out:
RewriteRule ^default.php?s=([0-9]+)&lang=en$ default.php?id=$1&lang=en

Edit.
A more generic version.
RewriteRule ([^?]+)?s=([0-9]+)&lang=([A-z]{2})$ $1?id=$2&lang=$3


text:
Q: Check if date is between hours interval or week-end. If not, calculate how many hours left until available hour I need some help if someone would be so kind.
For 2 days I'm squeezing my brains trying to make a script which will inform visitors about tech support online status.
The office hours are from 10AM to 18:30PM.
If the visitor is in this hours interval, it's easy, the message will be "online".
If he's out of the office hours, I need to display the number of hours remaining until tech support will be available and if week-ends or Friday evening, another message will be displayed.
This is my script and I don't really figure where I'm wrong.
Any help appreciated.
Thanks.
$date2 = date("l", time());
$date3 = strtolower($date2);

$now = (int) date('Hi');
$time1 = 1000;
$time2 = 1830;

$currentTime = time();
if (date("G") >= 19 || (date("G") == 18 && date("i") > 00)) {
$datetime1 = 10 * 3600 + strtotime("now") + (24 - date("G")) * 3600 +
(60 - date("i")) * 60;
} else {
$datetime1 = strtotime(date("Y-m-d") + " 10:00:00");
}

$interval = abs($datetime1 - $currentTime);
$hours = round($interval / 3600);

if (($date3 == "saturday") || ($date3 == "sunday")) {
$status = '
OFFLINE. We\'ll be available on Monday    morning.';
} elseif ($date3 == "friday") {
if ($now > $time2) {
    $status = '
OFFLINE. We\'ll be available on     Monday morning.';
} elseif ($now < $time1) {
    $status = '
OFFLINE. We\'ll be online in about ' . $hours . ' hours.  ';
} else {
    $status = 'ONLINE, solving customer issues. ';
}
} else {
if ($now > $time1 && $now < $time2) {
    $status = 'ONLINE, solving customer issues.';
} else {
    $status = 'OFFLINE. We\'ll be become online in about ' . $hours . ' hours.';
}
}

echo $status;

A: Have you considered refactoring your code by using the DateTime class? It's compatible with PHP 5.2+ and it's usually the recommended way of dealing with dates in PHP.
$start_date = new \DateTime('today 10:00');
$end_date = new \DateTime('today 18:30');
$now = new \DateTime();

if ($now->format('N') >= 6) {
    // weekend
}

if ($start_date <= $now && $now < $end_date) {
    // office hours
} else {
    // closing hours
}

The above example is much easier to read/understand/debug and it spares you the trouble of manually doing all the calculations and date conversions yourself.
The Datetime class will also allow you to easily calculate the time difference between 2 individual dates:
$opening_time = new \DateTime('tomorrow 10:00');
$now = new \DateTime();

$time_difference = $now->diff($opening_time);
$remaining_time = $time_difference->format('%h hours, %i minutes');

echo $remaining_time . ' until we will open.';

This should output something like `13 hours, 15 minutes until we will open.".


text:
Q: How to store the content of a listview row in a SQL database with C#? I have a program that updates an Audit Trail (a listview) when something happens, like a user login, create/delete a new user and so on.
The listview has 10 columns like: Date, Time, Message Description, Event type and so on.
I need to store each listview entry (subItems of a raw) in a SQL database whenever I update the listView with new subItems. I couldn't find a listView ItemsChanged event, so I used the ItemSelectionChanged event. But how can I copy these data into the database at each ItemSelectionChanged event?
Please help

A: If you need to make insert/update when a new row is added/changed.

*

*get a reference to a new row thru event args.

*row has a SubItems property.

*check whether each subitem has a Name property set otherwise you'll get NullReferenceException.

*build your insert/update query using references to those subitems values:
cmd.CommandText = "insert into CustomTable(title, price) values(@title, @price)";
cmd.Parameters.AddWithValue("@title", row.SubItems["title"]);
// apply all necessary conversions
cmd.Parameters.AddWithValue("@title", row.SubItems["price"]);

*you got the point)

*good luck!