text:
Q: Variable Selection for Bayesian Linear Model Consider the Bayesian linear model $y_i\sim N(x_i\beta,\sigma^2 ), i=1,\ldots,n$  where $$\sum_{i=1}^n x_i=0, \sum_{i=1}^n x_i^2 =1, \sum_{i=1}^n x_i y_i=\gamma $$ The prior for $\beta$ and the dummy variable $z$ is given by $$\pi (\beta \mid z)=(1-z)\delta_0(\beta ) + zN(\beta \mid 0,\tau ^{2}) $$$$\pi (z)=q^z(1-q)^{1-z}$$
Suppose $\sigma , \tau , q$ are all known and $\delta_0(\beta )$ is the indicator function which is 1 when $\beta=0$ and is $0$ otherwise. So, $\beta=0$ if $z=0$ and $\beta =N(0,\tau^2)$ if $z=1$.
(1) Find $p(y_1,\ldots,y_n\mid z=0)$
(2) By integrating out $\beta$, Find $p(y_{1},...,y_{n}\mid z=1)$
(3) Hence, find $P(z=1\mid y_{1},...,y_{n})$
(4) What is $P(z=1\mid y_{1},...,y_{n})$ when $\gamma =0$ and with large $n$
(5) Under the condition in (4), give an intuitive explanation why $P(z=1\mid y_{1},...,y_{n})$
takes this value when $n → ∞$.
=======================================================================================
For the (1), my answer is $N(0,\sigma^2)(1-q)$
For the (2), my answer is $N(0,\tau^2)q$ - I am not sure about this one.
I have trouble to get the answers from (3) to (5), please help me to solve this problems and any input will be grateful and I really appreciate your time and help!

A: The exercise requires some calculations.
Try using these hints and see/tell us where you find issues:
(1) When $z=0$, $\beta=0$ almost surely, so that :
$p(y_1,...,y_n|z=0)=p(y_1,...,y_n|\beta=0)=\prod_i N(0,\sigma^2)(y_i)$
so there is not the factor $1-q$ that you propose. The presence of a  factor by the way would make also the density unnormalized. The notation $N(\mu,\sigma^2)(x)$ denotes the gaussian density evaluated at x.
(2)
$p(y_1,...,y_n|z=1)=\int d \beta p(y_1,...,y_n|\beta) p(\beta|z=1)$,
where you have to compute the Gaussian integral analytically end the densities on the left you know..
(3) Using Bayes:
$p(z=1∣y_1,...,y_n)=p(y_1,...,y_n|z=1)\frac{p(z=1)}{p(y_1,...,y_n|z=1)p(z=1)+p(y_1,...,y_n|z=0)p(z=0)}$
and now you can plug in results of previous points into this expression.
Once you arrive here with the calculations, I guess that then you can tackle points 4 and 5.

A: Thanks for your answer first. For the (2), I am using the following calculation: $$p(\beta |z=1)=N(\beta|0,\tau ^2)=N(0,\tau ^2)$$
$$\int p(y|\beta )p(\beta |z=1)d\beta =N(0,\tau^2)\int p(y|\beta )d\beta$$
COMMENT: $N(0,\tau^2)$ is a function of $\beta$ ( can you write it explicetly in the exponential form ? Remember that $0,\tau^2$ are the parameters of the distribution, and $\beta$ in this case is where you evaluate it). Think of it from the first equation you wrote. It is the conditional distribution over $\beta$ when $z=1$ and therefore depends on $\beta$. That is why you cannot take it out of the integral, but have to perform the integral explicitly.
Since $y\sim N(\beta ,\sigma ^2)$, will $\int p(y|\beta )d\beta=1?$ if so, the answer for (2) will be $\prod _{i}N(0,\tau^2)$ ?
COMMENT: The normalization does not work like that. It is $\int p(y|\beta )dy=1$ the right, albeit not very useful here,  normalization condition. Further, since from the previous comment the density is evaluated at $\beta$, you have no $y$ dependence on your answer, which therefore does not make much sense even from a qualitative point of view (i.e. the answer cannot be right).


text:
Q: If a sequence of measurable functions converges to $f_∗$ a.e. and to $g_∗$ in metric, then $f_* = g_*$ a.e.? Let $X$ be the space of all measurable functions $f: \Omega \to \mathbb{R}$ from $\Omega \subseteq \mathbb{R}^n$ to $\mathbb{R}$ and $(X,d)$ be a metric space with the metric $d:X \times X \to \mathbb{R}$.
Suppose that $\{f_j \in X\}_{j=1}^\infty$ be a sequence that converges to some function $f_*$ a.e. and at the same time converges to $g_* \in X$ in metric $d$, i.e.,
\begin{equation}
   \lim_{j \to \infty} d(f_j,g_*) = 0.
\end{equation}
Then, can we conclude that both types of convergence have the a.e. same limit point, i.e., $f_* = g_*$ a.e.?

I know that if $d$ is induced from $L^p$-norm ($1 \leq p< \infty$):
\begin{equation}
   d(f,g) := \Big ( \int_\Omega |f(x) - g(x)|^p \; d\mu(x) \Big )^{1/p},
\end{equation}
where $\mu$ is a measure on (a $\sigma$-algebra of) $\Omega$, then there is a subsequence $f_{j_n}$ that converges to $g_*$ a.e., and by the a.e. convergence $f_j \to f_*$, it is true that $f_* = g_*$ a.e.. Some related post for $p = 2$: Can a sequence of functions converge to different functions pointwise and on average?
In my post here, however, I am seeking the general answer, where the metric $d$ is not a form of $L^p$-norm, but just arbitrarily given. Can you give a counter-example if it is not true? Or, can you give a specific required condition or form (perhaps on the metric $d$) for $f_* = g_*$ a.e. to be true?

For your reference, this post is the general and refined version of the statement (If a sequence of continuous functions converges to $f_*$ pointwisely and to $g_*$ in metric, then $f_* = g_*$?) I previously posted, which turns out to be trivially NOT TRUE.

A: This is not true if you take an arbitrary metric. Let $\Omega = \{0\}$ with the counting measure. Hence, essentially we have $X = \mathbb{R}$.
Now, take any metric $d$ on $\mathbb{R}$ such that $\frac1n \to 1$ w.r.t. the metric $d$.
Then, $f_j = 1/j$ converges towards $0$ a.e. on $\Omega = \{0\}$, but towards $1$ w.r.t. the metric $d$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parallel Invoke of Windows Service in c# I have a 3rd party SDK (Cognitec) that has a wsdl file for a windows service. I can host this wsdl file on IIS and add a Service Reference using to it from IIS.
The service has a method called Identify() that takes 2 seconds. I am trying to call this method using Parallel.For():
    Parallel.For(0, 3, i =>
    {
    var start = DateTime.Now;
    wsdl.Identify();
    var time = DateTime.Now-start;
    Console.WriteLine(time);
    }

The Result:
2.1204121,
4.2135541,
5.8927112
The question is why Parallel.For() takes different execution time every time? I tried testing the same idea in WCF service & hosted it on IIS and the time result was the same for each call.


text:
Q: Can I store credit card data in SQL Server encrypted locally I have a C# application running on local server which is inside firewall. Only the employees (4-6) have access to application. Payments not done through application payments are processed online via bank app.
Now case is: customer gives their credit card detail over phone for payments and we need to do payments in 2 or more installments, so is it okay to store this information (including cc no. or may be cvv as well) in SQL Server installed on a local server, or should we make hard copy of data or just ask data again from user?
Thank you for your help!


text:
Q: C# Sql CTE Query - Select out extra information I am trying to write a CTE Recursive Query to build a tree relationship of a flat table with a 'marketGroupID' (that element's ID) and a 'parentGroupID' (the element's parent ID).  Where each 'marketGroup' can have any number of children 'marketGroups' and so on.
Here is my working query (tested in Sql Server Management):
    With cte As
(SELECT [marketGroupID]
      ,[parentGroupID]
      ,[marketGroupName]
      ,[description]
      ,[iconID]
      ,[hasTypes]
      , 0 As Level
  FROM [Eve_Retribution_1.0.7].[dbo].[invMarketGroups]
  WHERE [parentGroupID] IS NULL
  UNION All
  Select mg.marketGroupID
    ,mg.parentGroupID
    ,mg.marketGroupName
    ,mg.description
    ,mg.iconID
    ,mg.hasTypes
    ,c.Level + 1 As Level
  FROM [Eve_Retribution_1.0.7].dbo.invMarketGroups mg
  Inner Join cte c On mg.parentGroupID = c.marketGroupID
  WHERE mg.marketGroupID <> mg.parentGroupID
)
  SELECT marketGroupID
    ,parentGroupID
    ,marketGroupName
    ,description
    ,iconID
    ,hasTypes
    , Level
  FROM cte

This Query correctly lists the Elements in the correct order and the Level parameter is meant to be used to build the tree from the elements.
Translating this into C# is where I have a problem.  I have integrated this database and all the corresponding tables have been built from my database into my code automatically.  I try to call this query with C# as follows:
    EveOnlineClassesDataContext context = new EveOnlineClassesDataContext();
    IEnumerable<invMarketGroup> results = context.ExecuteQuery<invMarketGroup>
            (@"**ABOVE QUERY**");

Where the 'invMarketGroup' class is the automatically created class built by the O/R Designer.  My problem is that I lose access to the Level parameter for each 'marketGroup' as it was not part of the table itself and has no element in the provided class.
I want to retrieve from the query the actual 'invMarketGroup' class objects and the level corresponding to each so I can build a tree from this in memory representing this structure.  How would I go about doing this?
Thanks

A: Might be easier to create a View vwInvMarketGroup inside your database using that query:
CREATE VIEW vwInvMarketGroup AS
    With cte As
(SELECT [marketGroupID]
      ,[parentGroupID]
      ,[marketGroupName]
      ,[description]
      ,[iconID]
      ,[hasTypes]
      , 0 As Level
  FROM [Eve_Retribution_1.0.7].[dbo].[invMarketGroups]
  WHERE [parentGroupID] IS NULL
  UNION All
  Select mg.marketGroupID
    ,mg.parentGroupID
    ,mg.marketGroupName
    ,mg.description
    ,mg.iconID
    ,mg.hasTypes
    ,c.Level + 1 As Level
  FROM [Eve_Retribution_1.0.7].dbo.invMarketGroups mg
  Inner Join cte c On mg.parentGroupID = c.marketGroupID
  WHERE mg.marketGroupID <> mg.parentGroupID
)
  SELECT marketGroupID
    ,parentGroupID
    ,marketGroupName
    ,description
    ,iconID
    ,hasTypes
    , Level
  FROM cte
GO

Then you can use this:
IEnumerable<invMarketGroup> results = context.ExecuteQuery<invMarketGroup>(@"SELECT * FROM vwInvMarketGroup");


text:
Q: std::vector Destruction and Unexpected Memory Leak Consider the following example:
#include <vector>
class Foo {
    std::vector<int*> v;
public:
    Foo() {
        this->v.push_back(new int(23));
        this->v.push_back(new int(24));
        this->v.push_back(new int(25));
    }

    ~Foo() {
    }
};

int main() {
    Foo f;
    return 0;
}

When f goes out of scope in main(), f's destructor is called, which should indirectly free f.v.  According to this, the destructor of each element of the vector v should now be called.
However, when I run this program in valgrind, I find that the int*'s were not deallocated.
$ valgrind --leak-check=full ./a.out

What am I missing here?

A:
The destructor of each element of the vector v should now be called

Yes:  the int* objects stored in the vector are destroyed (which is effectively a no-op).  The objects pointed to by the pointers in the container are not destroyed.
Consider the following, equally valid program:
{
    int x;
    std::vector<int*> v;
    v.push_back(&x);
}   // x cannot be delete'd because it isn't dynamically allocated.

You should use a smart pointer, like std::unique_ptr or shared_ptr so that you don't have to worry about the memory management (do not use std::auto_ptr; it is incompatible with the Standard Library containers because it isn't really copyable).  If you don't use a smart pointer then you need to destroy the dynamically objects yourself; doing this correctly is rather difficult.

