text:
Q: PCB layout and testpoints
*

*What are your personal policies for selecting which nodes should have testpoints?

*Can a testpoint be used as a node for powering a circuit?

*Does a testpoint on a line create a stub, subject to interference or crosstalk, making it better to not have a testpoint in some situations?

*Do you put testpoint on I2C and UART RX/TX lines for debugging?

A: *

*ground should always be a test point, power supplies are good test points too, because if the power is bad that can cause unusual behaviours. other signals that pass between circuit blocks make good test points too.

*some circuits can be powered by the test points

*stubs, yes at several gigahertz, not usually a problem except on fast circuits like PCIe

*yes, especially if those lines do not emerge on external connectors.


text:
Q: On the definition of improper integral I have a question regarding the definition of integral for functions that are continuous in an open interval $(a, b)$ but are not necessarily defined or continuous at the endpoints $a, b$.
Courant and John, in the book "Introduction to Calculus and Analysis", define it in the following way:

If the limit $$F = \lim_\limits{\epsilon \to 0}
\int_{\alpha_\epsilon}^{\beta_\epsilon} f(x) \ dx$$ exists when $\
a < \alpha_\epsilon < \beta_\epsilon < b \ $ and $ \
\lim_\limits{\epsilon \to 0} \ \alpha_\epsilon = a, \  $ $
\lim_\limits{\epsilon \to 0} \ \beta_\epsilon = b,\ $ and if  $F$ is
independent of the particular choice of $\alpha_\epsilon$ and
$\beta_\epsilon$ we say that the improper integral $\int_a^b f(x) \
dx$ converges and has value $F$.

The way I interpret this definition is:

*

*Let $(\alpha_n)_{n \in \mathbb{N}}$ and $(\beta_n)_{n \in \mathbb{N}}$ be two arbitrary real sequences converging to $a$ and $b$, respectively, such that $$(\forall n \in \mathbb{N}): \ a < \alpha_n < \beta_n < b. \ $$ If for each $n \in \mathbb{N},$ the definite integral $\int_{\alpha_n}^{\beta_n} f(x) \ dx $ has the same value $F$, we say that the improper integral $\int_a^b f(x) \ dx$ converges and has value $F$.

I feel they could have also wrote something like this:

*

*If the limit $$F = \lim_\limits{\epsilon \to 0} \int_{\alpha + \epsilon}^{\beta - \epsilon} f(x) \ dx$$ (where the points $\ \alpha + \epsilon\ $ and $ \ \beta - \epsilon \ $ approach the endpoints $a$ and $b$, respectively, from the interior of the interval) exists, then we say that the improper integral $\int_a^b f(x) \ dx$ converges and has value $F$.

Are these rewordings of the definition correct? I'm just not quite sure what they mean by "if $F$ is independent of the particular choice of $\alpha_\epsilon$ and $\beta_\epsilon$".

A: A few things to mention here.

*

*The first definition says $\lim_{t \to 0} \alpha_\epsilon =  \lim _{t \to 0} \beta_\epsilon= 0$. Surely you want these to converge to the endpoints $\alpha,\beta$? Not sure if this is a typo on your behalf or their behalf.

*In your interpretation of the first definition, you talk about the definite integral having the "same value F" along these sequences - this is not the case. The value of the integral may change, we're just looking for what it converges to. (The idea is that we take ANY pair of sequences and look at what the integral tends to. If it's the same value in every case, the improper integral is said to converge to that value. If even one choice of sequences yields a different value, the improper integral doesn't converge.)

*Your second definition is not the same - the first allows the limit to be taken at separate rates, which is important.
To elaborate on that last point, consider evaluating
$$\int_{-\pi/2}^{\pi/2} \tan x \, \text{d} x$$
which does not converge by the first definition, but does by the second.
Why? We have $\int_{\alpha_n}^{\beta_n} \tan x \, \text{d}x = \ln \frac{\cos \alpha_n}{\cos \beta_n}$. If we use the second definition, then we always have $\alpha_n = -\beta_n$ and so the integral is $0$ for every $n$, hence $0$ in the limit. However if $\beta_n$ and $\alpha_n$ are independent, we can let $\beta_n \to \pi / 2$ at a much faster rate than $\alpha_n \to -\pi/2$, so asymptotically $\ln \frac{\cos \alpha_n}{\cos \beta_n} \sim +\infty$. Similarly, if $\alpha_n$ converges faster, then $\ln \frac{\cos \alpha_n}{\cos \beta_n} \sim -\infty$.
Your proposed definition is in fact related to the Cauchy Principal Value, which you may be interested in looking at.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why am I getting an 'Error in UseMethod(arrange) in r? I'm writing an r program which lists sales prices for various items. I have a column called InvoiceDate, which lists date and time as follows: '12/1/2009 7:45'.  I'm trying to isolate the date only in a separate field called date, and then arrange the dates sequentially.  The code I'm using is as follows:
library(dplyr)
library(ggplot2)

setwd("C:/Users/cshor/OneDrive/Environment/Restoration_Ecology/Udemy/Stat_Thinking_&_Data_Sci_with_R/Assignments/Sect_5")
retail_clean <- read.csv("C:/Users/cshor/OneDrive/Environment/Restoration_Ecology/Udemy/Stat_Thinking_&_Data_Sci_with_R/Data/retail_clean.csv")

retail_clean$date <- as.Date(retail_clean$InvoiceDate)#, format = "%d/%m/%Y")

   total_sales = sum(retail_clean$Quantity, na.rm=TRUE) %>%
arrange(retail_clean$date) %>% ggplot(aes(x=date, y=total_sales)) + geom_line()

Initially, everything works fine, and the date field is created.  However, I get the following error for the arrange() function:
Error in UseMethod("arrange") :no applicable method for 'arrange' applied to an object of class "c('integer', 'numeric')"

I've searched for over a week for a solution to this problem, but have found nothing that specifically addresses this issue.  I've also used '.asPosixct' instead of .asDate, with similar results.  Any help as to why the program interprets Date data as numeric, and how I can correct the problem, would be greatly appreciated.

A: First, the error message is not about Date time.
Let's look at the code you provided:
total_sales = sum(retail_clean$Quantity, na.rm=TRUE) %>%
arrange(retail_clean$date) %>% ggplot(aes(x=date, y=total_sales)) + geom_line()

The result of this term sum(retail_clean$Quantity, na.rm=TRUE) is an integer in your case, and it is piped into the first argument of the dpyr::arrange function, which calls UseMethod("arrange").
Then, the piped argument is inspected as being an object of class of integer and numeric, and arrange do not have a method for these classes, that is, neither arrange.integer nor arrange.numeric are defined. Hence the error msg. There is nothing wrong with you date convertion except that you do need that format term you commented out in the code sample.
The solution is also simple. Change sum to something that returns a data.frame or other classes that arrange is aware of. You can check what methods are available for arrange:
$>methods(dplyr::arrange)
[1] arrange.data.frame*

In this R instance, you can only put a data.frame object through arrange, but you can always define specific methods for other classes.
Looks like this is a Udemy course assignment. Maybe here you need to calculate a sum for each day or each month, whichever your assignment is asking you to do, but sum is definitely not the right answer.
By the way, welcome to SO!
Update:
An example
n <- 100
data <- data.frame(sales = runif(n), day = sample(1:30, n, replace = TRUE))
data$date_ <- paste0(data$day, "/1/2009 7:45")
head(data$date_) # This is the orignial date string
data$date <- as.Date(data$date_, format = "%d/%m/%Y")
head(data$date) # Check here to see the formated date

library(dplyr)
library(ggplot2)
data %>%
    group_by(date) %>%
    summarise(totalSale = sum(sales, na.rm=TRUE)) %>%
    arrange(date) %>%
    ggplot(aes(x = date, y = totalSale)) +
    geom_line()

Here is the plot

It looks fine, isn't it? The sales are all ordered by date now.


text:
Q: PayPal: express checkout pay without account , Not possible? I have used the answers given in
Paypal express checkout without account
enter link description here
But even after adding LOCALECODE=us,SOLUTIONTYPE=Sole,LANDINGPAGE=Billing and setting AccountOptional to ON in website preferences,
I can able to set the checkout option without paypal account?
I am using a Paypal Business account, country - US.
Any idea?


text:
Q: How can I bind the Enter key to my tkinter window I would like to do this for the Enter key but not the Return key:
root.bind('<Return>',func)

If you are not clear on the difference between the enter key and the return key
http://en.wikipedia.org/wiki/Enter_key
I would appreciate help, thank you!

A: One way to find out what's the correct key binding is to create a key binding for all keys and printing the keysym of the event. Now, just hit the key you want to bind the event to and see what it prints.
import Tkinter
root = Tkinter.Tk()
def func(event):
    print event.keysym
root.bind("<Key>", func)
root.mainloop()

When pressing the Enter key, this will print KP_Enter, so your binding should be
root.bind('<KP_Enter>', func)


text:
Q: How to obtain the handler for a secondary activity started by a first activity using an intent? I have a main activity in my project from which i am starting a secondary activity using an intent. On a separate thread, I want to get the handler of the second activity for send some control messages to the second activity. How can i receive the handler for the second activity which i have started using an intent?

A: I would begin sending messages to this second activity, when it has been already created. That means, I would create a Handler object in the onCreate() method of this second activity, and pass that handler to the thread you want to send the message from.


text:
Q: Not sure how to return a Class in java I have this class
public class Bid {
private User buyer;
private double bidValue;

public Bid(User buyer, double bidValue) {
  if(buyer == null || bidValue <1) {
  throw new IllegalArgumentException();
}

this.buyer = buyer;
this.bidValue = bidValue;
}

public User getBuyer() {
 return buyer;
}

public double getBidValue() {
return bidValue;
}

public String toString() {
 return this.buyer + " bid £" + this.bidValue;
 }

}

and this class
import java.util.*;

public class Product {
private int productId;
private String productName;
private double reservedPrice;
private List<Bid> bids = null;

public Product(int productId, String productName, double reservedPrice) {
  this.productId = productId;
  this.productName = productName;
  this.reservedPrice = reservedPrice;
  this.bids = new ArrayList<Bid>();
}

public Bid getHighestBid() {
  double max = 0.0;
  for(Bid bidValue :bids) {
    if(bidValue.getBidValue() > max)
    max = bidValue.getBidValue();
   }
  return null;
 }

}

In the getHighestBid method I am trying to determine the highest unique bid that a user has placed, however I am not quite sure how to do that as the return type has to be Bid and I keep getting that max cannot be resolved to type double. Although I do understand what that means but I'm not sure how to fix it.

A: public Bid getHighestBid() {
  Bid max = null;
  for(Bid bidValue :bids) {
    if(max==null || bidValue.getBidValue() > max.getBidValue())
    max = bidValue;
   }
  return max;
}

