text:
Q: Cannot compile GDB7.8 with Python support I am trying to install GDB7.8 with Python support. From the source folder, I am running ./configure --with-python
When I did tab-complete from --with- I did not see Python in the list.
But when I ran configure with that flag, it did not baulk.
When I run make, it complains that Python is not found.
checking for python2.7... no

but Python is installed:
 $ which python
python                python2.7             python2.7-dbg-config
python2               python2.7-dbg

$ which python2.7
/usr/bin/python2.7

I compiled GDB without --with-python
and things installed without error. I was under the impression that GDB7.8 had Python support without the need for special flags. But when I run:
$gdb python
(gdb) run test.py

I get some sort of cannot import gdb Import error
So then I tried calling "pi":
(gdb) pi printf.py
Python scripting is not supported in this copy of GDB.

So... how do I get Python support in GDB7.8? is it actually not supported? Or should I not call "pi"?

A: With benefit of Peter Schaeffer's excellent answer, I was able to build & install GDB 8.3.1 with Python 3.6, from source.  The critical insight was that the LDFLAGS and LIBS which ./configure accepts are different from the LDFLAGS and LIBS which make requires.  Yes they should be same, but in this case they were not.

Pre-requisite Steps

*

*install python3 package

*install python3-devel package

*install texinfo package

*run /usr/bin/python3.6-config --includes; that printed (twice!)
-I/usr/include/python3.6m

*run /usr/bin/python3.6-config --ldflags; that printed
-L/usr/lib64 -lpython3.6m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic

*run /usr/bin/python3.6-config --libs; that printed
-lpython3.6m -lpthread -ldl -lutil -lm

*find the real path of "python3" binary, by running readlink --canonicalize-existing $(which python3); that printed
/usr/bin/python3.6

Build Steps
export CFLAGS="-I/usr/include/python3.6m"
export LDFLAGS="-L/usr/lib64"
export LIBS="-lpython3"

readonly configureOptions="\
--disable-ada \
--disable-cloog-version-check \
--disable-gdbmi \
--disable-host-shared \
--disable-isl-version-check \
--disable-libssp \
--disable-libquadmath \
--disable-libquadmath-support \
--disable-objc-gc \
--disable-source-highlight \
--disable-stage1-checking \
--disable-static-libjava \
--disable-tui \
--disable-werror \
--enable-stage1-languages=c,c++ \
--enable-vtable-verify \
--with-python=/usr/bin/python3.6 \
--with-static-standard-libraries \
--with-system-zlib \
--without-cloog \
--without-guile \
--without-isl \
--without-mpfr \
"
./configure $configureOptions

export LDFLAGS="-L/usr/lib64 -lpthread -ldl -lutil -lm -Xlinker -export-dynamic"
export LIBS="-lpython3.6m -lpthread -ldl -lutil -lm"

make

make install

A: I spent quite a bit of time working on getting gdb (7.9) to work with Python (2.7). In the end everything worked rather well. However, there are a bunch of things that you have to get right. The key point is that the gdb configure script tries to compile a small C program that looks like this.
#include "Python.h"
int
main ()
{
Py_Initialize ();
  ;
  return 0;
}

If this program won't compile, then Python support won't be built. For this program to compile, the Python.h include file must be found in /usr/include/python2.7. This file will only exist if the python-devel package is installed. On my system (redhat), the command for installing this package is sudo yum install python-devel.
However, that's not enough to get Python installed. Before the configure script tries to compile the C program, it gets various options from python-config.py. If these options aren't correct, then the C program won't compile. On my system, python-config.py returned the options below.
-lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic

These options didn't cause any problems in my environment. Other folks have had problems with the options returned from python-config.py and have made changes to python-config.py to resolve these problems. On my system the complete compile command was
gcc -o conftest -g -O2   -I/usr/include/python2.7 -I/usr/include/python2.7 \
    conftest.c -ldl -lncurses -lz -lm -ldl    -lpthread -ldl -lutil -lm \
    -lpython2.7 -Xlinker -export-dynamic

This compile command completed without any errors as soon as I installed python-devel. Note you don't have to manually enter the gcc command. I did run the gcc command several times to make sure everything was correct. Normally, the configure script will run the
compiler for you. Also note that to get the overall gdb install process to complete, makeinfo also had to be installed. The command for installing makeinfo was sudo yum install texinfo.
Overall, the correct set of steps seems to be

*

*Install python-devel

*Install texinfo

*Download the gdb source and gunzip it and untar it.

*cd to the gdb-7.9 directory with the configure file.

*
./configure --prefix=/usr --with-python
make
sudo make install

It should be possible to get gdb to work with Python 3. The various gdb scripts and install programs mention Python 3 in many, many places. However, the correct procedure for installing gdb with Python 3 is unknown to me at this point.


text:
Q: Popover keeps presenting modally I'm trying to add a popover when an image is tapped but it keeps being presented modally. Every answer to this question/ topic suggest to add adaptivePresentationStyleForPresentationController but it won't work for me. I'm trying to do this on an iPhone. Here's my code:
class ParkingInfoTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate {
    ...
    func presentPopover(sender:UITapGestureRecognizer) {
    let storyboard : UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
    let infoViewController = storyboard.instantiateViewControllerWithIdentifier("ImagesInfoPopupViewController")
    infoViewController.modalPresentationStyle = .Popover
    infoViewController.preferredContentSize = CGSizeMake(150, 75)

    let popoverPresentationViewController = infoViewController.popoverPresentationController
    popoverPresentationViewController?.permittedArrowDirections = .Any
    popoverPresentationController?.delegate = self
    popoverPresentationViewController?.sourceView = sender.view
    popoverPresentationViewController?.sourceRect = CGRect(
        x: sender.locationInView(sender.view).x,
        y: sender.locationInView(sender.view).y,
        width: 1,
        height: 1)

    self.presentViewController(infoViewController, animated: true, completion: nil)

}

func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
    return .None
}

The cell with the image is:
        let cell = tableView.dequeueReusableCellWithIdentifier(AppConstants.moreInfoCellReusableIdentifier) as! MoreInfoTableViewCell

        let tapped = UITapGestureRecognizer(target: self, action: #selector(presentPopover))
        tapped.numberOfTapsRequired = 1
        cell.securityImage.addGestureRecognizer(tapped)
        cell.securityImage.userInteractionEnabled = true

        return cell

A: The following is for a Swift 3 (Xcode 8) solution
I faced this problem when migrating from Swift 2.2 (Xcode 7) to Swift 3 (Xcode 8).
For the UIPopoverPresentationControllerDelegate I implemented both below:
public func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
    return .none
}

public func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    return .none
}

While preparing for the segue I did the following in prepare(for segue...):
let popover = segue.destination
popover.popoverPresentationController?.delegate = self
popover.modalPresentationStyle = .popover

Assuming that you have a class for your popover controller, in viewDidLoad() you can replicate the following:
super.viewDidLoad()
...
self.preferredContentSize = CGSize(width: 123, height: 456)

And finally, my segue that is defined in the storyboard is configured as the following:

*

*Kind: Present As Popover

*Anchor: A Button Bar Item (will vary for your implementation)

*Directions: All checked by default