A: Each element of your vector is an int *.  When an int * is destroyed, the language does not automatically call delete on it.  In other words, it's the pointer being destroyed, not the pointee.

A: Since you are using the new keyword, the integers are being allocated on the heap rather than the stack. In other words, they are being allocated dynamically. In other words, you need to clean up after it.
The "destructor" for a pointer type is to simply delete that pointer. It does not touch the data which is located at the memory address stored by the pointer. Consider the following example:
int a = 5;
int* i = &a;
if (true)
{
   int* j = i;
} //j goes out of scope, should *i and a be deleted? no.

So you will need to do this in the destructor:
std::vector<int*>::iterator iter;
for (iter = v.begin(); iter != v.end(); iter++)
{
   delete *iter;
}

A: std::vector<T> does indeed call the destructor of T when it is destroyed. Here T is int *. The destructor of int * does nothing. The storage for the int * itself is freed, but the ints they point to are not.
Consider:
int main() {
   int *x = new int(23);
   return 0;
}

This exhibits the same problem; when x goes out of scope, its destructor is indeed called, and the storage for the pointer that is x is freed, but since the destructor of a pointer is a no-op, the pointed-to int is not freed.
More to the point, vector doesn't know how the ints were allocated. They might be allocated by new int, but they could also point to elements inside an array allocated with new int[200], or they might point to malloc'd data, or they might point into a mmap'd buffer, or they might point to struct elements, or two vectors might be pointing to the same ints... etc. vector isn't smart enough to divine what you want done with these, and so it leaves them alone (additionally, giving vector logic to delete pointed-to elements would break vectors of non-pointer elements such as std::vector<int>, as you can't delete an int!)
You need to either use a std::vector<int>, or use a smart pointer in conjunction with it, eg std::vector<boost::shared_ptr<int> >. Note that using smart pointers may add overhead; with C++0x you should be able to use std::vector<std::unique_ptr<int>> in conjunction with std::move to avoid this overhead. Boost also has pointer vectors that free the pointed-to elements as you expected as well.


text:
Q: eclipse command line switch to start with project What is the command line option to start eclipse with a specific project?
I can get the correct workspace using -data.
Within that workspace, I want to have a specific project loaded, similar to the "Go Into" command.

A: I don't think there is such an option right now.
Oening a file from the command line has only taken 9 years: bug 4922:
If your Eclipse Helios 3.6 eclipse.ini file contains "--launcher.defaultAction", you can open any file with:
eclipse.exe myFile

But open directly a project is still missing.

A: See this SO question which contains an Eclipse plugin that only loads specific projects (which are defined in a config file) into the workspace.


text:
Q: Write a Scheme function (sumList) Write a Scheme function (sumList) that returns the sum of all the numbers in a list which should be passed as a parameter. The list can have numbers, non-numeric symbols, and other lists. Your function should select all the number in the sublists and add them to the total. You can assume that the total is 0 if the list is empty. Example Usage:

(sumList  '((1 2 3)  5 a (10) ())
  21

A: (define (sumList lst)
  (cond
    ([empty? lst]
        0)
    ([list? (car lst)]
        (+ (sumList (car lst)) (sumList (cdr lst))))
    ((not(number? (car lst)))
        (sumList (cdr lst)))
    (else
        (+ (car lst)(sumList (cdr lst))))))


text:
Q: Generating dependencies for gcc I'm writing a Makefile to compile a very long project.
Basicaly, I've defined the all objects I need.
The problem comes when I need to generate the dependencies.
I'm doing something like this:
a.o: $( $(CXX) -MM $(INCLUDE) A/a.cpp | sed 's/a.o: //')
 $(CXX) $(CXXFLAGS) $(INCLUDES) A/a.cpp

b.o: $( $(CXX) -MM $(INCLUDE) A/b.cpp | sed 's/b.o: //')
 $(CXX) $(CXXFLAGS) $(INCLUDES) A/b.cpp

libab.a: a.o b.o
 $(LXX) $(LXXFLAGS) libab.a a.o b.o

The output of $(CXX) -MM $(INCLUDE) A/a.cpp | sed 's/a.o: //' lists all dependencies that a.cpp needs to be compilated so I'm trying to put the output of this command like dependencies when I'm declaring the object but it's not working.
Do you have an idea about how to do it?
Thanks.

A: Why are you trying to remove the target prefix which is exactly what you already had typed manually?
Instead just include the whole dependency files.
-include $(ALL_CPP_FILES:%.cpp=%.d)

My usual flags to automatically generate the .d (dependency) files is:
CPPFLAGS+=-MMD    # automatic .d dependency file generation

This is like -MD, except it mentions only user header files, not system header files.
Sample:
# BUILD=RELEASE

PRJNAME=demo
#
TARGETS+=bin/test

build: \
    $(TARGETS) \
    tags

all: build

clean:
    rm -rf bin/* $(ALL_OBJ_FILES)
    rm -rf $(ALL_CPP_FILES:%.cpp=%.d)

##############################
# definition
CC=gcc
CXX=g++

CPPFLAGS+=-MMD    # automatic .d dependency file generation
CPPFLAGS+=-std=c++11

ifeq ($(BUILD),RELEASE)
    CPPFLAGS+=-g -O3
    CPPFLAGS+=-march=native
else
    CPPFLAGS+=-g -O0
    CPPFLAGS+=-DDEBUG -D_DEBUG
    CPPFLAGS+=-DUNIT_TESTS
endif

CPPFLAGS+=-Wall -Wextra -pedantic
#CPPFLAGS+=-Werror

LDFLAGS+=-lpthread

ALL_CPP_FILES=A/a.cpp A/b.cpp
ALL_OBJ_FILES=$(patsubst %.cpp,%.o,$(ALL_CPP_FILES))

##############################
tags: $(ALL_CPP_FILES)
    ctags -R A/

%.o: %.cpp
    $(CXX) -c $(CPPFLAGS) $< -o $@

##############################
# tool targets
bin/test: $(ALL_OBJ_FILES)
    mkdir -pv $(@D)
    $(CXX) $^ $(LDFLAGS) -o $@

.PRECIOUS: S(ALL_OBJ_FILES)
.PHONY: clean all build

-include $(ALL_CPP_FILES:%.cpp=%.d)


text:
Q: Open all files with a certain extension in Powershell On Linux if I am in a directory and I want to open all .py files with an application (such as atom), I would simply type atom *.py and then all .py files will open with atom. If I type the same thing in Powershell, I receive an error, so I assume the syntax is different on Powershell. How would I accomplish this with Powershell?
Sorry if this is a very beginner question, its my first time using Powershell.

A: Collect the files you want to open first, then pipe them to the call of your external program:
Get-ChildItem -Path .\* -Include *.py | ForEach-Object {Start-Process -FilePath atom.exe -ArgumentList "`"$($_.FullName)`""}

Adjust the path to your external program if needed and also the the argument list (named arguments instead positional for example). Through the special quoting, this statement is prepared to even handle filenames with spaces.
If this line is to long for your *nix background, you can shrink it to:
gci *.py|%{start atom "`"$($_.FullName)`""}

A: Try this:
& "Full path of atom.exe" @("*.py")

A: If atom is set as the default for items with the .py extension you could run gi *.py.  Assuming this is not the case i'd right some function as part of a profile script to do this:
$AtomPath = "Path\To\Atom.exe"

function openWithAtom{

Get-ChildItem -Path .\* -Include $args[0] | ForEach-Object {Start-Process -FilePath $AtomPath -ArgumentList "`"$($_.FullName)`""}

}

new-item alias:atom -value openWithAtom

then you would run it with this: atom *.py, or atom filename.py
This tutorial should help with seting up a profile https://www.howtogeek.com/126469/how-to-create-a-powershell-profile/
Also if you haven't already id style your window so it looks more like a terminal.


text:
Q: How to change localization after an iPad app has been started i am currently working on an iPad app (iOS SDK v3.2). The app is localized in several languages, i.e. english, german, russian, ...
I want the user to be able to switch the localization for some UI elements after the app has been started. What is the best way to achieve this? NSLocalizedString always chooses the locale defined in the system preferences, so that won't help.
Note: the localization is all done by using .strings files, there are no localized NIBs in my project.
To make the whole process more clear, here's an example:
When the app is started the UI is displayed in english. The user can select a different language from a UITableView and parts of the UI get updated with the chosen language.
Do i have to manually load the specific Localizable.strings file and parse it all the way through or is there a better option, to get the relevant strings?
Any helpful advice is appreciated.
Thank you very much in advance and best regards.

A: I guess i found an answer to my own question:
NSLocale *selectedLocale; // defined in the classes interface
NSString *language = [selectedLocale objectForKey:NSLocaleLanguageCode];
NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj"];
NSBundle *bundle = [NSBundle bundleWithPath:path];

self.textView.text = NSLocalizedStringFromTableInBundle(@"Yadayada", @"Localizable", bundle, @"Yadayada comment");

A: Thanks @XCoder, that did work great.
However I do have an app BAD_EXC on the NSLocaleLanguageCode.
I got it solved using the method mentionned here:
iPhone Localization - Get the phone's language code?


text:
Q: Parallel and Single Threaded code having relatively same performance in Java I wrote a program to render a Julia Set. The single threaded code is pretty straightforward and is essentially like so:
private Image drawFractal() {
    BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
    for (int x = 0; x < WIDTH; x++) {
        for (int y = 0; y < HEIGHT; y++) {
            double X = map(x,0,WIDTH,-2.0,2.0);
            double Y = map(y,0,HEIGHT,-1.0,1.0);
            int color = getPixelColor(X,Y);

            img.setRGB(x,y,color);
        }
    }

    return img;
}

private int getPixelColor(double x, double y) {
    float hue;
    float saturation = 1f;
    float brightness;

    ComplexNumber z = new ComplexNumber(x, y);
    int i;
    for (i = 0; i < maxiter; i++) {
        z.square();
        z.add(c);
        if (z.mod() > blowup) {
            break;
        }
    }

    brightness = (i < maxiter) ? 1f : 0;
    hue = (i%maxiter)/(float)maxiter;
    int rgb = Color.getHSBColor(hue,saturation,brightness).getRGB();
    return rgb;
}

As you can see it is highly inefficient. Thus I went for Parallelizing this code using the fork/join framework in Java and this is what I came up with:
private Image drawFractal() {
    BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);

    ForkCalculate fork = new ForkCalculate(img, 0, WIDTH, HEIGHT);
    ForkJoinPool forkPool = new ForkJoinPool();
    forkPool.invoke(fork);
    return img;
}

//ForkCalculate.java
public class ForkCalculate extends RecursiveAction {
BufferedImage img;
int minWidth;
int maxWidth;
int height;
int threshold;
int numPixels;

ForkCalculate(BufferedImage b, int minW, int maxW, int h) {
    img = b;
    minWidth = minW;
    maxWidth = maxW;
    height = h;
    threshold = 100000; //TODO : Experiment with this value.
    numPixels = (maxWidth - minWidth) * height;
}

void computeDirectly() {
    for (int x = minWidth; x < maxWidth; x++) {
        for (int y = 0; y < height; y++) {
            double X = map(x,0,Fractal.WIDTH,-2.0,2.0);
            double Y = map(y,0,Fractal.HEIGHT,-1.0,1.0);
            int color = getPixelColor(X,Y);

            img.setRGB(x,y,color);
        }
    }
}

@Override
protected void compute() {
    if(numPixels < threshold) {
        computeDirectly();
        return;
    }

    int split = (minWidth + maxWidth)/2;

    invokeAll(new ForkCalculate(img, minWidth, split, height), new ForkCalculate(img, split, maxWidth, height));
}

private int getPixelColor(double x, double y) {
    float hue;
    float saturation = 1f;
    float brightness;

    ComplexNumber z = new ComplexNumber(x, y);
    int i;
    for (i = 0; i < Fractal.maxiter; i++) {
        z.square();
        z.add(Fractal.c);
        if (z.mod() > Fractal.blowup) {
            break;
        }
    }

    brightness = (i < Fractal.maxiter) ? 1f : 0;
    hue = (i%Fractal.maxiter)/(float)Fractal.maxiter;
    int rgb = Color.getHSBColor(hue*5,saturation,brightness).getRGB();
    return rgb;

}

private double map(double x, double in_min, double in_max, double out_min, double out_max) {
    return (x-in_min)*(out_max-out_min)/(in_max-in_min) + out_min;

}
}

I tested with a range of values varying the maxiter, blowup and threshold.
I made the threshold such that the number of threads are around the same as the number of cores that I have (4).
I measured the runtimes in both cases and expected some optimization in parallelized code. However the code ran in the same time if not slower sometimes. This has me baffled. Is this happening because the problem size isn't big enough? I also tested with varying image sizes ranging from 640*400 to 1020*720.
Why is this happening? How can I run the code parallely so that it runs faster as it should?
Edit
If you want to checkout the code in its entirety head over to my Github
The master branch has the single threaded code.
The branch with the name Multicore has the Parallelized code.
Edit 2 Image of the fractal for reference.

A: Here is your code rewritten to use concurrency. I found that my Lenovo Yoga misreported the number of processors by double. Also Windows 10 seems to take up an enormous amount of processing, so the results on my laptop are dubious. If you have more cores or a decent OS, it should be much better.
package au.net.qlt.canvas.test;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class TestConcurrency extends JPanel {

    private BufferedImage screen;
    final Fractal fractal;

    private TestConcurrency(final Fractal f, Size size) {
        fractal = f;
        screen = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
        setBackground(Color.BLACK);
        setPreferredSize(new Dimension(size.width,size.height));
    }

    public void test(boolean CONCURRENT) {
        int count = CONCURRENT ? Runtime.getRuntime().availableProcessors()/2 : 1;
        Scheduler scheduler = new Scheduler(fractal.size);
        Thread[] threads = new Thread[count];
        long startTime = System.currentTimeMillis();
        for (int p = 0; p < count; p++) {
            threads[p] = new Thread() {
                public void run() {
                    scheduler.schedule(fractal,screen);
                }
            };
            threads[p].start();
            try {
                threads[p].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        DEBUG("test threads: %d - elasped time: %dms", count, (System.currentTimeMillis()-startTime));
    }
    @Override public void paint(Graphics g)       {
        if(g==null) return;
        g.drawImage(screen, 0,0, null);
    }

    public static void main(String[]args) {
        JFrame frame = new JFrame("FRACTAL");
        Size size = new Size(1024, 768);
        Fractal fractal = new Fractal(size);
        TestConcurrency test = new TestConcurrency(fractal, size);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(test);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        for(int i=1; i<=10; i++) {
            DEBUG("--- Test %d ------------------", i);
            test.test(false);
            test.repaint();
            test.test(true);
            test.repaint();
        }
    }
    public static void DEBUG(String str, Object ... args)   { Also System.out.println(String.format(str, args)); }
}

class Fractal {

    ComplexNumber C;
    private int maxiter;
    private int blowup;
    private double real;
    private double imaginary;
    private static double xs = -2.0, xe = 2.0, ys = -1.0, ye = 1.0;
    public Size size;

    Fractal(Size sz){
        size = sz;
        real        =     -0.8;
        imaginary   =     0.156;
        C           =     new ComplexNumber(real, imaginary);
        maxiter     =     400;
        blowup      =     4;
    }

    public int getPixelColor(Ref ref) {
        float hue;
        float saturation = 1f;
        float brightness;
        double X = map(ref.x,0,size.width,xs,xe);
        double Y = map(ref.y,0,size.height,ys,ye);
        ComplexNumber Z = new ComplexNumber(X, Y);

        int i;
        for (i = 0; i < maxiter; i++) {
            Z.square();
            Z.add(C);
            if (Z.mod() > blowup) {
                break;
            }
        }

        brightness = (i < maxiter) ? 1f : 0;
        hue = (i%maxiter)/(float)maxiter;
        return Color.getHSBColor(hue*5,saturation,brightness).getRGB();

    }
    private double map(double n, double in_min, double in_max, double out_min, double out_max) {
        return (n-in_min)*(out_max-out_min)/(in_max-in_min) + out_min;

    }
}
class Size{
    int width, height, length;
    public Size(int w, int h) { width = w; height = h; length = h*w; }
}
class ComplexNumber {
    private double real;
    private double imaginary;

    ComplexNumber(double a, double b) {
        real = a;
        imaginary = b;
    }

    void square() {
        double new_real = Math.pow(real,2) - Math.pow(imaginary,2);
        double new_imaginary = 2*real*imaginary;
        this.real = new_real;
        this.imaginary = new_imaginary;
    }

    double mod() {
        return Math.sqrt(Math.pow(real,2) + Math.pow(imaginary,2));
    }

    void add(ComplexNumber c) {
        this.real += c.real;
        this.imaginary += c.imaginary;
    }
}
class Scheduler {
    private Size size;
    private int x, y, index;
    private final Object nextSync = 4;

    public Scheduler(Size sz) { size = sz; }
    /**
     * Update the ref object with next available coords,
     * return false if no more coords to be had (image is rendered)
     *
     * @param ref Ref object to be updated
     * @return false if end of image reached
    */
    public boolean next(Ref ref) {
        synchronized (nextSync) {
            // load passed in ref
            ref.x = x;
            ref.y = y;
            ref.index = index;
            if (++index > size.length) return false;    // end of the image
            // load local counters for next access
            if (++x >= size.width) {
                x = 0;
                y++;
            }
            return true;        // there are more pixels to be had
        }
    }
    public void schedule(Fractal fractal, BufferedImage screen) {
        for(Ref ref = new Ref(); next(ref);)
            screen.setRGB(ref.x, ref.y, fractal.getPixelColor(ref));
    }
}
class Ref {
    public int x, y, index;
    public Ref() {}
}


text:
Q: Como corrigir fonte serrilhada no chrome? Estou com um problema no Google Chrome. Não sei se é o CSS, mas as fontes declaradas no CSS estão ficando serrilhadas principalmente no Chrome. Já tentei as seguintes propriedades para diminuir o serrilhamento (anti-alising):
-webkit-font-smoothing;
font-smooth;
text-stroke;
text-shadow;

O site que está com este problema é este.

A: Este comportamento foi corrigido no Chrome 37. Para simular um resultado comparável ao antialias, você pode utilizar text-shadow, como no exemplo a seguir:

.teste
{
    color: black;
    font-size: 50px;
    text-align: center;
    line-height: 1;
}

.teste.antialias{
    -webkit-font-smoothing: antialiased;
    -webkit-text-shadow: rgba(0,0,0,.01) 0 0 1px;
    text-shadow: rgba(0,0,0,.01) 0 0 1px;
    }
Alias

(pre-Chrome 37)

Antialias

Fonte: How to apply font anti-alias effects in CSS?, Stack Overflow (em inglês)


text:
Q: How do we algebraically manipulate non-commutative equations? (Ie. Diagonalization: $A=PDP^{-1} \rightarrow AP=PD$)
*

*How can we manipulate non-commutative equations? (See question 3 below)

*It seems in the formula for Diagonalization, $A=PDP^{-1} \rightarrow AP=PD$, does one just multiply both sides by P?

*Main question: How do we manipulate it instead to $PAP^{-1}=D$?

A: First of all, it's not the equation that is non-commutative, but rather the operation used in the equation.
As to the main point, there's actually nothing special here, we just have to be a bit more careful. The basic logical apparatus of equality (see here for more on this) tells us that given any well-defined function $F$ and any true equation $s=t$, the equation $F(s)=F(t)$ is again a true equation. In particular, this applies to $F(x)=xy$ for a fixed $y$, as well as to $G(x)=yx$ for a fixed $y$. The non-commutativity of multiplication in our current setting means that $F$ and $G$ are not the same in general, but that's fine.
So, looking at your particular example, we argue as follows:

*

*We start with $A=PDP^{-1}$ by assumption.

*We now apply the principle above with $F(x)=xP$. This gives $$F(A)=F(PDP^{-1})\quad\implies \quad AP=PDP^{-1}P\quad\implies AP=PD.$$
Now we are still being a bit informal - we're being rather cavalier with respect to the associative property of multiplication (which still holds). Ultimately a fully formal approach will involve some parentheses-juggling. But the above is perfectly adequate for the topic.
Note that we didn't simply "multiply by $P$" - in the absence of commutativity, "multiplication by $P$" isn't well-defined. Our $F$ in this case was multiplication on the right by $P$. We could also have multiplied by $P$ on the left on both sides of the equation, getting $$PA=P^2DP^{-1}.$$ However, we could not multiply by $P$ on the left in the left hand side and on the right on the right hand side: $PA=PD$ is not something we can conclude from $A=PDP^{-1}$ (without further hypotheses, at least).


text:
Q: Binary searching via bitmasking? I have used this algorithm many times to binary search over Ints or Longs. Basically, I start from Long.MinValue and Long.MaxValue and decide to set the bit at ith position depending on the value of the function I am maximizing (or minimizing). In practice, this turns out to be faster (exactly 63*2 bitwise operations) and easier to code and avoids the many gotchas of traditional binary search implementations.
Here is my algorithm in Scala:
/**
 * @return Some(x) such that x is the largest number for which f(x) is true
 *         If no such x is found, return None
 */
def bitBinSearch(f: Long => Boolean): Option[Long] = {
  var n = 1L << 63
  var p = 0L
  for (i <- 62 to 0 by -1) {
    val t = 1L << i
    if (f(n + t)) n += t
    if (f(p + t)) p += t
  }
  if (f(p)) Some(p) else if (f(n)) Some(n) else None
}

I have 3 questions:

*

*What is this algorithm called in literature? Surely, I can't be the inventor of this - but, I did not find anything when I tried googling for various combinations of binary-search + bit-masking/toggling. I have been personally calling it "bitBinSearch". I have not seen this mentioned at all in articles going over binary search over an Int or Long domain where this would be trivial to write.

*Can the code be improved/shortened in anyway? Right now I keep track of the negative and positive solutions in n and p. Any clever way I can merge them  into single variable? Here are some sample test cases: http://scalafiddle.net/console/70a3e3e59bc61c8eb7acfbba1073980c before you attempt an answer

*Is there a version that can be made to work with Doubles and Floats?

A: As long as you're bit-twiddling (a popular pastime in some circles) why not go all the way?  I don't know if there's any efficiency to be gained, but I think it actually makes the algorithm a little clearer.
def bitBinSearch(f: Long => Boolean): Option[Long] = {
  var n = Long.MinValue
  var p = 0L
  var t = n >>> 1
  while (t > 0) {
    if ( f(n|t) ) n |= t
    if ( f(p|t) ) p |= t
    t >>= 1
  }
  List(p,n).find(f)
}

Of course, if you go recursive you can eliminate those nasty vars.
import scala.annotation.tailrec
@tailrec
def bitBinSearch( f: Long => Boolean
                , n: Long = Long.MinValue
                , p: Long = 0L
                , t: Long = Long.MinValue >>> 1 ): Option[Long] = {
  if (t > 0) bitBinSearch(f
                         , if (f(n|t)) n|t else n
                         , if (f(p|t)) p|t else p
                         , t >> 1
                         )
  else List(p,n).find(f)
}

Again, probably not more efficient, but perhaps a bit more Scala-like.
UPDATE
Your comment about Int/Long got me wondering if one function could do it all.
After traveling down a few dead-ends I finally came up with this (which is, oddly, actually pretty close to your original code).
import Integral.Implicits._
import Ordering.Implicits._
def bitBinSearch[I](f: I => Boolean)(implicit ev:Integral[I]): Option[I] = {
  def topBit(x: I = ev.one):I = if (x+x < ev.zero) x else topBit(x+x)
  var t:I = topBit()
  var p:I = ev.zero
  var n:I = t+t
  while (t > ev.zero) {
    if ( f(p+t) ) p += t
    if ( f(n+t) ) n += t
    t /= (ev.one+ev.one)
  }
  List(p,n).find(f)
}

This passes the following tests.
assert(bitBinSearch[Byte] (_ <= 0) == Some(0))
assert(bitBinSearch[Byte] (_ <= 1) == Some(1))
assert(bitBinSearch[Byte] (_ <= -1) == Some(-1))
assert(bitBinSearch[Byte] (_ <= 100) == Some(100))
assert(bitBinSearch[Byte] (_ <= -100) == Some(-100))
assert(bitBinSearch[Short](_ <= 10000) == Some(10000))
assert(bitBinSearch[Short](_ <= -10000) == Some(-10000))
assert(bitBinSearch[Int]  (_ <= Int.MinValue) == Some(Int.MinValue))
assert(bitBinSearch[Int]  (_ <= Int.MaxValue) == Some(Int.MaxValue))
assert(bitBinSearch[Long] (_ <= Long.MinValue) == Some(Long.MinValue))
assert(bitBinSearch[Long] (_ <= Long.MaxValue) == Some(Long.MaxValue))
assert(bitBinSearch[Long] (_ < Long.MinValue) == None)

A: I don't know Scala, but this is my version of Binary searching via bitmasking in java

My algorithm is like this
We start with the index with highest power of 2 and end at 20. Every time we see A[itemIndex] ≤ A[index] we update itemIndex += index
After the iteration itemIndex gives the index of the item if present in the array else gives the floor value in A
int find(int[] A, int item) { // A uses 1 based indexing
    int index = 0;
    int N = A.length;
    for (int i = Integer.highestOneBit(N); i > 0; i >>= 1) {
        int j = index | i;
        if (j < N && A[j] <= item) {
            index = j;
            if (A[j] == item) break;
        }
    }
    return item == A[index] ? index : -1;
}


text:
Q: Installing Microsoft's ODBC Driver for SQL Server on Raspberry Pi I'm trying to use pyodbc python package on raspberry pi 4. I install pyodbc and then I followed this link: https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15 to download the ODBC driver but I get this error when I run my script:
Traceback (most recent call last):
  File "/home/pi/Desktop/water.py", line 22, in <module>
    conn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)")