You have to store the Bid object, not just the value, and then check against it.

A: public Bid getHighestBid() {
    double max = Double.NEGATIVE_INFINITY;
    Bid maxBid = null;
    for (Bid bid : bids) {
        double bidValue = bidValue.getBidValue();
        if (bidValue > max) {
            max = bidValue;
            maxBid = bid;
        }
     }
     return maxBid;
 }

Notes:
Perhaps allow for negative values, even though it is constrained in the constructor. Strictly speaking the could be all NaN.
double max = 0.0;

Each bid is a bid, not a bid value.
for(Bid bidValue :bids) {

Just keep hold of the max bid object as well as its value. (You could get the value each time, but looks cleaner if you don't.)
The stream version goes something like:
return bids.stream()
    .max(Comparator.comparingDouble(Bid::getBidValue)).orElse(null);

(As always, I have not so much as compiled this code).

A: if you "just want to fix your code", you could use something like
public Bid getHighestBid() {
  double max = 0.0;
  Bid maxBid = null;
  for(Bid bid : bids) {
    if(bid.getBidValue() > max)
    max = bid.getBidValue();
    maxBid = bid;
  }
  return maxBid;
}

but you should go one step further and implement the Comparableinterface for bid:
public class Bid implements Comparable<Bid> {
   ...
   int compareTo (Bid other) {
      // return -1,0 or 1 depending on comparison of bid Values of this and other
   }

}

then, in your Productclass, you could
public Bid getHighestBid() {
  return Collection.max(bids);
}

this approach uses build-in functionality of comparison and sorting. and usually is more readable..


text:
Q: Should I open the same page in every test? Java + Selenium I'm new to automated testign and asking for your help.
As I know every test should have its own steps and if I define several tests in one class, should I open the same page several times in each test or I can open it one time somewhere (in first test maybe) and then it will be keeped open all time. Which approach is more correct?

A: I'd say its a better idea to have one WebDriver instance per test, or one entire browser for each test, as your default approach.  I would only try to re-use a WebDriver session if you have a particular test case that might require it and I would say that is generally not very common.


text:
Q: ActionScript 2.0 List Component - Change pointer icon to hand for list items I am working on an older Flash project created in CS3 ActionScript 2.0 How can I make the pointer cursor change to the hand when hover over a list item?
_root.slidePanel.myList

'myList' is the list. I have traced out the contents of the List MC and it has a child MC called 'content_mc'. I assumed this was the object containing all of my list items but the only members of this MC I can see (when tracing them out) are 'setRGB' and 'searchKey'.
Can someone offer some help?

A: Not sure about AS2, but this should work in AS3. If you don't want AS3 answers, you may want to untag 'actionscript-3'
To get a custom cursor you'll need to attach MouseEvent.MOUSE_ENTER and MouseEvent.MOUSE_LEAVE to whatever it is you want to have the custom cursor.
function mouseEntered(e:MouseEvent):void
{
 Mouse.hide();
 stage.addEventListener(MouseEvent.MOUSE_MOVE, moveCursor);
 //create mouse cursor and add to stage
}

function mouseLeft(e:MouseEvent):void
{
 Mouse.show();
 stage.removeEventListener(MouseEvent.MOUSE_MOVE, moveCursor);
 //remove mouse cursor from stage
}

function moveCursor(e:MouseEvent):void
{
 // move the mouse cursor to wherever the mouse is.
}

This is one way of handling a custom cursor. You'll need to design a cursor that can be moved around the stage as the mouse is moved.
EDIT to add:
In AS3, Sprites have a property: useHandCursor that can be set to true to show the pointer when hovered over.


text:
Q: Sorting a collection in doctrine2 I've written the following query (that may or may not be efficient, I'm still a newbie):
    $collection     = $this->dm->getConnection()->selectCollection('db_name', 'collection_name');
    $query          = array('array_name' => new \MongoId(id));
    $cursor         = $collection->find($query)->limit(9)->sort('r', 'desc');

I'm trying to sort by an r value that looks like this in the document:
"r": 0.58325652219355106354

but it isn't actually sorting it by that r-value. What am I doing wrong?

A: Pretty sure sort takes an array argument.  Try
->sort(['r' => 'desc]);

I looked it up...
http://apigen.juzna.cz/doc/doctrine/mongodb/source-class-Doctrine.MongoDB.Cursor.html#564-585


text:
Q: Login to admin pending forever with Valet+ I'm using Valet+ on MacOS and have tweaked the Nginx and PHP configs to increase execution time etc.
Doing a fresh install, the frontend will load, slow at first, but fast after subsequent reloads, as expected.
The admin login screen is the same, loads slow, then fast afterwards.
Now, when I enter the correct credentials, the request to login is pending for 20+ minutes.
I have all caches enabled, except compiled_config and I have redis setup for sessions and caching.
There are is no data in the store either.
What is causing this never-ending load time for the admin?


text:
Q: Windows 8 Phone sample app to play / stop an audio file Where can I find a simple audio player code sample for a Windows 8 Phone app ?
I am new to Windows 8 Phone development and was trying out to make an app that simply plays audio files. Being new to XAML and this Windows 8 Phone SDK, I find it very difficult in understanding where to start about from.
I tried searching for sample project from here : http://code.msdn.microsoft.com/wpapps/
But couldn't understand which project does what.
Can somebody please direct me to a sample project and simply does the following

*

*Play audio

*Pause audio

*Stop audio

these audio files will be locally be added to the solution.
Please share your thoughts on this.

A: Take a look at Beginners for how to Media player using the Silverlight on Windows Phone


text:
Q: Upgrading to Gnome 3.12 in Fedora 20 Hello my friends. Recently Gnome 3.12 was released as an update for gnome users. so I decided to upgrade to the newest version as explained here.
After step 1, I tried to update Fedora using Yumex, But I got this error:

Dependency Resolution Errors:
Package: 1:NetworkManager-bt-0.9.9.1-3.git20140317.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
    Requires: NetworkManager(x86-64) = 1:0.9.9.1-3.git20140317.fc20
    Removing: 1:NetworkManager-0.9.9.0-33.git20131003.fc20.x86_64 (@updates)
        NetworkManager(x86-64) = 1:0.9.9.0-33.git20131003.fc20
    Obsoleted By: 1:NetworkManager-adsl-0.9.9.1-4.git20140319.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        Not found
    Updated By: 1:NetworkManager-0.9.9.1-4.git20140319.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-4.git20140319.fc20
    Available: 1:NetworkManager-0.9.9.0-20.git20131003.fc20.x86_64 (fedora)
        NetworkManager(x86-64) = 1:0.9.9.0-20.git20131003.fc20
    Available: 1:NetworkManager-0.9.9.1-0.git20140228.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-0.git20140228.fc20
    Available: 1:NetworkManager-0.9.9.1-1.git20140310.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-1.git20140310.fc20
    Available: 1:NetworkManager-0.9.9.1-2.git20140314.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-2.git20140314.fc20
    Available: 1:NetworkManager-0.9.9.1-3.git20140317.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-3.git20140317.fc20Package: ekiga-4.0.1-6.fc20.x86_64 (@fedora)
    Requires: libcamel-1.2.so.45()(64bit)
    Removing: evolution-data-server-3.10.4-3.fc20.x86_64 (@updates)
        libcamel-1.2.so.45()(64bit)
    Updated By: evolution-data-server-3.12.0-1.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
       ~libcamel-1.2.so.49()(64bit)
    Available: evolution-data-server-3.10.2-2.fc20.x86_64 (fedora)
        libcamel-1.2.so.45()(64bit)
    Available: evolution-data-server-3.11.90-1.fc20.i686 (rhughes-f20-gnome-3-12-i386)
        Not found
    Available: evolution-data-server-3.11.91-1.fc20.i686 (rhughes-f20-gnome-3-12-i386)
        Not found
    Available: evolution-data-server-3.11.92-1.fc20.i686 (rhughes-f20-gnome-3-12-i386)
        Not foundPackage: nm-connection-editor-0.9.9.0-9.git20140123.fc20.x86_64 (@updates)
    Requires: libgnome-bluetooth.so.12()(64bit)
    Removing: 1:gnome-bluetooth-libs-3.10.0-1.fc20.x86_64 (@anaconda)
        libgnome-bluetooth.so.12()(64bit)
    Updated By: 1:gnome-bluetooth-libs-3.12.0-1.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
       ~libgnome-bluetooth.so.13()(64bit)Package: 1:NetworkManager-atm-0.9.9.1-3.git20140317.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
    Requires: NetworkManager(x86-64) = 1:0.9.9.1-3.git20140317.fc20
    Removing: 1:NetworkManager-0.9.9.0-33.git20131003.fc20.x86_64 (@updates)
        NetworkManager(x86-64) = 1:0.9.9.0-33.git20131003.fc20
    Obsoleted By: 1:NetworkManager-adsl-0.9.9.1-4.git20140319.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        Not found
    Updated By: 1:NetworkManager-0.9.9.1-4.git20140319.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-4.git20140319.fc20
    Available: 1:NetworkManager-0.9.9.0-20.git20131003.fc20.x86_64 (fedora)
        NetworkManager(x86-64) = 1:0.9.9.0-20.git20131003.fc20
    Available: 1:NetworkManager-0.9.9.1-0.git20140228.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-0.git20140228.fc20
    Available: 1:NetworkManager-0.9.9.1-1.git20140310.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-1.git20140310.fc20
    Available: 1:NetworkManager-0.9.9.1-2.git20140314.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-2.git20140314.fc20
    Available: 1:NetworkManager-0.9.9.1-3.git20140317.fc20.x86_64 (rhughes-f20-gnome-3-12-x86_64)
        NetworkManager(x86-64) = 1:0.9.9.1-3.git20140317.fc20

A: Thanks for your support.
At first, I entered this to enable gdm.service:

systemctl enable gdm.service

Then, I restarted it using this:

systecmtl restart gdm.service

Thanks to IL Mostro because of the codes and great instructions!


text:
Q: Why doesn't Anakin's lightsaber explode when it's chopped in half on Geonosis? We see that lightsabers can create considerable explosions when Luke's is Force-pulled in half in the throne room fight in The Last Jedi, but when Anakin's is chopped in half on the conveyor belt in the Battle Droid Foundry on Geonosis in Attack of the Clones, it just fizzles.
Is there a good reason to expect that these two actions would have different effects on lightsabers, or that these two lightsabers would respond differently to having their hilts split in half?

A: The lightsaber destroyed by Rey and Kylo had its 'kyber crystal' broken, releasing the power within.

Until, finally, the crystal sheared apart, its unleashed energy
tearing the lightsaber's housing in half and filling the throne room
with a flash of brilliant, blinding white.
Star Wars: The Last Jedi: Expanded Edition

By comparison Anakin's lightsaber, assuming it was constructed in the same fashion as Luke's, was chopped in half by the cutter above the place where the kyber crystal is stored, across the field energisers. This evidently doesn't result in an explosion.

Images courtesy of Star Wars: The Visual Dictionary and Star Wars: Attack of the Clones


text:
Q: How to pass hibernate dialect in test using testContainers to match my container in a generic way I don't find any information on the reason I get the error below or a way to pass the dialect in a generic way.
I'm using spring boot version 2.2.4
I have the following test for my application with test containers library against MySQL.
I'm using an application context initializer especially for the test and I must set the JPA dialect otherwise I'm getting an error in the log, the test still passes but I'm trying to understand where the error is coming and why.
I'm searching for a way to pass the dialect in a generic way
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PetClinicApplication.class,
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = {BootTestContainersSpockApplicationTests.Initializer.class})
public class BootTestContainersSpockApplicationTests {

@Autowired
private SpecialtyService specialtyService;

@ClassRule
public static MySQLContainer mySQLContainer = (MySQLContainer) new MySQLContainer("mysql:5.5")
        .withInitScript("db/schema.sql")
        .withDatabaseName("sampleapp")
        .withUsername("user")
        .withPassword("password");

@Test
public void testAgainstMySQL() {

    loadSpecialties();

    assertEquals(3L, specialtyService.findAll().size());

}

private void loadSpecialties() {
    Arrays.asList(new Specialty("radiology"),
            new Specialty("surgery"),
            new Specialty("dentistry")).forEach(specialty -> specialtyService.addSpecialty(specialty));
}

static class Initializer
        implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        TestPropertyValues.of(
                "spring.datasource.url=" + mySQLContainer.getJdbcUrl(),
                "spring.datasource.username=" + mySQLContainer.getUsername(),
                "spring.datasource.driver-class-name=" + mySQLContainer.getDriverClassName(),
                "spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect",
                "spring.datasource.password=" + mySQLContainer.getPassword()
        ).applyTo(configurableApplicationContext.getEnvironment());
    }
}
}