A: Also add:
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle{
    return .None
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: java general question about interfaces considering i have a method which gets a List passed as an param. Within this method i want to use for instance an ArrayList specific function on that list (lets say trimToSize()). What would be the general approach to deal with a problem like this ?
Here two example:
 First approach (i don't think this is good)
private void doSomething(final List<T> list) {
  // ... do something
  ((ArrayList<T>) list).trimToSize();
  // ... do something
}

Second approach (i think this one is better)
private void doSomething2(final List<T> list) {
final List<T> myList = new ArrayList<T>();
// Collections.copy(myList, list); or
myList.addAll(list);
((ArrayList<T>) myList).trimToSize();
//..do something
}

I'm curious whats the best solution for a problem like this.

A: Why not just declare method as a private void doSomething(final ArrayList<T> list), if you want only ArrayList as parameter?

A: If you're accepting any object implementing the List interface then your function should only invoke methods implemented from the interface.
If you want to invoke functions from ArrayList class then have ArrayList as your parameter. Much safer than either of your options.

A: The second we have huge overhead with big lists, but is safer. I would go for the first, but with check whether the provided List is ArrayList and then make a cast.
You should have a strong reasons to not take an ArrayList as a parameter though.

A: The first option you've shown only works for ArrayLists so it's not an option if you want to support any type of List. If you want to support any type of List you must convert (not cast) it to an ArrayList.
I think there might be some confusion because the List and ArrayList are so closely related (by inheritance). It is only coincidence that the parameter type and the class we need to call the function on are related in this way.
If we abstract the requirements a bit:

*

*We need to act on a series of values

*We need to use trimToSize() on the
series of values.

If the values were coming as an array there would be no question but to create a new ArrayList with the values from the array and then use trimToSize(), because casting would not be an option. It is just bad luck that the method we need trimToSize() happens to be on a subclass of List, and the author wants to pass the values as a List.

A: What about
private void doSomething(final List<T> list) {
    final ArrayList<T> arrayList;
    if (list instanceof ArrayList) {
        arrayList = (ArrayList<T>) list;
    } else {
        arrayList = new ArrayList<T>(list);
    }
            ...
    arrayList.trimToSize();
}

Of course, I agree with Chinmay Kanchi: for a private method, it makes no sense to accept a more general type than necessary. My approach is only feasible if it causes no problems to modify the given list.

A: Well, the preferred option is to just write the method to take an ArrayList in the first place. If you need ArrayList specific functionality, the method has no business taking a List. Transfer the responsibility of ensuring that the parameter is of the right type to the caller and don't fiddle around with it inside the method.

A: Your first method changes the List passed to the method while the other one doesn't. Two methods are not comparable.

A: Since it is a private method, the convention of using the List interface is not overly important.  There is no public API affected so use whichever method is the most convenient for its usage in the class.
For example, if 5 other methods call this method with potentially varying types of List, then use your second option and centralize the conversion in 1 method (you can even throw in a check for type and not convert if you like).  If your class only deals with ArrayList internally anyway, and you know that is what it will be when called, then declare it as a ArrayList and make your life easy for yourself.


text:
Q: Cran-R can't find jvm.dll when issuing command library(rJava) My Cran-R x64 3.3.4 was working fine. However recently, I installed a the latest version of Java because another program required it (Interactive Brokers TWS). Now when I run R and want to load rJava or xlsx I get an error message that jvm.dll can't be found.  TWS runs fine, but apparently R is unhappy. I looked at my PATH variable and found PATH=C:\ProgramData\Oracle\Java\javapath which when I looked at line in the directory has   javapath_target_25729042.
Other posts on Stack Overflow recommend changing  the PATH environment to include the path to jvm.dll. Doesn't this conflict with what the Oracle installation of Java and also that one is hard coding an environmental variable which can cause problems later on? (such as installing a new version of Java)  An uninstall of Java later on might not remove the hard coding, so leaving the path pointing to something wrong.
So the basic question is: What is the correct way to point to the jvm.dll file?
Quite frankly, I'm, rather tired that each time I update Java, there are problems pointing to jvm.dll. I've had similar problems with Eclipse not finding jvm.dll too after a new install.

A: I suggest to reconfigure R using  R CMD javareconf and then, installing rJava from sources.
> install.packages("rJava", type="source")


text:
Q: GGRidges: single density plot too high I have a data frame which is made of one single dependent variable and multiple independent variables. Groups of relationships were taken from different tests (but this is not important to solve the problem that I met).
I'm using the package ggridges to represent one graph with density plots for each relationship. When there is only one value for one relationship, ggridges produce a point instead of a density plot. My issue is that in that case the density plot below overlaps with the space above. Probably because ggridges does not see another density plot and expands the space that the density plot below can take.
The option "scale" can be used to avoid the overlap of two density plots but not to avoid the overlap between a density plot and a point (at least I think so).
If I set scale = 0.5, I can solve the problem but this is not the best thing to do because each density plot becomes smaller. Also those ones that do not overlap with others.
Below I attached a reproducible example that produces a graph with the problem I met.
Thanks to anyone could help me.
library(magrittr)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(forcats)
library(ggplot2)
library(ggridges)
library(RCurl)
#> Carico il pacchetto richiesto: bitops

y_ex <- c("y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1","y1")
x_ex <- c("x1","x1","x2","x3","x3","x3","x3","x3","x3","x4","x4","x4","x5","x5","x5","x5","x5","x5","x5","x5","x5","x5","x5")
value_ex <- c(0.26,0.40,0.47,0.72,0.71,0.69,0.74,0.73,0.24,0.39,0.43,0.46,0.21,0.18,0.14,0.10,0.16,-0.10,-0.11,0.56,0.50,0.49,0.43)

data_ex <- data.frame(y_ex,x_ex,value_ex)

r_ex <- data_ex %>%
  dplyr::mutate(x_ex = forcats::fct_reorder(x_ex, desc(value_ex), fun = mean))

r_ex %>%
  ggplot(aes(x = value_ex, y = x_ex)) +
  ggtitle(paste0("Predictors of ",y_ex)) +
  geom_density_ridges(fill = "royalblue",
                      scale = 0.9,
                      color = NA,
                      alpha = 0.7,
                      rel_min_height = 0.01) +
  geom_point(size = 0.5, alpha = 0.5, pch = 16) +
  geom_point(data = r_ex %>% group_by(x_ex) %>% dplyr::summarise(value_ex = mean(value_ex)),
             color = "firebrick",
             pch = 16,
             alpha = 0.5) +
  scale_y_discrete("") +
  scale_x_continuous("", limits = c(0, 1)) +
  theme_grey(base_size = 16, base_family = "serif") +
  theme(plot.title = element_text(hjust = 0.5,
                                  lineheight = .8,
                                  face = "bold",
                                  margin = margin(10, 0, 20, 0),
                                  color = "gray15"),
        legend.position = "none")
#> Picking joint bandwidth of 0.0453
#> Warning: Removed 2 rows containing non-finite values (stat_density_ridges).
#> Warning: Removed 2 rows containing missing values (geom_point).`

A: What is happening is that the scaling heuristic is getting confused by the missing data. The scaling heuristic takes the total range of baseline y values and divides it by the number of groups - 1, see here.
In your case, the scaling heuristic produces a reference scale that is exactly a factor 2 too large, and hence you should use scale = 0.45 to get the same effect you would be getting with scale = 0.9 if there weren't any missing levels.
Note that all areas need to be scaled together, because the areas under the distributions need to be of the same size (1 in some units). Your x5 distributions are not as tall because they are bimodal and hence much wider.


text:
Q: Heroku deployment error: failed to push some refs to Front-end react based app.
I initialized a git repo to github, used git a . to add everything, git commit -m "", then git push to push everything to my repo.
Then I used heroku create to create a heroku app which worked
However, when I try to push it all to heroku app with git push heroku master I get this error: error: failed to push some refs to 'https://git.heroku.com/todo-bja.git'
I've done this process before without any errors so am I missing something? (Using a webpack that includes Procile and everything needed.)


text:
Q: Trying to understand what's happening over key=lambda x: (count[x], -x)? I am trying to understand what key=lambda x: (count[x], -x) meaning in this function.

def frequencySort(self, nums: List[int]) -> List[int]:
        count = collections.Counter(nums)
        return sorted(nums, key=lambda x: (count[x], -x))

A:
The sort key is a tuple, (count[x], -x). count[x] is the frequency of x. -x is the negated value for x. So this will sort the values first by their frequency, and if the frequencies are the same, then by their negative values - i.e reverse order == larger values come before smaller ones

-- comment by rdas (with minor corrections)


text:
Q: Restart Docker Compose with update to database I've been working with a simple MySQL table using Docker Compose that only included ID and NAME column.  I attempted to update my myDb.sql file that initially creates the table like this:
CREATE TABLE `Person` (
  `id` int(11) NOT NULL,
  `firstName` varchar(50) NOT NULL, // updated this column
  `lastName` varchar(50) NOT NULL  // added this column
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I updated the NAME column to firstName, and added a lastName column.
I then stopped the Docker containers by running DOCKER-COMPOSE STOP.
I then restarted the Docker containers by running DOCKER-COMPOSE UP.  I even tried DOCKER-COMPOSE RESTART.
The error message I was able to print in the console was this:
SELECT '', id, `firstName` From Person<br>Unknown column 'firstName' in 'field list'

This leads me to believe that I did not restart Docker Compose correctly.
How do I restart Docker Compose so that it runs the CREATE TABLE command?
Edit
Here is my docker-compose.yml file:
version: "3.7"
services:
www:
    build: .
    ports:
        - "8001:80"
    volumes:
        - ./www:/var/www/html/
    links:
        - db
    networks:
        - default
db:
    image: mysql:5.7.13
    ports:
        - "3306:3306"
    environment:
        MYSQL_DATABASE: myDb
        MYSQL_USER: user
        MYSQL_PASSWORD: test
        MYSQL_ROOT_PASSWORD: test
    volumes:
        - ./dump:/docker-entrypoint-initdb.d
        - persistent:/var/lib/mysql
    networks:
        - default
phpmyadmin:
    image: phpmyadmin/phpmyadmin
    links:
        - db:db
    ports:
        - 8000:80
    environment:
        MYSQL_USER: user
        MYSQL_PASSWORD: test
        MYSQL_ROOT_PASSWORD: test
volumes:
    persistent:

My Dockerfile looks like this:
FROM php:7.0.30-apache
RUN docker-php-ext-install mysqli

A: Do docker-compose down whenever you update your schema, it will remove containers and docker network and do docker-compose up to bring your environment with your new schema. Hope it helps. If not, try updating to latest mysql image, the image you are using is almost 3 years old.

A: The docker-entrypoint-initdb.d mechanism only runs the first time a database container starts up, with an empty database.  You'll need to explicitly docker-compose rm your containers after you docker-compose stop them to cause the current database to be deleted, and then a new empty table will be created in a new empty database.
If you need to preserve the data in an existing database, you are looking for a mechanism called a migration.  The various Docker database images don't directly have migration support; this is almost always something that is packaged with your application-level database library (Ruby on Rails and Python's SQLAlchemy both have migration facilities, for instance).
Once you have a migration system anyways, it's probably better to just use that to create the initial database tables.  docker-entrypoint-initdb.d makes a little more sense for database-level setup like creating initial users or loading a seed database dump, but in practice you will always need a migration system for changes like what you're describing.

A: So I was thinking that restarting docker-compose would automatically run the CREATE TABLE query in the myDb.sql file.  As indicated above, I changed the name of 'name' column to 'firstName' and added a column called 'lastName'.
Again, I am not sure if there was a command that actually does this, but in the end, I was able to alter the table in phpmyadmin.  Once I altered the table there, now I am getting data back to the page with no errors.


text:
Q: What is a .backup format? Some time ago i was working on a database made in Postgresql, i learned to make backups by exporting the database to a .sql file, but i recently found a .backup file with the name of the database that i was working on at that time and i don't know how to restore the database from that file since Postgresql throw me an error when i try to restore the database. Anyone know anything about this format and how to restore anything in it?

A: Typically, Postgres backups are little more than large SQL scripts that are gzipped. You may want to see if you can "gzcat" the file and get any sanity out of it.

A: Postgres does have a "custom" format produced by pg_dump -Fc. Try doing pg_restore -l <filename> and see if it lists the file's contents.


text:
Q: How to pass values through a WCF Service in a ASP.NET Website I am working on a Outlook Addin for our Website. I want to pass the selected date, time and subject from outlook calender to our website which loads in a webcontrol inside Outlook. The Webservice is WCF.
I can transfer the calender values to WCF like this:
 [OperationContract]
string getBookingURL(string guid, BookingRequest request,string token,string exitURL);

BookingRequest is the class where i pass the calender values:
[ServiceContract]
public class BookingRequest
{
    public long bookingID { get; set; }
    public DateTime startUTC { get; set; }
    public DateTime endUTC { get; set; }
    public string subject { get; set; }
    public int numParticipants { get; set; }
}

now the next step would be something like this on my asp.net Website:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

if (BookingRequest!=Null) then
FromDateTextfield.Text = BookingRequest.startUTC
ToDateTextfileld.Text = BookingRequest.EndUTC
SubjectTextfield.Text = BookingRequest.subject
End If

End Sub

The problem is that I don't know how to pass the Values from WCF to the Webpage on load.
Maybe there is a solution without WCF.
Could you help me to solve this problem?

A: i am assuming that you have created proxy class on client side. so using the object you can call service using proxy object. as bellow:
 ProxyServClient client = new ProxyServClient();
 BookingRequest bookingrequest = client.GetBookingDetails();
 if(BookingRequest!=Null)
  {
    FromDateTextfield.Text = BookingRequest.startUTC;
    ToDateTextfileld.Text = BookingRequest.EndUTC;
    SubjectTextfield.Text = BookingRequest.subject;
  }

for this you have to create Booking request property class which has properties as your service is going to return.


text:
Q: JSOUP parsing two table I have parsed the first table but I don't know how to parse the second table.

Arrivi

        Ultimo aggiornamento: 17/04/2014 10:12

            Compagnia
            N.
            Provenienza
            Schedulato
            Stimato
            Stato

                RYANAIR
                03071
                Londra Stansted
                17/04/2014 12:40
                17/04/2014 12:32

 In orario

                RYANAIR
                04075
                Kaunas
                17/04/2014 16:10
                17/04/2014 16:10

 In orario

                RYANAIR
                07316
                Dublino
                17/04/2014 20:45
                17/04/2014 20:45

 In orario

Partenze

        Ultimo aggiornamento: 17/04/2014 10:12

            Compagnia
            N.
            Destinazione
            Schedulato
            Stimato
            Stato

                RYANAIR
                03074
                Londra Stansted
                17/04/2014 13:05
                17/04/2014 13:05

 In orario

                RYANAIR
                04076
                Kaunas
                17/04/2014 16:35
                17/04/2014 16:35

 In orario

                RYANAIR
                07317
                Dublino
                17/04/2014 21:10
                17/04/2014 21:10

 In orario

The first table parsed with:
org.jsoup.nodes.Document doc = Jsoup.connect("http://site.eu").timeout(7*1000).get();

org.jsoup.nodes.Element tabella = doc.getElementsByClass("tabella-voli").first();
Iterator<org.jsoup.nodes.Element> iterator = tabella.select("td").iterator();

while(iterator.hasNext()){

Can you help me with parsing ONLY the second table? I want only td elements.

A: You can instantiate an Elements class instead on directly invoque "first()" on it.
Then you will be able to parse the table you wish with the "get(int)" method:
Elements tables = currentServerPage.getElementsByClass("tabella-voli");
Element secondTable = tables.get(1);
Elements tdElements = currentServerPage.getElementsByTag("td");

Then you'll get a list of Elements, containing all the "td" in the second table.


text:
Q: Linux all files of folder modified yesterday I have modified some files present in various folders in my webroot. This was development environment. Now I have to find all files modified yesterday to migrate to productions.
Is there any way (Linux command) to list only those files modified yesterday in my webroot tree?

A: find . -mtime +2 -prune -o -mtime +1 -print

This does a find but excludes anything that was modified more than two days ago, then finds anything that was modified more than one day ago.

A: find ./ -mtime -1
Finds everything, what was modified in the current directory at the last 24 hours.

A: find . -daystart -mtime 1 -print

This gets just files modified YESTERDAY - ie: today is Jun 21, only files for Jun 20 are found.
(-mtime takes a '-', a '+', or an explicit number of exact days).
If you want a long listing, substitute
-exec ls -ld \;

for the
-print.


text:
Q: My CSS files are not responding for my Django Project. How am I suppose to make it work? base.html file
{% load static %}
<!DOCTYPE html>

<html lang="en">
<head>

    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
    <link href="https://fonts.googleapis.com/css
    family=Tangerine:bold,bolditalic|Inconsolata:italic|Droid+Sans" rel="stylesheet" type="text/css">
    <link rel="stylesheet"
     href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="{% static'css/blog.css'%}">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css"
     integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
     crossorigin="anonymous">
    <link href=" https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet">

    <link rel="stylesheet" href="{% static'css/zenburn.css' %}">

</head>

Setting.py #
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

I have looked at all the solutions on the stack overflow. But none of them able to solve the issue  I have added {% load static %} on the base.html and also add the code on setting.py. I do not know what else I can do?

A: I had the same problem and I don't know what causes it. But what I did was:

*

*Turned off my local server and restarted it.

*Then I went back to my page and did a hard refresh by pressing Ctrl+Shift+R

*If it didn't work the first time then I gave a hard refresh again and it worked that time.

I tried using hard refresh only but that doesn't work for some reason. You have to restart your server and turn it back on and hard refresh it. And it's not only for CSS it's for any static file. It just doesn't work for some reason and whenever I want to see the changes that I made I have to do all these steps.
But for some reason this problem does not occur in Firefox. So you can try opening your site on Firefox and see if it works.


text:
Q: BASH how do I check if numeric permissions passed as argument are a valid combination? I have a script that reads a set of numeric file permissions as argument it works like this:
$ bash script 755
This will give 755 permissions to some file on the disk. I want to know how to check if the number passed as parameter contains a valid set of permissions. Any ideas?
thanks

A: You can use this regex:

[0-7]{3}

https://regex101.com/r/bQ8jB6/1

if you prefer:

^[0-7]{3}$

https://regex101.com/r/bQ8jB6/2

A: chmod returns an error code and visible error text to the shell if you pass chmod invalid permissions, e.g.,
> chmod 788 some/file
chmod: Invalid file mode: 788
so
chmod $1 some/file || <handle the error>

in your script will either chmod successfully, or else handle the error however you like.
Or, more verbosely:
chmod $1 some/file
if [ $? != 0 ]; then
    <handle the error>
fi

If, for some unexplained reason you, prefer a pure regex answer before attempting to chmod, a modified version of @siete.sh's will work, e.g.,
[[ "$1" =~ ^[0-7]{3}$ ]] && chmod $1 some/file
or, since 1 to 5 digits are all valid arguments to chmod:
[[ "$1" =~ ^[0-7]{1,5}$ ]] && chmod $1 some/file


text:
Q: Is it possible to write an Eslint plugin to check if a required file exist? We use Eslint to check our javascript projects, it works great, but we have some special requirements like checking if a required file existed or not, e.g. .gitignore.
I tried to write a custom eslint plugin, but can't get an idea: seems like eslint can only check the AST of the code, but not the files themselves.
Does eslint provide any API that I can get all the files of the project and I can have a check?

A: No, ESLint doesn't provide any APIs dealing with files. ESLint is JavaScript static analysis tool, and as such doesn't really deal with file system. However, ESLint rules are just JavaScript, so you can execute arbitrary code in it. You can take a look at eslint-plugin-import which already does what you are looking for.


text:
Q: What do these old symbols from set theory mean? (Large E, $\cdot$ and $+$ for sets, and $\ \bar{\!\bar X}\,non\!\geqslant\frak n$) So, I'm trying to prove the theorems in this paper by Tarski:
On Well-ordered Subsets of any Set, Fundamenta Mathematicae, vol.32 (1939), pp.176-183
but it is from 1939, and I don't recognize a few of the notations from a modern set-theory perspective. Here are the relevant snippets.
The big-E notation, and set multiplication: (I'm okay with using subtraction to denote set complement.)

More set multiplication, and addition with a singleton:

And the double overbar, fraktur script, and "non" before an inequality: (I assume the double overbar means cardinality, and the fraktur $\frak n$ refers to a cardinal number, although I'm not sure if these cardinals are initial ordinals or the ZF variety using the rank-minimal elements of an equipotence class.)

A: I would be very surprised if the Fraktur cardinals are intended to be well-orderable.  In those days, it was fairly common to distinguish between "cardinals" and "alephs", the latter being the cardinals of well-orderable sets.  Equations, inequalities, and algebraic operations for cardinal numbers were treated simply as abbreviations for statements about sets of those cardinalities.  I don't think people worried about getting actual sets to serve as cardinal numbers.
The double-bar notation for cardinal numbers goes back to Cantor. His idea was that, if you have a set $X$, you obtain its cardinal by two abstractions.  First, you abstract from what particular elements constitute the set; second, you abstract from the order in which the elements are given. (That implies, in contrast to how we think of sets nowadays, that a set is to be regarded as "given" with an ordering of its elements.)  Cantor represented these acts of abstraction by bars.  So a single bar was his notation for the order-type of a set, and double bar meant cardinality.

A: This answer collects our educated guesses about this notation.
The operations $+$ and $\cdot$ between sets mean union and intersection, respectively. The symbols $\sum$ and $\prod$ extend these to indexed unions and intersections in the obvious way. From what I can tell this notation was pretty much standard in the first half of the 20th century.
The large $E$ operator seems to stand for set comprehension (in which case it probably comes from the word ensemble) and translates to modern notation as $E_y[\varphi(y)]=\{y;\varphi(y)\}$. There is evidence for this interpretation on page 181 of the linked paper.
The double bar $\bar{\bar{X}}$ undoubtedly means the cardinality of $X$, although it isn't clear how this is interpreted if $X$ is not well-orderable. It is possible, since the symbol always appears in relation to another cardinality, that the relations mean the existence of certain functions (probably injections) and the symbol $\bar{\bar{X}}$ by itself has no meaning.
It is likely that initial ordinals are meant when talking about cardinal numbers (written in fraktur). This is supported by the appearance of $\aleph_0,\aleph_1$ and others in the paper. Also, I expect it was much too early for the minimal rank representative workaround (which is basically Scott's trick) to have been known.
The symbol $\mathrm{non}\leq$ stands for $\not\leq$ and similarly for other relations. Note that $\mathrm{non}\in$ also appears in the paper.

A: The reference is too old. I only know:

$\overline{\overline{X}}$ denotes the cardinality, i.e., $|X|$.


text:
Q: does the Dispose method inside a function matters? so lately i've been working with disposable object and i was wondering would it be benific to dispose an object inside a function ?
like between those 2 functions is the use of .Dispose() really matters  inside a function since all objects within a function will vanish as soon as it finishes
void FOO()
{
    var x= new DisposableObject();
    //stuff
}

void FOO()
{
    using(var x= new DisposableObject())
    {
        //stuff
    }
}

A: You should always Dispose() an object that needs it. Even if the object is garbage collected, there could be unmanaged resources that don't get released. Calling Dispose() (or a using as in your second example) ensures that the object can properly release unmanaged resources that it needs to.

A:
All objects within a function will vanish as soon as it finishes

The objects will stay, the local references will vanish. The objects will 'vanish' when garbage collector runs and determines they are unreachable.
Before an unreachable object is removed from memory, it's finalizer will run (if implemented), cleaning all unmanaged resources.
The problem is that all that is not deterministic. You never know when GC will run, in some cases the finalizer will not even be executed.
You should always call Dispose method if it's possible.
If you want more details about finalizers, you should read these 2 articles: part 1, part 2.

A: Objects do not simply vanish.
The GC collects instances that are not referenced anymore. This may take time as the GC decides when to run and the instance will not be disposed until it does.
If this disposable has unmanaged resources and is implemented correctly the resources will be disposed by the finalizer which is a single thread.
If you're okay with the instance not being disposed for some time and the finalizer isn't busy.. then go ahead. But it's much better if you dispose of it as soon as possible.

A: Set a breakpoint in the Dispose() method and run these tests with debugging.
TestMethod1 doesn't hit the breakpoint while TestMethod2 does.
As others have noted this is because of the way that GC works in .Net
If you are going to implement the IDiisposeable interface, you probably want to put your class in a using statement or call .Dispose() so you have more predictable application behavior.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var disposable = new DisposableObject();
            disposable.DoSomething();
        }

        [TestMethod]
        public void TestMethod2()
        {
            using (var disposable = new DisposableObject())
            {
                disposable.DoSomething();
            }
        }
    }

    public class DisposableObject : IDisposable
    {
        public void Dispose()
        {
            // dispose here
        }

        public void DoSomething()
        {
            // do something here
        }
    }
}


text:
Q: EncryptedSharedPrefereces doesn't raise UserNotAuthenticatedException I'm developing an Android App to securly store user secrets.
In the following code I'm expecting the raise of UserNotAuthenticatedException when try to create the EncryptedSharedPreferences because i set  .setUserAuthenticationRequired(true).
The function documentation says
Sets whether this key is authorized to be used only if the user has been authenticated.
No prompt is opened to authenticate the user.
Unfortunatly the code works, it writes and then reads the value correctly.
What am I missing?
override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC
        mainKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec)

        // Set up the key generator parameter specifications
        val builder = KeyGenParameterSpec.Builder(
            mainKeyAlias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
        )
        builder
            .setUserAuthenticationRequired(true)
            .setUserAuthenticationParameters(
                AUTHENTICATION_DURATION_SECONDS,
                KeyProperties.AUTH_DEVICE_CREDENTIAL
            ).build()

        val sharedPreferences = EncryptedSharedPreferences.create(
            "shared_prefs",
            mainKeyAlias,
            applicationContext,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
        )

        with (sharedPreferences.edit()) {
            // Edit the user's shared preferences...
            // Write the user's name to the preferences
            putString("name", "John")
            apply()
        }

        // Get the user's name from the preferences
        val name = sharedPreferences.getString("name", null)
        Log.v(TAG, "Name: $name")


text: Q: Explanation of why poles in the S-matrix corresponding to particle production/bound states? I've frequently heard the statement that the only singularities of the S-matrix in QFT correspond to things like the existence of bound states and the possibility of multi-particle production. I'm certain I've seen this worked out before, but for some reason I can't find any place that explicitly shows how these singularities arise in the S-matrix for these cases. Can someone point me to a reference for this, or explain why this is the case?


text:
Q: Possible Memory Issue on DialogFragment Initialization? I have seen some people use the code below. To initialize and call a fragment.
FIRST WAY
FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
        Fragment prev = manager.findFragmentByTag("yourTag");
        if (prev != null) {
            ft.remove(prev);
        }

DialogFragment newFragment = YourFragmentDialog.newInstance();
newFragment.show(ft, "yourTag");

SECOND WAY
DialogFragment newFragment = YourFragmentDialog.newInstance();
newFragment.show(getFragmentManager(), "yourTag");

I have 3 questions:

*

*Is the first way necessary?

*Is the second approach would cause a memory leak?

*After a DialogFragment is canceled or dismissed. Would it be garbage collected automatically or should we explicitly set it to null?

A: You can use the following method to show your DialogFragment which will properly remove & replace any currently showing dialog with new one, from the official doc.you can go through it for understanding the right way to implement it.use getSupportFragmentManager() for better.Just avoid these type of confusions by following official docs.
void showDialog() {
    // DialogFragment.show() will take care of adding the fragment
    // in a transaction.  We also want to remove any currently showing
    // dialog, so make our own transaction and take care of that here.
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment prev = getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    // Create and show the dialog.
    DialogFragment newFragment = MyDialogFragment.newInstance();
    newFragment.show(ft, "dialog");
}


text:
Q: How to make sure that several processes has started using pool in the below code, in postTasksForNSegments() method, i am creating a process in a pool for each iteration. to confirm that there are several process started in every iteration i placed the print-statement
print(f".current_process:{multiprocessing.current_process}")
At run-time, i received the below posted output for the print-statement.
Given the memory address as stated below which is 0x0000017F7A4F1D80, does that mean i did not start several processes and it is only one process started?
please let me know why i am getting the same memory address every time?
please tell me how to make sure that i did start several process in a pool?
if the code below indicates that it is only one process started, please let me know how to modify the code to start several processes
code:
@staticmethod
def initPool():
    DebugGridCellsProcessingPerNRowsUsingPool.pool = Pool(cpu_count() -1)

@staticmethod
def closePool():
    DebugGridCellsProcessingPerNRowsUsingPool.pool.close()
    DebugGridCellsProcessingPerNRowsUsingPool.pool.join()

def postTasksForNSegments(self):
    for i in range (0,self.numOfRows):
        self.res = DebugGridCellsProcessingPerNRowsUsingPool.pool.map_async(self.run,[[
        tasksCarierForRowsOfGridCellsClassifications,
        tasksCarierForRowsOfNDVIsTIFFDetails,
        tasksCarierForRowsOfPixelsValuesSatisfyThresholdInTIFFImageDatasetCnt,
        tasksCarierForRowsOfPixelsValuesDoNotSatisfyThresholdInTIFFImageDatasetCnt,
        tasksCarierForRowsOfpixelsValuesSatisfyThresholdInMixedNZCAndZCCnt,
        ....
        ....
        ....
        tasksCarierForRowsOfPixelsValuesOfNoDataInNoDataCell,
        ]],
        chunksize=self.numOfRows // cpu_count()
        )
        DebugGridCellsProcessingPerNRowsUsingPool.procs.append(self.res)
        print(f".current_process:{multiprocessing.current_process}")

output of print-statement in the above code
numOfRows:30
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:27
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:24
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:21
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:18
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:15
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:12
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:9
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:6
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>
numOfRows:3
(numOfSegments:3
.current_process:<function current_process at 0x0000017F7A4F1D80>

A: You are printing from the parent process, not from a worker process.
To print from the worker process, you should put the print statement in the run method.
To uniqely identify a process, it is better to use os.getpid().
Some style remarks;

*

*Instead of a for-loop with map_async, why not use a simple map (or imap_unordered)?

*The length of the variable names in combination with CamelCase makes the code hard to read.

Edit2:

i tested the code on a single process and surprisingly, the processing time using single cpu is must faster the it using multi-cpus. any reason for that please?

Your question doesn't contain enough information to be sure. What follows is my best guess.
There is an amount of overhead associated with multiprocessing. Think about this: All the data that you sumbit to apply_async in args has to be packaged (using pickle) and sent to the worker processes via interprocess communication and unpackaged. The same goes for any data returned by the workers!
If the amount of data is large, the time for that needed could overwhelm the time needed for the execution of the run method.
If large amounts of data have to be sent to or received from workers, I would recommend writing that data to a file on an SSD or RAM-disk, and send the workers merely the name of the input file. Similarly the workers should only return the (random!) name of any output file.
Hint: You can use the cProfile module to get an idea about where your programs are spending there time. On my website I've published several articles about profiling Python programs. Here is the start of that series. If you want to improve program performance, you should always start with profiling.


text:
Q: Finding this summation: $\sum_{n=1}^{\infty}\frac{(2n+99)!(3n-2)!}{(2n)!(3n+99)!}$ What would be an easy method to find the approximate value of/close the form (the former will work too, if reasonably correct, a few decimal places, not more than that.):
$$\sum_{n=1}^{\infty}\frac{(2n+99)!(3n-2)!}{(2n)!(3n+99)!}$$
I thought we could write it as:
$$\frac{99!}{101!}\sum_{n=1}^{\infty}\frac{(2n+99)!(3n-2)!(101)!}{(2n)!(99)!(3n+99)!}=\frac{1}{101\times100}\sum_{n=1}^{\infty}\frac{\displaystyle\binom{2n+99}{99}}{\displaystyle\binom{3n+99}{101}}$$
I don't know of a simple way to proceed.

A: For any $s \ge 1$, let
$$\Delta_s = \sum_{n=1}^\infty \frac{(2n+s-1)!}{(2n)!}\frac{(3n-2)!}{(3n+s-1)!}$$
In particular, $\Delta_{100}$ is the sum we want to compute. Notice
$$
\begin{align}
\frac{(2n+s-1)!}{(2n)!}
&= \left.\left(\frac{d}{dz}\right)^{s-1} z^{2n+s-1}\right|_{z=1}
= \frac{\Gamma(s)}{2\pi i}\oint_{C} \frac{z^{2n+s-1}}{(z-1)^s}dz\\
\frac{(3n-2)!}{(3n+s-1)!}
&= \frac{1}{\Gamma(s+1)}\frac{\Gamma(3n-1)\Gamma(s+1)}{\Gamma(3n+s)} = \frac{1}{\Gamma(s+1)}\int_0^1 t^{3n-2} (1-t)^s dt
\end{align}$$
where $C_1 \subset \mathbb{C}$ is a small circular contour centered at $z = 1$.
We have following integral representation for $\Delta_s$.
$$s\Delta_s = \frac{1}{2\pi i}\int_0^1 \oint_C
\left(\frac{z(1-t)}{z-1}\right)^s \frac{zt}{1 - z^2t^3} dz dt
$$
Let $\Delta(\eta)$ be the OGF for $s\Delta_s$,
$$\Delta(\eta) \stackrel{def}{=} \sum_{s=1}^\infty s\Delta_s \eta^{s-1}$$
Let $\omega = (1-\eta + \eta t)^{-1}$ and $C_{\omega} \subset \mathbb{C}$ be a circular contour centered at $\omega$. Since
$$\sum_{s=1}^\infty \left(\frac{z(1-t)}{z-1}\right)^s \eta^{s-1} =
\frac{z(1-t)}{z(1-\eta + \eta t) - 1} = \frac{z(1-t)\omega}{z-\omega}
$$
We find
$$\begin{align}
\Delta(\eta)
&=
\frac{1}{2\pi i}\int_0^1 \oint_{C_\omega}  \frac{z^2 t (1-t)}{1 - z^2 t^3}\frac{\omega}{z - \omega} dz dt
= \int_0^1 \frac{\omega^3 t(1-t)}{1 - \omega^2 t^3} dt\\
&= \int_0^1 \frac{ t dt }{(1-\eta +\eta t)((1-\eta)^2 + (1-\eta^2) t + t^2)}\\
&= \frac{1}{1-\eta}\int_0^{\frac{1}{1-\eta}} \frac{t dt}{(1+\eta t)(1 + (1+\eta)t + t^2)}\\
&= \frac{1}{(1-\eta)^2}\int_0^{\frac{1}{1-\eta}}
\left[\frac{t+\eta}{1 + (1+\eta)t + t^2} - \frac{\eta}{1+\eta t}\right] dt\\
&= \frac{1}{(1-\eta)^2}\left[
\frac12 \log(3-2\eta) - \sqrt{\frac{1-\eta}{3+\eta}}\tan^{-1}\left(\frac{\sqrt{(1-\eta)(3+\eta)}}{3-\eta}\right)
\right]
\end{align}
$$
Throw the last expression to a CAS and ask it to compute the coefficient of $\eta^{s-1}$ for $s = 100$. We get
$$
\Delta_{100} = \frac{1}{100}\left( 50 \log(3) - A \frac{\pi}{3^{199/2}} - \frac{B}{C}\right)$$
where
$$\begin{array}{rcl}
A &=& 279620009275010140018538432376916760970649320550\\
B &=& 402992750960761749592608273159927666000520075786\\
  & & 76797445589033694041389862879632396903\\
C &=& 782839087808164519964649481706120884210784218785\\
  & & 090048580229772278114461980652430352
\end{array}
$$
If one multiply this expression by $101 \times 100$, one reproduce the number in Lucian's comment (which is off by above factor).
Numerically, $\Delta_{100}$ is very close to $\frac{1}{200}$,
$$\Delta_{100} \approx 0.004999999999999999999533961997106313117\ldots$$
There is a good reason for this. For small $\delta$, we have
$$
\Delta(1-\delta) = \frac{1}{\delta^2}\left(\frac12\log(1+2\delta) - \sqrt{\frac{\delta}{4-\delta}}\tan^{-1}\left(\frac{\sqrt{\delta(4-\delta)}}{2+\delta}\right)\right)
\approx \frac{1}{2\delta} + O(1)
$$
This implies $\Delta(\eta)$ has a simple pole at $\eta = 1$ with residue $-\frac12$.
Let us subtract this pole from $\Delta(\eta)$ and look for the singularities
for the remaining pieces nearest the origin.

*

*For the piece $\log(3 - 2\eta)$, the nearest singularity is clearly $\eta = \frac32$.

*For the piece
$\displaystyle\;\sqrt{\frac{1-\eta}{3+\eta}}\tan^{-1}\left(\frac{\sqrt{(1-\eta)(3+\eta)}}{3-\eta}\right)\;$
the nearest singularity occurs at those $\eta$ where
$\displaystyle\;\frac{\sqrt{(1-\eta)(3+\eta)}}{3-\eta} = \pm i\;$. Once again, this leads to $\eta = \frac32$.
What this means is after we subtract the pole from $\Delta(\eta)$, the remaining piece is analytic over the circle $|z| < \frac32$. If we pick a circle with radius $1 < r < \frac32$ and extract the power series of the remaining piece at $z = 0$ using Cauchy integral formula, the coefficients of $\eta^{s-1}$ for the remaining piece will grow at most as fast as $r^{1-s}$.
Using this, we can conclude for large $s$,
$$s \Delta_s = \frac12 + O( r^{1-s} ), \quad 1 < r < \frac32.$$
In order to estimate the coefficient in front of the $O(r^{1-s})$ term,
we need to study $\Delta(\eta)$ near $\eta = \frac32$. One can show that the leading singular behavior there is given by
$$\Delta(\eta) \approx \frac{4}{3} \log\left(\frac32 - \eta\right) + \cdots \quad\text{ for }\quad \eta \approx \frac32.$$
This suggests for large $s$,
$$s\Delta_s \approx \frac12 - \frac{4}{3(s-1)} (2/3)^{s-1}$$
Let use $s = 100$ as a test case, this estimate gives
$$\left[\frac{100 \Delta_{100} - \frac12}{(2/3)^{99}}\right]_{\verb/approx/} = -\frac{4}{297}
\approx -0.01346801346801347$$
This is within $7\%$ from corresponding exact value. Our hand waving estimate turns out to be reasonably decent (at least for $s \approx 100$).
$$\left[ \frac{100 \Delta_{100} - \frac12}{(2/3)^{99}}\right]_{\verb/exact/} \approx -0.012631530615502$$

A: $$\begin{align}
S_p&=\sum_{n=1}^p \frac{(2n+99)\dots(2n+1)}{(3n+99)\dots(3n-1)}\\
S_p&=\sum_{n=1}^p \sum_{k=-1}^{99}\frac{a_k}{3n+k}
\end{align}$$
Where:
$$a_k=\frac{[2\left(\frac{-k}{3}\right)+99]\dots[2\left(\frac{-k}{3}\right)+1]}{[3\left(\frac{-k}{3}\right)+99]\dots[3\left(\frac{-k}{3}\right)+k-1][3\left(\frac{-k}{3}\right)+k+1]\dots[3\left(\frac{-k}{3}\right)-1]}$$
All of the $a_k$ can be calculated precisely since they're just rational numbers. But I don't have a way of doing it.
If we can find an approximation of $\sum_{n=1}^p \frac{1}{3n+k}$ to the order of $o(1)$, we can calculate the result.
To do that, we only need an approximation of $\sum_{n=1}^p \frac{1}{3n}$, $\sum_{n=1}^p \frac{1}{3n+1}$, and $\sum_{n=1}^p \frac{1}{3n+2}$
$$\sum_{n=1}^p \frac{1}{3n}=\frac\gamma3 + \frac{\ln(p)}{3}+o(1)$$
$$\sum_{n=1}^p \frac{1}{3n+1}=\frac{-\psi(4/3)}{3}+\frac{\ln(p)}{3}+o(1)$$
$$\sum_{n=1}^p \frac{1}{3n+2}=\frac{-\psi(5/3)}{3}+\frac{\ln(p)}{3}+o(1)$$
Where $$\psi(4/3)=3-\gamma-\frac{\pi}{2\sqrt3}-\frac{3 \ln(3)}2$$
$$\psi(5/3)=\frac32-\gamma+\frac{\pi}{2\sqrt3}-\frac{3 \ln(3)}2$$
Now we have
$$\begin{align}
S_p&=\sum_{n=1}^{p}\frac{a_0+a_3+\dots+a_{99}}{3n}+\frac{a_1+a_4+\dots+a_{97}}{3n+1}+\frac{a_{-1}+a_2+\dots+a_{98}}{3n+2}\\
&-\left(a_3\frac{1}{3}+a_6\left(\frac{1}{3}+\frac{1}{6}\right)+\dots+a_{99}\left(\frac{1}{3}+\frac{1}{6}+\dots+\frac{1}{99}\right)\right)\\
&-\left(a_4\frac{1}{4}+a_7\left(\frac{1}{4}+\frac{1}{7}\right)+\dots+a_{97}\left(\frac{1}{4}+\frac{1}{7}+\dots+\frac{1}{97}\right)\right)\\
&-\left(a_5\frac{1}{5}+a_8\left(\frac{1}{5}+\frac{1}{8}\right)+\dots+a_{98}\left(\frac{1}{5}+\frac{1}{8}+\dots+\frac{1}{98}\right)\right)\\
&+a_{-1}\frac{1}{2}+o(1)\\
S_p&=\frac{(a_0+a_3+\dots+a_{99})\gamma}{3}\\
&+\frac{-(a_1+a_4+\dots+a_{97})\psi(4/3)}{3}\\
&+\frac{-(a_{-1}+a_2+\dots+a_{98})\psi(5/3)}{3}\\
&-\left(a_3\frac{1}{3}+a_6\left(\frac{1}{3}+\frac{1}{6}\right)+\dots+a_{99}\left(\frac{1}{3}+\frac{1}{6}+\dots+\frac{1}{99}\right)\right)\\
&-\left(a_4\frac{1}{4}+a_7\left(\frac{1}{4}+\frac{1}{7}\right)+\dots+a_{97}\left(\frac{1}{4}+\frac{1}{7}+\dots+\frac{1}{97}\right)\right)\\
&-\left(a_5\frac{1}{5}+a_8\left(\frac{1}{5}+\frac{1}{8}\right)+\dots+a_{98}\left(\frac{1}{5}+\frac{1}{8}+\dots+\frac{1}{98}\right)\right)\\
&+a_{-1}\frac{1}{2}+o(1)\\
\end{align}$$
This is as far as I could go. There could be some relations between the $a_k$ that'll make this simpler but I can't think of anything. (although, according to wolfram alpha, the sum seems to be close to $1/200$)

A: This is the answer given by Lucian:
$$\sum_{n=1}^{\infty}\frac{(2n+99)!(3n-2)!}{(2n)!(3n+99)!}=\frac{1}{204} {_6F_5}(\{\frac23,1,1,\frac43,51,\frac{103}{2}\},\{\frac32,2,\frac{103}{3},\frac{104}{3},35\},1)$$
an evaluation of which would be
$$0.0049999999999999999995339619971063131170085423478892$$


text:
Q: Am I calculating percentages wrong? Let's say someone enters a competition where the winner is select randomly. To enter you just post a comment. Now there are 1,300 entries and 17 prizes, so the chance to win a prize is 1/1,300*17*100 = 1.3%.
But if someone decides to cheat and posts 100 comments, hell have a 130% chance to win (100/1,300*17*100). How is that possible? If TotalComments - YourComments = >=17 then you have less than a 100% chance to win, because there is still the chance for any other 17 comments other than your 100 to be selected.
Can someone tell me where my calculation formula is wrong? If you didnt get the formula it's
nOfYourComments/nOfTotalComments * nOfPrizes * 100

A: If the cheater puts in $100$ tickets, then there is some chance he will win more than $1$ prize.  That's where the math needs to change.

*

*Your calculation ${100 \times 17 \over 1300} \approx 1.3$ actually shows the expected (a.k.a. average) number of prizes he would win. That's why it can be $> 1$.  However, the fact that it is $> 1$ does not mean he will win something for sure.  It's still possible the number of prizes he wins $= 0, 1, 2, 3, 4,\dots$

*To calculate the probability he will win something, i.e. at least $1$ prize, you need a different method.

*

*Any specific ticket will lose with probability $ = a = 1 - \frac{17}{1300} \approx 0.987$.

*So probability that all of them lose $= b = a^{100} \approx 0.268$.

*So probability that he will win something = $1 - b \approx 0.732 = 73.2\%$.


text:
Q: Prolog adjecent2interchange I am trying to make a rule for an assignment but it doesnt seem to work,
the assignment is a simple tube map, and one of the tasks is to find:
stations which are adjacent to and interchange station, but are not interchange staions themselves.
I have already done the prequisite task to find how many lines run through a station:
station_numlines(Station,NumberOfLines) :-
    findall(M, station(Station,M), Ms),
    sort(Ms, SortedMs),
    length(SortedMs, NumberOfLines).

now ive got to make a rule which checks which stations are not interchange stations, in the format of :
adjecent2interchange(NonInterStation, InterChangeStation) :-

how can i use station_numlines to find all the non interchange stations?
like my guess is, run the number of lines on all of the stations from a list, then just store it and print out all of the non interchange stations.
I am just hopeless in writting this myself with near 0 experience in the very confusing language.
Stations:
station(al,metropolitan).
station(bs,metropolitan).
station(fr,metropolitan).
station(kx,metropolitan).
station(ls,metropolitan).

station(bg,central).
station(cl,central).
station(lg,central).
station(ls,central).
station(nh,central).
station(oc,central).
station(tc,central).

station(br,victoria).
station(fp,victoria).
station(kx,victoria).
station(oc,victoria).
station(vi,victoria).
station(ws,victoria).

station(ec,bakerloo).
station(em,bakerloo).
station(oc,bakerloo).
station(pa,bakerloo).
station(wa,bakerloo).

station(em,northern).
station(eu,northern).
station(ke,northern).
station(tc,northern).
station(ws,northern).

%adjecent stations %

% Central line

adjacent(nh,lg,central,4).
adjacent(lg,oc,central,4).
adjacent(oc,tc,central,4).
adjacent(tc,cl,central,4).
adjacent(cl,ls,central,4).
adjacent(ls,bg,central,4).

% Victoria Line
adjacent(br,vi,victoria,4).
adjacent(vi,oc,victoria,4).
adjacent(oc,ws,victoria,4).
adjacent(ws,kx,victoria,4).
adjacent(kx,fp,victoria,4).

% Northern Line
adjacent(ke,em,northern,4).
adjacent(em,tc,northern,4).
adjacent(tc,ws,northern,4).
adjacent(ws,eu,northern,4).

% Metropolitan Line
adjacent(al,ls,metropolitan,4).
adjacent(ls,kx,metropolitan,4).
adjacent(bs,fr,metropolitan,4).

% Bakerloo Line
adjacent(ec,em,bakerloo,4).
adjacent(em,oc,bakerloo,4).
adjacent(oc,pa,bakerloo,4).
adjacent(pa,wa,bakerloo,4).

A: The key to this, as in all Prolog programming, is to decompose the problem into its constituent parts. Let's worry about "interchanges", "non-interchanges", and "adjacency" separately.
Given your definition of station_numlines/2, you can define:
Edit: Your definition of station_numlines/2 is not very good because it cannot be used to enumerate all stations and the number of lines they are on, as in station_numlines(Station, N) with unbound arguments. Here is a definition that makes this possible:
station_numlines(Station,NumberOfLines) :-
    setof(M, M^station(Station,M), Ms),
    length(Ms, NumberOfLines).

Given this, you can define:
interchange_station(Station) :-
    station_numlines(Station, N),
    N > 1.

and
non_interchange_station(Station) :-
    station_numlines(Station, 1).

Edit: Even without the complexity of station_numlines/2, we can find relatively simple alternative definitions for these predicates:
interchange_station(Station) :-
    station(Station, Line1),
    station(Station, Line2),
    dif(Line1, Line2).   % or: Line1 \= Line2

non_interchange_station(Station) :-
    station(Station, _SomeLine),
    \+ interchange_station(Station).

This is arguably cleaner but, it enumerates interchange stations several times. In any case:
Then, if you also have a definition of adjacent/2, your predicate becomes:
adjacent_to_interchange(NonInterchange, Interchange) :-
    non_interchange_station(NonInterchange),
    interchange_station(Interchange),
    adjacent(NonInterchange, Interchange).


text:
Q: Deleting a cookie with value NULL I'm trying to erase completely a cookie that is set if a particular URL parameter is present.
I've tried:
function delete_cookie (cookie_name) {
    var cookie_date = new Date ();
    cookie_date.setTime(cookie_date.getTime()-1);
    document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

delete_cookie('MyCookie');

And it sets the cookie value to null but the cookie itself or at least the name of the cookie stays in the browser so that when the same URL is opened again, it will not update the cookie value from  null to XXX nor is a second cookie with the URL value created.
For the new cookie to be setup again I have to right-click on the cookie name (in Chrome) and choose delete. This way the cookie name and its value null are truly erased otherwise it stays with null value.
How can I completely erase the cookie file and not just set it to null with javascript?
** NEW INFO **
I should mention that I also have the following function to grab the cookie from the URL parameter and to keep it from the first page until the final page (where it should be deleted after the cookie value is added to another URL). The second page will turn the link into a session where the URL parameter is no longer visible
Here is the code for it:
function URLparam(name) {
return unescape(
    (RegExp(name + '(?:\\[\\d+\\])?=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}

$(document).ready(function () {

if (URLparam("MyParameter") !== null && !get_cookie ("MyCookie")) {
    set_cookie ("MyCookie", URLparam("MyParameter"));
}

Any ideas?

A: The easiest way to delete the cookie would be like this:
function delete_cookie( name ) {
    document.cookie = name + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Updated: Had to add the path to get it to work.
Here's a Plunk showing it working.  The top buttons in the Plunk use a library to set/view/delete the null cookie.  Use the bottom button to delete with the old school method (above) and then use the library show button to verify it is gone.


text:
Q: Why do regression models predicting a change score vs. predicting T2 controlling for T1 yield slightly different results? I am running multiple regression models testing whether a change from T1 to T2 in my IV predicts a change in my DV (also from T1 to T2). I am running these analyses in R using the glm function.
I ran the same model again in a slightly different manner, predicting change in my DV directly rather than by controlling for my DV at T1. However, this yields slightly different results. Why is this? I assumed the two models would be doing exactly the same thing, but apparently not. Both models also contain both my IV and my DV at two measurement points, so this can't be due to more missings in of the two models. Here is my R-code:
### Version 1:
M0 <- glm(IV.t2 ~ IV.t1,
          data = data,
          na.action = na.omit)

Res_IV <- resid(M0)

M1 <- glm(DV.t2 ~ DV.t1 + Res_IV,
          data = data,
          na.action = na.omit)

### Version 2:
M0.1 <- glm(IV.t2 ~ IV.t1,
          data = data,
          na.action = na.omit)

Res_IV <- resid(M0.1)

M0.2 <- glm(DV.t2 ~ DV.t1,
          data = data,
          na.action = na.omit)

Res_DV <- resid(M0.2)

M2 <- glm(Res_DV ~ Res_IV,
          data = coronaUK_T1_T2_cost,
          na.action = na.omit)

What might be the reason for these differences? Do the two analyses mathematically do something different?

A: I'm not sure I follow your code, and how it relates to what you have in mind.
For starters, it's slightly odd that you are using glm() but aren't setting the family argument.  By default, family=gaussian, in which case, glm() fits a standard linear model, like what you would get by using lm().  The differences are that glm() estimates the parameters by searching using a variant of the Newton-Raphson algorithm, instead of using ordinary least squares (OLS).  In addition, it tests the parameters using Wald $z$-tests, instead of $t$-tests.  In both cases, there are (slight) reasons to prefer the methods used by lm().  Moreover, there are methods that operate over the output (e.g., summary()) that will provide more useful information if lm() was used.  Was this supposed to be a model for non-normal data (e.g., a binary response or a count)?
Second, neither of your models uses the difference between measures at time 1 and time 2, as far as I can tell.  Instead, you seem to be using the part of the time 2 measure that cannot be explained by knowledge of the time 1 measure.  That's not the same thing.  Consider this simple simulation (coded in R):
set.seed(5758)  # this makes the example exactly reproducible

t1  =             round(rnorm(6, mean=50, sd=10), digits=1)
t2  = 10 + 2*t1 + round(rnorm(6, mean=0,  sd=1),  digits=1)
dif = t2-t1
m   = lm(t2~t1)
round(coef(summary(m)), digits=2)
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)    10.00       1.66    6.03        0
# t1              2.01       0.03   64.71        0
res = residuals(m)
cor(dif,res)  # [1] 0.06151258
data.frame(t1, t2, dif, res)
#     t1    t2  dif         res
# 1 62.3 134.9 72.6 -0.07585836
# 2 64.6 140.4 75.8  0.81043618
# 3 58.2 125.4 67.2 -1.35142689
# 4 52.6 115.9 63.3  0.38194292
# 5 42.6  95.8 53.2  0.34153188
# 6 33.9  77.9 44.0 -0.10662574
windows(width=7, height=4)
  layout(matrix(1:2, nrow=1))
  dotchart(t1, xlim=c(min(t1,t2),max(t1,t2)), cex=.8,
           main="Values\n(w/ differences implied)")
  axis(side=2, at=1:6, cex=.8)
  points(t2, 1:6, pch="+")
  plot(t1, t2, main="Scatterplot\n(w/ residuals implied)", cex.axis=.8)
  abline(coef(m), col="gray")
windows()
  plot(dif, res)

Setting that aside, we can ask if the answers have to / should be the same.  The answer is no.  Consider these simulations:
set.seed(2621)

y1c = rnorm(10, mean=100, sd=15)
y2c = y1c + rnorm(10, mean=0, sd=1)

y1d = rnorm(10, mean=0, sd=1)
y2d = rnorm(10, mean=5, sd=1)

round(coef(summary(lm(y2c~y1c))), digits=2)
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)     5.00       4.81    1.04     0.33
# y1c             0.95       0.05   20.76     0.00
round(coef(summary(lm(y2c-y1c~1))), digits=2)
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)      0.1       0.35    0.27     0.79

round(coef(summary(lm(y2d~y1d))), digits=2)
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)     4.97       0.48   10.29     0.00
# y1d            -0.08       0.55   -0.15     0.89
round(coef(summary(lm(y2d-y1d~1))), digits=2)
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)     5.43       0.49   11.18        0

The short answer is that the two methods can give different answers because they correspond to different questions.  In general, regression models treat $X$ and $Y$ variables asymmetrically.  Specifically, $x$-values are taken to be fixed and known, whereas $y$-values are considered to be a mix of true signal and random noise.  Using change scores as your response, means that you are assuming the differences are a combination of input from $X$ and some pure randomness.  On the other hand, when you model time 2 values controlling for time 1 values, the time 1 values are treated as constants measured with perfect accuracy, and the time 2 values are partly stochastic error.

This leads to a third question, which should you use?  You should be aware that, as @rolando2 points out, this is a very contentious topic in statistics.  There have been various camps in favor of each that have been fussing at each other for decades.  The threads he links to are worth reading to get some perspective.  If pressed, I suppose I would say you should use the method that best corresponds to your research question.


text:
Q: Server Sent Events using NodeJS and Redis I receive updates (messages) from a Redis Database and I need to show those messages in real time on the client, for this purpose I'm using SSE (Server Sent Events).
So, my code looks like this:
Client side javascript:
var source = new EventSource('/updates');

source.addEventListener('pmessage', function(e) {
  console.log('Event: ' + e.event);
  console.log('Data: ' + e.data);
}, false);

Server side (Node + Express):
    req.socket.setTimeout(Infinity);

    var redisURL = url.parse(process.env.REDISCLOUD_URL);
    var client = redis.createClient(redisURL.port, redisURL.hostname, {ignore_subscribe_messages: true});
    client.auth(redisURL.auth.split(":")[1]);

    client.psubscribe('updates');

    client.on('error', function (err) {
    console.log('Error: ' + err);
  });

  client.on('psubscribe', function (pattern, count) {
    console.log('psubscribe pattern: ' + pattern);
    console.log('psubscribe count: ' + count);
  });

  client.on('pmessage', function (pattern, channel, message) {
    console.log('pmessage pattern: ' + pattern);
    console.log('pmessage from channel: ' + channel);
    console.log('pmessage message: ' + message);
    res.write("data: " + message + '\n\n');
  });

  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });
  res.write('\n');

I do not receive any updates from the server to the client (the server receive the message correctly from redis).
If I refresh the server I receive this error: net::ERR_INCOMPLETE_CHUNKED_ENCODING
I'm new to SSE, so probably I'm doing it wrong. I hope in your help.

A: The solution is to write res.flush() every time you need to send messages to the client, in my case:
  client.on('pmessage', function (pattern, channel, message) {
    console.log('pmessage pattern: ' + pattern);
    console.log('pmessage from channel: ' + channel);
    console.log('pmessage message: ' + message);
    res.write("data: " + message + '\n\n');
    res.flush();
  });

Solved.


text:
Q: How do I properly resize all aspects of a ggplot in R, including the legend? I'm making scatterplots in ggplot2 and then using ggsave to export PDFs of specific widths and heights. However, the figure legend never gets properly resized with ggsave (its borders don't stay within the plot). Is there another way to simultaneously resize all parts of a ggplot for easy exporting? I've also tried using pdf(), but the same problem occurs.
Here is an example of what's going on using iris:
data(iris)

test <- ggplot(iris, aes(x = iris$Sepal.Length, y = iris$Sepal.Width,
  colour = iris$Species)) +
  geom_point(size = .1) +
  theme(panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), panel.border = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black", size = .8),
    legend.key=element_blank(),
    axis.ticks = element_line(colour = "black", size = .6),
    axis.text=element_text(size=6, colour = "black"),
    plot.title = element_text(hjust = 0.0, size = 6, colour = "black"),
    axis.title=element_text(size= 6),
    legend.text=element_text(size = 6),
    legend.title=element_text(size = 6, face = "bold"),
    legend.position = c(.9, .15)) + labs(colour = "Species")

##saving plot with no resizing
ggsave(plot = test, file = "NoResize.pdf", dpi = 600, family = "ArialMT")

##saving plot with resizing results in relatively larger legend
ggsave(plot = test, file = "Resize.pdf", device = "pdf", width = 3.5,
    height = 3, units = "in", dpi = 600, family = "ArialMT")

The legend seems to be changing, but it seems to get relatively bigger than the other aspects of the plot, such that it no longer fits within the plot axes.

A: The size argument is in points.  If you have a preferred size for the default 7 inch by 7 inch graphic then you'll need to scale the size accordingly for a different size graphic.
Two other notes.

*

*Don't use $ in the ggplot2::aes call.  This will cause you problems in the future.  It is sufficient to use ggplot(iris) + aes(x = Sepal.Length).

*absolute legend.position in this example can be difficult to use in the different size graphics.  I would recommend legend.position = "bottom" instead.
Here are two ways to control the relative size of the font in your example.
library(ggplot2)

data(iris)

# Okay solution, using a scaling value in an expression.  I would not recommend
# this in general, but it will work. A better solution would be to use a
# function
test <-
  expression({
  ggplot(iris) +
  aes(x = Sepal.Length, y = Sepal.Width, colour = Species) +
  geom_point(size = .1) +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border     = element_blank(),
        panel.background = element_blank(),
        axis.line        = element_line(colour = "black", size = .8),
        legend.key       = element_blank(),
        axis.ticks       = element_line(colour = "black", size = .6),
        axis.text        = element_text(size = 6 * scale_value, colour = "black"),
        plot.title       = element_text(hjust = 0.0, size = 6 * scale_value, colour = "black"),
        axis.title       = element_text(size = 6 * scale_value),
        legend.text      = element_text(size = 6 * scale_value),
        legend.title     = element_text(size = 6, face = "bold"),
        legend.position  = c(.9, .15)) +
  labs(colour = "Species")
  })

scale_value <- 1
ggsave(eval(test), width = 7 * scale_value, height = 7 * scale_value, file = "sotest1.pdf")

scale_value <- 3/7
ggsave(eval(test), width = 7 * scale_value, height = 7 * scale_value, file = "sotest2.pdf")

# Define a function to do the work.
iris_plot <- function(scale_value = 1, filename) {
  g <- ggplot(iris) +
    aes(x = Sepal.Length, y = Sepal.Width, colour = Species) +
    geom_point(size = .1) +
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.border     = element_blank(),
          panel.background = element_blank(),
          axis.line        = element_line(colour = "black", size = .8),
          legend.key       = element_blank(),
          axis.ticks       = element_line(colour = "black", size = .6),
          axis.text        = element_text(size = 6 * scale_value, colour = "black"),
          plot.title       = element_text(hjust = 0.0, size = 6 * scale_value, colour = "black"),
          axis.title       = element_text(size = 6 * scale_value),
          legend.text      = element_text(size = 6 * scale_value),
          legend.title     = element_text(size = 6, face = "bold"),
          legend.position  = c(.9, .15)) +
    labs(colour = "Species")

  ggsave(g, width = 7 * scale_value, height = 7 * scale_value, file = filename)
}