I believe my machine doesn't find the ODBC driver 17 that I just downloaded. Although, I can see all the odbc file downloaded under usr/lib/arm-linux-gnueabihf/odbc.
Could someone help me to use import pyodbc on a rpi4?
Here is the line where the error is found in my script:
conn = pyodbc.connect('DRIVER = {ODBC Driver 17 for SQL Server}; SERVER = projectdb.database.windows.net; DATABASE = projectdb; UID= AppLogin; PWD= 87dwwg4ed')

A:
I can see all the odbc file downloaded under usr/lib/arm-linux-gnueabihf/odbc.

The path suggests that your Pi is using the Arm architecture. It is very possible that Microsoft does not offer a package for Arm. The product list for Buster …
https://packages.microsoft.com/config/debian/10/prod.list
… only lists the amd64 architecture:
deb [arch=amd64] https://packages.microsoft.com/debian/10/prod buster main

So, you may need to use FreeTDS ODBC instead:
pi@raspberry:~ $ sudo apt install tdsodbc

(That seems to be what most Raspberry Pi users are doing based on other questions I've seen.)


text:
Q: How many disk space oracle synonym takes? We've a problem at my company because everyone shares the development oracle database. Thus, if a developer wants to modify a procedure or package, for example, other's application will fail, until this first developer ends his work.
So I thought it will be great if I could create a User in my database for each demand of work within a synonym (or many) for datase objects.
Here comes the example:
I have a demand called D9877, for instance. My work on this demand is to alter a package named MYPCKG. So to start assignment, I first create a Oracle user as D9877 within a synonym for my MYPCKG. This way, any modification will be applied on synonym, without affecting any other developers.
And here are my questions:

*

*Could I do that without my server storage explodes?

*How many disk space a oracle synonym takes?

A: I think your understanding of synonyms is not quite correct.
Synonym is a link on another object. As a shortcut on file on Windows or link on Linux.
To be able to parallel change of some packages you need to make sure that your application could be installed on dedicated schema. You can create local synonyms on you tables (because tables do take space!) from main application schema and compile packages in your schema. Another developers can have their own version of application (i.e. packages, views).
However you need to consider some cases like triggers (it could be tricky to have 2 versions of the trigger on the same table), some dynamic DDL to tables executed by your application, like truncate table and etc.

A: Synonym takes several bytes of disk space, but it isn't important at all. This approach will not solve this problem.
First of all it seems like you misunderstand what synonym means. It's an other name for the same object. You cannot 'apply modifications to the synonym', but even if you can, you'll modify the object itself.
Sometimes synonyms can be used to distinguish package versions. Say, you have package A; all uses it. You can make packages A_VERSION_1 and A_VERSION_2, public synonym A for A_VERSION_2 and private synonym A for A_VERSION_2. If you do so, you'll can to debug your application with A_VERSION_2 while all others works with A_VERSION_1.
Bad news is this approach does not work too. It works only when you directly call A from your application. But let's imagine we have two packages, A and B (authid definer). B uses A. You call B from your application and you should to modify A. In this case B will never look to your private synonym. You'll be in need to make B_VERSION_2 with it's private synonym too etc. In view of number of intercalls between database objects it's impossible way to use.


text:
Q: "Conflicting models in application..." with external database tables I have an project with a number of applications that accesses both my local MySQL database with 100s of tables, and also several external MySQL and Ms-SQL Server databases with many more tables.  All of the external tables are defined in models using the "managed=False" meta data.
I recently upgraded Django from 1.6 to 1.7 following the instructions in the release notes and other hints, etc. from StackOveflow.
Everything seems to be working again with the exception of all of my applications that access the remote database tables.  Here is an example message:
RuntimeError: Conflicting 'bugview_deferred_description_disposition_divisioaf59cb28117de5eb6ddfea0476dab601' models in application 'nvbugsdw': <class 'bug_metrics.models_bugs.BugView_Deferred_Description_Disposition_Divisioaf59cb28117de5eb6ddfea0476dab601'> and <class 'bug_metrics.models_bugs.BugView_Deferred_Description_Disposition_Divisioaf59cb28117de5eb6ddfea0476dab601'>.

The table BugView is defined in a file names models_bugs.py as follows:
class BugView(models.Model):
BugId            = models.BigIntegerField(primary_key=True)
Module           = models.CharField(max_length=128, null=False)
Requester        = models.CharField(max_length=128, null=False)
QAEngineer       = models.CharField(max_length=128, null=False)
Engineer         = models.CharField(max_length=128, null=False)
RequestDate      = models.DateTimeField(null=False)
ModifiedDate     = models.DateTimeField(null=False)
Priority         = models.CharField(max_length=50, null=False)
Severity         = models.CharField(max_length=50, null=False)
Disposition      = models.CharField(max_length=64, null=False)
BugAction        = models.CharField(max_length=64, null=False)
Origin           = models.CharField(max_length=64, null=False)
GeographicOrigin = models.CharField(max_length=128, null=False)
Division         = models.CharField(max_length=64, null=False)
Synopsis         = models.CharField(max_length=256, null=False)
Description      = models.CharField(max_length=1024, null=False)
BugType          = models.CharField(max_length=50, null=False)
OriginalBugId    = models.BigIntegerField()

class Meta:
    app_label = 'nvbugsdw'
    managed   = False
    db_table  = 'bugview'

In the views.py file the class is imported like:
from .models_bugs import BugView

I also tried
from models_bugs import BugView
from bug_metrics.models_bugs import BugView

"bug_metrics" is the application name.
I followed all of the suggestions previously posted on https://code.djangoproject.com/ticket/22280 to no effect.
I'm at a loss at this point.  Any suggestions?
Also, this may not be related, but in trying to debug this issue (by dumping sys.path in manage.py), I noticed that the code in manage.py is executed twice when I run the command
./manage.py runserver --nothreading 0.0.0.0:8081

My sys.path is:
/opt/graphic_tools/gtools
/usr/local/lib/python2.7/dist-packages/South-0.8.4-py2.7.egg
/usr/lib/python2.7
/usr/lib/python2.7/plat-linux2
/usr/lib/python2.7/lib-tk
/usr/lib/python2.7/lib-old
/usr/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages/PIL
/usr/lib/python2.7/dist-packages/gst-0.10
/usr/lib/python2.7/dist-packages/gtk-2.0
/usr/lib/pymodules/python2.7
/usr/lib/python2.7/dist-packages/ubuntu-sso-client
/usr/lib/python2.7/dist-packages/ubuntuone-client
/usr/lib/python2.7/dist-packages/ubuntuone-control-panel
/usr/lib/python2.7/dist-packages/ubuntuone-couch
/usr/lib/python2.7/dist-packages/ubuntuone-installer
/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol

"/opt/graphic_tools/gtools" is my project directory.  It does NOT contain a init.py file and does contain all of the application sub-directories  including a "gtools" sub-directory.

A: One suggestion. Did you try to synchronize your 'remote' databases after upgrading to the new version of Django? Maybe they are not synced?
I assume you have something like:
DATABASES = {
'default': {some credentials},
'remote_db_name1': {some credentials},
'remote_db_name2': {some credentials},
...
}
you can run

./manage.py migrate --database=remote_db_name1
./manage.py migrate --database=remote_db_name2

etc.
(Also, I assume you ran 'makemigrations' for your app before.)
The reason is that by default migrate operates on 'default' db, so the others could be skipped.

A: So, in my particular case, the problem was caused by running an older version of Django.  I thought I installed 1.7.11 but actually installed 1.7.0.  When I installed 1.7.11 the problem went away.
Wrong way:
sudo pip install django=="1.7"

Correct way:
sudo pip install django=="1.7.11"


text:
Q: Is there a way to assign a column attribute in Postgres based on another column and its percentage of a total group I am new to Postgres and am developing some test data.  I have a table (family_zone) with 1,000 unique family ids and their corresponding regional zone, for example:

Family_ID
Zone

1
100

2
100

3
100

4
100

...
...

1000
100

I have another table that maps zip codes to zones (zip_map) along with the number of families that live in each zip code, for example:

ZIP
Zone
family_num

10001
100
125

10002
100
25

10003
100
50

10004
100
200

10005
100
150

10006
100
130

10007
100
120

10008
100
75

10009
100
125

...
....
...

10099
200
125

10100
200
25

I need to assign each family id to a zip code.  The number of family ids mapped to each zip code needs to match the percentage of families that live in each zip compared to the total number of families in the zone (i.e. if there are 1,000 families in zone 100 and 125 families live in 10001, then 12.5% of the family ids in zone 100 or 125 family ids should be assigned to zip code 10001, 25 should be assigned to zip 10002, etc. ).  I need to add an attribute to the first table with the zip assigned to each family id.

Family_ID
Zone
assigned_ZIP

1
100
10001

2
100
10001

3
100
10001

...
...
...

125
100
10001

126
100
10002

...
...
...

150
100
10002

151
100
10003

...
...
...

1000
100
10009

Can this be done solely in PostgreSQL?


text:
Q: Can anybody locate the "AppleScript Resources for Office 2004" by Microsoft I'm looking for the (official MS) guide to scripting Excel with Applescript. I found one for Word from same era but not Excel. Even four MS support staff (three calls) can't find anything for me, in fact they don't even bother looking.
A document called "MicrosoftOfficeforMac2004ResourceKitv2" links to the microsfot.com/mac page and says goto Resources > Developer Center > AppleScript Resources for Office 2004 section. It doesn't exist any more.

A: Give this a try, it's what i've been using lately:
http://download.microsoft.com/download/3/A/7/3A70FB4B-0C6A-43E3-AAB7-AC9166B25632/Excel2004AppleScriptRef.pdf


text:
Q: How to manage the device (update drivers, see with device are faulty, etc.) of a windows server 2016 core? I just installed windows server 2016 core. Now how can I manage the device drivers (or see with device are in fault) as their is no devmgmt.msc on server core ?

A: Run mmc on your management machine, click file -> Add Snap-In or press Ctrl+M and select the device management MMC. If you add it you can tell it to work on a remote machine (your core server).
Alternatively you might be able to use WMI or PowerShell but I'm not sure about the commands in that case.


text:
Q: could not get a field value by reflection hibernate JPA + GF 4 I am using JPA 2.1 with Hibernate 4.3.x on Glassfish 4, also tried the suggestion listed at https://coderwall.com/p/e5fxrw still get the below error. Could some one let me know what might be the issue ?
javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.dstar.entity.PurchaseOrder.idpurchaseorder
Below is the entity code, skipped getter and setter methods:
@Entity
@Table(name="purchaseorder")
@PersistenceUnit(name="dstarwarehouse",unitName="dstarwarehouse")
public class PurchaseOrder implements Serializable{

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int idpurchaseorder;
    private boolean cash;
    private boolean credit;
    private String supplier;
    private String orderedBy;
    private String submittedBy;
    private String approvedBy;
    private Date expectedDate;
    private Date creationDate;
    private Date submittedDate;
    private Date approvalDate;
    private String purchaserName;

    private double total;

    @JoinColumn(name="idpurchaseorder", referencedColumnName="idpurchaseorder")
    private List<Part> parts;

}

A: I had the same problem, using glassfish 4.1, hibernate 4.3.6, and injecting entity manager thru @PersistenceContext in a Stateless Session Bean, and saw some things interesting.
First, if I get the entity manager direct from the Persistence.createEntityManagerFactory("xxxxxx").createEntityManager() the problem disappear. Obviously, I don't like get things right in this way.
Change the server from glassfish 4.1 to glassfish 4, seems solve the problem too. So, at this moment, the problem looks like for me something wrong in glassfish 4.1.


text:
Q: how to reduce number of similar queries I'm making a very basic analytics feature for my Rails app. I want to provide statistics that tell users how many visitors have viewed their profile, and then also break those down according to the particular role (I'm using 'rolify' in my app) each visitor has.
In the show action of the Users controller, I do this
@profileviews = Profileview.where(:user_id => @user.id)
@profileviewsbysomerole = Profileview.where({:user_id => @user.id, :viewer_role => 'someRole'})
@profileviewsbysomeotherrole = Profileview.where({:user_id => @user.id, :viewer_role => 'someOtherRole'})