the test works fine but when I mark this line
"spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect"

in a comment I get the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'SEQUENCES' in information_schema
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3933) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3869) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2675) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2439) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1365) ~[mysql-connector-java-5.1.48.jar:5.1.48]
at com.zaxxer.hikari.pool.ProxyStatement.executeQuery(ProxyStatement.java:111) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.executeQuery(HikariProxyStatement.java) ~[HikariCP-3.4.2.jar:na]
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:42) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.sequenceInformationList(JdbcEnvironmentImpl.java:403) [hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:268)


text:
Q: How to enable required authentification in server side blazor app? I am writing a server sided blazor app for our intranet.
Is there anyway to force the user to login before he/she can access any other side besides of login and register?
In ASP.NET Webforms it was possible with the Web.config file.
<authentication mode="Forms">
  <forms loginUrl="login.aspx" defaultUrl="default.aspx" />
</authentication>
<authorization>
  <deny users="?" />
</authorization>

A: You can simply annotate your Index component with the Authorize attribute as follows:
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]

That will initiate the authentication flow before the user can access other resources....
Hope this helps...


text:
Q: How to adjust two pictures side by side in just one column of multicol environment? First of all, thanks to the group member Harish Kumar because of whose advise finally I was able to fix the caption line under the figure/ float in multicol environment. This is what I then faced:
\documentclass[10pt, twoside]{book}
\usepackage[demo]{graphicx}   %%% remove demo in your file
\usepackage{multicol}
\usepackage{caption}

\begin{document}

 \begin{multicols}{2}
 a test file for picture inclusion along with the captions and labeling
\begin{center}
 \fbox{\includegraphics[scale=0.2]{Cauchy_sequence_illustration-png}}
 \captionof{figure}{Cauchy Seq1}\label{Cauchy1}
 \fbox{\includegraphics[scale=0.2]{Cauchy_sequence_illustration-png}}
 \captionof{figure}{Cauchy Seq2}\label{Cauchy2}
 \end{center}
 \end{multicols}

 \end{document}

The problem is : I am willing to include two pictures "side by side" rather than up-down way. But in vain. Can anyone please help me how to do that?
Thanks in advance

A: Is it like this?
\documentclass[10pt, twoside]{book}
\usepackage[demo]{graphicx}   %%% remove demo in your file
\usepackage{multicol}
\usepackage{caption}
\usepackage{kantlipsum}

\begin{document}

 \begin{multicols}{2}
 a test file for picture inclusion along with the captions and labeling

\noindent
\begin{minipage}{0.5\columnwidth}
\centering
 \fbox{\includegraphics[width=\dimexpr\textwidth-2\fboxsep-2\fboxrule\relax]{Cauchy_sequence_illustration-png}}
 \captionof{figure}{\protect\raggedright Cauchy Seq1}\label{Cauchy1}
\end{minipage}%
\begin{minipage}{0.5\columnwidth}
\centering
 \fbox{\includegraphics[width=\dimexpr\textwidth-2\fboxsep-2\fboxrule\relax]{Cauchy_sequence_illustration-png}}
 \captionof{figure}{\protect\raggedright Cauchy Seq2}\label{Cauchy2}
 \end{minipage}
 \kant[2]
 \end{multicols}
 \end{document}


text:
Q: If you delete widget from list it reset state of all the widgets below it in flutter? Using floating action button you can add questions, but when you delete particular question it reset state of all the widget below it in the list, everything above it maintains its state. TextField didn't retain data though I'm using TextFieldController. I'm unable to figure out why this is happening.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kaloory/constants.dart';

class AddQuestionsForTest extends StatefulWidget {
  AddQuestionsForTest({Key key}): super(key: key);

  @override
  _AddQuestionsForTestState createState() => _AddQuestionsForTestState();
}

class _AddQuestionsForTestState extends State<AddQuestionsForTest> {
  int count = 1;
  List<InputWidget> children;

  void removeInputWidget(index){
    setState(() {
      children.remove(index);
    });
  }
  @override
  void initState(){
    super.initState();
    setState(() {
      children = List.generate(count, (int i) => new InputWidget(removeInputWidget, key: ValueKey(i),));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

        appBar: titleAppbar(title: "Create Test"),

        body: Container(
          color: backgroundColor,
          height: MediaQuery.of(context).size.height,
          child: ListView.builder(
            itemCount: children.length,
            itemBuilder: (context, index) {
              final child = children[index];
              return child;
            },
          ),
        ),
        floatingActionButton: new FloatingActionButton(
          backgroundColor: primaryColor,
          splashColor: primaryColor.withOpacity(0.5),
          child: new Icon(Icons.add),
          onPressed: () {
            setState(() {
              children.add(InputWidget(removeInputWidget,key: ValueKey(count),));
              count = count + 1;

            });
          },
        ));
  }

}

class InputWidget extends StatefulWidget {
  final Function(InputWidget) removeInputWidget;

  InputWidget(this.removeInputWidget,{Key key}): super(key: key);

  @override
  _InputWidgetState createState() => _InputWidgetState();
}

class _InputWidgetState extends State<InputWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.symmetric(horizontal: 30, vertical: 5),
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            BuildDropDown(),
            Divider(),
            IconButton(icon: Icon(Icons.delete_outline), onPressed: (){
                widget.removeInputWidget(this.widget);
            })
          ],
        ));
  }
}
class BuildDropDown extends StatefulWidget {

  @override
  _BuildDropDownState createState() => _BuildDropDownState();
}

class _BuildDropDownState extends State<BuildDropDown> {
  TextEditingController ques = TextEditingController();
  String newValue;
  @override
  Widget build( BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        new Padding(
          padding: const EdgeInsets.symmetric(vertical: 10),
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              new ListTile(
                title: Container(
                  padding: EdgeInsets.all(8),
                  height: 40,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      border: Border.all()),
                  child: DropdownButtonHideUnderline(
                    child: new DropdownButton<String>(
                        hint: Text('Choose'),
                        onChanged: (String changedValue) {
                          newValue = changedValue;
                          setState(() {
                            print(newValue);
                          });
                        },
                        value: newValue,
                        items: <String>[
                          'Multiple Choice',
                          'Short Answer Type',
                          'Long Answer Type'
                        ].map((String value) {
                          return new DropdownMenuItem<String>(
                            value: value,
                            child: new Text(value),
                          );
                        }).toList()),
                  ),
                ),
              ),
            ],
          ),
        ),
        Container(
          height: 40,
          margin: EdgeInsets.only(top: 10),
          padding: EdgeInsets.symmetric(horizontal: 20),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            border: Border.all(color: Colors.black.withOpacity(0.5)),
          ),
          child: TextField(
            controller: ques,
            decoration: InputDecoration(
              border: InputBorder.none,
              focusedBorder: InputBorder.none,
              enabledBorder: InputBorder.none,
              errorBorder: InputBorder.none,
              disabledBorder: InputBorder.none,
              hintText: "Untitled Question",
            ),
          ),
        ),

      ],
    );
  }
}

A: This is because TextField has it's own internal state, and it's not being saved even though you have assigned a key to the parent.
I think the solution is to save the text value somewhere in the widget state, and in build() check if the contents of the controller.text != _currentText, if they don't match, then inject the last known _currentText.


text:
Q: When using RMSE loss in TensorFlow I receive very small loss values smalerl than 1 Hello I have a network that produces logits / outputs like this:
logits = tf.placeholder(tf.float32, [None, 128, 64, 64]) // outputs
y = tf.placeholder(tf.float32, [None, 128, 64, 64]) // ground_truth, targets

--> y ground truth values are downscaled from [0, 255] to [0, 1] in order to increase perforce as I have read it is better to use range [0, 1]
Now I want to calculate the RMSE / EuclideanLoss like this:
loss = tf.reduce_mean(tf.square(logits - y))

or
loss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(y, logits))))

not sure which one is better.
When doing so my loss values start at roughly 1. and then quickly go down to 2.5e-4. When I use the EuclideanLoss in Caffe for the same network my loss values starts from roughly 1000 and goes down to 200. Am I doing anything wrong in Tensorflow or why are the loss values that small? I can't really track the loss values in tensorboard since they are so small. Can anyone help me?

A: The first loss you propose is the better one (the second introduces an unnecessary sqrt).
Values equal to or smaller than 1 seem to be the only possible values since the range of values you provide is within 0 and 1 - so the biggest possible error is 1.
If you have trouble visualising the loss in tensorboard, try showing the graphs using a log scale (one of the two buttons under the graphs)


text:
Q: How can I use multiple classes in Model - MVC Java? I am creating an app in Java and I am using the MVC architecture. I have the Model, View and Controller classes, and I have also another classes that help me with data. For example, I have the
next classes: Product, Store, Manager. How can I use the data in the Model class, I tried to copy paste my Classes and my code from main file, but all I have are errors.

In the second image I have the problems, the Model class. I really do not know what to do to make it work.