iris_plot(filename = "iris7x7.pdf")
iris_plot(4/7, filename = "iris4x4.pdf")

EDIT
Using the package magick will give you a nice programming interface for resizing and editing graphics via imagemagick
For example
library(ggplot2)
library(magick)

g <-
  ggplot(iris) +
  aes(x = Sepal.Length, y = Sepal.Width, colour = Species) +
  geom_point(size = .1) +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border     = element_blank(),
        panel.background = element_blank(),
        axis.line        = element_line(colour = "black", size = .8),
        legend.key       = element_blank(),
        axis.ticks       = element_line(colour = "black", size = .6),
        axis.text        = element_text(size = 6, colour = "black"),
        plot.title       = element_text(hjust = 0.0, size = 6, colour = "black"),
        axis.title       = element_text(size = 6),
        legend.text      = element_text(size = 6),
        legend.title     = element_text(size = 6, face = "bold"),
        legend.position  = c(.9, .15)) +
  labs(colour = "Species")

ggsave(g, file = "iris7x7.pdf", width = 7, height = 7)

iris_g <- image_read("iris7x7.pdf")

iris_3x3 <- image_scale(iris_g, "216x216")
image_write(iris_3x3, path = "iris3x3.pdf", format = "pdf")

Note, the resized graphic may require some edits to deal with pixelation or blurriness.
Again, I would recommend against using an absolute legend.position value.  Perhaps, if you know you need a 3in by 3in graphic you can open a dev window with those dimensions to build your graphic in and then save appropriately.  For example, open a 3in by 3in X Window via X11(width = 3, height = 3).