and then in the show action, I'd do
Your profile has been viewed <%= @profileviews.size %> times.
Your profile has been viewed by users with a particular role <%= @profileviewsbysomerole.size %> times.
Your profile has been viewed by users with some other role <%= @profileviewsbysomeotherrole.size %> times.

Is there a way to accomplish what I'm trying to do without making three separate queries, or is this the best way (in terms of not degrading performance) to obtain these stats.

A: In terms of performance I think it is OK. The other option would be to query for all the objects and then filter in memory, but I don't think this is a good idea. It's best to let the database do what it does best.
One thing that comes to mind -- you could use a single query and group_by in order to avoid making the second and third calls, but that's relevant if you're looking to get some aggregated data.
In terms of coding style, you could define scopes for the different queries and use them from the view, but it might be an overkill.

A: If you find yourself using these things together a lot, it might be nice to bundle them up together something like this:
# in user model
def profile_view_hash(*roles)
  views = { 'all' => Profileview.where(:user_id => id).all }
  roles.each do |role|
    views.merge!({
      role => Profileview.where(:user_id => id, :viewer_role => role).all
    })
  end
  views
end

This should allow you to use it like this:
# in controller
@profile_views = @user.profile_view_hash('someRole','someOtherRole')

# in view
<%= @profile_views['all'] %>
<%= @profile_views['someRole'] %>
<%= @profile_views['someOtherRole'] %>