text:
Q: how to derive the equality: $E X 1_{X > b} = \int_0^\infty dy \mathbb{P}\{X 1_{X > b} > y\}$?
Can someone explain how to derive this equality?

A: $$\mathbb{E}\left[\xi^p\right]= p\int_0^\infty \mathbb{P}(\xi>t)t^{p-1} \, \text{d}t = p\int_0^\infty \mathbb{P}(\xi\geq t)t^{p-1} \,
 \text{d}t $$
for all $p>0$.
Proof. By Fubini's theorem and calculus, we get
\begin{align}
    \mathbb{E}\left[\xi^p\right] &= \int_\Omega  \xi^p \, \text{d} \mathbb{P}\\
    &=  p\int_\Omega \int_{0}^\xi t^{p-1}\, \text{d}t \,\text{d}\mathbb{P}\\
     &= p\int_\Omega \int_{0}^\infty 1_{\{\xi>t\}} t^{p-1}\, \text{d}t \,\text{d}\mathbb{P}\\
     &= p\int_{0}^\infty t^{p-1}\int_\Omega  1_{\{\xi>t\}}\,\text{d}\mathbb{P}\, \text{d}t \\
    & = p\int_0^\infty \mathbb{P}(\xi>t)t^{p-1} \, \text{d}t .
 \end{align}
The proof of the second expression is similar.


text:
Q: странное поведение use в процедурном svg Вопрос про процедурный svg.
https://codepen.io/anon/pen/ggKKvp?editors=1010
Проблема с use: он перестает работать хотя, если смотреть по DOM, все правильно. В HTML комментировал нормальный SVG.
Если заменить use на rect всё прекрасно работает или немного изменить DOM в браузере например :viewBox="0 0 450 100" на viewBox="0 0 400 100". С чем такое связано не понимаю. Может как-то надо перерисовать?
defs.appendChild(rect.cloneNode(true))
svgg.appendChild(defs.cloneNode(true))
svgg.appendChild(use.cloneNode(true))
svgg.appendChild(use2.cloneNode(true))
svgg.appendChild(use3.cloneNode(true))

A: Проблема была проста на 21 строчке было:
if(i === 'href')

А нужно было заменить на:
if(i === 'xlink:href')

Как-то так.Простите что отвлек Вас.Спасибо всем.

A: Начните поиск ошибки в своем коде с того, что постарайтесь не использовать в именах переменных зарезервированные имена в SVG - rect, defs, тем более use очень специфичной команды, которая переводит создаваемый элемент в теневой ДОМ.

<svg id="svg1" version="1.1"  xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 width="450" height="100" viewBox="0 0 450 100"
  style="border:1px solid rgb(150,150,150);">

  <defs>
  <rect id="def-rect" x="-25" y="-25" width="50" height="50" fill="#29e" />

  </defs>
   <use xlink:href="#def-rect" transform="translate(100 50)"></use>
   <use xlink:href="#def-rect" transform="translate(200 50)"></use>
   <use xlink:href="#def-rect" transform="translate(300 50)"></use>
</svg>

Просто сравните с файлом на codepen


text:
Q: How to use rxNetty client with EmbeddedChannel for testing Given that I have TcpClient like this:
TcpClient.newClient(...)
         .pipelineConfigurator(...)
         .createConnectionRequest()
         .flatMap(c -> c.getInput())

I would like to test it using Netty's EmbeddedChannel to simulate the interactions between the server and the client and make assertions on both EmbeddedChannel and TestSubscriber.
I am struggling to find a way of passing EmbeddedChannel to achieve this. I was looking at channelProvider() to do it like this:
EmbeddedChannel channel = new EmbeddedChannel()
ChannelPorivderFactory providerFactory = (a,b,c,d) -> n -> Observable.just(channel);

TestSubscriber<Object> subscriber = new TestSubscriber<>();

TcpClient.newClient(...)
         .pipelineConfigurator(...)
         .channelProvider(providerFactory)
         .createConnectionRequest()
         .flatMap(c -> c.getInput())
         .subscribe(subscriber);

embeddedChannel.writeInbound(serverMessage);
subscriber.assertValueCount(1);

I can now channel.writeInbound(someServerResponse) and I can see in Netty wire logs the bytes are written but I am getting this message
Data received on channel, but no subscriber registered. Discarding data.
I am defo writing the data AFTER subscription
what am I missing?


text:
Q: Show list of angular components v2 or v4 I need to display a list of angular components from a ts file. How I can doing?
  // file ResolventePage.ts

  listFormulas: IFormula[] = [{
     name: "Formula 1",
     description: "a description",
     element: AComponent1
  }, {
     name: "Formula 2",
     description: "a description 2",
     element: AComponent2
  }, ... ]

But I do not know how to place it dynamically within the cycle:
 <ion-item *ngFor="let item of listFormulas">
   <ion-label>{{ item.name }}</ion-label>

   <!-- Here I need to render the component "item.element" -->
 </ion-item>

Thank you very much for any help.

A: If I understood correctly each element in your listFormulas is and angular Component.
Option 1
First import all components in your .ts file, for example:
import { AComponent1} from './AComponent1';
import { AComponent2} from './AComponent2';
// ...

Then try this quick hack:
<ion-item *ngFor="let item of listFormulas">
  <ion-label>{{ item.name }}</ion-label>

  <{{item.element.name}}></{{item.element.name}}>
</ion-item>

Option 2
If this doesn't work then here's a plunker of the proper but kind of advanced way to do this. This is a demo from the very detailed official documentation for loading components dynamically.


text:
Q: Retrieving tweets with only media_url I'm currently working on an app, and i only want to load tweets which contain a media_url. I have tried stopping it from loading the tweets into the tableView, however that lead to lots of blank tweets for obvious reasons.
Code i used for that:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    id tweet = [self.timeline objectAtIndex:[indexPath row]];

    NSString *example = [NSString stringWithFormat:@"%@",[tweet valueForKeyPath:@"entities.media.media_url"]];
    NSLog(@"%@", example);

    if ([example isEqual: @"(null)"] ) {

    } else {
        cell.textLabel.text = [tweet valueForKeyPath:@"text"];
        cell.detailTextLabel.text = [tweet valueForKeyPath:@"user.name"];
    }

    return cell;
}

So now i'm looking for an alternative way which will successful only load tweets which have a media_url, and put them in the order that they come up. I'm using NSJSONSerialization to parse my data.
Code I used for that:
- (void)fetchData
{
    [_refreshHeaderView refreshLastUpdatedDate];
    NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1/statuses/home_timeline.json?count=199&include_entities=true"];
    TWRequest *request = [[TWRequest alloc] initWithURL:url
                                                 parameters:nil
                                              requestMethod:TWRequestMethodGET];
    [request setAccount:self.account];
    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
        if ([urlResponse statusCode] == 200) {
            NSError *jsonError = nil;
            id jsonResult = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
            if (jsonResult != nil) {
                self.timeline = jsonResult;
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
            }
            else {
                NSString *message = [NSString stringWithFormat:@"Could not parse your timeline: %@", [jsonError localizedDescription]];
                [[[UIAlertView alloc] initWithTitle:@"Error"
                                            message:message
                                           delegate:nil
                                  cancelButtonTitle:@"Cancel"
                                  otherButtonTitles:nil] show];
            }
        }
    }];
   [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.0];
}

So I want to know is there anyway i can make the data that is added into timeline, only those of tweets which contain media_url, or is there a better way of doing this using a different method.
Thanks.

A: Maybe try with something like this to check if the tweet contains or not a media url:
if([tweet valueForKey:@"entities.media.media_url"] == [NSNull null])


text:
Q: Slidingmenu navigation nothing happen I'me trying to write an sliding menu following this tutorial http://androidsolution4u.blogspot.it/2013/05/android-sliding-menu-like.html
It's ok and i have my list of items but i want that clicking on the item i can open an activity. So i try to write in the fragment this:
@Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                switch (arg2) {
                case 0:
                    Intent i = new Intent(getActivity().getBaseContext(), HomeActivity.class);
                    i.putExtra("CPU Statistics", "0"); MenuFragment.this.startActivity(i);
                break;
                case 5:

                    Intent intent1 = new Intent(getActivity().getBaseContext(), settings.class);
                    startActivity(intent1);

                }
            }

the menu it's in strings.xml
<string-array name="marray">
        <item>Chart</item>
        <item>settings</item>
    </string-array>

But nothing happen when i click the items. Something's wrong?


text:
Q: Call to undefined function mysql_query_del() in I am new in php and I'm trying to execute multiple query in a php file, and it gives me this error "Call to undefined function mysql_query_del() in" if I execute only one query it works but if I execute 2 or more queries then it's not working. Can someone help me with this please?
This is my code I want to execute.
I want it to delete the values from table after I transfer it to another table.
<?php
//make connection
mysql_connect('localhost', 'root', '');
//select db
mysql_select_db('mjj_app');

$sql="INSERT INTO tbl1_viewer (fname,fqty) SELECT food,quantity FROM table1_orderlist;";
$list=mysql_query($sql);
?>

<?php

// if successfully insert data into database, displays message "Successful".
if($list){
$sqldel="DELETE * FROM table1_orderlist;";
$result=mysql_query_del(sqldel);
    if($result){
            header("Location: index.php");
    }
}

else {
echo "ERROR";
}
?>

A: DELETE * FROM table1_orderlist;

is a syntax error.
it should be
DELETE FROM table1_orderlist;

which will delete all the rows, if that is really what you want

A: http://php.net/manual/en/book.mysql.php
there is no such function like mysql_query_del
replace
$result=mysql_query_del(sqldel);

with
$result=mysql_query($sqldel);

also replace
$sql="INSERT INTO tbl1_viewer (fname,fqty) SELECT food,quantity FROM table1_orderlist;";

with
$sql="INSERT INTO tbl1_viewer (fname,fqty) (SELECT food,quantity FROM table1_orderlist)";

and as @Drew said
replace
$sqldel="DELETE * FROM table1_orderlist;";

with
$sqldel="DELETE FROM table1_orderlist;";

A: change:
$result=mysql_query_del(sqldel);

to:
$result=mysql_query($sqldel);

and use prepared statements PDO/MySQLi because your code is vulnerable to sql injection.

A: $sqldel="DELETE * FROM table1_orderlist;";
$result=mysql_query_del(sqldel);

replace this line with it:
$sqldel="DELETE  FROM table1_orderlist;";
$result=mysql_query(sqldel);


text:
Q: Why did Voldemort kill Lily Potter instead of stunning her? Voldemort offered Lily Potter mercy at Snape's request, demanding that she get out of the way so he could kill Harry. When she refused, why didn't he simply stun her or put her in a full body-bind or something like that? It seems obviously unnecessary for him to kill her; there was no clear benefit to him, and he risked alienating a loyal follower.
Which he did, because:

 Severus Snape became an inside man for Dumbledore.