text:
Q: Can i close modal to click window.close() in webview in flutter? I made webview in modalbottomsheet by using webview_flutter and modal_bottom_shteet library. I want to close the modalbottomsheet if user click close button that controlled by javascript(class is "apBtnClose") in webview.
Future agreement001Modal(context) {
  return showMaterialModalBottomSheet(
      backgroundColor: Colors.white,
      enableDrag: false,
      context: context,
      expand: true,
      builder: (context) => SafeArea(
            child: Column(
              children: [
                const Expanded(
                  child: WebView(
                    javascriptMode: JavascriptMode.unrestricted,
                    initialUrl:
                        "https://safe.ok-name.co.kr/eterms/agreement001.jsp",
                  ),
                ),
              ],
            ),
          ));
}

webview code
닫기


text:
Q: Finding extreme values of $f(x,y,z)=x^2+2y^2+3z^2$ on unit sphere $x^2+y^2+z^2=1$ I defined $G(x)=x^2+y^2+z^2-1$, such that the gradient of G $\nabla G=(2x, 2y, 2z)$, so that $\nabla f=(2x, 4y, 6z)=\lambda (2x,2y,2z)$.
The conclusion I drew was that the only possible value was either $\lambda=0$, or y and z were both 0 but x can be anything. This seems incorrect to me, but I'm not sure how to proceed.