By the way, in your example, you are only showing the output of .size. If that's all you need, you should be using count instead of all

A: I would leave them all out of the controller, and make the view like this:
Your profile has been viewed <%= @user.profileviews.size %> times.
Your profile has been viewed by users with a particular role <%= @user.profileviews.select { |profile_view| profile_view.viewer_role == 'someRole' }.size %> times.
Your profile has been viewed by users with some other role <%= @user.profileviews.select { |profile_view| profile_view.viewer_role == 'someOtherRole' }.size %> times.

You could take this even further by moving this logic to the Profileview, maybe like:
def views_for_role( role )
  select { |profile_view| profile_view.viewer_role == role }.size
end

and delegating it in the User, maybe like:
delegate :views_for_role, :to => :profileview

Which would make your view look like this:
Your profile has been viewed <%= @user.profileviews.size %> times.
Your profile has been viewed by users with a particular role <%= @user.views_for_role 'someRole' %> times.
Your profile has been viewed by users with some other role <%= @user.views_for_role 'someOtherRole' %> times.


text:
Q: Performance of Holt-Winter´s seasonal method is different from Python to Excel I have to code the "Forecast.ETS" function from excel in Python to predicts a future values based on existing (historical) values.
In the Excel documentation they write that it is based on the AAA version of the Exponential Smoothing (ETS) algorithm.
Excel Documentation:
Microsoft: Calculates or predicts a future value based on existing (historical) values by using the AAA version of the Exponential Smoothing (ETS) algorithm. The predicted value is a continuation of the historical values in the specified target date, which should be a continuation of the timeline.
Python Documentation:
ETS models in python the specific ETS model for AAA is the Holt-Winters.
Coding that: Data would be daily data and we want to predict 50 days
data = [533.0,769.0,1014.0,1362.0,1368.0,1490.0,1493.0,1570.0,2240.0,2543.0,2617.0,
        3180.0,3401.0,3452.0,3513.0,3666.0,3710.0,3961.0,4029.0,4084.0,4217.0,4464.0,
        5109.0,5198.0,5279.0,5731.0,5923.0,6169.0,6361.0,6455.0,6713.0,6885.0,7267.0,7422.0,
        7670.0,8300.0,8401.0,8430.0,8850.0,10162.0,10366.0,10640.0,10820.0,
        10892.0,10940.0,11282.0,11403.0,12150.0,12637.0,13173.0]

index_values = pd.date_range('2021-01-15', '2021-03-05', freq="D")
data_analysis = pd.Series(data, index=index_values)

model = ETSModel(data_analysis, error="add", trend="add", seasonal="add",damped_trend=True,
seasonal_periods=7)
fit = model.fit()

pred = fit.get_prediction(start='2021-03-05', end='2021-05-14')
df_prediction = pred.summary_frame(alpha=0.25)
df_prediction

the output from python look like this:
             mean             pi_lower       pi_upper
2021-03-06  13632.805132    13341.737194    13923.873071
2021-03-07  13899.410604    13461.334446    14337.486761
2021-03-08  14189.704924    13620.755823    14758.654025
2021-03-09  14609.667134    13915.355002    15303.979266
2021-03-10  14825.921265    14008.092306    15643.750223

The same algorith in Excel return that data:
            mean    pi_lower pi_upper
2021-03-06  13386   12910    13862
2021-03-07  13631   12990    14271
2021-03-08  13876   13105    14647
2021-03-09  14121   13238    15003
2021-03-10  14365   13383    15347

So the predictions are very similar but not the same, is this normal, should I be worried, is this to be expected because excel requires "int" and the python method needs float ?


text:
Q: Same session in multiple tabs and when a user logs in any tab and if they navigate in a new tab of same browser they must already be logged in I would like to know how to get same session multiple tabs and clear the session when all tabs are gone.Then,

*

*When a user logs into the site in any tab and if they navigate to the site in a new tab they must already be logged in in the same browser.

*When a user logs out of any tab they must log out of all tabs immediately.

*A user can refresh the page and stay logged in.
-Once all tabs are closed the user is logged out and must log back in.

Here,i set and get the sessionStorage in Utils,
let getSessionStorage = (key) => {
 return sessionStorage.getItem(key);
};
let setSessionStorage = (key, value) => {
    sessionStorage.setItem(key, value);
};

Here is my code after getting login success, i set the sessionStorage data,
if (this.props.isLoginSuccess)
{
      Utils.setSessionStorage('clu_email', this.props.userData.clu_email);
      Utils.setSessionStorage('cli_name', this.props.userData.cli_name);
      Utils.setSessionStorage('clu_id', this.props.userData.usr_id);
      Utils.setSessionStorage('clu_idv', this.props.userData.clu_idv);
      Utils.setSessionStorage('clu_name', this.props.userData.clu_name);
      Utils.setSessionStorage('clu_type', this.props.userData.clu_type);
      Utils.setSessionStorage('clu_cat', this.props.userData.clu_cat);
      Utils.setSessionStorage('cli_depart', this.props.userData.cli_department);
      Utils.setSessionStorage('cli_logo_image', this.props.userData.cli_logo_image);
      Utils.setSessionStorage('usr_id', this.props.userData.usr_id);
      if (this.props.userData.clu_type == 1){
      this.props.history.push('fmp/dashboard');
      }
      else
      {
        Utils.setSessionStorage('org_id', this.props.userData.cli_id);
        Utils.setSessionStorage('cli_name', this.props.userData.cli_name);
        Utils.setSessionStorage('cli_logo_image', this.props.userData.cli_logo_image);
        this.props.history.push('client/dashboard');
       }
      window.location.reload();
    }
  }