A: He had already threatened to kill her and so if he did not kill her after saying he would, his reputation would be damaged.
He was also aware that Lily was a member of the Order of the Phoenix and he would have seen her not only as a threat to him but an opportunity for him to damage the order and for him to stay in power.

A: While Au101's answer offers an excellent explanation, another
point is this: Voldemort's concern for the wants/needs/desires of others
(including Snape) is entirely utilitarian.  He is only willing to accommodate
their wants/needs/desires as long as he perceives a net benefit to himself from doing so.
In this situation, the liability of Lily
Potter's continued life exceeded the utility of pleasing Snape by
giving her to him following the deaths of James and Harry.  This utilitarian view was shown in the final line quoted by Au101:

He could have forced her away from the cot, but it seemed more prudent to finish them all....

Another example of his utilitarian view of people (even of Snape!) was demonstrated by the way in which Voldemort killed Snape when it became beneficial for him to do so:

"...[I]t is of you that I wished to speak, Severus.... You have been very
valuable to me.  Very valuable....
"You have been a good and faithful servant, and I regret what must
happen....
"The Elder Wand cannot serve me properly, Severus, because I am not its true
master.  The Elder Wand belongs to the wizard who killed its last owner.  You
killed Albus Dumbledore.  While you live, Severus, the Elder Wand cannot be
truly mine....
"It cannot be any other way," said Voldemort.  I must master the wand,
Severus.  Master the wand, and I master Potter at last."

*

*Deathly Hallows, Chapter 32

A: Well we know essentially why, because we see the murder from Voldemort's own eyes.

'Not Harry, not Harry, please not Harry!'
'Stand aside, you silly girl ... stand aside, now ...'
'Not Harry, please no, take me, kill me instead -'
'This is my last warning -'
'Not Harry! Please ... have mercy ... have mercy ... Not Harry! Not Harry! Please - I'll do anything -'
'Stand aside - stand aside, girl -'
He could have forced her away from the cot, but it seemed more prudent to finish them all ...
Harry Potter and the Deathly Hallows - p.281 - Bloomsbury - Chapter 17, Bathilda's Secret

It seems really, then, that he was a killer through and through. He didn't need to kill her. But he didn't really need to kill James either, they were in the way. He would have spared her for Snape, but she defied him, she stood up to him. She tested his patience as we see here. And, after all, this was his big moment, wiping out, once and for all, the one inexplicable, great threat to him. Not a time for half-measures. A time for a show of strength surely.

A: There are a couple of reasons:

*

*So he didn't have to deal with her.  If he got past her without killing her and then killed her son, her life would be ruined--and she would probably go into the revenge business, which could be a nuisance for him.

*Because he's Voldemort.  He's evil.  That's just what he does.

*To make a Horcrux. Killing her can only be good for Voldemort--he can make another Horcrux if he wants and he doesn't have to deal with her annoying noises.  There's no reason in his mind not to kill her.

*She's a Mudblood.  We all know that Voldy would rather have less of those in the world.

Or maybe he killed her simply because he didn't even think of doing anything else. For Voldemort, stunning isn't really an option.  It just doesn't cross his mind to stun people, especially people he has no use for.

A: My answer first take on this question was this--we know from the books that this spell, the killing curse, is unblockable. As far as ol' Voldie knew at the time, any other spell would have a chance of failure if she had any magical protection.
Second take is that she's an enemy and would definitely be an enemy after he killed her son. Why not eliminate an enemy when you have the chance.
Third take on it was that Avada Kedavra is actually a signature spell of Voldie's.
Fourth take is what others have already covered--he's an evil dude, and this is what he does.
As to the risk of alienating Snape, consider how close to the vest Snape played his cards--he may have asked for Voldie to spare Lily, but Voldie underestimated what effect that would have because, as we all know, he doesn't understand the power of love. The only reason why he did not kill her outright to begin with is because Snape asked. As far as V is concerned, he tried.

'Well, Severus? What message does Lord Voldemort have for me?'
'No - No message - I'm here on my own account....
'I - I come with a warning - no, a request - please....'
'What request could a Death Eater make of me?'
'The - the prophecy... the prediction... Trelawney...'
'Ah, yes,' said Dumbledore. 'How much did you relay to Lord Voldemort?'
'Everything - everything I heard!' said Snape. 'That is why - it is for that reason - he thinks it means Lily Evans!'
'The prophecy does not refer to a woman,' said Dumbledore. 'It spoke of a boy born at the end of July -'
'You know what I mean! He thinks it means her son, he is going to hunt her down - kill them all -'
'If she means so much to you,' said Dumbledore, 'surely Lord Voldemort will spare her? Could you not ask for mercy for the mother, in exchange for the son?'
'I have - I have asked him -'

As you can see from this exchange, Snape may have asked, but he certainly didn't beg--to do so would have shown his hand and make him someone that Voldie might watch in future. Judging from Snape's overall actions and words throughout all the books, especially in concern to Voldie, he KNEW what a monster he is--and he KNEW that he could only push so far without raising suspicions--plus it's likely he already had the back up plan of going to Dumbledore to get Lily protection, something he could only do if his protest was framed in a way that wasn't "weak." Likely he told Voldie that he owed her something, or that he wanted her as a plaything later, rather than that he loved her.


text:
Q: Append to Body Issues in IE I am having issues appending a div to the body tag in IE 9 and down. This is working in Firefox and Chrome.
var currenturl = "the url I am loading";