A: Without calculus: $f(x,y,z)=x^2+2y^2+3z^2 = 2(x^2+y^2+z^2) + z^2-x^2= z^2-x^2+2\,$.
Since $0 \le x^2,z^2 \le 1$ it follows that $-1\le z^2-x^2 \le 1$. The extrema are actually attained at $f(\pm 1, 0, 0) = -1+2 = 1$ and $f(0,0,\pm 1)=1+2=3\,$.

A: Well, you can generalize to two of $x,y,z$ being $0$, and then choose the Lagrange multiplier as appropriate. But remember the constraint, if two of them are $0$, the last has to be $1$ on the unit sphere.

A: You can write the Lagrangian as:
$$\mathcal L(x,y,z,\lambda)=x^2+2y^2+3z^2-\lambda(x^2+y^2+z^2-1)$$
So we can get the gradient and putting it equal zero:
\begin{cases}2x-2x\lambda=0\\4y-2y\lambda=0\\6z-2z\lambda=0\\x^2+y^2+z^2=1 \end{cases}\begin{cases}2x(1-\lambda)=0\\ 2y(2-\lambda)=0\\2z(3-\lambda)=0\\x^2+y^2+z^2=1\end{cases}
and we have these solutions: $(\pm1,0,0,1)$, $(0,\pm1,0,2)$ and $(0,0,\pm1,3)$.