Here,i get the session data and check if its is true it navigate to dashboard else it navigates to login,
<Route path="/fmp/dashboard" render={props => (
                     Utils.getSessionStorage('clu_id')
                        ? <FMPDashboard {...props} />
                        : <Redirect to={{ pathname: '/login'}} />
                )} />

A: You can save the key in localStorage instead of the sessionStorage and detect if the storage changed like this:
window.addEventListener("storage", function () {
  // Check if the key changed and is empty
  // Do your logout logic
}, false);

Keep in mind the event will be raised in all the tabs/windows OTHER than the one that triggered the change, so you will have to manually log out of the windows that changed the storage.


text:
Q: Dealing with noise for Frenet-Serret Frames I have a curve and I calculate Frenet-serret frames for each point on the curve. If the curve is smooth (e.g. generated using a formula like a helix) the T-N-B frames are well formed. However, when I use a path recorded using a vision sensor, while tracking a marker, the estimated T-N-B frame is really noisy. How can I deal with such noise while not loosing the desired frames? I sample of the noisy frames can be seen .
I have tried filtering the frames using filter command in MATLAB. The problem is the T-N-B frames loose their properties and are not anymore perpendicular and normalized.


text:
Q: callback are executing multiple times react native someone please tell me how to fix this issue , this function is calling multiple times , i don't know why and it is so annoying to fix
function NewProduct({ navigation }) {
  const supplierApi = useApi(suppliers.getSuppliers);
  useEffect(() => {
    supplierApi.request();
  }, []);
  return console.log(supplierApi);
}

the log is like below...
    {data: Array(0), error: false, loading: false, request: ƒ}
    {data: Array(0), error: false, loading: true, request: ƒ}
    {data: Array(0), error: false, loading: false, request: ƒ}
    {data: Array(0), error: false, loading: false, request: ƒ}
    {data: Array(7), error: false, loading: false, request: ƒ}

A: You can call the function as follows, this will same as componentDidMount for class component.
function NewProduct({ navigation }) {
  useEffect(() => {
    const supplierApi = useApi(suppliers.getSuppliers);
    supplierApi.request();
    console.log(supplierApi);
  }, []);
}


text:
Q: How to add left and right padding to a tbody tag to indent the top and bottom border? I have a table, which is composed of tbody tags.  I am using a hide class to toggle the collapse of tbody elements.  I would like to add left and right padding to the tbody, to indent the top and bottom border.  The tbody section is the white section in the screenshot below.  I have tried using border-spacing and tbody:before in my css styles, but it is not working.  Can anyone advise how I can accomplish this?  I have added a codesandbox and code snippet for your review.
Image:

Code Snippet:

            Regian
            Q1 2010
            Q2 2010
            Q3 2010
            Q4 2010

        {/*
 */}

              Accounting
              <input
                type="checkbox"
                name="accounting"
                id="accounting"
                data-toggle="toggle"
                onClick={showNestedData}
              ></input>

            Australia
            $7,685.00
            $3,544.00
            $5,834.00
            $10,583.00

            Central America
            $7,685.00
            $3,544.00
            $5,834.00
            $10,583.00


text:
Q: How to split text into multiple columns? I have a column that has text in the format:
ID-XXXXX Process for Description [1/5]

I would like this to be broken into three columns where:
A = ID-XXXXX

B = Process for Description

C = 1/5

Any ideas on how to split this properly?

A: here is an attempt to help you. Mind that the first part is a bit tricky and I used a regex with the idea that XXXXX will always be 5 character long.
d = "ID-XXXXX Process for Description [1/5]"

a =sub('[  ].+',"",d)

c = sub('.+[  ][[]',"",d) ; c = sub('[]]',"",c)

b = sub('[  ][[].*[]]',"",d) ;b = gsub('ID-.{5}[ ]',"",b)

f = c(a,b,c) ; f
# [1] "ID-XXXXX" "Process for Description" "1/5"

A: Using stringr, there are several options:
dat <- data.frame(my_string = "ID-XXXXX Process for Description [1/5]")

dat %>%
  mutate(A = str_extract(string = my_string, pattern = "ID-.{5}"),
         B = str_replace(string = my_string, pattern = "ID-.{5}\\s(.+)\\s\\[.*\\]", replacement = "\\1"),
         C = str_match(string = my_string, pattern = "\\[(.*)\\]")[2])

A : extract the following pattern : ID- followed by exactly 5 characters
B : captures the group between ID-XXXXX and [X-X], and replace the entire pattern with the captured pattern
C : matches the captured pattern (.*) between the squared brackets (the 2nd column of str_match returns the captured pattern)
Result:
                               my_string        A                       B   C
1 ID-XXXXX Process for Description [1/5] ID-XXXXX Process for Description 1/5

EDIT :
I just remembered that the extract() function from tidyr does exactly that.
Using capturing groups between parenthesis in the regex argument, you get these into new columns directly.
dat <- data.frame(my_string = paste0("ID-0000", 1:5, " Process_", LETTERS[1:5], " [", 1:5, "/5]"))

extract(data = dat,
        col = my_string,
        into = c("A", "B", "C"),
        regex = "(ID-.{5})\\s(.+)\\s\\[(.*)\\]",
        remove = FALSE)

                 my_string        A         B   C
1 ID-00001 Process_A [1/5] ID-00001 Process_A 1/5
2 ID-00002 Process_B [2/5] ID-00002 Process_B 2/5
3 ID-00003 Process_C [3/5] ID-00003 Process_C 3/5
4 ID-00004 Process_D [4/5] ID-00004 Process_D 4/5
5 ID-00005 Process_E [5/5] ID-00005 Process_E 5/5

If you don't want to keep the original string, use remove = TRUE.

A: You may also use tidyr::extract to do this sytematically.  Example elaborated for purpose of demonstration-

*

*extract everything upto first space into first capture

*extract everything upto [ into second capture group

*extract everything upto ] into third capture group

This way you don't have limitation in number of characters per capture group.
vec <- c("ID-XXXXX Process for Description [1/5]", "ID-XXXXXYZ Process for Description something [1/5]", "ID-XXXXXFFF Process for Description something else [1/905]", "ID-XXXXXYYYYP Process for Description [900001/5]")
df <- data.frame(col = vec)
df
#>                                                          col
#> 1                     ID-XXXXX Process for Description [1/5]
#> 2         ID-XXXXXYZ Process for Description something [1/5]
#> 3 ID-XXXXXFFF Process for Description something else [1/905]
#> 4           ID-XXXXXYYYYP Process for Description [900001/5]
library(tidyverse)
df %>%
  extract(col, into = c('A', 'B', 'C'), regex = '^([^\\s]*)\\s([^\\[]*)\\[([^\\]]*)\\]$')
#>               A                                       B        C
#> 1      ID-XXXXX                Process for Description       1/5
#> 2    ID-XXXXXYZ      Process for Description something       1/5
#> 3   ID-XXXXXFFF Process for Description something else     1/905
#> 4 ID-XXXXXYYYYP                Process for Description  900001/5

Created on 2021-05-30 by the reprex package (v2.0.0)

A: We could use str_extract
df %>%
  mutate(A = str_extract(col1, "ID-XXXX"),
         B = str_extract(col1, "Process for Description"),
         C = str_extract(col1, "\\[1\\/5\\]"))

Output:
# A tibble: 1 x 4
  col1                                   A       B                       C
  <chr>                                  <chr>   <chr>                   <chr>
1 ID-XXXXX Process for Description [1/5] ID-XXXX Process for Description [1/5]