$(document.body).append('

');
// ^ This is the line that is erorring

$("#overlaytransparency").show();
$("#overlaymessage").show();

$("#overlaytransparency").click(function () {
    $("#overlaytransparency").hide();
    $("#overlaymessage").hide();
});

    $("#overlayframe").load(currentPath);

I am getting this error in IE:
SCRIPT438: Object doesn't support property or method 'getElementsByTagName'
Thanks in advance for any help.

A: what about
$(document).ready(function() {
    $("body").append();
});

A: Try using $('body') instead of $(document.body).append('<div
$('body').append('<div ...

A: i think you are using getElementsByTagName somwhere in your script
see this ref: https://developer.mozilla.org/en/DOM/element.getElementsByTagName
Note: While the W3C specification says elements is a NodeList, this method returns a HTMLCollection both in Gecko and Internet Explorer. Opera returns a NodeList, but with a namedItem method implemented, which makes it similar to a HTMLCollection. As of January 2012, only in WebKit browsers the returned value is a pure NodeList.


text:
Q: Color discrepancy when using Android emulator, real device and Gimp on Ubuntu When I set a background color #FF7200C2 in any Layout in Android, I thought I would get:

This looks so in Gimp as well as in graphical Android editor in Eclipse. But when I launch the app on emulator or a real device it looks like this:

Why does it differ and what is the correct color now?
It's very strange, when I try to make a screenshot from the emulator, on the screenshot it looks different than on the emulator: On the screenshot it's the same as the first color, on the emulator it's like the second color)
Maybe this is a problem with the underlying OS, Ubuntu. Any ideas what's going on here?

A: Try to remove the alpha from the color,ie remove the "ff"


text:
Q: Change Background Color to White when Printing with Microsoft Print To Pdf in WPF I am Printing my canvas area with Microsoft Print To Pdf and Canvas had black background
However, i need to change the background color
Code
public void RenderCanvasImage(int maxRight, int maxBottom, Canvas surface, Transform transform)
        {
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap(maxRight, maxBottom,96d, 96d, PixelFormats.Pbgra32);
            renderBitmap.Render(surface);
            PrintDialog dialog = new PrintDialog();
            if (dialog.ShowDialog() != true)
            {
                return;
            }
            Grid grid = new Grid();
            Image myImage = new Image();
            myImage.Source = renderBitmap;
            myImage.Stretch = Stretch.Uniform;
            grid.Children.Add(myImage);
            Grid.SetColumn(myImage, 0);
            Grid.SetRow(myImage, 1);
            grid.Measure(new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight));
            grid.Arrange(new Rect(new Point(0, 0), grid.DesiredSize));
           if (dialog.PrintQueue.FullName == "Microsoft Print to PDF")
            {
                Microsoft.Win32.SaveFileDialog savedialog = new Microsoft.Win32.SaveFileDialog();
                savedialog.DefaultExt = "pdf";
                savedialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
                if (savedialog.ShowDialog() != true)
                {
                    return;
                }
                else
                {
                    if (savedialog.FileName.Contains(","))
                    {
                        MessageBox.Show("Comma(,) is not allowed in File Name/Directory.", "Message", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                        return;
                    }
                }
                System.Drawing.Bitmap bmp;
                using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
                {
                    BitmapEncoder enc = new BmpBitmapEncoder();
                    enc.Frames.Add(BitmapFrame.Create((BitmapSource)new WriteableBitmap(renderBitmap)));
                    enc.Save(outStream);
                    bmp = new System.Drawing.Bitmap(outStream);

                }

                System.Drawing.Printing.PrintDocument doc = new System.Drawing.Printing.PrintDocument()
                {
                    PrinterSettings = new System.Drawing.Printing.PrinterSettings()
                    {
                        // set the printer to 'Microsoft Print to PDF'
                        PrinterName = "Microsoft Print to PDF",
                        // tell the object this document will print to file
                        PrintToFile = true,
                        // set the filename to whatever you like (full path)
                        PrintFileName = savedialog.FileName,

                    }
                };
                doc.PrintPage += (sender, args) =>
                {
                    args.Graphics.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, (int)grid.DesiredSize.Width, (int)grid.DesiredSize.Height));
                };
                doc.Print();
            }

        }

Kidnly provide some solution as previously i was having issue that when having comma(,) in file name or path then Microsoft Print To Pdf will not create file so giving user error when using comma i am using this code.


text:
Q: Unindo doisdata frames pelos eixos Sou principiante no estudo da programação e estou com uma dúvida:
Preciso unir dois dataframes pela coluna da data. Um data frame mostra informações sobre uma empresa que aluga bicicletas e outra as informações meteorológicas do dia.
O DF da empresa possuí muito mais linha e uma mesma data se repete diversas vezes, no outro é uma linha para cada data.
Poderiam me ajudar

A: Opa...
eu uso o pd.merge, se as colunas nos dois dataframes são os mesmos utilizo "on".
import pandas as pd

pd.merge(df_1,df_2,on='data')

se os nomes são diferentes utilizo "left_on" e "right_on", ex:
import pandas as pd

pd.merge(df_1,df_2,left_on='data',right_on='data')

left_on para a coluna do dataframe da esquerda e right_on para a coluna do dataframe da direita.
Referencia: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html


text:
Q: import a csv from google cloud storage to google cloud automatically I  want to import a csv file from google cloud storage to google cloud sql and for this i am using the following query . when i execute the query in apps script i am getting following errors
*getservice() is not defined
arguments ----Arguments (219473067)
service---- undefined
token----undefined
result-----undefined
i-----undefined
f----undefined
path-----undefined
payload-----undefined
and the java script i used is
function uploadtoCloudSQL() {

var service = getService();

  if (!service.hasAccess()) {
    Logger.log(service.getAuthorizationUrl());
    return;
  }

  var token = service.getAccessToken();

  // Getting list of files to be processed

var result = JSON.parse(
    UrlFetchApp.fetch('https://www.googleapis.com/storage/v1/b/test/o', {
      method: "GET",
      headers: {
        Authorization: 'Bearer ' + token
      }
    }).getContentText());

 for (var i = 0; i < result.items.length; i++) {
    if (result.items[i].name.indexOf(".") !== -1) {
      files.push(result.items[i].name);
    }
  }

  for (var f = 0; f < files.length; f++) {

    var path = files[f].split("/");

    var payload =
      '{"importContext" : { "csvImportOptions": {"table":"test_table"}, "fileType": "CSV", "database": "nmp", "uri": "gs://revealer_test/data/Sample_data.csv"}}'
      .replace("data", path[0])
      .replace("Sample_data.csv", path[1]);

    UrlFetchApp.fetch('https://www.googleapis.com/sql/v1beta4/projects/PROJECT/instances/INSTANCE/import', {
      method: "POST",
      contentType: "application/json",
      headers: {
        Authorization: 'Bearer ' + token
      },
      payload: payload,
      muteHttpExceptions: true
    });

    UrlFetchApp.fetch('https://www.googleapis.com/storage/v1/b/test/o/' + encodeURIComponent(files[f]), {
      method: "DELETE",
      headers: {
        Authorization: 'Bearer ' + token
      }
    });

    // Wait for the previous import job to end
    Utilities.sleep(5000);

  }

}

please help me to rectify the error..
Thank you

A: Wrt Cloud SQL part, are you using the right project name and instance name in the googleapis url?
I see https://www.googleapis.com/sql/v1beta4/projects/PROJECT/instances/INSTANCE/import. You should replace PROJECT and INSTANCE with your own values.


text:
Q: Java multiple regular expression search I have a string some thing like this:
If message contains sensitive info like: {Password:123456, tmpPwd : tesgjadgj, TEMP_PASSWORD: kfnda}

My pattern should look for the particular words Password or tmpPwd or TEMP_PASSWORD.
How can I create a pattern for this kind of search?

A: I think you are looking for the values after these words. You need to set capturing groups to extract those values, e.g.
String content = "If message contains sensitive info like: {Password:123456, tmpPwd : tesgjadgj, TEMP_PASSWORD: kfnda} ";
Pattern p = Pattern.compile("\\{Password\\s*:\\s*([^,]+)\\s*,\\s*tmpPwd\\s*:\\s*([^,]+)\\s*,\\s*TEMP_PASSWORD:\\s*([^,]+)\\s*\\}");
Matcher m = p.matcher(content);
while (m.find()) {
  System.out.println(m.group(1) + ", " + m.group(2) + ", " + m.group(3));
}

See IDEONE demo
This will output 123456, tesgjadgj, kfnda.
To just find out if there are any of the substrings, use contains method:
System.out.println(content.contains("Password") ||
                       content.contains("tmpPwd") ||
                       content.contains("TEMP_PASSWORD"));

See another demo
And if you want a regex-solution for the keywords, here it is:
String str = "If message contains sensitive info like: {Password:123456, tmpPwd : tesgjadgj, TEMP_PASSWORD: kfnda} ";
Pattern ptrn = Pattern.compile("Password|tmpPwd|TEMP_PASSWORD");
Matcher m = ptrn.matcher(str);
while (m.find()) {
   System.out.println("Match found: " + m.group(0));
}

See Demo 3

A: Finally I am using it like as per my requirement .

private final static String censoredWords =
  "(?i)PASSWORD|pwd";

The (?i) makes it case-insensitive


text:
Q: Having trouble integrating $\int \int \frac{r\sin\theta \ln(1-r\cos\theta -r\sin\theta )}{r\cos\theta-\sqrt{r^2 }} r \,d\theta \,dr$ Im having trouble integrating this function.
$$\int_0^{0.5}\int_0^{\pi/4} \frac{r\sin\theta \ln(1-r\cos\theta -r\sin\theta )}{r\cos\theta-\sqrt{(r\cos\theta)^2+(r\sin\theta)^2 }} r \,d\theta \, dr$$
I can simplify this to:
$$\int_0^{0.5}\int_0^{\pi/4} \frac{r\sin\theta \ln(1-r\cos\theta -r\sin\theta )}{r\cos\theta-\sqrt{r^2 }} r \,d\theta \,dr$$
Im stuck on the integration.
Can anyone help me, thanks in advance

A: Keep simplifying, we get
$$ I = -\int_{0}^{\frac{1}{2}}\int_{0}^{\frac{\pi}{4}} r \cot\left(\frac{\theta}{2}\right) \log\left(1-r\sqrt{2}\sin\left(\theta+\frac{\pi}{4}\right)\right)\,d\theta\,dr$$
but $\cot\left(\frac{\theta}{2}\right)\sin\left(\theta+\frac{\pi}{4}\right) $ has a non-integrable singularity in a right neighbourhood of $\theta=0$, hence the above integral is simply not converging.


text:
Q: Apex Controllers: What do the get; set; do? I've built a few apex controllers, and like most people have copied some code from here and there. In the controllers, there's typically an expression that looks like the following:
public *var type* someName {get; set;}

Initially I thought I needed to supply a function to the get part if the VF page was grabbing data, something like so:
get = getData(); set;

public function string getData(){
    return 'data!';
}

And the opposite for set (if users were inputting data). But now I see my controllers work perfectly well just having the top expression as {get;set;}.
I've looked through the salesforce docs and I've read all the parts regarding creating custom controllers - I see the get; set; being referenced, but nowhere explaining what this part does and how I can use it.
Have you come across any docs on what this part does and how I can use it?
Thank you all!
Zac

A: This was answered on SF dev forums: Reg: Get and set Methods
That post linked to a great aticle on the behavior of the default get/set methods:
Getter and setter methods - What are they??

A: Visualforce requires a "getter" and "setter" to reference a variable in the controller or extension. Without a getter or setter, even public or global variables cannot be referenced in Visualforce expressions.
"get;" is basically: public *datatype* getVarName() { return varName; }
"set;" is basically: public void setVarName(*datatype* value) { varName = value; }
There are subtle differences though. For example, the function doesn't actually exist; it's called implicitly.
You can make variables read-only by not including set;, and you can make them write-only by not including get;.
Inside Apex Code, you can also use these to control readability and writeability.
For example:
public static Integer counter {
    get { if(counter == null) counter = 0; counter++; return counter; }
    private set; }

This counter increases by 1 each time it's used, but can't be set outside of the class that contains it.
public class OtherClass {
   public void someMethod() {
       System.debug(FirstClass.counter);
       System.debug(FirstClass.counter);
       FirstClass.counter = 10; // Compiler error
   }
}

Without the compiler error, it would debug 0, then 1.

A: public *var type* someName {
    get {
        // this block equals to:
        //     public *var type* getSomeName()

        // work with someName
        return someName;
    }
    set {
        // this block equals to:
        //     public void setSomeName(*var type* value)

        // work with value
        someName = value;
    }
}

A: This excerpt is taken from Learning Apex Programming, by Matt Kaufman.
In order for an Apex class to function as a controller for a Visualforce page, the
variables and methods in the class need to use the correct syntax. The variables in the
class are made accessible to the page through the use of getter and setter methods.
A getter method is a nonstatic method that has no input parameters and returns an
object. Visualforce pages use getter methods to get objects from your custom controller.
A setter method is a nonstatic method that has only one input parameter and does not
return anything. Visualforce pages use setter methods to set the value of an object in
your custom controller. Let's take a look at some getter and setter methods:
//First declare your variable
Account myAccount;
//Here is the getter
public Account getMyAccount(){

//We don't want to return a null value
if ( myAccount == null ){
myAccount = new Account();
}
return myAccount;
}
//Here is the setter
public void setMyAccount(Account a){
myAccount = a;
}

Pretty neat, right? Just by naming our method getX or setX and using the right
signature, they are automatically accessible by our Visualforce page. This just gets
better; our getter and setter are using a whole record and our page has access to all
of the fields on that record. We can even use a collection of records and have access
to all of the records in the collection and all of their fields. In fact, your getters and
setters can work with any object and your Visualforce page automatically has access
to all of the instance attributes and action methods on that object.
Getters and setters seem simple, but the previous example really seems like a lot
of code to just allow our Visualforce page to work with a single object. This is why
Apex also includes a shortcut for getters and setters called properties. A property
combines the instance of our variable with the getter and setter methods and greatly
reduces the amount of code you need to write. Take a look at the property equivalent
to the previous code block:
//Declare your property and you're done
Account myAccount {get;set;}

Yes, we are serious that one line of code replaces the variable and the getter and setter
methods. It really doesn't get more efficient than that! Now, if you've been paying
attention, you will see a flaw in our property. If our myAccount variable is null, our
Visualforce page can get a nasty error. Our getter took care of that possibility, but our
property does not. There are two options to get around this. Let's look at the first option:
//Declare your property with logic and you're done
Account myAccount {
get{
if ( myAccount == null ){
myAccount = new Account();
}
}
set;
}

In this property, we expanded the getter to include our logic. This combines the
getter method with the property concept. Although perfectly legitimate, the second
option is actually the most common one, and this is to set the value of your attributes
in your class' constructor, as shown in the following lines of code:
public class myCustomController{
//Here's our property
Account myAccount {get;set;}
//Here's our constructor
public myCustomController(){
myAccount = new Account();
}
}

The key to this code block is in knowing that constructors are called prior to getters.
This allows us to execute our code before the Visualforce page communicates with
our controller. This pattern of using properties and setting their initial state in the
constructor is very common and uses a lot less code. In fact, most classes used with
Visualforce have a whole list of properties at the top of the class.

A: What you are seeing with {get;set;} is an example of automatic properties.
From the Apex Documentation on Automatic Properties.

Properties do not require additional code in their get or set accessor
  code blocks. Instead, you can leave get and set accessor code blocks
  empty to define an automatic property. Automatic properties allow you
  to write more compact code that is easier to debug and maintain. They
  can be declared as read-only, read-write, or write-only. The following
  example creates three automatic properties:

Here is the example from the docs
public class AutomaticProperty {
   public integer MyReadOnlyProp { get; }
   public double MyReadWriteProp { get; set; }
   public string MyWriteOnlyProp { set; }
}

You could just as easily do something like this instead, but using the automatic properties saves a lot of time and coding.
public class nonAutomaticProperty {
   public integer MyReadOnlyProp {
        public get {return MyReadOnlyProp;}
        private set;
   }
   public double MyReadWriteProp {
        public get {return MyReadWriteProp;}
        public set;
   }
   public string MyWriteOnlyProp {
        private get {return MyWriteOnlyProp;}
        public set;
   }
}


text:
Q: Approaching Bayesian question with no prior Saw this question elsewhere online, couldn't quite get a grip on it:
"You have three friends, who tell the truth with probability 2/3 and lie with probability 1/3. You ask them independently if it is raining in your city, and they all say yes. What is the probability that it is raining?"
Now, if we have a prior for rain in our city this is a simple application of Bayes rule. But if we don't? I suspect it is then an ill posed/unsolvable problem, but one approach I considered was that the probability of them all lying is 1/27, so it should rain with probability 26/27. That doesn't seem right though.

A:
one approach I considered was that the probability of them all lying is 1/27, so it should rain with probability 26/27. That doesn't seem right though.

The reason that this doesn't work is that $1/27$ is your prior probability for them all to be lying. Once you've heard that they all say it's raining, then $1/27$ is no longer the correct number to use. In particular, the probability that they're all lying depends on your prior for wheather it's raining or not. If you initially think it's extremely unlikely to be raining (say $1:1\,000\,000$) then when they say it's raining you will think it's very unlikely that they're telling the truth. Conversely if you think it's very likely to be raining then you'll think it's very likely that they are telling the truth.
You do need your prior to answer the original question. Let $A$="they all say it's raining" and $B$="it rains" then $P(A|B)=8/27$ and $P(A|¬B)=1/27$ so (cancelling factors of 27) $$P(B|A)=\frac{8.P(B)}{8.P(B)+1.(1-P(B))}=\frac{8P(B)}{1+7P(B)}$$

A: Oscar's answer is mostly correct. Using the notation in his answer, i.e. $A$ = "they all say it's raining" and $B$ = "it rains", the Law of Total Probability gives us
$$
P(A) = P(A|B) * P(B) + P(A|\neg B) * (1- P(B)).
$$
The above probabilities $P(A|B) = 8/27$ and $P(A|\neg B) = 1/27$ are correct, allowing us to conclude
$$
P(A) = \left(\frac{8}{27}\right) * P(B) + \left(\frac{1}{27}\right) * (1-P(B)) = \frac{1 + 7 P(B)}{27}.
$$
The probability you want, $P(B|A)$ ("it is raining given that all three friends said 'yes'") is then
$$
P(B|A) = \frac{P(A|B) * P(B)}{P(A)} = \frac{\frac{8}{27} P(B)}{\frac{1 + 7P(B)}{27}} = \frac{8 P(B)}{1 + 7 P(B)}.
$$


text:
Q: Triangular Distribution in VBA What I currently have:
Option Explicit

Function Triangular(a As Double, b As Double, c As Double) As Double

Randomize
Application.Volatile

Dim d As Double
Dim uniform As Double
Dim retval as Double

d = (b - a) / (c - a)
    uniform = Rnd()

    If uniform <= d Then
    Triangular = a + (c - a) * Sqr(d * uniform)

Else

    Triangular = a + (c - a) * (1 - Sqr(1 - d) * (1 - uniform))

End If

End Function

I'm having trouble in  regards to creating a triangular distribution function in VBA, which calculates a random number from arguments made from:

*

*Calculate d = ( b - a )/( c - a )

*Generate a uniformly distributed random number U between 0 and 1 with VBA's Rnd function.

*If U <= d, return a + ( c - a ) × sqr(d×U) as the random number. (Sqr(x) is a VBA function which returns the square root of x.

*If U > d , return a + ( c - a ) × (1 - sqr((1- d )×(1-U))) as the random number.
The parameters a and c are the minimum and maximum possible values respectively, and
the parameter b is the most likely value (where you see the high point in the triangle).
I'm unsure on how to create this function and was wondering if someone could lend a hand? In working on the function I realize I need to use randomize function in order to not generate similar results each time the function is called, as well as the application.volatile operation.

A: You have a bug in the code. Should be in second branch
Triangular = a + (c - a) * (1 - Sqr((1 - d) * (1 - uniform)))

A: Not sure of the correctness of your generating equations. Take a look Here for the correct equations; with the difference that b and c are switched with respect to your definition. Here's an implementation adapting the formulas of that page to your own definitions of a, b and c:
Function Triangular(a As Double, b As Double, c As Double) As Double
    Application.Volatile
    Dim U As Double: U = Rnd()
    If U < (b - a) / (c - a) Then
      Triangular = a + sqrt(U * (b - a) * (c - a))
    Else
      Triangular = c - sqrt(U * (c - b) * (c - a))
    End If
End Function

To generate a sequence from the above distribution in a new Worksheet, you can
1- Create the new worksheet
2- Write your parameters in cells A1, B1 and C1
3- write this formula in A2:  =Triangular($A$1, $B$1, $C$1)
4-  Copy/Paste cell A2 down the column

A: Please notice (1-Prob) in the second case. The Wikipedia link shows the correct formula but it was not implemented correctly by A.S.H.
Function Triangular(ByVal Min As Single, ByVal ML As Single, ByVal Max As Single) As Single
    Application.Volatile
    Dim Prob As Single
    Prob = Rnd
    If Prob < (ML - Min) / (Max - Min) Then
      Triangular = Min + Sqr(Prob * (ML - Min) * (Max - Min))
    Else
      Triangular = Max - Sqr((1 - Prob) * (Max - ML) * (Max - Min))
    End If
End Function


text:
Q: Multiple instances of the same form field I have invite form with two fields defined as person and email as follows:
class InviteForm(Form):
    person = TextField("person", validators=[validators.Required("Please enter persons name.")])
    email =  EmailField("email", validators=[validators.Required("Please enter valid email."), validators.Email("Please enter valid email.")])

    def validate(self):
        return validate_form(self)

Where validate_form function is a cusotm validator which check few conditions for invite.
My requirement is to allow users to invite more than one person at a time. To achieve this I have added jquery function which replicates these fields in html form and allow to invite multiple people.
But the problem is in my view function when I extract results from post request it gives only first persons information. How can I get all the persons details. My view is defined as follows:
@app.route("/invite", methods=["GET", "POST"])
def invite():
   invite_form = InviteForm()
   if invite_form.validate_on_submit():
       print invite_form.person
       print invite_form.email

This gives only one field, instead of array of fields.
Is this possible with python wtf? How?

A: What you're looking for is FormField which lets you build a list of the WTF Fields (or groups even).
Here's a simple example-- it'll render three string fields as a html list because that's the minimum required.  If you want to add extras via javascript, then just adhere to the same naming scheme, in the case below, a fourth would have a name of person-3.
from flask import Flask, render_template_string
from flask.ext.wtf import Form
from wtforms import FieldList, StringField

app = Flask(__name__)
app.secret_key = 'TEST'

class TestForm(Form):
    person = FieldList(StringField('Person'), min_entries=3, max_entries=10)
    foo = StringField('Test')

@app.route('/', methods=['POST', 'GET'])
def example():
    form = TestForm()
    if form.validate_on_submit():
        print form.person.data
        ## [u'One', u'Two', u'Three']

    return render_template_string(
        """
            <form method="post" action="#">
            {{ form.hidden_tag() }}
            {{ form.person }}
            <input type="submit"/>
            </form>
        """, form=form)

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


text: Q: Memory error calculating Pearson correlation on huge dask.dataframe I have a huge dataset (9M rows * 125 cols) and I am trying to find a way to calculate the Pearson correlation for a variable vs rest. I receive memory error for this task. I tried dask as a solution as suggested in [enter link description here][1] but it did not work.


text:
Q: Fatal error: Call to a member function query() on null I'm not sure what's going wrong here. I was just following a tutorial online and these errors popped up.
I'm getting the following errors
Error
Notice: Undefined variable: db in C:\xampp\htdocs\wisconsindairyfarmers\admin\login.php on line 7

Fatal error: Call to a member function query() on null in C:\xampp\htdocs\wisconsindairyfarmers\admin\login.php on line 7

Code
<?php
$db = new mysqli('127.0.0.1', 'root', '', 'wisconsindairyfarmers');
?>

<?php
require '../db/connect.php';
require '../functions/general.php';

    function user_exists($username){
        //$username = sanitize($username);
        $result = $db->query("SELECT COUNT(UserId) FROM users WHERE UserName = '$username'");
        if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;
    }}

if(empty($_POST) === false){

    $username = $_POST['username'];
    $password = $_POST['password'];

    if(empty($username) === true || empty($password) === true){
        echo 'You need to enter a username and password';
    }
    else if(user_exists($username) === false) {
        echo 'We can\'t find that username.';
    }
}

?>

A: First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;

And I guess, when you wrote:
if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }

which is equivalent to:
return $result->num_rows == 1;

A: put this line in parent construct : $this->load->database();
function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..


text:
Q: SFMC Receiving dedicated IPAddress information from _JOB per JobID I'm trying to create a report to retrieve IPAddress from _Job table per each JobID using query but i comes back as NULL. According to SFMC information IPAddress is only available to users without dedicated IP addresses assigned which doesn't really make logical sense to me... Is there any other way I can create a report to see what IP addresses are used for each Job ID?
Thanks


text:
Q: Firebase REST api: orderBy 2 params Is it possible to order by 2 different params in firebase REST API and what's the correct api call should for that:
I need to get posts by userId and category. What's the correct endpoint should be for that?
 FIREBASE_URL/?orderBy="userId"&orderBy="category"&equalTo="${userId}"&equalTo=${category}`;

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": "true",
    ".write": "auth != null",
    "todos": {
      ".indexOn": ["category", "userId"]
    }
  }
}


text:
Q: How can i get the Parent in Binary tree How can i get the Parent in Binary tree in this code ?
I wrote this :
public class Node
{
    public string state;
    public Node Left;
    public Node Right;

    public Node (string s , Node L , Node R )
    {
        this.state = s;
        this.Right = R;
        this.Left = L;
    }

    public Node (string s)
    {
        this.state = s;
        this.Right = null;
        this.Left = null;
    }

}

And code this for tree of some data  :
1
2
Now , how can i get the parent of Node like ( new Node("22lltrk", null, null) )
what i need to add to my code and where ?
thanks .

A: Opt 1: add a parent link to your class
public class Node
{
    public string state;
    public Node Left;
    public Node Right;
    public Node Parent; // new

    public Node (string s , Node L , Node R )
    {
        this.state = s;
        this.Right = R;
        this.Right.Parent = this; // new
        this.Left = L;
        this.Left.Parent = this; // new
    }

    public Node (string s)
    {
        this.state = s;
        this.Right = null;
        this.Left = null;
        this.Parent = null; // new
    }
}

Opt 2: Tree traversal
Node FindParent(Node root, Node child)
{
   // Base Cases
   if(root.Left == null && root.Right == null)
    return null;

   if(root.Left == child || root.Right == child)
    return root;

   // Recursion
   var leftSearch = FindParent(root.Left, child);
   if (leftSearch != null)
       return leftSearch;

   return FindParent(root.Right, child);
}


text:
Q: Getting count of occurrences for X in string Im looking for a function like Pythons
"foobar, bar, foo".count("foo")

Could not find any functions that seemed able to do this, in a obvious way. Looking for a single function or something that is not completely overkill.

A: I think that right now the closest built-in thing to what you're after is the length of a split (minus 1). But it's not difficult to specifically create what you're after.
I could see a searchall being generally useful in Julia's Base, similar to matchall.  If you don't care about the actual indices, you could just use a counter instead of growing the idxs array.
function searchall(s, t; overlap::Bool=false)
    idxfcn = overlap ? first : last
    r = findnext(s, t, firstindex(t))
    idxs = typeof(r)[] # Or to only count: n = 0
    while r !== nothing
        push!(idxs, r) # n += 1
        r = findnext(s, t, idxfcn(r) + 1)
    end
    idxs # return n
end

A: Adding an answer to this which allows for interpolation:
julia> a = ", , ,";
julia> b = ",";
julia> length(collect(eachmatch(Regex(b), a)))
3

Actually, this solution breaks for some simple cases due to use of Regex. Instead one might find this useful:
"""
count_flags(s::String, flag::String)

counts the number of flags `flag` in string `s`.
"""
function count_flags(s::String, flag::String)
counter = 0
for i in 1:length(s)
  if occursin(flag, s)
    s = replace(s, flag=> "", count=1)
    counter+=1
  else
    break
  end
end
return counter
end

A: Julia-1.0 update:
For single-character count within a string (in general, any single-item count within an iterable), one can use Julia's count function:
julia> count(i->(i=='f'), "foobar, bar, foo")
2

(The first argument is a predicate that returns a ::Bool).
For the given example, the following one-liner should do:
julia> length(collect(eachmatch(r"foo", "bar foo baz foo")))
2

Julia-1.7 update:
Starting with Julia-1.7 Base.Fix2 can be used, through ==('f') below, as to shorten and sweeten the syntax:
julia> count(==('f'), "foobar, bar, foo")
2

A: What about regexp ?
julia> length(matchall(r"ba", "foobar, bar, foo"))
2

A: Sorry to post another answer instead of commenting previous one, but i've not managed how to deal with code blocks in comments :)
If you don't like regexps, maybe a tail recursive function like this one (using the search() base function as Matt suggests) :
function mycount(what::String, where::String)
  function mycountacc(what::String, where::String, acc::Int)
    res = search(where, what)
    res == 0:-1 ? acc : mycountacc(what, where[last(res) + 1:end], acc + 1)
  end
  what == "" ? 0 : mycountacc(what, where, 0)
end

A: This is simple and fast (and does not overflow the stack):
function mycount2(where::String, what::String)
    numfinds = 0
    starting = 1
    while true
        location = search(where, what, starting)
        isempty(location) && return numfinds
        numfinds += 1
        starting = location.stop + 1
    end
end

A: one liner: (Julia 1.3.1):
julia> sum([1 for i = eachmatch(r"foo", "foobar, bar, foo")])
2

A: Since Julia 1.3, there has been a count method that does exactly this.
  count(
      pattern::Union{AbstractChar,AbstractString,AbstractPattern},
      string::AbstractString;
      overlap::Bool = false,
  )

  Return the number of matches for pattern in string.
  This is equivalent to calling length(findall(pattern, string)) but more
  efficient.

  If overlap=true, the matching sequences are allowed to overlap indices in the
  original string, otherwise they must be from disjoint character ranges.

  │ Julia 1.3
  │
  │  This method requires at least Julia 1.3.

julia> count("foo", "foobar, bar, foo")
2

julia> count("ana", "bananarama")
1

julia> count("ana", "bananarama", overlap=true)
2


text:
Q: How to copy all files with a particular prefix to new directories with python? Suppose I have the following directory structure:
C:\Test
C:\Test\2009
C:\Test\2009\files\Artists
C:\Test\2009\files\Artists\SnoopDog
C:\Test\2009\files\Artists\SnoopDog\albums.txt
C:\Test\2009\files\Artists\SnoopDog\albums.jpg
C:\Test\2009\files\Artists\SnoopDog\hobbies.doc
C:\Test\2009\files\Artists\SmashMouth\albums.txt
C:\Test\2009\files\Artists\SmashMouth\hobbies.doc
C:\Test\2010\files\Artists\SnoopDog\albums.txt
C:\Test\2010\files\Artists\SnoopDog\albums.jpg
C:\Test\2010\files\Artists\SnoopDog\hobbies.doc

The following is the directory structure I want as a goal:
C:\ToDirectory\
C:\ToDirectory\2009\albums\SnoopDog_albums.txt
C:\ToDirectory\2009\albums\SnoopDog_albums.jpg
C:\ToDirectory\2009\albums\SmashMouth_albums.txt
C:\ToDirectory\2009\albums\SmashMouth_albums.jpg
C:\ToDirectory\2009\hobbies\SmashMouth_hobbies.doc
C:\ToDirectory\2009\hobbies\SnoopDog_hobbies.doc
C:\ToDirectory\2010\albums\SnoopDog_albums.txt
C:\ToDirectory\2010\albums\SnoopDog_albums.jpg

Assuming C:\Test contains all the files and C:\ToDirectory starts off as being an empty directory.
What is the most efficient way to have a function where I simply give its source directory C:\Test and a target directory ToDirectory and the script goes to the lowest level of C:\Test, goes through each file in the directory and checks whether the filename (ignoring extension) is a durectiry in the ToDirectory structure, if not, create it and copy the file into it with the parent directory appended at the beginning of its name with python?
I am using os.listdir and os.isdir in a series of nexted loops, but it appears to be very lengthy and though it does it job, appears inefficient...

A: You can achieve shorter code using recursion instead of nesting loops explicitly.
Recursion is not always more efficient but your code will look a lot better!.

A: try pythons high level file operations library ( import shutil )
Also consider using pythons excellent directory walking function ( from os import walk )
You shouldn't need to copy the files but just rename the directories and filenames.


text:
Q: Trying to iterate through a returned list of addresses, select one and submit to next php file having a bit of trouble with this one.
This is part of a SOAP WSDL API system.
I send the SOAP API a street address and it looks it up and returns me a WSDL listing of valid addresses. I should be able to click on the correct result and then submit that to my 2nd php file to further process and send to the SOAP API.
I get something back like this (should have multiple addresses back, but it's a testing environment, so only ever get this address. In live platform, I will get multiple addresses back).
<?xml version="1.0" encoding="ISO-8859-1"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <FindServiceProviderLocationIdResponse xmlns="http://www.aapt.com.au/FrontierLink/xsd">
      <serviceProviderLocationList>
        <serviceProviderLocationList>
          <serviceProvider>NBN</serviceProvider>
          <locationList>
            <addressInformation>
              <serviceProvider>NBN</serviceProvider>
              <locationId>LOC000000000002</locationId>
              <address>
                <streetNumber>6</streetNumber>
                <streetName>TEST</streetName>
                <streetType>STREET</streetType>
                <suburb>GLEBE</suburb>
                <state>NSW</state>
                <postcode>2037</postcode>
              </address>
              <displayAddress>6 TEST ST GLEBE NSW 2037</displayAddress>
            </addressInformation>
          </locationList>
        </serviceProviderLocationList>
      </serviceProviderLocationList>
    </FindServiceProviderLocationIdResponse>
  </soapenv:Body>
</soapenv:Envelope>

part of my PHP code that should iterate through these results and give me a list of links for the user to click on the correct address (thus submitted to the next php file for processing is).
//Display a list of address options to the user
echo '
Please select a location from the list
';

//Squirt out the address list for the user to pick from
foreach($locidRes as $l){
    echo ''.$l['displayAddress'].'
';
};

//When the user selects a location ID from the list, we then submit that to the next file -> qualify.php

echo '
';
echo json_encode($locidRes);

I am however getting this error
Please select a location from the list
Fatal error: Uncaught Error: Cannot use object of type stdClass as array in /var/www/html/getLocationId.php:70 Stack trace: #0 {main} thrown in /var/www/html/getLocationId.php on line 70
Thanks in advance,
Steve


text:
Q: The sum $\sum_{r=0}^{20}r(20-r)\binom{20}{r}^2$
Find the value of: $$\displaystyle \sum_{r=0}^{20}r(20-r)\dbinom{20}{r}^2$$

Attempt:
Using, $\dbinom{n}{r}= \dfrac n r \dbinom{n-1}{r-1}$, I get $400\sum_{r=0}^{20}\left(\dbinom {19} r \dbinom{19}{r-1}\right)$
What do I do next? I tried to use $\dbinom n r +\dbinom n {r-1}= \dbinom{n+1}{r}$ but that didn't help. Also, I know that the sum of square of binomial coefficients is $\dbinom {2n}{n}$ and the Vandermonde's identity is $\dbinom{n+m}{r}= \sum _{k=0}^r \dbinom m k \dbinom n {r-k}$.

A: Hint: Write the sum as $$\sum_{r=0}^{20}\left(r\binom{20}{r}\right)\cdot\left((20-r)\binom{20}{20-r}\right) = \sum_{r = 0}^{20}a_ra_{20-r},$$
where $a_r = r\binom{20}{r}.$ This is the coefficient of $x^{20}$ in the expansion of $$\left(\sum_{r=0}^{20}a_rx^r\right)^2.$$

A: $$\sum_{r=0}^{20} r(20-r)\binom {20}{r} ^2=20\sum_{r=0}^{20} r\binom {20}{r} ^2- \sum_{r=0}^{20} r^2\binom {20}{r} ^2=400\sum_{r=1}^{20} \binom {19}{r-1}\binom {20}{20-r} - 400\sum_{r=1}^{20} \binom {19}{r-1}\binom {19}{19-(r-1)}$$
Hence by Vandermonde's identity we get $$400\left(\sum_{r=1}^{20} \binom {19}{r-1}\binom {20}{20-r} - \sum_{r=1}^{20} \binom {19}{r-1}\binom {19}{19-(r-1)}\right) =400\left(\binom {39}{19}- \binom {38}{19}\right) $$
Now by Pascal's rule $$400\left(\binom {39}{19}- \binom {38}{19}\right) =400\binom {38}{18}$$
Alternatively you can reach answer by your way too
$$400\sum_{\color{red}{r=1}}^{\color{red}{19}} \binom {19}{r}\binom {19}{20-r}$$
Hence by using Vandermonde's identity we get $$400\sum_{r=1}^{19} \binom {19}{r}\binom {19}{20-r}=400\binom {38}{20}=400\binom {38}{18}$$