text:
Q: Passing multiple -std switches to g++ Is it safe to assume that running g++ with
g++ -std=c++98 -std=c++11 ...

will compile using C++11? I haven't found an explicit confirmation in the documentation, but I see the -O flags behave this way.

A: The GCC manual doesn't state that the
last of any mutually exclusive -std=... options specified takes effect. The first occurrence
or the last occurrence are the only alternatives. There are numerous
GCC flags that take mutually exclusive alternative values from a finite set - mutually
exclusive, at least modulo the language of a translation unit. Let's call them mutex options for short.
It is a seemingly random rarity for it to be documented that the last setting takes effect. It is
documented for the -O options as you've noted, and in general terms for mutually exclusive warning options, perhaps
others. It's never documented that the first of multiple setting takes effect, because
it's never true.
The documentation leans - with imperfect consistency - on the historical conventions
of command usage in unix-likes OSes. If a command accepts a mutex option
then the last occurrence of the option takes effect. If the command were - unusually -
to act only on the first occurrence of the option then it would be a bug for
the command to accept subsequent occurrences at all: it should give a usage error.
This is custom and practice. The custom facilitates scripting with tools that
respect it, e.g. a script can invoke a tool passing a default setting of some
mutex option but enable the user to override that setting via a parameter of the script,
whose value can simply be appended to the default invocation.
In the absence of official GCC documentation to the effect you want, you might get
reassurance by attempting to find any GCC mutex option for which it is not
the case that the last occurrence takes effect. Here's one stab:
I'll compile and link this program:
main.cpp
#include <cstdio>