text:
Q: Sammy.js not understanding my json? I´m using sammy.js with a ASP.NET MVC Backend. I have a route that loks like this:
        this.get("#/member/inbox", function (context) {
          this.load('CurrentUser/Messages')
            .then(function (items) {
                $.each(items, function (i, item) {
                    context.log(item.Subject, '-', item.Text);
                });
            });

But item.Subject and item.Text is undefined. My json looks like this:
[{"Text":"Lorem ipsum","Created":"\/Date(1343375945089)\/","Subject":"test"},{"Text":"testext","Created":"\/Date(1343375945089)\/","Subject":"test2"}]

If I exchange this-load with a call to $.get it works but I want to do this "the sammy way"
Any ideas?

A: Are you sure that "items" is an array?  A quick check is to console.log(items) and see what you get.  Chances are the array is not a top-level thing, but rather there is a wrapper object holding the array so that your JSON actually looks more like this by the time it makes it up to the browser (take note of object and the "d" property):
{"d": [{"Text":"Lorem ipsum","Created":"\/Date(1343375945089)\/","Subject":"test"},{"Text":"testext","Created":"\/Date(1343375945089)\/","Subject":"test2"}]}

A: Your script that generates JSON should set the HTTP Content-type to application/json or text/json
For ASP.NET this would be:
Response.ContentType = "application/json";

or
Response.Headers.Add("Content-type", "application/json");

A: Ok, so I changed line 1535 in sammy.js
from:
dataType: is_json ? 'json' : 'text'

to:
dataType: is_json ? 'json' : null

And now sammy understands that the content is json, not sure why at this moment.

A: I have the same issue.  I've found that sammy will load a local file saved as .json correctly. But anything that is called from http will not work even with ("Content-type", "application/json")
You can test your own set-up by copy/pasting your own api json feed into a file.
Then see if sammy is able to load it correctly.
this.get('#/contact', function(context) {
     $('#header').html('This is the Contact Page')
       this.load('Backboneapp_data.json')
      .then(function(items) {
            $.each(items, function(i, item) {
              context.log(item);
            });
        });

    });

A: There's definitely something to improve in the Sammy code in those cases. What I do when I have this situation is use
var jsonItems = $.parseJSON(items);

This will generate a proper JSON object from the response.


text:
Q: Ubuntu 14.04 says I have no space left I had been having issues trying to boot ubuntu. When the system had booted I had a blank locked screen. The mouse was able to move and I could access the terminal with ctrl alt F2but apart from this the computer was at a standstill.
Recently I fixed this issue with the command
sudo tune2fs -m1 /dev/sda5

This is not a recommended fix but it did allow me to access my desktop and use ubuntu apps. This command allows more space for the root user. Now that I am able to access my ubuntu apps I decided to install BleachBit which is the equivalent of Windows auto cleaner.
BleachBit has since crashed and now I get errors saying I have less that 4kb left of space.
Heres the question.  The laptop is dual booted. If I were to remove dual boot and use only one OS will this alleviate these issues?
Whats the best practice for maintaining ubuntu performance and speed?

A:
This command allows more space for the root user.

No, tune2fs -m sets the percentage of space reserved for the root user. 5% is a common default, so you just reduced the space available for the root user to 1% (-m1). What you did was increase the amount of space available to non-root users. So sudo bleachbit might allow it to run if that reserved space is available, since it will run with root privileges.
If you are dual booting off of one drive, then removing the partition(s) for the other OS and expanding the full Ubuntu partition into that space will give you more room for files.
Depending on your situation, cleaning out files taking up a lot of space and deleting unneeded apps will help to get you more space as well.
For best performance, keeping a drive at 75% full or less is a good rule. Depending on the size, it should still work fine up to 90% or 95%. But you need to be careful not to run into 100%, which is where you are at right now.
A few helpful commands for cleaning up packages are here (applies to desktops as well).


text:
Q: Как поместить все страницы PDF-файла в Indesign используя python? Поиски по интернету дали такие плоды:
import win32com.client
app = win32com.client.Dispatch('InDesign.Application')

myFile = r'C:\test.indd'
myDocument = app.Open(myFile)
myPage = myDocument.Pages.Item(1)

for x in range(0, 5):
    myPage = myDocument.Pages.Add()

for a in range(0,5):
    myPage = myDocument.Pages.Item(a + 1)
    myRectangle = myPage.Rectangles.Add()
    myRectangle.GeometricBounds = ["0", "0", "297mm", "210mm"]
    myRectangle.StrokeWeight = 0
    myPlace = myRectangle.Place(r'C:\mail.pdf')

Мне осталось сделать так, чтобы из PDF-файла помещались страницы (например с 1-20стр.) на каждую отдельную страницу в Indesign. Я нашел этот код на сайте adobe indesign, но не получается додумать до конца... Выскакивает ошибка, что такой переменной не существует (myPage.PDFPlacePreference.PageNumber = "2").
myPage.PDFPlacePreference.PageNumber = "2"
myPlacePDFFile = myPage.Place(r'C:\mail.pdf')

A: Попробуй добавить букву 's' в 'Preferences', app вместо myPage, 2 вместо "2":
app.PDFPlacePreferences.PageNumber = 2


text:
Q: How to clean saved dockerfiles after build I'm new at Docker and I'm checking how to build some containers.
After successfully install docker app on my linux server, I've executed the following command:

docker build -t Dockerfile .

Content of this file:
FROM ubuntu:14.04

#Install.
RUN \
  apt-get update && \
  apt-get -y install apache2 && \
  rm -rf /var/lib/apt/lists/*

After some executions I've modified the content of the file and also, the name of the file but it is still executing the same code.
I've done the following steps:

docker rmi -f

and also:

docker rm $(docker ps -a -q)

But the dockerfile executed is still being executed as it was in the first instance but now it looks like:
FROM ubuntu:14.04

RUN echo "Hola"

A: The Dockerfile is "executed" only by the docker build command.
It interprets the Dockerfile and creates (or updates on subsequent runs) an image. The image is used to create the containers.
Think of Dockerfile as the source code of your program written in a compiled language (C, C++, Java etc). The image is the executable program stored in a file on disk. The container is the program launched in execution (in memory).
Of course, after you modify the Dockerfile you have to run docker build again to update the image then use the image with docker run to launch new containers based on it.


text:
Q: Django email attachment of an uploaded file using modelname.filevariable.url I have a Django library application, wherein from a list of books, the customer can email a particular book's pdf file link that was originally uploaded using FileField by the admin.
Now, the email is being sent/received successfully, however the pdf file is not getting attached.
I have also looked into other Stack Overflow references for the same, but I am unable to interpret the correct solution: Django email attachment of file upload
On clicking the email button, the form is submitted as follows: three hidden values are also being submitted on submitting the form, one of which is the book.file.url.
   <form method="POST" action ="{% url 'email_book' %}" enctype="multipart/form-data">
       {% csrf_token %}

       # correction made
       <input type="hidden" name="book_title" value="{{ book.id }}">

       <button type="submit" class="btn btn-info">  Email</button>
   </form>

In views.py, I have used Django's EmailMessage class as follows:
    def send_email(request):
       # corrections made, pdf file path is being retrieved
       book = Book.objects.get(pk=int(request.POST.get('id')))
       book_title = book.title
       book_author = book.author
       book_pdf = book.file.path  #inplace of book.file.url

      email_body = "PDF attachment below \n Book: "+book_title+"\n Book Author: "+book_author

try:
    email = EmailMessage(
        'Book request',
        email_body,
        'sender smtp gmail' + '<dolphin2016water@gmail.com>',
        ['madhok.simran8@gmail.com'],
    )

    # this is the where the error occurs
    email.attach_file(book_pdf, 'application/pdf')

    email.send()
except smtplib.SMTPException:
    return render(request, 'catalog/index.html')
return render(request, 'catalog/dashboard.html')

The uploaded files are stored in /media/books_pdf/2018/xyz.pdf. And the book.file.url contains the above file path, and yet the pdf file is not getting attached to the email.
So I am retrieving the file path dynamically using book.file.url, and yet the code is right.
How do I retrieve that book's pdf file path/name required.
Update/solution
To retrieve the pdf file path, we have to use book.file.path instead of book.file.url.

A: The problem is that the attach_file() method expects a filesystem path. You're not passing a path, you're passing the URL.
You could change your template to output the path into the hidden field - e.g.
<input type="hidden" name="book_pdf" value="{{ book.file.path }}">

But it might be better to pass the id of the Book, and then from that you can look up all the attributes you need. For example:
Pass the id of the Book in the template:
   <form method="POST" action ="{% url 'email_book' %}" enctype="multipart/form-data">
       {% csrf_token %}
       <input type="hidden" name="book_id" value="{{ book.id }}">
       <button type="submit" class="btn btn-info">  Email</button>
   </form>

Modify the view to look up the Book from the id:
def send_email(request):
    book = Book.objects.get(pk=int(request.POST.get('id')))
    book_title = book.title
    book_author = book.author
    book_pdf = book.file.path  # Use the path of the book


text:
Q: Do jquery operations after php operation fails/succeeds I am new to php. I wanna open login window after php registration fails "Email already exists"
This is the php code i have
  if (mysqli_num_rows($result1) > 0)
   {
        //echo "This Email is already used.";
        //Write code to go back to register window
        header('Location: ../homepage.html');
        echo '<script type="text/javascript">
                console.log("cdsafcds");
                $(".login_links_login").trigger("click")
                </script>';
   }

It is not triggering it. My .js file is separate from .php file. Both .js and .php are in separeate folders.
I read a lot of SO posts all suggested to use <script> tag.
Please clear my doubts what i am doing wrong

A: I'm supposing your homepage.html page can handle php request...
  header('Location: ../homepage.html?trigger=trigger');

in your homepage.html
 <?php if(isset($_GET['trigger'])) { ?>
 <script type="text/javascript">
    console.log("cdsafcds");
    $(".login_links_login").trigger("click")
 </script>
 <?php } ?>

Hope this may help you..


text:
Q: Definite article when referring to named works If I've watched a named film, let's say "Ice Age".
Is it incorrect to say:

"I was watching Ice Age film"

Without a definite article?
As opposed to:

"I was watching the Ice Age film".

If you have to include "the" - why is that?

A: In the first instance, 'Ice Age' acts as an adjective and the impression is that you are watching film footage that was brought back from the Ice Age. In the second instance, it seems that the film is about the Ice Age but not clear which film - having used 'the' we are talking about an Ice age film that is probably known at the time of watching but lacks enough context to determine if the film is named like this. If the film was released recently and it is well known this option is better.
In order to sound specific to the feature film, I propose:
"I was watching Ice Age, the film."
or just
"I was watching Ice Age"
I hope this helps.


text:
Q: how to check the request is https in app engine python I would like to know if is there a way to validate that a request (say a POST or a GET) was made over https,
I need to check this in a webapp2.RequestHandler to invalidate every request that is not sent via https
best regards

A: Check the self.request.environ['HTTPS'] == 'on' # or 'off'.
If you only use https, consider using secure:always in your app.yaml as follows:
handlers:
- url: /.*
  script: main.app
  secure: always

A: The answer provided above to use the app.yaml config works well but in some case you need the granularity of checking this your python code itself, which is I believe what you asked for since you want to check in the RequestHandler.
Here is what you can do inside your RequestHandler:
if self.request.scheme.lower() != 'https':
    self.abort(403)
else:
    # handle your request here, you know it's secured!

A: If you are using GAE Flex (where the secure: directive doesn't work), the only way I've found to detect this (to redirect http->https myself) is to check if request.environ['HTTP_X_FORWARDED_PROTO'] == 'https'


text:
Q: Access deny on Sharepoint 2010 's search service application We have done migration from SharePoint 2007 to 2010, configured its Search Service.
After that the Search service found default web application setting that was created in first step of 2010 installation and this will work for default web application service only
and for next web applications that we have before migration or  create new one and added to the content source list not crawled and ->Type start addresses below field, we will receive this error:

(((Access is denied. Verify that either the Default Content Access
  Account has access to this repository, or add a crawl rule to crawl
  this repository. If the repository being crawled is a SharePoint
  repository, verify that the account you are using has "Full Read"
  permissions on the SharePoint Web Application being crawled))))

And in addition, my user has full permission in SQL and SharePoint farm.


text:
Q: Will I get the trophy if I defeat the ender dragon on peaceful? I'm playing Minecraft PS3 (Legacy Console) on Peaceful difficulty, and I'm about to go into The End. If I defeat the Ender Dragon on Peaceful, will I still get the trophy?

A: Yes you will, I tried it myself and got it. It only doesn't work when you're in creative mode of course.

A: There is no ender dragon on peaceful because there is no mobs not including animals so you must be on easy or above.

A: You can get the trophy in peaceful mode, and the ender dragon does spawn in peaceful because it's a boss and not a mob.

A: You will get the trophy on any difficulty, and you will even get the trophy when you defeat the Ender Dragon in Creative Mode.


text:
Q: Import big text images in shiny App with R In my project I developed algorithms with R and R studio to process big images from microscopy analysis. I work on big matrix of pixel value (around 3Gb ), extract biological informations from specific regions of these images especially perform particle detection at specific position of the matrix and then perform statistical analysis.
To be able to transfer the whole process to other people without applying multiple scripts functions... I tried to create a Shiny App but I struggle to import the big images .txt
Actually I use as.matrix(read.table()) function on the file provided by the shiny app user through the file input box
Is any one has an idea to import these matrix easily and more quickly ? even  on Rstudio I wait ~20minutes for each picture import.
Thanks a lot in advance for the answers,
Best,
Romain


text:
Q: Branching points and genus of riemann surface of algebraic function Consider the Riemann surface $N$  of the algebraic function given by
$$  w=   ((z-2)^2 (\sqrt(z) + i))^{\frac{1}{3}} $$
What are the branching points of  S?  What are their orders? What is the genus?
I think the  branching points are $z=2$ and $z= 1$ with orders of $2$ and $1$ respectively? Am I correct in my assessment? Regarding the Riemann surface I know that there is a correspondence between Riemann surfaces and algebraic fuctions. Is the genus of this Riemann surface equal to 1?


text:
Q: declaring file pointer in main() and using it in multiple functions while the file is opened So basically i need to declare file pointer in main functions, and use it in multiple sub-functions, file will be opened in sub function.

    int main(){
        FILE *filepointer;

       function print(filepointer);
       function count_line(filepointer);
}

now in function_print i do basic print whats inside the file, i dont close the file, because it will be done in the next function, and both function have to be done in sequence.
void print(FILE *filepointer){
      filepointer = fopen("example.txt", "r+");
      char ch;
      while(ch != EOF){
          ch = fgetc(filepointer);
          printf("%c",ch);
      }
}

now in second function i have to reset the file pointer to the beggining and count how many lines in file
void count_line(FILE *filepointer){
    fseek(filepointer, 0, SEEK_SET);
    int counter=0;
    char ch;
    while(ch != EOF){
        ch = fgetc(filepointer);
        if(ch == '\n'){
            counter+=1;
        }
    }
    printf("Number of lines = %d",(counter);
    fclose(filepointer);
}

I tried using rewind() rather than fseek, but it didn't help. The print function works normally, I don't get any errors or warnings. But the count_line function doesnt work, it just prints
Number of liner = 0

Thank you for any help. Honestly i think its gonna be some ** or * problem within the print function, maybe it doesn't change the value in main or something, but i tried doing it with double pointer and i couldn't get it right.
Thank you.


text:
Q: How to run T4 template in Blazor project on build I have a Blazor project with a T4 template I wrote for scaffolding some code automatically. It works great from within Visual Studio, but I have to modify & save the template to get it to run again (as documented and expected).
I also want to run the template when building the project, so instead of VS running the template, it has to be MSBuild. I went through a bunch of articles about the topic and it looks like I have to re-import the default targets, as explained here.
I added the following to the top of my .csproj file, and this is when things went south:
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk.Web" />

This is the error I'm getting:

The TargetFramework value 'netstandard2.1' was not recognized. It may
be misspelled. If not, then the TargetFrameworkIdentifier and/or
TargetFrameworkVersion properties must be specified
explicitly.   TestProject C:\Program
Files\dotnet\sdk\3.1.401\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.TargetFrameworkInference.targets    93

Full .csproj file:
<Project Sdk="Microsoft.NET.Sdk.Web">

    <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk.Web" />

    <PropertyGroup>
        <TargetFramework>netstandard2.1</TargetFramework>
        <RazorLangVersion>3.0</RazorLangVersion>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.1" />
        <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.1" PrivateAssets="all" />
        <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.1" PrivateAssets="all" />
        <PackageReference Include="System.Net.Http.Json" Version="3.2.0" />
    </ItemGroup>

</Project>

What am I missing/doing wrong?

A: You should note the info from the article:

Fortunately, there's a workaround: you can import the default targets
file explicitly, and import the text templating targets after that:

Solution
You should import those targets after netstandard 2.1 node.
In my side, I use these:
<Project Sdk="Microsoft.NET.Sdk.Web">

           <PropertyGroup>
               <TargetFramework>netstandard2.1</TargetFramework>
               <RazorLangVersion>3.0</RazorLangVersion>
           </PropertyGroup>

         <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk.Web" />
         <Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets"/>

           <ItemGroup>
               <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.1"/>
               <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build"
   Version="3.2.1" PrivateAssets="all" />
               <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer"
   Version="3.2.1" PrivateAssets="all" />
               <PackageReference Include="System.Net.Http.Json" Version="3.2.0"/>
           </ItemGroup>

 </Project>

Then,


text:
Q: Чем отличается Virtual Proxy от Value Holder? Фалер в разделе Lazy Load перечисляет несколько способов реализации, где 2 из них это:

*

*Virtual Proxy

*Value Holder

Однако, что-то не могу увидеть между ними какую-то разницу и профит использования одной подхода перед другим...


text:
Q: PHP - Display different image based on mysql row result Sorry for my English.
I'm learning PHP and I try to create a small member area, I think it's a good way to learn.
In my member area, some members are "verified" and some are not.
How can I display different pics based on data stored in Mysql using PHP?
What I want is to display "Picture1" if "1" is the value stored in a MySQL column and "Picture2" if "2" is the value, etc... You are "unverified member" so you see picture 1, verified member see picture 2...
I know how to SELECT data using MySQLi but I can't find what I have to do next?
Thank you.

A: There's a few ways. If it will always follow a number system... use this:
$picture = "Picture" . $verified;
// example: $picture = "Picture1", if $verified = 1

Lots of ways to concatenate...
$pic = "Picture$verified.png";
$picture = "Picture" . $verified . ".jpeg";

It will just depends on how you have it setup..
switch($verified){
 case 1:
  $picture = "Picture1";
  break;
 case 2:
  $picture = "Picture2";
  break;
 case default:
  $picture = "Picture1";
  break;
}

Another way...
if($verified == 1){ $picture = "Picture1"; } else { $picture = "Picture2"; }

The reason for the switch statement, or this if/else statement is that it can account for verified being equal to 0, null, or another non 1 or 2 value that may be stored in the database for whatever reason. With the first example, if $verified (verified column = to 1 or 2) has an odd value, the picture# may not actually be real.
Now, of course this is just to handle the different ways. You would have to make sure it lines up properly with your actual image...
$picture = "Picture1"; // would be dynamic to code above
$ext = ".png"; // optional, could be added into the $picture variable above easily too
$filePath = "/images/user_uploads/"; // make sure path is correct
$filePathName = $filePath . $picture . $ext;
// see? We combine path/pictureName/extension to create an image URL
if(file_exists($filePathName) !== false){ // make sure exists
 $imageCode = "";
} else {
 // file does not exist! ut oh!
}

A: Lets assume that you have a database named as db and table as tb with columns name and verify. Name is string and verify is Boolean. Also verify stored 1 if user is verified and 0 it isn't.
so, you can do it by iteration statements (either by using if else or by switch statements)
<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$query="SELECT * FROM `tb`";
$sql=$conn->query($query);

if($sql->num_rows>0)
{
while($row=$sql->fetch_assoc())
{
//display name
echo $row['name'];

//check if user is verified or not

//using if else statement
if($row['verify']=="0")
{
echo '';
}
else
{
echo '';
}

//using switch case
switch($row['verify'])
{
case(0):
{
echo '';
}
case(1);
{
echo '';
}
}

//remember i have used both methods hence it will show the image twice , i did it just you possible ways , you choose any one from it.(if else or switch case)
}
}

$conn->close();

?>

A: It depends on how your images map to the values in your database, but assuming you have a simple relationship like:

*

*1: /images/1.jpg

*2: /images/2.jpg
Simply grab the data from your database and map it to a variable (in my example it's $image), and then concatenate it with the filepath inside an echo statement inside of an  attribute:
<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>

This will output:

Based on the chosen image.
Now you just have to set that variable to the right value based on your conditional:
<?php

if ($authenticated) {
  $image = 1;
}
else {
  $image = 2;
}

?>

<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>

Or more succinctly with a ternary:
<?php ($authenticated ? $image = 1 : $image = 2) ?>
<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>

A: Try this:
<img src="<?php echo "/pictures/Picture{$number}.jpg"; ?>" />


text:
Q: React native upload image file to django backend Hi i want to post photo to the django backend. I can easily post with postman. But i cant do it with react native. Here is my post request:
handleSubmit(photoUri){
    let formData = new FormData();
    formData.append('file',photoUri);
    formData.append('name', 'a');
       fetch('http://localhost:8000/test/', {
      method: 'POST',
      body:formData,
    }).then(res => res.json())
      .then((data) => {
        console.log(data);
      })
      .catch(err => console.log(err));
  }

In this post django serializer is like that:
FileSerializer(data=<QueryDict: {'file': ['file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Ftez2-1599e0c7-8863-4da6-b20f-5e6e94be9342/Camera/b2116349-cdfb-4309-8d6e-51c9a36be4fb
.jpg'], 'name': ['a']}>):

but with postman it is like this:
FileSerializer(data=<QueryDict: {'name': ['a'], 'file': [<InMemoryUploadedFile: a.jpg (image/jpeg)>]}>):

I think issue is something with InMemoryUploadedFile i cant upload file in this form with react native. How can i do it ?

A: I understand its late too much to answet this question.
But you can try this:
handleSubmit(photoUri){
    let formData = new FormData();
    const photo_data = { // Edit Here
        uri : image_path_here // Edit Here,
        name : image_name // Edit Here, Image Name with Extension very important
        type : 'image/jpg' // Edit Here
    }
    formData.append('file', photo_data ); // Edit Here
    formData.append('name', 'a');
       fetch('http://localhost:8000/test/', {
      method: 'POST',
      body:formData,
    }).then(res => res.json())
      .then((data) => {
        console.log(data);
      })
      .catch(err => console.log(err));
  }

A: I found the answer first thing is i need to post object in question i am only posting string. Second thing is there is some problem in flipper version 0.33.1 you cant post images. You need to upgrade or you can work around and comment this line in ReactNativeFlipper.java
// builder.addNetworkInterceptor(newFlipperOkhttpInterceptor(networkFlipperPlugin));

for more detailed information look here: https://github.com/facebook/react-native/issues/28551#issuecomment-624347067
Third issue is in android platform you need fix the uri like in here: Photo upload on React Native Android produce Type Error Network Error
I am run into these problems in this question.


text:
Q: VHDL-PWM Weird Behavior and Physical Upper/Lower limitations I am trying to generate picosecond PWM signal using the Spartan 3e board in VHDL (Xilinx ISE+ISim).
library ieee;
use ieee.std_logic_1164.all;

entity pwm is
  port(clk     : in     std_logic;
       pwm_out : buffer std_logic);
end entity;

architecture rtl of pwm is
begin
  process (clk)
    variable count      : integer range 0 to 50000;
    variable duty_cycle : integer range 0 to 50000;
    variable flag       : integer range 0 to 1;
  begin
    if (rising_edge(clk)) then
      count := count+1;
      if (count = duty_cycle) then
        pwm_out <= '1';
      end if;
      if (count = 50000) then
        pwm_out <= '0';
        count   := 0;
        if(flag = 0) then
          duty_cycle := duty_cycle+50;
        else
          duty_cycle := duty_cycle-50;
        end if;
        if(duty_cycle = 50000) then
          flag := 1;
        elsif(duty_cycle = 0) then
          flag := 0;
        end if;
      end if;
    end if;
  end process;
end rtl;

I am using the embedded 50Mhz for the global clock (C9) but the simulation showed a weird behavior; from 0ps to 1000000ps clk (clock) and pwm_out (output) seems to be HIGH always and there is nothing after 1000000ps both for clk and pwm_out in time domain under ISim.
I am trying to do is to investigate and solve this behavior and then increase the frequency of output (pwm_out). Also I would like to learn about how fast (rise/fall times and in the frequency) can I generate the pulse (physical limitations).
I would appreciate some guidance from experienced users.

A: The pwm_out output has not initial value, so it has to be assigned in the process before it gets a well defined value.  But the process variables (holding process state) all have an initial value of zero, and since count is incremented first thing in the process loop, count will not equal duty_cycle (being 0) at the beginning.  So pwm_out is not assigned until it equals 50000, which (with a 50 MHz clock) happens at 50000 / 50 MHz = 1 ms.
However, if you synthesize this and run it in the FPGA, you may experience some unexpected behavior, depending on your clock source and control.  For example, if the pwm module is running from a clock that is not stable right when the FPGA is loaded, for example an internal PLL clock, then the initial clock behavior may not adhere to the timing constraints applied to the design, and any value may end up in for example the duty_cycle variable (register).  But, the design is based on the assumption that the duty_cycle register has a value of (50 * n), and otherwise it won't increment and decrement as anticipated due to the equal compare (=) with 0 and 50000.  So if the duty_cycle get the value 1, due to initial timing violations as a result of an initial "invalid" clock, the flag variable (state) won't operate as expected, and so on.  One way to amend this is to add a reset input and apply this to the variable state until the clock is stable, or use inequality operators for comparison.