#if __cplusplus >= 201103L
static const char * str = "C++11";
#else
static const char * str = "Not C++11";
#endif

int main()
{
    printf("%s\n%d\n",str,str); // Format `%d` for `str` mismatch
    return 0;
}

with the commandline:
g++ -std=c++98 -std=c++11 -m32 -m64 -O0 -O1 -g3 -g0 \
-Wformat -Wno-format -o wrong -o right main.cpp

which requests contradictory option pairs:

*

*-std=c++98 -std=c++11: Conform to C++98. Conform to C++11.

*-m32 -m64: Produce 32-bit code. Produce 64-bit code.

*-O0 -O1: Do not optimise at all. Optimize to level 1.

*-g3 -g0: Emit maximum debugging info. Emit no debugging info.

*-Wformat -Wno-format. Sanity-check printf arguments. Don't sanity check them.

*-o wrong -o right. Output program wrong. Output program right
It builds successfully with no diagnostics:
$ echo "[$(g++ -std=c++98 -std=c++11 -m32 -m64 -O0 -O1 -g3 -g0 \
-Wformat -Wno-format -o wrong -o right main.cpp 2>&1)]"
[]

It outputs no program wrong:
$ ./wrong
bash: ./wrong: No such file or directory

It does output a program right:
$ ./right
C++11
-1713064076

which tells us it was compiled to C++11, not C++98.
The bug exposed by the garbage -1713064076 was not diagnosed because
-Wno-format, not -Wformat, took effect.
It is a 64-bit, not 32-bit executable:
$ file right
right: ELF 64-bit LSB shared object, x86-64 ...

It was optimized -O1, not -O0, because:
$ "[$(nm -C right | grep str)]"
[]

shows that the local symbol str is not in the symbol table.
And it contains no debugging information:
echo "[$(readelf --debug-dump right)]"
[]

as per -g0, not -g3.
Since GCC is open-source software, another way of resolving doubts
about its behaviour that is available to C programmers, at least,
is to inspect the relevant source code, available via git source-control at
https://github.com/gcc-mirror/gcc.
The relevant source code for your question is in file gcc/gcc/c-family/c-opts.c,
function,
/* Handle switch SCODE with argument ARG.  VALUE is true, unless no-
   form of an -f or -W option was given.  Returns false if the switch was
   invalid, true if valid.  Use HANDLERS in recursive handle_option calls.  */
bool
c_common_handle_option (size_t scode, const char *arg, int value,
            int kind, location_t loc,
            const struct cl_option_handlers *handlers);

It is essentially a simple switch ladder over option settings enumerated by scode - which
is OPT_std_c__11 for option -std=c++11 - and leaves no doubt that it
puts an -std option setting into effect regardless of what setting was in effect previously. You can look at branches other than master
(gcc-{5|6|7}-branch) with the same conclusion.
It's not uncommon to find GCC build system scripts that rely on the validity of
overriding an option setting by appending a new setting. Legalistically, this
is usually counting on undocumented behaviour, but there's a better
chance of Russia joining NATO than of GCC ceasing to take the last setting that
it parses for a mutex option.


text:
Q: Django objects and openpyxl cells. How to set cell value like a value of django object field? I have to write a block of code which generates an xlsx report from Django dataset( few models). Frame of the report have more difficult structure than usual x rows y columns (some cells was united). It should look like that:

So I wrote view function:
from cut.models import *
from django.http import HttpResponse
from openpyxl.workbook import Workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font

def get_report(request):

    rent_test = Renters.objects.all

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    )
    response['Content-Disposition'] = 'attachment; filename=FORM_1-IL.xlsx'.format()
    workbook = Workbook()

    worksheet = workbook.active
    worksheet.title = 'A_REPORT'

    worksheet.merge_cells('A2:A5')
#...
    worksheet.merge_cells('M4:M5')

    worksheet['A2'].value = 'name of forestry'
#...etc.
    columns = [
    'only_one_column'
    ]
    row_num = 1

    for col_num, column_title in enumerate(columns, 1):
        cell = worksheet.cell(row=row_num, column=col_num)
        cell.value = column_title

    workbook.save(response)

    return response

So it is all understandable and simple.
But how I can use Django fields? I wish to transfer them to relative cell( value of field instead red font "field value"


text:
Q: They ARE Klingons, and it's a long story... What's the story? I just watched the episode of Star Trek DS9 Trials and Tribble-ations where the Defiant is taken back in time to the events of 'The Trouble with Tribbles' episode from Star Trek TOS. Those who remember the TOS Klingons know that they they don't look anything like Klingons as we now know them.
23rd Century Klingons:

When they're pointed out to Bashir and Odo as Klingons, they look on in disbelief, then all heads turn to Worf for an explanation:

Worf says that they are Klingons, but that it's a long story, and it isn't discussed with outsiders.
What's the story? Why do these 23rd century Klingons look like humans?

A: At the time "Trials and Tribble-ations" was shot, nobody involved with the production of Trek had figured out an in-universe way to explain changes in makeup and costume budgets between 1966 and 1979 (when the Klingon cranial ridges first appeared in TMP).  So at that time, there was no in-universe answer.  Giving Worf the "we don't discuss it with outsiders" line was a good way to acknowledge that yes, we know there's a discrepancy on screen, but the explanation isn't relevant to the story that's happening right now.  And it was a funny line, which was well-suited to the episode as a whole.

A: IN-Universe - As Worf said, it's something not discussed with non-Klingons.
OUT of Universe - To summarize, it's a very meta in-joke.
In the original series, they had a limited budget, and makeup options were few.  So the Klingons got goatees and dusky skin, and belt buckles made of bubble wrap.
When they made Star Trek: The Motion Picture, Roddenberry had the budget to give the Klingons the more alien look he maintained he wanted to give them all along.
But the fans went to great lengths to try to come up with an in-universe explanation for the change.  Both the possible explanations given in that scene were examples of those fan theories.
So when this episode came along, when we finally got to see "new" and "Classic" Klingons, there was much hope that an official reason would be given. So for Worf to then basically say "it's a secret" was a perfect response to that desire.
There was much screaming and shaking of fists.

A: Viral Mutation
This apparent discrepancy was explained in Star Trek Enterprise. Long story short, Klingons experimented with genetic mutation to make themselves stronger, much like what was accomplished with Kahn and the Augments, but there were side effects that made the Klingons look "hoo-mahn". These side effects were spread by a resulting virus, and after a cure was developed the human traits ware still passed on genetically by some.
From Memory Alpha:

In 2154, Klingon scientists working under the direction of Antaak
  recovered several Augment embryos from a hijacked Bird-of-Prey
  destroyed in orbit of Qu'Vat colony during the Augment Crisis. Fearing
  that Humans could overwhelm the Empire if they moved to staffing their
  ships with Augments, a project was set up to attempt to create their
  own Augments to counter the perceived threat.
The effort failed dreadfully. The Augments created did develop
  enhanced strength and intelligence, but they also began to show Human
  characteristics, from the blatant to the subtle. These included
  personality alterations and loss of the characteristic forehead
  ridges. Ultimately, the subjects died agonizing deaths when the
  incompatible DNA resulted in neural system breakdown. While working to
  stabilize the augmentation process, the scientific team enhanced a
  test subject who was, unknown to the team, also infected with Levodian
  flu. The flu virus in some manner incorporated the Augment DNA,
  turning a carefully controlled experiment into an epidemic. As the
  unstable augmentation process always killed the subject, this epidemic
  threatened the Klingon race with extinction.
The virus spread very rapidly, infecting millions within months. One
  of the first planets struck was N'Vak Colony. The Klingons attempted
  to capture Doctor Arik Soong to help develop a cure, but their efforts
  were thwarted by Soong's incarceration in a high security detention
  facility. They then moved to kidnap Doctor Phlox, using Rigelian
  intermediaries and the assistance of Section 31 agents. Phlox was
  forced to work with Antaak to find a cure. However, the Klingon High
  Council was unwilling to wait, and dispatched a fleet to annihilate
  the infected planets, starting with N'Vak Colony. Afterward it set
  course to Qu'Vat colony. (ENT: "Affliction")
When it became
  clear to the research team on Qu'vat colony that it would take weeks
  to develop a cure, stabilizing the augment virus became the
  researcher's primary concern. Their efforts proved successful; a
  method was developed that stabilized the process in the early stages,
  after the cranial ridges had dissolved and some minor neural
  re-ordering had occurred (which caused personality changes), but
  before the virus became contagious, enhanced augment abilities, and
  caused a fatal neural pathway breakdown.
Eventually, Admiral Krell convinced the High Council to call off their
  sterilization program of destroying the infected planets. The cure was
  distributed throughout the Empire. Because afflicted Klingons' DNA had
  been altered by the virus, the Human appearance and genetic traits
  were passed onto the descendants of the infected. Initially there were
  millions of Klingons who had to live with the disfigurement. (ENT:
  "Divergence")
In 2154, Antaak and Laneth
  feared that Klingons without ridges would become outcasts, lose their
  positions and would no longer have a place in the Empire. (ENT:
  "Divergence") However, by the 2260s, affected Klingons served as the
  captains and crews of front-line starships in the Klingon Defense
  Force. (Star Trek: The Original Series) Later on, some of them even
  achieved the title of Dahar Master and earned their statues among the
  Hall of Heroes on Qo'noS. (DS9: "Blood Oath", "The Sword of Kahless")
By the 24th century, knowledge of Klingons with smooth foreheads had
  been generally forgotten by the population of the United Federation of
  Planets. Also, the reason for Klingons having smooth foreheads a
  hundred years earlier was not widely known outside the Empire. When
  asked by Miles O'Brien and Julian Bashir, Worf simply gave the answer
  "we don't discuss it with outsiders", though Bashir immediately
  suspected viral mutation to be the cause. (DS9: "Trials and
  Tribble-ations")


text:
Q: Quasar iOS build - need podfile I have a web project based on quasar framework. I am also wrapping it in mobile apps. Android app building is fine. But when I try to build the ios app using the command "quasar build -m capacitor -T ios", it asks for a POD file.
✖ Updating iOS native dependencies with "pod install" (may take several minutes): ENOENT: no such file or directory, open '/Users/me/myapp/quasar/src-capacitor/ios/App/Podfile'
How do I get or create this file?


text:
Q: C++11 lambda - why do I need to capture auto duration variables? When writing a lambda function in capture '[]' part I need to specify only auto-duration variables while global and static variables are used within lambda function without needed to be captured. Why is that? Why are we not able to use auto-duration variables the same way as the global and static ones?

A: Because a lambda defines a separate scope: it is equivalent to this:
int global_i;

struct Lambda {
    Lambda(int captured_j) : captured_j(captured_j) {}
    void operator()(){
        // in this scope, global_i is accessible, and by capturing auto_j, we make that visible as well, but we can't see auto_i
    }

    int captured_j;
}

void foo() {
    int auto_i;
    int auto_j
    // this lambda
    [j](){}
    // is just shorthand for this:
    Lambda lambda(j);
}

The lambda is converted by the compiler into a function object (Like the Lambda class in my example). And the function object doesn't have access to local variables declared in the scope where the function object was instantiated. Unless you "capture" them by passing them to the constructor.
As for why the compiler doesn't do this implicitly, without requiring you to prompt it, it can't, because it doesn't know whether you want to capture by value or by reference. In GC'ed languages, you always capture by reference, because it doesn't matter -- the objects you reference stay alive as long as you need them.
But in C++, you need to manage the lifetime of those objects, and if a lambda always captured by reference, it would be virtually useless outside the scope it was declared in (because it would contain references to objects that had been destroyed). So in C++, you have to specify whether you want to capture by value or reference. And since you have to specify that, the compiler can't just do it for you.

A: Consider this simple function:
std::function<foo()> f()
{
    foo afoo;

    return [=](){ return afoo; };
}

int main()
{
    auto l = f();

    l();
}

If you don't capture the variable afoo, it goes out of scope before the closure formed by the lamda is ever used!
Also note that I used by-value capture exactly for the same reason: Returning references/pointers to local variables has undefined behaviour.

A: Essentially, there's not much magic about a lambda; simply consider it an anonymous functor.
A conventional functor would also not know about local variables where it is ctored, you'd need to provide them to its ctor. An anonymous thing like a lambda has no customizable c'tor, thus you provide context via this "[]" syntax.
Or consider
const float g_foo = 42.f;

struct A {
    float _bar;
    struct B {
        B() : _baz(_bar /*oops*/) {}
        float _baz;
    };
};

in A::B's closure there's no notion of a A's "_bar", but g_foo would be known.


text:
Q: Transparent border in WPF programmatically It's trivial to generate a border (to use for Trackball events) transparent over the viewport in the XAML file:
<Border Name="myElement" Background="Transparent" />

But how do I do it in the .cs?
Border border = new Border();
**border.Background = (VisualBrush)Colors.Transparent;**
grid.Children.Add(viewport);
grid.Children.Add(border);

This does not work of course.

A: Use a SolidColorBrush:
border.Background = new SolidColorBrush(Colors.Transparent);

The VisualBrush has a different purpose. See an overview of the main types of WPF brushes here:
http://msdn.microsoft.com/en-us/library/aa970904.aspx

A: You can also create a SolidColorBrush with transparent color:
This will create a fully transparent color
border.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));

but you can also make semitransparent color by changing alpha (this will look like 50% transparent red:
border.Background = new SolidColorBrush(Color.FromArgb(128, 255, 0, 0));

A: This is because you can't just cast a Color to be a Brush. use the Transparent brush instead
border.Background = Brushes.Transparent;


text:
Q: Windows Static Library with Default Functions I would like to create a static library (.lib) in Windows that can be used in subsequent builds as a "backup" for undefined functions.
For instance let's say I have foobar.lib which has definitions for:
FOO
BAR

and I have some other program that defines FOO only and is to be built into a DLL that must export FOO and BAR. I want to be able to use foobar.lib to automatically export the default definition of BAR in the resulting DLL (and ignore the definition of FOO in foobar.lib).
I have tried sending foobar.lib to the linker but I get a multiple defined symbols error (/FORCE is supposed to override that but with strong warnings that it probably won't work as expected). I've also tried using /NODEFAULTLIB:foobar.lib but then it completely ignores the library and says BAR is undefined.
I am almost 100% certain there is a way to do this because I use an application that does this (Abaqus) to allow users to write plug-ins and not have to define all of the required exports for the plug-in DLL. And they do not use the /FORCE option.

A: I figured out a solution (not sure if it is the only or best solution).
I was trying to define FOO and BAR in foobar.lib using one object file (foobar.obj). If I split it up into foo.obj and bar.obj and then use those to create foobar.lib the linker can effectively ignore the appropriate .obj files.
So the short answer is: one function per object file for the static library.