text:
Q: How to program outside the main UI thread I don't know if a UI thread exists by default, how to create it if not, or how to tell when I'm "in" it where it begins and ends if so. How do I make sure PacketListener isn't part of the main UI thread?
I keep running into this NetworkOnMainThreadException. I understand that means that I'm trying to do something in the main UI thread that should have its own separate thread. However, I can't find much to tell me HOW to actually do that.
I had thought that the MainActivity class would BE the UI thread, since, well, I had a UI and it worked. However, I've created a seperate class that implements Runnable, and put the network connection stuff in there, and am still getting the exception, so it's still part of the main thread, yes? I can see that MainActivity doesn't extend Thread, so maybe that was a dumb assumption. I don't have the feeling that anything will change if I add another class that implements Runnable/extends Thread. Will it?

MainActivity.java
public class MainActivity extends AppCompatActivity {

    ArrayList<String> listItems;
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listItems = new ArrayList<>();
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
        ListView listview = (ListView) findViewById(R.id.listview);
        listview.setAdapter(adapter);

        (new Thread(new PacketListener(adapter))).run();
    }
}

PackageListener.java:
public class PacketListener implements Runnable {
    ArrayAdapter<String> adapter;

    public PacketListener(ArrayAdapter<String> adapter) {
        this.adapter = adapter;
    }

    public void run() {
        byte[] buf = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        try {
            DatagramSocket socket = new DatagramSocket();
            socket.receive(packet);
        }
        catch(Exception e) {
            adapter.add("Exception: " + e.toString() );
            e.printStackTrace();
        }
        catch(Error e) {
            adapter.add("Unspecified Error: " + e.toString() );
            e.printStackTrace();
        }
    }
}

EDIT:
My latest attempt, trying to follow this page's example, has gone the route of most of my attempts, and broke the app completely. SendAnother is a testing method bound to a button:
public void sendAnother(View view) {
    adapter.add("button clicked");

    new Thread(new Runnable() {
        public void run() {
            listview.post(new Runnable() {
                public void run() {
                    adapter.add("inside worker thread");
                }
            });
        }
    });
}

I think next I'll finally try AsyncTask. I no longer much care if it's "dirty".

A: ui thread is main thread.  you know about current thread by
Thread.currentThread().getName();

sorry i didn't read your whole question but you have to do blocking proccess in another thread than mainThread.
there are many ways to do that : AsyncTask , Services , ExecutorService and RxJava .
and which one to pick depends on your need
this link would be helpful :)

A: Your last method is correct, except the thread isn't started yet. So you need to call the start():
public void sendAnother(View view) {
  //adapter.add("button clicked");

  new Thread(new Runnable() {
    public void run() {
      listview.post(new Runnable() {
        public void run() {
          adapter.add("inside worker thread");
        }
      });
    }
  }).start();
}

A: I'm still not sure I like AsyncTask for this project, so if someone can offer advice or a link to a tutorial to use Handler or Runnable, PLEASE post it!
Strictly speaking though, this at least finally lets me do stuff outside the UI thread, and that was the question. Sooo, for what it's worth to any others having this problem, here's what first worked for me.
public class MainActivity extends AppCompatActivity {
    ArrayAdapter<String> adapter;
    private static final int PORT= 8888;
    private static final int TIMEOUT_MS = 500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<String> listItems = new ArrayList<>();
        ListView listview = (ListView) findViewById(R.id.lvMain);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
        listview.setAdapter(adapter);

        UpdateView task = new UpdateView();
        task.execute();

        //just to show these parts are in different threads
        String temp = Thread.currentThread().getName();
        adapter.add("onCreate: " + temp);
    }

    private class UpdateView extends AsyncTask<URL, Integer, Long> {
        protected Long doInBackground(URL... urls) {
            //just to show these parts are in different threads
            String temp = Thread.currentThread().getName();
            adapter.add("UpdateView: " + temp);

            byte[] buf = new byte[256];
            byte[] ipAddress = {(byte)192,(byte)168,0,1};

            try {
                InetAddress address = InetAddress.getByAddress(ipAddress);

                String message = "\"xyz\"";
                DatagramSocket socket = new DatagramSocket(PORT);
                DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), address, PORT);
                socket.send(packet);

                packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);
            }
            catch(IOException e) {
                adapter.add("IO Exception: " + e.toString() );
                e.printStackTrace();
            }

            adapter.notifyDataSetChanged();
            return 0L;
        }
    }
}


text:
Q: Hibernate date don't save the milliseconds I'm saving an entity in hibernate with a creation date
            @Id
    @Column(name = "dtcreation")
    @Type(type="timestamp")
    private Date creation;
and I put a new Date on this field:
        entity.setCreation(new Date());
    entityDao.persist(entity);
but when it is saved on the db the time don't contains the milliseconds, but put it a 0
if I try to update with a query the value of the milliseconds it works...someone can help me?

after the persist method i have a record with 01/06/2011 15:00:00.0
but if i made an UPDATE i can change the milliseconds, so the db supports it..
the database is informix

A: This is consistent with the documented behavior of java.util.Date and java.sql.Timestamp
java.util.Date stores down to the second, and java.sql.Timestamp is a thin wrapper to accommodate the nanosecond value of a SQL timestamp value. If you read the note on the Timestamp javadoc, it clearly states this difference.
If you don't want to lose your second fractions, and don't want to investigate alternative date libraries (e.g. the aforementioned Joda Time) you'll need to make the field a java.sql.Timestamp, and use the milisecond value of the current date to construct the initial value
java.util.Date date = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
entity.setCreation(timestamp);

A: Without your code to test it's difficult for me to definitively answer, but in taking a look at the Javadoc for java.sql.Timestamp, it appears that you're mixing types with annotating the field as a timestamp.  Change the java type from Date to Timestamp and see if that solves your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring aop expression This is applicationContext.xml AOP part:
<bean id="logHandler" class="demo.anderson.aop.LogHandler"></bean>
<aop:config>
    <aop:aspect id="log" ref="logHandler">
        <aop:pointcut id="addLog" expression="execution(* demo.anderson.controller.StudentController.*(..)) || execution(* demo.anderson.controller.ScoreController.*(..))"  />
        <aop:before method="beforeLog" pointcut-ref="addLog" />
        <aop:after method="afterLog" pointcut-ref="addLog" />
    </aop:aspect>
</aop:config>

It's working!
But when I configure aop:pointcut like this:
<aop:pointcut id="addLog" expression="execution(* demo.anderson.controller.*.*(..))"  />

It's broken:

18-Jul-2017 11:06:39.416 嚴重 [http-nio-8090-exec-71]
  org.apache.catalina.core.StandardContext.listenerStart Exception
  sending context initialized event to listener instance of class
  org.springframework.web.context.ContextLoaderListener
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name
  'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0':
  Initialization of bean failed; nested exception is
  java.lang.IllegalStateException: Expected raw type form of
  org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$Match
  ............................................................. Caused
  by: java.lang.IllegalStateException: Expected raw type form of
  org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$Match
  .............................................................
18-Jul-2017 11:06:39.434 資訊 [http-nio-8090-exec-71]
  org.apache.catalina.core.ApplicationContext.log Closing Spring root
  WebApplicationContext

Can somebody tell me why? What's the correct configuration?

A: <aop:pointcut id="addLog" expression="execution(* demo.anderson.controller..*.*(..))"  />

refered from spring docs.
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html
The execution of any method defined in the service package or a sub-package:
execution(* com.xyz.service..*.*(..))


text:
Q: Enable touch indicator for iOS app demo video recording I would like to record a demo video of an iOS app with QuickTime on Yosemite. (I found this tutorial) Is it possible to enable a tap indicator, like a small circle, for touch events so users can easily spot where the author tapped?

A: If you want to demo your own applications (i.e. where you have the actual source code and can make a special demo build), then the best way is to add a helper to your Xcode project, such as https://github.com/toddreed/Touchpose or https://github.com/mapbox/Fingertips. Both overlay your touches with a (customizable) fingerprint indicator when connected to an external mirror (such as when using AirPlay or Quicktime to record).

A: The touch events don't get captured on iOS 9 and lower, so you'll need to either set up a camera to capture the taps and present that side by side with the detailed capture or use it to overlay the taps in post production.
This is such a great idea, that I've filed a bug report to officially ask Apple to support this.

*

*http://openradar.appspot.com/22538143

A: defaults write com.apple.iphonesimulator ShowSingleTouches 1

How did I find this setting?
Hidden options can be found by running the command below and then, well, figuring out what they do. They are undocumented and can be removed at any time.
strings /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator | grep -E '^[A-Z][[:alpha:]]+$'

If you can be bothered to go through the garbage add
| grep -E '(Enable|Disable|Show|Number)' | sort

I got
AppleTVRemoteWindowDidShow
EnableKeyboardSync
NSDisabledCharacterPaletteMenuItem
NSDisabledDictationMenuItem
NSScreenNumber
ShowChrome
ShowChromeUIRects
ShowPinchPivotPoint
ShowPinches
ShowSingleTouches
ShowUITestMenu
TouchBarShowRemoteTemplate

ShowChrome is Window > Show Device Bezels. ShowChromeUIRects draws some lines around the bezel. The pinch ones are self descriptive. ShowUITestMenu displays a disabled menu in the simulator bar (?). I'll test TouchBarShowRemoteTemplate when I'm back in my Macbook touch. I don't know what the others do.
For Xcode the command should be:
strings /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/IDEKit | grep -E '^IDE[[:alpha:]]+$'

and the defaults command should carry the prefix com.apple.dt.Xcode. For instance
defaults write com.apple.dt.Xcode IDEIndexerActivityShowNumericProgress 1

ShowSingleTouches is truly useful, but most options are meaningless or just noise. The command above for instance, shows you the number of files that are being indexed, instead a generic progress bar. Thus, just noise.

A: If you are building your own app, there are a few libraries that you can use. At the time of posting, here are the 4 iOS libraries I've found ordered by GitHub stars:

*

*https://github.com/conopsys/COSTouchVisualizer (Obj-C, 936 stars)

*https://github.com/mapbox/Fingertips (Obj-C, 724 stars)

*https://github.com/morizotter/TouchVisualizer (Swift, 638 stars)

*https://github.com/toddreed/Touchpose (Obj-C, 533 stars)

A: Free, portable and effective solution by Kane Cheshire: ShowTime.
Can be added via cocoapods or by including single file into the project. Thanks him for his efforts!

A: You can do it creating your own tap gesture through Settings > General > Accessibility > AssistiveTouch > CreateNewGesture as it is explained in the following link: record-iphone-ios-screen-showing-touches-tap-signs
Then, select the gesture as a favourite before recording the movie with QuickTime player.

A: You can also touch /AppleInternal on your drive to unlock hidden options in simulator (GUI to some of these hidden defaults)
Might need to boot into recovery to do this on modern OS versions

A: I've been looking for a solution as well since video conferences are essential nowadays. I am able to add a touch indicator in a real device using a Bluetooth mouse.
I was able to connect my MX Master 2S mouse to an iPad by following this guide: https://support.apple.com/en-us/HT210546

A: Just connect a bluetooth mouse to your iphone / ipad.
It works perfectly ! https://support.apple.com/en-us/HT210546

A: Solution since 2021
If you want to enable touch or gesture recording you can set it up in Simulator > Settings and update the Visual indicators.
Then press ⌘ R you can record the video or go to File > Record screen.

See this tutorial


text:
Q: Is there a way to change a .iso files volume id from the command line? I have a .iso file under linux and have been trying to find a way to change the volume id without having to recreate the .iso file. Most of the authoring tools such as mkisofs provide a switch for setting the volume (-V) for example. However I can't figure out how to change it on a pre-existing .iso file.
For clarification, the bit I'm trying to change is this Volume id: string. Here's an example dump from the isoinfo command.
% isoinfo -d -i /usr/share/virtualbox/VBoxGuestAdditions.iso
CD-ROM is in ISO 9660 format
System id: Win32
Volume id: VBOXADDITIONS_4.1.8_75467
Volume set id:
Publisher id:
Data preparer id:
Application id: MKISOFS ISO 9660/HFS FILESYSTEM BUILDER & CDRECORD CD-R/DVD CREATOR (C) 1993 E.YOUNGDALE (C) 1997 J.PEARSON/J.SCHILLING
Copyright File id:
Abstract File id:
Bibliographic File id:
Volume set size is: 1
Volume set sequence number is: 1
Logical block size is: 2048
Volume size is: 22203
Joliet with UCS level 3 found
Rock Ridge signatures version 1 found

A: xorriso can do this:
$ xorriso -dev ./VBoxGuestAdditions.iso -volid 'YourLable' -commit
xorriso 1.4.6 : RockRidge filesystem manipulator, libburnia project.

xorriso : NOTE : Loading ISO image tree from LBA 0
xorriso : UPDATE : 32 nodes read in 1 seconds
Drive current: -dev './VBoxGuestAdditions.iso'
Media current: stdio file, overwriteable
Media status : is written , is appendable
Media summary: 1 session, 29111 data blocks, 56.9m data, 20.3g free
Volume id    : 'VBOXADDITIONS_5.1.34_121010'
xorriso : WARNING : -volid text does not comply to ISO 9660 / ECMA 119 rules
ISO image produced: 27 sectors
Written to medium : 192 sectors at LBA 29120
Writing to './VBoxGuestAdditions.iso' completed successfully.

xorriso : NOTE : Re-assessing -outdev './VBoxGuestAdditions.iso'
xorriso : NOTE : Loading ISO image tree from LBA 0
xorriso : UPDATE : 32 nodes read in 1 seconds
Drive current: -dev './VBoxGuestAdditions.iso'
Media current: stdio file, overwriteable
Media status : is written , is appendable
Media summary: 1 session, 29147 data blocks, 56.9m data, 20.3g free
Volume id    : 'YourLable'
$

A: Volume ID is always stored at offset 0x8028 as 32 byte ASCII string. Edit it in place.
#!/usr/bin/perl
use strict;
use warnings;

die "Use: $0 <iso_file> <new volume id>\n" unless @ARGV == 2;
open my $file, "+<", $ARGV[0] or die "Cannot open: $!";
seek $file, 0x8028,0;
printf $file "%-32.32s", uc($ARGV[1]);

Test - (isovolid.pl is a name of the above script):
$ genisoimage -V A123456798012345678901234567890X -o aaa.iso *
$ isoinfo -d -i aaa.iso | grep 'Volume id:'
Volume id: A123456798012345678901234567890X
$ ./isovolid.pl aaa.iso NEWVOLUMEID
$ isoinfo -d -i aaa.iso | grep 'Volume id:'
Volume id: NEWVOLUMEID


text:
Q: Is it possible to construct a quasi-vectorial space without an identity element? I mean if there is any construction that satisfies all the conditions for an vectorial space except it lacks an identity element? This questions was posed to me by a classmate last semester and I have been puzzling over it since then.

A: In an old sci.math post by Dave Rusin, he discusses dropping sundry axioms form the usual set of axioms of vector spaces. What is below is taken from there.
So, let's recall what axioms we are dealing with: normally, a vector space $\mathbf{V}$ over a field $\mathbb{F}$ is defined to be a set, together with operations $+\colon\mathbf{V}\times\mathbf{V}\to\mathbf{V}$ and $\cdot\colon \mathbb{F}\times\mathbf{V}\to\mathbf{V}$, written in their usual infix notation, which satisfies the following conditions:

*

*For all $x,y\in\mathbf{V}$, $x+y=y+x$.

*For all $x,y,z\in\mathbf{V}$, $(x+y)+z = x+(y+z)$.

*There exists a vector $\mathbf{0}\in\mathbf{V}$ such that for all $x\in\mathbf{V}$, $x+\mathbf{0}=x$.

*For each $x\in\mathbf{V}$ there exists $y\in\mathbf{V}$ such that $x+y=\mathbf{0}$.

*For all $x\in\mathbf{V}$, $\alpha,\beta\in \mathbb{F}$, $\alpha(\beta x) = (\alpha\beta)x$.

*For all $x\in\mathbf{V}$, $1x = x$.

*For all $x,y\in\mathbf{V}$, $\alpha\in\mathbb{F}$, $\alpha(x+y) = \alpha x + \alpha y$.

*For all $x\in\mathbf{V}$, $\alpha,\beta\in\mathbb{F}$, $(\alpha+\beta)x = \alpha x + \beta x$.

You cannot just drop 3, because that would make 4 unintelligible. A way around it is to replace 4 with another statement which, in the presence of all other axioms, is equivalent to 4; namely:

4'. For all $x,y,w\in\mathbf{V}$, if $y + x = w + x$, then $y=w$.

That is, we have right cancellation. (This is important; if you set up cancellation on the "other side" as the identity, you run into some difficulties below)
Note that if you have 1-8, then you get 4'. And if you have 1-3, 4', and 5-8, then you get 4: first, note that since $\mathbf{0}+0x = 0x = (0+0)x = 0x + 0x$, then 4' implies that $0x = \mathbf{0}$. Then given any $x\in\mathbf{V}$, we have $x + (-1)x = (1+(-1))x = 0x = \mathbf{0}$, so 4 holds in this case. That is, 1, 2, 3, 4', 5, 6, 7, and 8, are an alternative way of defining vector spaces, with the added advantage that now you can drop any of the eight and the remaining statements are still intelligible.
If you take 1, 2, 3, 4', 5, 6, 7, and 8, then you can construct objects that are not vector spaces and satisfy any seven of these and not the eighth.

*

*All but 1: Take $\mathbf{V}=\mathbb{R}$, and define scalar multiplication by $\alpha x = x$, and $x+y = x$ for all $x$ and $y$.

*All but 2: Take $\mathbf{V}=\mathbb{R}^2$, define scalar multiplication the usual way, and
$$x+y = \left\{\begin{array}{ll}
(0,0) &\mbox{if $x=(0,0)$ or $y=(0,0)$;}\\
|\cos(\theta)|(x+y) & \mbox{if $x\neq(0,0)\neq y$, and $\theta$ is the angle from $x$ to $y$.}
\end{array}\right.$$

*All but 3: Take $\mathbf{V}=\emptyset$, with the empty addition and multiplication!

*All but 4 or 4': Take $\mathbf{V}=\mathbb{R}\cup\{\bigcirc\}$. Define addition so that it is the usual addition in $\mathbb{R}$, and $r+\bigcirc=\bigcirc+r = r$ for all $r\in\mathbb{R}$, and $\bigcirc+\bigcirc=\bigcirc$. Scalar multiplication is regular multiplication on $\mathbb{R}$, and $r\bigcirc = \bigcirc$ for all reals $r$.

*All but 5: Take $\mathbf{V}=\mathbb{R}$, and let $\sigma\colon\mathbb{R}\to\mathbb{Q}$ be any additive homomorphism of abelian groups. Define addition as usual, and scalar multiplication by $r x = \sigma(r)\cdot x$, where the multiplication on the right hand side is the usual real multiplication.

*All but 6: Take $\mathbf{V}=\mathbb{R}$ with the usual addition, but zero multiplication: $\alpha x = 0$ for all $x$ and all $\alpha$.

*All but 7: Take $\mathbf{V}=\mathbb{C}^2$, addition defined the usual way, and scalar multiplication given by:
$$\alpha(x,y) = \left\{\begin{array}{ll}
(\alpha x,\alpha y) & \mbox{if $x\neq 0$,}\\
(0, \overline{\alpha}y) & \mbox{if $x= 0$.}
\end{array}\right.$$
where $\overline{\alpha}$ is complex conjugation.

*All but 8: Take $\mathbf{V}=\mathbb{R}$ with usual addition, and scalar multiplication $r x = r^2\cdot x$, where the multiplication on the right hand side is the usual multiplication of real numbers.
Okay, but "All but 3" was almost cheating. What if we require that $\mathbf{V}$ be nonempty? Then you cannot have a structure that satisfies 1, 2, 4', 5, 6, 7, and 8, and does not satisfy 3:
Suppose $\mathbf{V}$ satisfies 1, 2, 4', 5, 6, 7, and 8, and is nonempty. Let $x\in V$. Then for all $y\in V$, we have:
\begin{align*}
(0x + y) + 0x &= 0x + (0x+y) &\quad&\mbox{(by 1)}\\\
 &= (0x+0x) + y &\quad&\mbox{(by 2)}\\\
&= (0+0)x + y &&\mbox{(by 8)}\\\
&= 0x + y\\\
&= y + 0x &&\mbox{(by 1)}
\end{align*}
By 4', this means that $0x+y = y$, so $\mathbf{0}=0x$ shows that 3 is satisfied.


text:
Q: Using canvas to simulate the Ising model I had originally posted this in ComputationalScience but I think perhaps it is best here as I think the challenge I have is with using classes and creating figures rather than the actual mathematical / physics behind the simulation.
I am attempting to simulate a 2D ising model. The simulation consists of an nxn matrix, whereby each element of the matrix has a value of 1 or -1, which flips based on condidtions outlined in the code. I would like to produce a moving figure which essentially produces a different picture for each iteration. but my figure will not appear. I am using an identical method (fig.canvas.draw()) to a code I ran previously with no problems.
Here is my code:
import numpy as np
import matplotlib.pyplot as plt

#initialised values

T = 1.0
N = 5
sweeps = 50

nx = N
ny = N #size of the NxN matrix

#Ising code

class Ising:
    """creating the ising model in this class"""
#creating a function which creates an initial matrix with randomly orientated spins of 1 and -1
    def __init__(self, nx, ny, random=False):
        if random:
            self._lattice = np.random.choice(np.array([-1,1]),size=(N,N))
        else:
            self._lattice = np.ones(N,N)

#creating a function which flips the spin of the individual lattice points
    def flipspin(self, x, y):
        if self._lattice[x,y] == 1.0:
            self._lattice[x,y] == -1.0
        else:
            self._lattice[x,y] == 1.0

    def nearestneighbours(self, N, x, y):
         neighbourList = [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]
        #check if neighbors have walked off the edge of the box, apply periodic boundary conditions if so
         for i,element in enumerate(neighbourList):
            for j,entry in enumerate(element):
                if (entry < 0):
                    neighbourList[i][j] = self.shape()[j]-1
                elif (entry >= self.shape()[j]):
                    neighbourList[i][j] = 0
         return neighbourList

def Hamiltonianenergy(lattice, x ,y):
    return 2 * lattice[x, y] * sum(lattice.nearestneighbours(lattice, N, x, y))

def metropolis(lattice,temperature,eps=1):
    J = 1
    t = 0
    switch = 0
    energies = 0
    energycount = []
    res = []
    fig = plt.figure()
    #evaluate inverse temperature
    beta = 1/temperature
    #construct ising lattice
    lattice = Ising(nx,ny,random=True)
    #sample x,y point on lattice from uniform distribution over the integers
    #flip spin and calculate dH

    #accept or reject according to metropolis function
    for t in range(sweeps):
        i = np.random.randint(N) #randomly selecting an individual lattice point
        j = np.random.randint(N)
        dH = Hamiltonianenergy(lattice,(i, j),eps,flip=True)
        if (dH > 0):
            boltzmann = np.exp(-1*beta*dH)
            randNum = np.random.uniform()
            result = True
            if boltzmann <= randNum:
                lattice.flip(i, j)
                result = False
        else:
            boltzmann = 1
            randNum = 1
            result = True
            energycount.append(energies)

        plt.imshow(lattice)
        fig.canvas.draw()
        plt.pause(0.01)
        plt.show()
        t +=1
        print t
        print energycount
        res.append(switch)

I am receiving the warning message on my figure:

local variable image is assigned to but never used

A: I've managed to fix all the programming issue of your code, but as I stated in a comment, I believe there is a problem with your metropolis part which is nod doing any flipping. Particularly, I think you're not doing your dH properly.
Placing comments (hopefully all of them) where I did change things to be able to run the code.
import numpy as np
import matplotlib.pyplot as plt

#initialised values

T = 1.0
N = 5
sweeps = 5

nx = N
ny = N #size of the NxN matrix

#Ising code

class Ising:
    """creating the ising model in this class"""
    #creating a function which creates an initial matrix with randomly orientated spins of 1 and -1
    def __init__(self, nx, ny, random=False):
        self._lattice = np.random.choice(np.array([-1,1]),size=(N,N))

#creating a function which flips the spin of the individual lattice points
    def flipspin(self, x, y):
        self._lattice[x,y] *= -1  # simplified the flipping

    def __getitem__(self, key):  # added a special method to be able to do the lattice[(i,j)] lookup
        x, y = key
        return self._lattice[x, y]

    def __str__(self):  # just for debugging purposes
        return str(self._lattice)

    def nearestneighbours(self, N, x, y):  # this was fine, you're doign the sum here already
       return self._lattice[(x - 1) % N, y] + self._lattice[(x + 1) % N, y] + \
           self._lattice[x, (y - 1) % N] + self._lattice[x, (y + 1) % N]

    def show(self):  # using a method to show graphically your 2D matrix
        fig = plt.figure()
        image = plt.imshow(self._lattice)
        fig.canvas.draw()
        plt.show()

def Hamiltonianenergy(lattice, x ,y):  # cleaned up to be able to call it without problems
    return 2 * lattice[(x, y)] *  lattice.nearestneighbours(N, x, y)

def metropolis(temperature,eps=1):
    J = 1
    t = 0
    switch = 0
    energies = 0
    energycount = []
    res = []

    #evaluate inverse temperature
    beta = 1/temperature
    #construct ising lattice
    lattice = Ising(nx,ny,random=True)
    print(lattice)

    #accept or reject according to metropolis function
    for t in range(sweeps):
        i = np.random.randint(N) #randomly selecting an individual lattice point
        j = np.random.randint(N)
        dH = Hamiltonianenergy(lattice, i,  j)  # here should be the problem, you have to make the difference of energies before and after the flip!

        if (dH > 0):
            boltzmann = np.exp(-1*beta*dH)
            randNum = np.random.uniform()
            result = True
            if boltzmann <= randNum:
                lattice.flipspin(i, j)  # you where not calling the method properly
                result = False
        else:
            boltzmann = 1
            randNum = 1
            result = True
            energycount.append(energies)

        # some console output
        print(t, i, j, result)
        print("dh: ", dH)
        print(lattice)

        t +=1

        res.append(switch)
        lattice.show()

metropolis(1000)  # running the metropolis function when executing the file


text:
Q: Group Policy Error Code 0x80070005 We have a group policy set up, it's a computer policy that moves a file from a network location to the standard Windows wallpaper location C:\Windows\Web\wallpaper. A user policy then sets the desktop background to that file. It works for all but 1 computer, which is getting a black background because the file never copies. When a report is run looking at that policy, it fails giving the error code '0x80070005'.
I've done some research, finding out it's an access denied error, but most of the answers relate to the computer or the user not having access to the file, both the computer and the user do. Also the policy is applied to a group of computers, every other computer is not having an issue copying that file, just this one.
I've done a reporting wizard, and the rest of the computers are still copying the file over with no issues, it really is just this one computer. I've checked, and it's in the same group (just a generic 'Domain Computers' group), and the user has all the permissions he should, he can go into that file and open it if he wants.
Does anyone know what might be causing the issue and how to solve it?

A: What I found was a simple issue in the GPO file dialogue box, I was putting the destination path with out specifying the destination file name and extension also. Once I filled that out correctly all errors went away and files came down.


text:
Q: beforeClose not working in jGrowl? I have the following code which pulls json data from an ASP.NET page and displays these as notifications. The code will also take a note of what's been pulled through and store it in an array to prevent it being shown again in the same session.
I'm now trying to implement functionality so that when the user closes a message, it's ID is recorded in a cookie to prevent it ever being shown again. To do this, I'm trying to write to the cookie when the beforeClose event fires.
Everything else works fine apart from the saving to a cookie bit. Is there something wrong with my code that I'm missing?
var alreadyGrowled = new Array();
var noteCookie = $.cookie("notificationsViewed");
if (noteCookie != null) { alreadyGrowled = noteCookie.split(","); }

function growlCheckNew() {
$.getJSON('getNotifications.aspx', function(data) {
    $(data).each(function(entryIndex, entry) {
        var newMessage = true;
        $(alreadyGrowled).each(function(index, msg_id) {
            if (entry['ID'] == msg_id) {
                newMessage = false;
            }
        });

        if (newMessage == true) {
            $.jGrowl(entry['Message'], {
                sticky: true,
                header: entry['Title'],
                beforeClose: function(e, m) {
                    $.cookie("notificationsViewed", entry['ID']);
                }
            });
        }
        alreadyGrowled.push(entry['ID']);
    });
});

}

A: This:
        $.jGrowl(entry['Message'], {
            sticky: true,
            header: entry['Title'],
            beforeClose: function(e, m) {
                $.cookie("notificationsViewed", entry['ID']);
            }
        });

Needs to be:
        var id = entry['ID'];
        $.jGrowl(entry['Message'], {
            sticky: true,
            header: entry['Title'],
            beforeClose: function(e, m) {
                $.cookie("notificationsViewed", id);
            }
        });

Your beforeClose happens later, with the context of the created element, but entry is not available at this point, you'll probably see the cookie is getting set to undefined or erroring...this should fix that by explicitly passing the id into the closure.

A: OK. Using the close event, I can add the id of the message to a cookie, my next issue is that the cookie appears to be null/empty in a new session, despite me setting an expiry.
//notification functions
var alreadyGrowled = new Array();
var keepClosed = new Array();
var noteCookie = $.cookie("notificationsViewed");
if (!noteCookie) {
    $.cookie("notificationsViewed", "", { expires: 365, path: '/' });
} else {
    keepClosed = noteCookie.split(",");
}

function growlCheckNew() {
     $.getJSON('getNotifications.aspx', function(data) {
    $(data).each(function(entryIndex, entry) {
        var newMessage = true;
        $(alreadyGrowled).each(function(index, msg_id) {
            if (entry['ID'] == msg_id) {
                newMessage = false;
            }
        });

        $(keepClosed).each(function(index, msg_id) {
            if (entry['ID'] == msg_id) {
                newMessage = false;
            }
        });

        if (newMessage == true) {
            var id = entry['ID'];
            alreadyGrowled.push(id);
            $.jGrowl(entry['Message'], {
                sticky: true,
                header: entry['Title'],
                close: function(e, m) {
                    keepClosed.push(id);
                    $.cookie("notificationsViewed", keepClosed);
                }
            });
        }
    });
});
}

A:     $.jGrowl(entry['Message'], {
        myId:entry['ID'],
        sticky: true,
        header: entry['Title'],
        close: function(e, m, o) {
            $.cookie("notificationsViewed", o.myId);
        }
    });

Pass your Id parameter through options.


text:
Q: Azure Static Website Hosting Is there any way to host static website (HTML + CSS  + JS) in Azure? Like we do Amazon S3 Static Website hosting, they charge only for storage.

A: UPDATE: 29-June-2018
It is now possible to host static websites in Azure Storage. You can read more about it here: https://learn.microsoft.com/en-gb/azure/storage/blobs/storage-blob-static-website

As of today, no. Azure doesn't have an equivalent of that. You can however host static sites as Web Apps and for free as well if you're comfortable with the restrictions with free tier.

A: It's not officially supported, but if you hosted your site in Azure Blob Storage's root container and made the container publicly accessible, you could probably achieve the same affect. You can even give the blob storage account a custom domain name.
Only downside is that you'll have to figure out a good deployment story.  Two of your options are to use an FTP-like client such as CloudBerry to manually deploy your site, or write your own deployment script using the blob storage api

A: I found a way to host a static website in an Azure blob, using a subdomain and an http re-direct
I do the following
1) In Azure I create a storage account with a container ( called docs ) that has Blob access policy.
2) I upload my static website to the docs container using the storage explorer. This includes some PHP files in a sub folder.
3) In the DNS I set up a cname record for a subdomain ( called info say) with alias myblob.blob.core.windows.net ( where myblob is the name of my blob)
4) In the DNS I create an Http redirect for record to a file on the subdomain for www with url http://info.mydomainname.com/docs/index.html
5) In Azure I create a custom domain for info.mydomainname.com
My website then works however if someone knows the location of the PHP files then they can download them which means I must not store secrets in them.
I have asked if there is a work around here


text:
Q: Share X axis of two pandas series' plots I have two pandas series. I need to plot them with shared X axis stacked on each other. I tried the code below but instead of stacking them it rather puts the two lines on the same plot. Why is that? How can I stack them?
n=10
x = pd.Series(data = np.random.randint(0,10, n), index=pd.date_range(pd.to_datetime('today'), freq='D', periods=n))
y = pd.Series(data = np.random.randint(0,10, n), index=pd.date_range(pd.to_datetime('today'), freq='D', periods=n))

ax = x.plot()
ax2 = y.plot()
ax2.sharex(ax)

I know the stacking can be done with subplots. If I understood correctly, pandas' only handle is the ax that is returned upon calling df.plot(). How can I use this ax to achieve the proper stacking with shared abscissa?

A: Use subplots to create shared axis:
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
x.plot(ax=ax1)
y.plot(ax=ax2)
plt.show()


text:
Q: Vue countdown timer prints out on console.log but don't get passed on as data I am using moment js to countdown the time as 10,9,8,7,6 . It successfully counts down time on console.log but I am not able to pass that as a data.
Below is my code on jsfiddle
https://jsfiddle.net/ujjumaki/817bqn52/9/

A: Change the function inside setInterval to an arrow functions, in order to read this as the Vue component:
setInterval(() => {
      duration.subtract(interval, "milliseconds"); //using momentjs substract function
      this.countdownTimer = moment(duration.asMilliseconds()).format('s');
      console.log(moment(duration.asMilliseconds()).format('s'));
      /* countdown timer works for console.log */
}, interval );

A: This is because this in the setInterval handler by default points to the window object. You could change this by adding .bind(this) to the function, or using an arrow function. Update JSFiddle: https://jsfiddle.net/qg4863tv
Read more about this here: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval#The_this_problem


text:
Q: V1 signed Release APK is not working in Android Q beta, but Works with V2 Signed APK For some reasons we can't use V2 Signed Released APK, we need to use V1 Signed APK. But with Android Q(Beta),after installing APK we are unable to launch app itself.
We will not get any logs to debug what went wrong.
Please let me know, how to solve this issue with Android Q.

A: V2 Signed or not signed APK will be generated and should run with out any issue.
Clean Project and Rebuild project(Tools>build Clean Project) and check if your device or emulator already have App with same package name. If so Uninstall old apk and try installing newly generated apk.
Use same key(key.jks) and password file that you created at first. Using different may cause error or Apk may not generate.
in Help>Show log in Explorer will show log if there is any error. Upload Log file if above doesn't help

A: Issue was with Android Q Beta-5 and is solved with Beta-6.
For Details, Please go through below Android bug tracker,
https://issuetracker.google.com/issues/139040934


text:
Q: I'm trying to sort the netlist error in proteus I'm simulating pic in Proteus loaded the hex file of the Proteus but I'm getting the following error:

Also I am getting the error of MQ-2 sensor library saying ".......\users\zain\appdata" not found (this library downloaded from The engineering projects.

A: On Proteus, you need to configure your power rails.
Go to Design -> Configure Power Rails

Then create the power rail and set the voltage. Select the power rail and click add to add it to the power rail.


text:
Q: when I am trying to upload image on imgbb from my react app by fetch I am getting this error "error : {message: 'Empty upload source.', code: 130}" I am Building a React App. For My Image Upload I Want To Use IMGBB .But When I Try To Upload Image BY FETCH I AM GETTING ERROR WITH BAD REQUEST.So How Can I Solve This Issue?
MY CODE-
const formData=new FormData();
        formData.append("file",e.target.files[0]);
        console.log(formData);
        const url=`https://api.imgbb.com/1/upload?key=MY_KEY`;
        fetch(url,{
            method: 'post',
            headers:{"content-type": "multipart/form-data"},
            body:formData
        })
        .then(res=>res.json())
        .then(data=>console.log(data));
    }

A: It should be
formData.append("image", e.target.files[0]);

Because Image bb is not accepting any name without 'image'.


text:
Q: Multipart htaccess redirect Hey guys I'm having a bit of trouble getting my htaccess to redirect properly and was hoping for some help.
I'm expecting DEV-domain.com?CampID=AB12345 to redirect to
http://DEV-www.domain.com/landing/external-marketing/direct-mail/AB?CampId=AB12345
RewriteCond %{HTTP_HOST} ^DEV-(www\.)?domain\.com [NC]
RewriteCond %{QUERY_STRING} ^CampID=
RewriteRule (\w{2})(\w{5})$ http://DEV-www\.domain\.com/landing/external-marketing/direct-mail/$1?CampId=$1$2 [R=301,L]

Unfortunetly I can't get it working for some reason?

A: Because the RewriteRule matching is meant for the url path, not query strings. Try this:
RewriteCond %{HTTP_HOST} ^DEV-(www\.)?domain\.com [NC]
RewriteCond %{QUERY_STRING} ^CampID=(\w{2})(\w{5})
RewriteRule .* http://DEV-www.domain.com/landing/external-marketing/direct-mail/%1?CampId=%1%2 [R=301,L]

also you don't need to escape dots . in the target url, only in matching patterns. And be aware that if you decide to make your target url CampID instead of CampId, you need to put in another condition:
RewriteCond %{REQUEST_URI} !^/landing/external-marketing/direct-mail/

to avoid an infinite redirect as a target with CampID would match your RewriteCond rule...


text:
Q: Is there any intuition for finding cohomology groups of famous manifolds? I am interested in seeing how do cohomology groups of sphere, torus, Mobius band, Klein bootle or projective plane look like? Is there any intuition, like for homology groups?
When it comes to homology, H0 counts number of connected components, H1 counts 1D holes (which is the same as fundamental group, when we talk about path-connected space, and all of those I am interested in actually are), H2 counts 2D holes (how many plugs you need to inflate it).
I found here http://www.tricki.org/article/How_to_compute_the_cohomology_of_a_space
that when it comes to cohomology, H0 also counts connected components (or path components) and that Hn=$\mathbb{Z}$, when space is connected, compact, orientable n-dimensional manifold.
Can someone list me cohomology groups for sphere, Mobius band, disk, torus, Klein bottle and projective plane and give me some intuition about H1 and H2? I know that Hn=0, for all n>2 for all of them above, because they are 1-dimensional or 2-dimensional manifolds.
Thanks in advance!

A: Cohomology is "basically the same" as homology.  To the extent that homology intuitively counts "$n$-dimensional holes", so does cohomology.  In fact, the cohomology groups of a space are completely determined by the homology groups, and are often isomorphic to them (though not canonically).
To be more precise, let us assume a space $X$ has finitely generated homology groups in each dimension.  Let us write $H_n(X)\cong F_n\oplus T_n$, where $T_n$ is the torsion subgroup of $H_n(X)$ and $F_n$ is a free abelian group.  Then the cohomology of $X$ (with coefficients in $\mathbb{Z}$) is given by the formula $$H^n(X)\cong F_n\oplus T_{n-1}.$$  That is, the "free part" of the cohomology is the same as homology, and the "torsion part" is shifted up one dimension from homology.  In particular, if the homology is torsion-free, the cohomology is isomorphic to the homology.
(When the homology groups are not finitely generated, or if you use different coefficients, or if you want a natural isomorphism identifying $H^n(X)$, the story is more complicated.  The general story is known as the universal coefficient theorem for cohomology.)


text:
Q: Efficiently eliminate common sub-expressions in .NET Expression Tree I've written a DSL and a compiler that generates a .NET expression tree from it.
All expressions within the tree are side-effect-free and the expression is guaranteed to be a "non-statement" expression (no locals, loops, blocks etc.).  (Edit: The tree may include literals,  property accesses, standard operators and function calls - which may be doing fancy things like memoization inside, but are externally side-effect free).
Now I would like to perform the "Common sub-expression elimination" optimization on it.
For example, given a tree corresponding to the C# lambda:
foo =>      (foo.Bar * 5 + foo.Baz * 2 > 7)
         || (foo.Bar * 5 + foo.Baz * 2 < 3)
         || (foo.Bar * 5 + 3 == foo.Xyz)

...I would like to generate the tree-equivalent of (ignore the fact that some of the short-circuiting semantics are being ignored):
foo =>
{
     var local1 = foo.Bar * 5;

     // Notice that this local depends on the first one.
     var local2 = local1 + foo.Baz * 2;

     // Notice that no unnecessary locals have been generated.
     return local2 > 7 || local2 < 3 || (local1 + 3 == foo.Xyz);
}

I'm familiar with writing expression-visitors, but the algorithm for this optimization isn't immediately obvious to me - I could of course find "duplicates" within a tree, but there's obviously some trick to analyzing the dependencies within and between sub-trees to eliminate sub-expressions efficiently and correctly.
I looked for algorithms on Google but they seem quite complicated  to implement quickly. Also, they seem very "general" and don't necessarily take the simplicity of the trees I have into account.

A: *

*Make a SortedDictionary<Expression, object> that can compare arbitrary Expressions.
(You can define your own arbitrary comparison function here -- for example, you can lexicographically compare the types of the expressions, and if they compare equal then you can compare the children one by one.)

*Go through all the leaves and add them to the dictionary; if they already exist, then they're duplicates, so merge them.
(This is also a good time to emit code -- such as creating a new variable -- for this leaf if it's the first instance of it; you can then store the emitted code inside the object value in the dictionary.)

*Then go through the parents of all the previous leaves and add them to the dictionary; if they already exist, then they're duplicates, so merge them.

*Keep on going up level by level until you reach the root.
Now you know what all the duplicates are, and where they occur, and you've generated code for all of them.

A: You are doing unnecessary work, common sub-expression elimination is the job of the jitter optimizer.  Let's take your example and look at the generated code.  I wrote it like this:
    static void Main(string[] args) {
        var lambda = new Func<Foo, bool>(foo =>
               (foo.Bar * 5 + foo.Baz * 2 > 7)
            || (foo.Bar * 5 + foo.Baz * 2 < 3)
            || (foo.Bar * 5 + 3 == foo.Xyz));
        var obj = new Foo() { Bar = 1, Baz = 2, Xyz = 3 };
        var result = lambda(obj);
        Console.WriteLine(result);
    }
}

class Foo {
    public int Bar { get; internal set; }
    public int Baz { get; internal set; }
    public int Xyz { get; internal set; }
}

The x86 jitter generated this machine code for the lambda expression:
006526B8  push        ebp                          ; prologue
006526B9  mov         ebp,esp
006526BB  push        esi
006526BC  mov         esi,dword ptr [ecx+4]        ; esi = foo.Bar
006526BF  lea         esi,[esi+esi*4]              ; esi = 5 * foo.Bar
006526C2  mov         edx,dword ptr [ecx+8]        ; edx = foo.Baz
006526C5  add         edx,edx                      ; edx = 2 * foo.Baz
006526C7  lea         eax,[esi+edx]                ; eax = 5 * foo.Bar + 2 * foo.Baz
006526CA  cmp         eax,7                        ; > 7 test
006526CD  jg          006526E7                     ; > 7 then return true
006526CF  add         edx,esi                      ; HERE!!
006526D1  cmp         edx,3                        ; < 3 test
006526D4  jl          006526E7                     ; < 3 then return true
006526D6  add         esi,3                        ; HERE!!
006526D9  mov         eax,esi
006526DB  cmp         eax,dword ptr [ecx+0Ch]      ; == foo.Xyz test
006526DE  sete        al                           ; convert to bool
006526E1  movzx       eax,al
006526E4  pop         esi                          ; epilogue
006526E5  pop         ebp
006526E6  ret
006526E7  mov         eax,1
006526EC  pop         esi
006526ED  pop         ebp
006526EE  ret

I marked the places in the code where the foo.Bar * 5 sub-expression was eliminated with HERE.  Notable is how it did not eliminate the foo.Bar * 5 + foo.Baz * 2 sub-expression, the addition was performed again at address 006526CF.  There is a good reason for that, the x86 jitter doesn't have enough registers available to store the intermediary result.  If you look at the machine code generated by the x64 jitter then you do see it eliminated, the r9 register stores it.
This ought to give enough reasons to reconsider your intend.  You are doing work that doesn't need to be done.  And not only that, you are liable to generate worse code than the jitter will generate since you don't have the luxury to estimate the CPU register budget.
Don't do this.

A: You're correct in noting this is not a trivial problem.
The classical way that compilers handle it is a Directed Acyclic Graph (DAG) representation of the expression.  The DAG is built in the same manner as the abstract syntax tree (and can be built by traversing the AST - perhaps a job for the expression visitor; I don't know much of C# libraries), except that a dictionary of previously emitted subgraphs is maintained. Before generating any given node type with given children, the dictionary is consulted to see if one already exists.  Only if this check fails is a new one created, then added to the dictionary.
Since now a node may descend from multiple parents, the result is a DAG.
Then the DAG is traversed depth first to generate code.  Since common sub-expressions are now represented by a single node, the value is only computed once and stored in a temp for other expressions emitted later in the code generation to use.  If the original code contains assignments, this phase gets complicated.  Since your trees are side-effect free, the DAG ought to be the most straightforward way to solve your problem.
As I recall, the coverage of DAGs in the Dragon book is particularly nice.
As others have noted, if your trees will ultimately be compiled by an existing compiler, it's kind of futile to redo what's already there.
Addition
I had some Java code laying around from a student project (I teach) so hacked up a little example of how this works.  It's too long to post, but see the Gist here.
Running it on your input prints the DAG below. The numbers in parens are (unique id, DAG parent count).  The parent count is needed to decide when to compute the local temp variables and when to just use the expression for a node.
Binary OR (27,1)
  lhs:
    Binary OR (19,1)
      lhs:
        Binary GREATER (9,1)
          lhs:
            Binary ADD (7,2)
              lhs:
                Binary MULTIPLY (3,2)
                  lhs:
                    Id 'Bar' (1,1)
                  rhs:
                    Number 5 (2,1)
              rhs:
                Binary MULTIPLY (6,1)
                  lhs:
                    Id 'Baz' (4,1)
                  rhs:
                    Number 2 (5,1)
          rhs:
            Number 7 (8,1)
      rhs:
        Binary LESS (18,1)
          lhs:
            ref to Binary ADD (7,2)
          rhs:
            Number 3 (17,2)
  rhs:
    Binary EQUALS (26,1)
      lhs:
        Binary ADD (24,1)
          lhs:
            ref to Binary MULTIPLY (3,2)
          rhs:
            ref to Number 3 (17,2)
      rhs:
        Id 'Xyz' (25,1)

Then it generates this code:
t3 = (Bar) * (5);
t7 = (t3) + ((Baz) * (2));
return (((t7) > (7)) || ((t7) < (3))) || (((t3) + (3)) == (Xyz));

You can see that the temp var numbers correspond to DAG nodes.  You could make the code generator more complex to get rid of the unnecessary parentheses, but I'll leave that for others.

A: Disclaimer:  I have never tackled a problem like this, I'm just throwing out an idea that seems reasonably efficient:
For every node in the tree have some sort of signature.  A hash should do, collisions can be dealt with.  The signature must map all Foo.Bar entries to the same value.
Traverse the tree (O(n)) building a list of signatures of INTERNAL nodes (ignore leaves), sort on a combined key of expression size and then signature (O(n log n)).  Take the most common item of the smallest expression in the list (O(n)) and go through replacing the expression with a local variable.  (Check that they are truly matches at this time just in case we had a hash collision.  B)
Repeat this until you accomplish nothing.  This can't possibly run more than n/2 times, thus bounding the whole operation to O(n^2 log n).

A: I agree with hans-passant about the practicality of doing this. However, if you're researching this academically you may be interested in the Quine-McCluskey algorithm. Beware this is a very complex problem. Mathematica has a very nice all-purpose expression optimizer and depending on your needs you may be able to just use it - e.g. if you feed it your expression:

(foo.Bar = A, foo.Baz = B, foo.Xyz = X)


text:
Q: Spring boot search filter and pagination I want to use pagination, filter and search in a single endpoint of a  RestController.
I am using spring 5. Can anyone suggest what will the best approach for this solution.

A: public class SearchFilter {
    private String searchValue;
    @Min(0)
    private int offset;
    @Min(1)
    private int limit;
}

@RestController
@RequestMapping("/texts")
public class MyController {

    @PostMapping("/search")
    public ResponseEntity<List<Text>> search(@RequestBody @Valid SearchFilter filter) {
        Query query = new Query(Criteria.where("text").regex(Pattern.compile(filter.getSearchValue()).pattern(), "i"))
            .skip(filter.getOffset())
            .limit(filter.getLimit());
        ...

Regarding the pagination (kind of limit and offset above), you can use also @RequestParam(required=false) for the pageSize and pageNumber, and then do if possible PageRequest.of(pageNumber, pageSize).


text:
Q: While using pull we are getting a path error PS C:\Merchant\merchant-app> git pull
error: invalid path 'c:UsersUSER_NAMEupload-keystore.jks'
The error is from some path we didn't know where its come from.

A: I am fetch similar problem, trying to checkout a repository from GitHub that contained files with a ":" in the name, on a Windows.
Please run git config core.protectNTFS false solved issue, but only if You took some steps before and after running it. The entire process went like so:

*

*Clone the Git repository locally

*'cd' into the local Git repository folder that has just been cloned

*Run git reset

*Run git config core.protectNTFS false

*Run git checkout


text:
Q: How to set and fix html5 table column size dyamicly using knockout I have table like this:

I want to have a grid like experience. So I don't want the text to wrap in the cell or make the cells to resize.
I want to have fixed sized cells which their height set to 30px and the width set to the colInfo.Width which comes from knockout.
But with the above code, the cells re-size to fit their content. How should I set the attributes to have fixed height and width?

A: To give a max-height to cell contents you'll need to wrap it in another element (e.g. a div). In addition, I'd recommend using the style binding, like this:

See this fiddle for a working demo.


text:
Q: What are CLOSE_WAIT and TIME_WAIT states? When I do netstat -a on my Windows machine, I get a listing of the ports with one of the four states:
- LISTENING
- CLOSE_WAIT
- TIME_WAIT
- ESTABLISHED

What do CLOSE_WAIT and TIME_WAIT mean/indicate?

A: Basically the "WAIT" states mean that one side closed the connection but the final confirmation of the close is pending.
See e.g. this diagram of TCP states for details:
https://en.wikipedia.org/wiki/File:Tcp_state_diagram_fixed.svg

A: Due to the way TCP/IP works, connections can not be closed immediately.  Packets may arrive out of order or be retransmitted after the connection has been closed.

*

*CLOSE_WAIT indicates that the remote endpoint (other side of the connection) has closed the connection.

*TIME_WAIT indicates that local endpoint (this side) has closed the connection.

The connection is being kept around so that any delayed packets can be matched to the connection and handled appropriately.  The connections will be removed when they time out within four minutes. See http://en.wikipedia.org/wiki/Transmission_Control_Protocol for more details.

A: TIME_WAIT represents waiting for enough time to be sure that remote TCP received the ACK of its FIN request. See
en.wikipedia.org/wiki/Transmission_Control_Protocol (and also RFC 793)


text:
Q: Web service response encoding issue I am developing a Web Services based on ASP.Net asmx web service. The server end will response byte[] to client encoded in UTF-8, and client to convert the byte[] to string.
My confusion is, the England pound character at server side (I dump just before the Http response is wrote, and the character at server side is correct to be England pound) will be received as ?? from client side.
Any ideas what is wrong? I suspect it is encoding issue, but I have no idea how to debug further and any settings (settings from client web service proxy?) which will impact?
Here is the header part which I got from Fiddler.
HTTP/1.1 200 OK
Date: Fri, 20 Feb 2009 16:51:30 GMT
Server: Microsoft-IIS/6.0
cache-control: no-cache
pragma: no-cache
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/xml
Content-Length: 22752
xml version="1.0" encoding="utf-8"

A: The first thing to do is to sniff what's actually being sent, in terms of the headers, the XML declaration and the bytes forming the text itself.
Fiddler is good as an HTTP proxy, or you could use WireShark to sniff at the network level.
Once you've got those three bits of information (the Content-Type header, the XML declaration and the bytes making up the pound sign) if you update your answer we'll see what we can do. It does sound odd, as usually ASP.NET just gets all of this right.
What does your client side code look like? Is that just the normal .NET web service client code as well?
EDIT: Try to find a binary (hex dump) display in Fiddler so you can find the bytes.
However, I strongly suspect that the problem is merely with dumping the result to the console. Here's a bit of code to use to dump the unicode code points:
static void DumpString (string value)
{
    foreach (char c in value)
    {
        Console.Write ("{0:x4} ", (int)c);
    }
    Console.WriteLine();
}

I suspect you'll see an 00A3 in the output, which is the Unicode for the pound sign. That means the string has actually reached your client fine - but writing it out to the console is failing.


text:
Q: Javascript return not working I have this code:
function get_id_from_coords (x, y)
{
    x = parseInt(x);
    y = parseInt(y);

    if (x < 0)
    {
        x = (x + 6) * 60;
    }
    else
    {
        x = (x + 5) * 60;
    }
    if (y < 0)
    {
        y = (y + 6) * 60;
    }
    else
    {
        y = (y + 5) * 60;
    }

    $('#planets').children().each(function(){
        if ($(this).attr('x') == x) {
            if ($(this).attr('y') == y) {
                alert (parseInt($(this).attr('id')));
                return parseInt($(this).attr('id'));
            }
        }
    });
}
alert(get_id_from_coords(x, y));

However, from this code I get two popups:
First, from inside the function, I get the proper value (like 63), but then, when I alert the return value, I just get undefined.

A: You get undefined as you function doesn't return - the last statement is a call to each function and it's not a return statement. If you put a return, e.g.
...
return $('#planets').children().each(function(){
    if ($(this).attr('x') == x) {
        if ($(this).attr('y') == y) {
            alert (parseInt($(this).attr('id')));
            return parseInt($(this).attr('id'));
        }
    }
});

it will return something - in this case, based on the docs:

*

*http://api.jquery.com/jQuery.each/
The method returns its first argument, the object that was iterated.

it will return the children of #planets.
If you want to find some value specifically using each, then you can do something like this:
...
val toRet;
$('#planets').children().each(function(){
    if ($(this).attr('x') == x) {
        if ($(this).attr('y') == y) {
            toRet = parseInt($(this).attr('id'));
        }
    }
});
return toRet;


text:
Q: Hook up C++ code to an HTML canvas in an Electron app? I'm current developing a MOBA as a hobby. The interface is made with Angular-Material, and I plan to move development into an Electron app at some point. I've planned to something like ASM JS in tandem with an HTML canvas for game rendering from the beginning. But now I'm wondering if I can use Node to hook up some internal C++ code to render to a canvas in my Electron app. Is this possible?

A: The Chromium API Electron is built on is not exposed to native Node addons, so I don't think you'll be able to directly render to the canvas from a native Node addon. But Electron does support Chromium's Pepper plugins, which should be capable of rendering GPU accelerated content, so that's probably your best bet. Unfortunately I've never managed to find any documentation that outlines the full capabilities of Pepper plugins, but at least there are some sample plugins you can look at.


text:
Q: Integrate function as a power series The problem:

Integrate the following as a power series, find the RoC: $$\int x^2\ln(1+x)dx$$

My work:
$$\ln(1+x)=\sum_{n=1}^\infty(-1)^{n-1}\frac{x^n}{n}$$
$$\int[ x^2\sum_{n=1}^\infty(-1)^{n-1}\frac{x^n}{n}]dx$$
$$=\int[\sum_{n=1}^\infty(-1)^{n-1}\frac{x^{n+2}}{n}]dx$$
$$=C + \sum_{n=1}^\infty(-1)^{n-1}\frac{x^{n+3}}{n(n+3)}$$
Which I believe to be correct. The book however has the following answer:
$$C + \sum_{n=1}^\infty(-1)^{\color{red}n}\frac{x^{n+3}}{n(n+3)}$$
I've worked through the problem several times, but I don't see where the change in power for the $(-1)$ comes from. I feel like I must be overlooking something simple/fundamental about the problem.
RoC is obviously $1$ either way.

A: The answer in the book is wrong. Your answer (and your solution) is correct.


text:
Q: Тип редактора tinymce Подскажите, пожалуйста, как решить проблему.
Есть drupal6 + wysiwyg + tinymce. На сайте все поля типа textarea выводятся в виде миниредактора. Мне хотелось бы на одной определенной страничке выводить textarea в обычном виде (без кнопок редактора, переключателя full html и т.п.)
A: Всё зависит от того, какая именно версия у tinymce. Я использовал jQuery package. Но принцип думаю одинаковый.
Открываем файл tiny_mce.js
Ищем init
tinyMCE.init({

Меняем mode с textareas на specific_textareas, и добавляем параметр editor_deselector: nowysiwyg
В итоге должно получиться так
tinyMCE.init({
    // General options
    mode : "specific_textareas",
    editor_deselector: "nowysiwyg",

Теперь textarea с классом nowysiwyg не будут преобразовываться в wysiwyg
A: Я полагаю этот код надо вводить на нужной странице в тэгах:
<script></script>

а не лезть в файл редактора напрямую.


text:
Q: Inserting removing elements from the DOM I have a code that inserts a div with content whenever the user clicks a button. What is the angularjs way to insert or remove elements from the DOM?

A: If the elements you want to add is somehow related to or near the button, use a directive.  Normally all DOM manipulation is performed by a directive.
However, there seems to be an exception to this rule: if you want to insert something like a modal dialog box -- i.e., something that doesn't have to be placed somewhere specific -- you might want to use a service.  Listen to a few minutes of Misko regarding this.
If you do want a dialog, see http://angular-ui.github.io/bootstrap/#/dialog and here is an SO answer that uses it in a plunker.

A: You should always use a directive to manipulate DOM, especially if the data is from control


text:
Q: Please help with this volume of solid of rotation question Find the volumes of the solids generated by revolving the region bounded by the graphs of the equations about the y-axis.
$$y = \sqrt(x), y=0, x=6$$
The reason this is confusing to me is because it's asking me to take an area that is bounded by the x axis, a function, and another line, and rotate it about the y axis. If the area were bounded by the y axis instead of the x axis, this would make much more sense to me.
If I want to revolve the function about the y axis, I should make it in terms of y:
$$y=\sqrt{x} , x=y^2$$
So to integrate with respect to y using $0$ to $6$ on the x-axis as my bounds, I have to convert my bounds to be on the y-axis, and they become $0$ and $\sqrt{6}$.
Then, I can try to integrate. The problem is that if I just integrate the function normally with respect to y, I'm finding the area bound by the function and the y axis:
$$\int_0^\sqrt{6}y^2dy$$
So, with respect to y, I tried treating it like the area between the function $x=6$ and $y^2$:
$$\int_0^\sqrt{6} 6-y^2 dx$$
Then, using the disk method formula, the volume would be:
$$π\int_0^\sqrt{6} (6-y^2)^2dy$$
Evaluate that and you get $\pi(\frac{96\sqrt{6}}{5})$, which my online homework's autochecker said was wrong. Could someone tell me my error in reasoning here? Thank you.

A: When the region you are trying to rotate does not touch the axis of rotation, the "disks" you get have circular holes in the middle.
Some people use the term washer method for this technique. where the "washer" is a disk with a hole in the middle, like the washers that one might use when assembling some mechanical object with nuts and bolts.
There are some explanations here and here. Note that the second link calls this the method of disks or the method of rings, but the formula for rotation around the $y$ axis is the same no matter what you call the method:
$$ \int_a^b A(y)\,dy
 = \int_a^b \pi ((\text{outer radius})^2 - (\text{inner radius})^2)\, dy. $$
This is because $A(y)$ is the area of a disk-with-a-hole (also called washer or ring or annulus) with an outer radius and an inner radius.
If it were a disk with the given outer radius and no hole, its area would be
$\pi (\text{outer radius})^2,$ but the hole removes
$\pi (\text{inner radius})^2$ from the area.
What you did was
$$\int_a^b \pi ((\text{outer radius}) - (\text{inner radius}))^2\, dy $$
which is effectively the area of a smaller disk without a hole.
You get a smaller result that way.


text:
Q: Method Calling Public/Private Members or Methods Best Practice - C#.NET What is the best practice for calling members/fields from a private method and public method? Should the private method always call private fields or should they call the public members?
private string _name;
public string Name
{
   get {return _name; }
   set { _name = value; }
}

public void DoSomething()
{
   _doSomething();
}

private void _doSomething()
{
   _name.ToLower();
}

A: I prefer to have all code go through the public interface, simply to reduce the number of places in the code that accesses the actual backing field. Two reasons are

*

*Simplifies debugging; if you have an issue where a value is changed, or returns an unexpected value, you can set a breakpoint inside the property getter or setter and easily trap any access to the value.

*Reduces impact of changes, you can make changes to the field and it will affect very few places in the code directly.

Or, to put it in a single word: encapsulation.

A: In some cases your public property might contain some logic which you need and in that case you will always use the property instead of the local variable, if you are sure that you want to use the private member variable, and not expose that functionality to the outside world, make that particular method private.


text:
Q: chrome android setting width to 100% I've got a problem with the css on android with the chrome browser
what i do in css is:
html{
max-width: 100%;
height: 100%;
width: 100%;
overflow: hidden;
position: relative;
}

body{
background-color: rgba(101,122,151,0.8);
margin: 0px;
width: 100%;
overflow: hidden;
position: relative;
}

header {
width: 100%;
min-width: 100%;
color: yellow;
font-size: 40px;
text-align: left;
}

and in the javascript i outprint the widths of the body and header
alert($('header').width());
alert($('body').width());

it is showing me the body width is 980 and the header width is 340
but I don't understand why. can someone help me?
Thanks

A: When loading a webpage on a mobile browser, the browser will assume the site is designed for a larger screen and gives a larger viewport than the device so the user can zoom in on the content.
If you want the width of the device, you need to set the viewport size which can be done with:
<meta name="viewport" content="width=device-width, initial-scale=1">

There is more info here: https://developer.mozilla.org/en-US/docs/Web/HTML/Viewport_meta_tag#viewport_basics

A: First, if you set max-width: 100% and then width: 100% means that width will override max-width, so you can remove max-width. Besides what's the point of setting min/max the same as width?
Second, if you set body width 100% then body takes max width of the viewport. So the question is what's the viewport size?

A: Have you tried to set min-width to 100% on the body?
Any reason you use position on html and body, and not header also?


text:
Q: Как присвоить переменой локальный класс Знаний почти ноль, пытаюсь аналезировать кусок кода:
(function(Fb, D) {
    Fb.lime = Fb.lime || {};
    Fb.lime.CYd = Fb.lime.CYd || {};
    Fb.lime.CYd.heroeshx = function(D, P) {
        (function(va, fa) {
...
            h["game.command.rpc.RpcClient"] = PN;
            PN.u = "game.command.rpc.RpcClient";
            PN.__interfaces__ = [t5a];
            PN.w = Mz;
            PN.prototype = k(Mz.prototype, {
...

Хочу присвоить переменной test класс PN, но не получается:
test = new window.lime.CYd.heroeshx.PN()
VM1748:1 Uncaught TypeError: window.lime.CYd.heroeshx.PN is not a constructor
    at eval (eval at <anonymous> (heroes.js:2634:1), <anonymous>:1:8)
    at heroes.js:2634:1
    at Fb.lime.CYd.heroeshx (heroes.js:14976:25)
    at <anonymous>:1:17

Может всё очень просто?)


text:
Q: Difference between static & dynamic pages? I was doing some research on the types of web pages available and I came across these 2 types: static & dynamic. However, the sites which I read it from does not provide me with much information for me to understand what does these types of pages do and preferred for what kinds of websites/functions. Can anyone explain to me the functions of each of these 2 webpage types and tell me the difference/when to use them? Thanks! :)

A: From Wikipedia:

A static web page (sometimes called a flat page) is a web page that is delivered to the user exactly as stored, in contrast to dynamic web pages which are generated by a web application.

Here's a good comparison:
Static Vs Dynamic websites - what's the difference?


text:
Q: Best (NoSQL?) DB for small docs/records, unchanging data, lots of writes, quick reads? I found a few questions in the same vein as this, but they did not include much detail on the nature of the data being stored, how it is queried, etc... so I thought this would be worthwhile to post.
My data is very simple, three fields:
- a "datetimestamp" value (date/time)
- two strings, "A" and "B", both < 20 chars
My application is very write-heavy (hundreds per second). All writes are new records; once inserted, the data is never modified.
Regular reads happen every few seconds, and are used to populate some near-real-time dashboards. I query against the date/time value and one of the string values. e.g. get all records where the datetimestamp is within a certain range and field "B" equals a specific search value.  These queries typically return a few thousand records each.
Lastly, my database does not need to grow without limit; I would be looking at purging records that are 10+ days old either by manually deleting them or using a cache-expiry technique if the DB supported one.
I initially implemented this in MongoDB, without being aware of the way it handles locking (writes block reads). As I scale, my queries are taking longer and longer (30+ seconds now, even with proper indexing). Now with what I've learned, I believe that the large number of writes are starving out my reads.
I've read the kkovacs.eu post comparing various NoSQL options, and while I learned a lot I don't know if there is a clear winner for my use case. I would greatly appreciate a recommendation from someone familiar with the options.
Thanks in advance!

A: I have faced a problem like this before in a system recording process control measurements.  This was done with 5 MHz IBM PCs, so it is definitely possible.  The use cases were more varied—summarization by minute, hour, eight-hour-shift, day, week, month, or year—so the system recorded all the raw data, but is also aggregated on the fly for the most common queries (which were five minute averages).  In the case of your dashboard, it seems like five minute aggregation is also a major goal.
Maybe this could be solved by writing a pair of text files for each input stream:  One with all the raw data; another with the multi-minute aggregation.  The dashboard would ignore the raw data.  A database could be used, of course, to do the same thing.  But simplifying the application could mean no RDB is needed.  Simpler to engineer and maintain, easier to fit on a microcontroller, embedded system, etc., or a more friendly neighbor on a shared host.

A: Deciding a right NoSQL product is not an easy task. I would suggest you to learn more about NoSQL before making your choice, if you really want to make sure that you don't end up trusting someone else's suggestion or favorites.
There is a good book which gives really good background about NoSQL and anyone who is starting up with NoSQL should read this.
http://www.amazon.com/Professional-NoSQL-Wrox-Programmer/dp/047094224X
I hope reading some of the chapters in the book will really help you. There are comparisons and explanations about what is good for what job and lot more.
Good luck.


text:
Q: problem with revalidating a jframe I have this code which should take the radio button input do a little math and display a popup. which it does fine. but then it is supposed to re validate and ask the next question.
when i get to the second question, the answer always comes out as the isSelected(true) value no matter which radio button you click on. SO to be clear the first time through it works fin but when the second question comes up, it just takes the default radio button every time.
public class EventHandler implements ActionListener {

private Main gui;

public EventHandler(Main gui){
    this.gui = gui;
}
public void actionPerformed(ActionEvent e){
    String answer = "";
    double val = 1;
    //get current answer set
    String [] anArr = gui.getAnswers(gui.currentStage, gui.currentQuestion);

    if(e.getSource() == gui.exit){
        System.exit(0);
    }
    if(e.getSource() == gui.submit){

        if(gui.a1.isSelected()){
           answer = anArr[0];
           val = gui.getScore(1);
        }
        if(gui.a2.isSelected()){
           answer = anArr[1];
           val = gui.getScore(2);
        }
        if(gui.a3.isSelected()){
           answer = anArr[2];
           val = gui.getScore(3);
        }
        if(gui.a4.isSelected()){
           answer = anArr[3];;
           val = gui.getScore(4);
        }
        JOptionPane.showMessageDialog(null, popupMessage(answer, val), "Your Answer", 1);

        //compute answer here

        //figure out what next question is to send
        gui.moveOn();
        gui.setQA(gui.currentStage, gui.currentQuestion);
        //resets gui
        gui.goWest();

        gui.q.revalidate();

    }
}
public String popupMessage(String ans, double val){
    //displays popup after an answer has been choosen

    gui.computeScore(val);
    String text = " You Answered " + ans + " Your score is now " + gui.yourScore ;

    return text;
}
}

public class Main extends JFrame {
public JLabel question;
public JButton exit;
public JButton submit;
public JRadioButton a1;
public JRadioButton a2;
public JRadioButton a3;
public JRadioButton a4;
public ButtonGroup bg;
public double yourScore = 1;
public int currentQuestion = 1;
public String currentStage = "startup";
JPanel q;

public Main(){
    setTitle("Ehtics Builder");
    setLocation(400,400);
    setLayout(new BorderLayout(5,5));
    setQA("startup", 1);

    goNorth();
    goEast();
    goWest();
    goSouth();
    goCenter();

    pack();
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void goNorth(){

}
public void goWest(){

    q = new JPanel();
    q.setLayout(new GridLayout(0,1));
    q.add(question);
    bg.add(a1);
    bg.add(a2);
    bg.add(a3);
    bg.add(a4);
    a1.setSelected(true);
    q.add(a1);
    q.add(a2);
    q.add(a3);
    q.add(a4);

    add(q, BorderLayout.WEST);
    System.out.println();
}
public void goEast(){

}
public void goSouth(){
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.CENTER));
    exit = new JButton("Exit");
    submit = new JButton("Submit");
    p.add(exit);
    p.add(submit);
    add(p, BorderLayout.SOUTH);

    EventHandler myEventHandler = new EventHandler(this);
    exit.addActionListener(myEventHandler);
    submit.addActionListener(myEventHandler);
}
public void goCenter(){

}

public static void main(String[] args) {
    Main open = new Main();
}
public String getQuestion(String type, int num){
    //reads the questions from a file
    String question = "";
    String filename = "";
    String [] ques;
    num = num - 1;
    if(type.equals("startup")){
        filename = "startup.txt";
    }else if(type.equals("small")){
        filename = "small.txt";
    }else if(type.equals("mid")){
        filename = "mid.txt";
    }else if(type.equals("large")){
        filename = "large.txt";
    }else{
        question = "error";
        return question;
    }

    ques = readFile(filename);

    for(int i = 0;i < ques.length;i++){
        if(i == num){
            question = ques[i];
        }
    }

    return question;
}
public String [] getAnswers(String type, int num){
    //reads the answers from a file
    String filename = "";
    String temp = "";
    String [] group;
    String [] ans;
    num = num - 1;
    if(type.equals("startup")){
        filename = "startupA.txt";
    }else if(type.equals("small")){
        filename = "smallA.txt";
    }else if(type.equals("mid")){
        filename = "midA.txt";
    }else if(type.equals("large")){
        filename = "largeA.txt";
    }else{
        System.out.println("Error");
    }

    group = readFile(filename);

    for(int i = 0;i < group.length;i++){
        if(i == num){
            temp = group[i];
        }
    }

    ans = temp.split("-");

    return ans;
}
public String [] getValues(String type, int num){
    //reads the answers from a file
    String filename = "";
    String temp = "";
    String [] group;
    String [] vals;
    num = num - 1;
    if(type.equals("startup")){
        filename = "startupV.txt";
    }else if(type.equals("small")){
        filename = "smallV.txt";
    }else if(type.equals("mid")){
        filename = "midV.txt";
    }else if(type.equals("large")){
        filename = "largeV.txt";
    }else{
        System.out.println("Error");
    }

    group = readFile(filename);

    for(int i = 0;i < group.length;i++){
        if(i == num){
            temp = group[i];
        }
    }

    vals = temp.split("-");

    return vals;
}
public String [] readFile(String filename){
    //reads the contentes of a file, for getQuestions and getAnswers
    String text = "";
    int i = -1;
    FileReader in = null;
    File f = new File(filename);
    try{
        in = new FileReader(f);
    }catch(FileNotFoundException e){
        System.out.println("file does not exist");
    }
    try{
        while((i = in.read()) != -1)
            text += ((char)i);
    }catch(IOException e){
        System.out.println("Error reading file");
    }
    try{
        in.close();
    }catch(IOException e){
        System.out.println("Error reading file");
    }

    String [] questions = text.split(":");
    return questions;
}
public void computeScore(double val){
    //calculates you score times the value of your answer
    yourScore = val * yourScore;
}
public double getScore(int aNum){
    //gets the score of an answer, stage and q number is already set in the class
    aNum = aNum - 1;
    double val = 0;
    double [] valArr = new double[4];
    for(int i = 0;i < getValues(currentStage, currentQuestion).length;i++){
        val = Double.parseDouble(getValues(currentStage, currentQuestion)[i]);
        valArr[i] = val;
    }
    if(aNum == 0){
        val = valArr[0];
    }
    if(aNum == 1){
        val = valArr[1];
    }
    if(aNum == 2){
        val = valArr[2];
    }
    if(aNum == 3){
        val = valArr[3];
    }
    // use current stage and questiion and trhe aNum to get the value for that answer
    return val;
}
public void nextQuestion(int num){
    //sets next question to use
    currentQuestion = num;
}
public void nextStage(String sta){
    // sets next stage to use
    currentStage = sta;
}
public void moveOn(){
    // uses the score and current question and stage to determine wher to go next and what stage to use next

    nextQuestion(2);
    nextStage("startup");
}
 public void setQA(String level, int num){
    String [] arr = getAnswers(level, num);
    question = new JLabel(getQuestion(level, num));
    bg = new ButtonGroup();
    a1 = new JRadioButton(arr[0]);
    a2 = new JRadioButton(arr[1]);
    a3 = new JRadioButton(arr[2]);
    a4 = new JRadioButton(arr[3]);
}

}

A: Instead of asking the JRadioButton whether it thinks it is selected:
 if(gui.a1.isSelected()){

you should ask the ButtonGroup
 if(gui.bg.isSelected(gui.a1.getModel())){

A: Having to check all the buttons to see which one is selected is a lot of similar code.  Instead why don't you create an Action class that is given to the JRadioButton. Make the action set your centrally located answer variable.  Then when the question is submitted the answer value just needs to be read.
The Action class would look like this.
public class AnswerAction extends AbstractAction{
    private String value;

    public AnswerAction(String value){
        super(value);
        this.value = value;
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        answer = value;
    }
}

Then instead of rebuilding all your buttons you would just do:
button.setAction(new AnswerAction("All of the above."));

A: It is hard to tell without being able to run the code (text files are missing) but you could try clearing the selection of the button group in your moveOn method
bg.clearSelection();


text:
Q: Add weather/images to GMap given the bounding coordinates. I have images of weather and other images that I would like to add to the GMap. I also have the bounding coordinates of these images(all 4 corners lat/lng). Now I just need to overlay these images to the map and bound them inside the coordinates. I have looked at the Demo.Clouds testing file for GMap and messed with it but I have no idea how I can integrate these bounding coordinates. Let me know if there is confusion.

A: The approach would be to create custom markers (as seen in the sources) adding your weather icons and place them at the midpoints of your bounding boxes (simple average calculation of the coordinates).
Do you also need to highlight the areas? Then you could add polygons GMapPolygon.


text:
Q: Fisher Exact test in R does not deliver odds ratio Regarding fisher's exact test in R... I wonder if I am misunderstanding something.
I have a table with several cells containing 0.
structure(list(`Fish group` = c("brain", "eyes", "muscle"), depleted = c(0L,
33L, 29L), enriched = c(33L, 0L, 0L)), row.names = c(NA, -3L), class = "data.frame")

So I thought it would be ok to use fisher's exact test for this case.
But if I run it, it does not show me parameters such as the odds ratio but it calculates a p-value.
fisher.test(dt[,2:3], dt$`Fish group`)

Is there something wrong?


text:
Q: What are the differences between the various mining picks & drills? The consumable digging implements could vary in the following attributes:

*

*Power (how many swings to break a block)

*Durability

*Effect size

The size is evident, every pick I've found has a 3x3 size. But I'm not immediately certain how the picks vary in power & durability.

A: The official wiki, Starbounder, currently answers this question on the Tools page.
For convenience, the relevant text is quoted below (2017-10-05, current Starbound version 1.3.2)

Pickaxes mine blocks in a 3x3 square 10 times per 3 seconds and break
  after 200 swings, which is about 1 minute of continuous use.
Drills mine blocks in a 2x2 square 10 times per second and break after
  1000 ticks of damage, which is about 1 minute and 40 seconds of
  continuous use.
Damage dealt per hit depends only on the material composition of the
  tool. Copper, silver, gold, platinum and diamond tools deal,
  respectively, 1.5, 2.0, 2.5, 3.0 and 3.5 damage per hit.


text:
Q: Python 3.4 Radioisotope Decay using functions, lists and, loops Could someone help me figure out how to trace decay activity day by day. I believe I need an open list somewhere. Here is the equation, Ad = Ad - 1*e - (decayConstant / isotope-half-life), where:

*

*Ad is the isotope activity at the end of day d,

*Ad-1 is the isotope previous activity at the end of day d-1 (the previous day),

*and A0 is the initial activity.

Therefore, the activity at the end of day 1 is A1 = A0 * e -(decayConstant / isotope-half-life), at the end of day 2,
A2 = A1 * e - (decayConstant / isotope-half-life), and so on.
import math
import time

#create and initialize variables and constants
decay_constant = 0.693
disposal_constant = 37

#process
def main():
        isotope = 0
        while isotope != 3:

            #input
            print("Please choose an isotope to calculate or exit")
            print("Type 1 for Chromium-51")
            print("Type 2 for Phosphorus-32")
            print("Type 3 to quit the program")
            isotope = int(input("Please input your choice now."))

            if isotope == 1:
                chromium()

            elif isotope == 2:
                phosphorus()

            elif isotope == 3:
                print("Goodbye.")

            else:
                print("Please try again.")

#Define function for Chromium
def chromium():
    half_life = 27.7025
    Ao = float(input("Please input initial activity of the
radioisotope(kBq):"))
    M_total = float(input("Please enter the total mass of the
 radioisotope(kg):"))
    M_percent = float(input("Please enter the percent mass of the
radioisotope present:"))
    Ad = int(input("Please enter a numerical start date:"))
    mass = M_total * (1-(M_percent/100))
    days = get_days_to_safe_level(Ao,mass,half_life)
    safe_level_days = safe_activity_level(Ao,safe_activity_level,half_life)
    activity = new_isotope_activity(Ad,decay_constant,half_life)

#Define function for Phosphorus
def phosphorus():
    half_life = 14.262
    Ao = float(input("Please input initial activity of the radioisotope:"))
    M_total = float(input("Please enter the total mass of the
radioisotope:"))
    M_percent = float(input("Please enter the percent mass of the
radioisotope   present:"))
    Ad = input("Please enter a numerical start date:")
    mass = M_total * (1-(M_percent/100))
    days = get_days_to_safe_level(Ao,mass,half_life)
    safe = safe_activity_level(Ao,safe_activity_level,half_life)
    activity = new_isotope_activity(Ad,decay_constant,half_life)

#output
    print("It takes", format(days,'.4f'), "days to reach safe level.")
    print("Final Activity: ", format(safe_activity_level,'.2f'),"kBq")
    print(isotope, "Activity After","=", new_isotope_activity,days)

#Define function for Days to Safe Level
def get_days_to_safe_level(Ao,mass,half_life):
    days_to_safe_level = (-
  half_life/decay_constant)*math.log(disposal_constant/(Ao/mass))
    return days_to_safe_level

#Define function for Safe Activitiy Level
def safe_activity_level(Ao,days,half_life):
    safe_activity_level = Ao * math.e**(-(decay_constant*days/(half_life)))
    return safe_activity_level

#Define function for New Isotope Activity
def new_isotope_activity():
    Ad = Ad*math.e**(-(decay_constant/(half_life)))
    return new_isotope_activity

#call main function
main()

The way the code sits gives me an error, unsupported operand for 'float' and 'function'.
Any help would be appreciated, thanks. I am in an intro to programming class so I apologize in advance for my lack of programming knowledge.

A: The problem is caused as the variable days which is implemented in the safe_activity_level function. As its used to calculate the safe_activity_level with the expression: Ao * math.e**(-(decay_constant*days/(half_life))).
def safe_activity_level(Ao,days,half_life):
safe_activity_level = Ao * math.e**(-(decay_constant*days/(half_life)))
return safe_activity_level

The variable days is not an integer or a string as wehn you call the variable you pass a function.
LINE 55:
safe = safe_activity_level(Ao,safe_activity_level,half_life)

the safe_activity_level is also the name of the function, therefore, its passing the function as the variable days.
FINALLY,
this means that the variable days is a function rather than an integer / a string as i stated before.
Hope i helped!

I cant reply yet as myy rep is below 50, but i would like to note that you call a function by adding ()
This means, you should call math.exp by math.exp(XXX) instead of math.exp**XXX.


text:
Q: Implement several order relations for one class? Which is the best way to implement several order relations for only one class? I have an idea with the Strategy Pattern but I'm not sure that's a good idea. And if there is not a best way, why?

A: Create a functor class and initialize a member with the order relation you want to use. Have operator() use the member to decide the ordering of the two operands.
class Ordering
{
public:
    Ordering(int method) : _method(method) {}
    bool operator()(const MyObject & first, const MoObject & second) const
    {
        switch(_method)
        {
            case 0:
                return first.name < second.name;
            case 1:
                return first.age < second.age;
            // ...
        }
    }
    int _method;  // an enum would be better
};

std::sort(myobjs.begin(), myobjs.end(), Ordering(selected_method));

A: I think Strategy is a better way here, and I'm not pretty sure that a switch structure is a good idea (imagine, 1000 comparison methods in one switch... Too heavy, isn't it?)
So let A, a class which need a method comparison.
I suggest to create one class per method, which instance will be A's component.
For instance :
class A{
    private:
    //Some attributes
    Comparator<A> comp_;

    public:
    //Some methods (including constructor)
    bool operator()(const MyObject & first, const MoObject & second) const
    {
        return comp_.compare(first,second);
    }
     void setComparator(Comparator<A>& comp){
        comp_ = comp;
    }
}

//Forgot the syntax about template. So there is a template with one parameter
class Comparator{
     public:
     //Constructor

     //To overwrite on subclasses
     virtual bool compare(T& first, T& second) = 0;

}

With that configuration, you can easily add a method, without modifying A, just set the right comparator at any moment of program's execution.


text:
Q: Polling subprocess object without blocking I'm writing a python script that launches programs in the background and then monitors to see if they encounter an error. I am using the subprocess module to start the process and keep a list of running programs.
processes.append((subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE), command))
I have found that when I try to monitor the programs by calling communicate on the subprocess object, the main program waits for the program to finish. I have tried to use poll(), but that doesn't give me access to the error code that caused the crash and I would like to address the issue and retry opening the process.
runningProcesses is a list of tuples containing the subprocess object and the command associated with it.
def monitorPrograms(runningProcesses):
    for program in runningProcesses:
        temp = program[0].communicate()
        if program[0].returncode:
            if program[0].returncode == 1:
                print "Program exited successfully."
            else:
                print "Whoops, something went wrong. Program %s crashed." % program[0].pid

When I tried to get the return code without using communicate, the crash of the program didn't register.
Do I have to use threads to run the communication in parallel or is there a simpler way that I am missing?

A: No need to use threads, to monitor multiple processes, especially if you don't use their output (use DEVNULL instead of PIPE to hide the output), see Python threading multiple bash subprocesses?
Your main issue is incorrect Popen.poll() usage. If it returns None; it means that the process is still running -- you should call it until you get non-None value. Here's a similar to your case code example that prints ping processes statuses.
If you do want to get subprocess' stdout/stderr as a string then you could use threads, async.io.
If you are on Unix and you control all the code that may spawn subprocesses then you could avoid polling and handle SIGCHLD yourself. asyncio stdlib library may handle SIGCHLD. You could also implement it manually, though it might be complicated.

A: Based on my research, the best way to do this is with threads. Here's an article that I referenced when creating my own package to solve this problem.
The basic method used here is to spin of threads that constantly request log output (and finally the exit status) of the subprocess call.
Here's an example of my own "receiver" which listens for logs:
class Receiver(threading.Thread):
    def __init__(self, stream, stream_type=None, callback=None):
        super(Receiver, self).__init__()
        self.stream = stream
        self.stream_type = stream_type
        self.callback = callback
        self.complete = False
        self.text = ''

    def run(self):
        for line in iter(self.stream.readline, ''):
            line = line.rstrip()
            if self.callback:
                line = self.callback(line, msg_type=self.stream_type)
            self.text += line + "\n"
        self.complete = True

And now the code that spins the receiver off:
 def _execute(self, command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                               shell=True, preexec_fn=os.setsid)
    out = Receiver(process.stdout, stream_type='out', callback=self.handle_log)
    err = Receiver(process.stderr, stream_type='err', callback=self.handle_log)
    out.start()
    err.start()
    try:
        self.wait_for_complete(out)
    except CommandTimeout:
        os.killpg(process.pid, signal.SIGTERM)
        raise
    else:
        status = process.poll()
        output = CommandOutput(status=status, stdout=out.text, stderr=err.text)
        return output
    finally:
        out.join(timeout=1)
        err.join(timeout=1)

CommandOutput is simply a named tuple that makes it easy to reference the data I care about.
You'll notice I have a method 'wait_for_complete' which waits for the receiver to set complete = True. Once complete, the execute method calls process.poll() to get the exit code. We now have all stdout/stderr and the status code of the process.


text:
Q: Bitmap-Image-Mat manipulation in emgucv : Overflow for imageSize I would like to ask for some help which could lead me to understand Mat, Image and Bitmaps. I'm using Emgu CV in C# and I would like to convert the captured desktop screen ( which is bitmap ) to mat. I found some advice here, but it didn't work for me.
What I would like to do is to convert the bitmap to image, the image to mat, then the mat back to image and the image back to bitmap, so that I can stream it to a picturebox. The problem is that when I'm converting from mat to image there is an exception thrown :

As I can see, there was a problem during converting the image to mat, as the rows (width) of the mat is exceptionally huge.

Here is the code I'm using.
public void Video()
{
      int Width = Screen.PrimaryScreen.Bounds.Width;
      int Height = Screen.PrimaryScreen.Bounds.Height;
      Size size = new Size(Height, Width);
      for ( ; ; )
      {
          System.Drawing.Image image;
          Bitmap bitmap = new Bitmap(Width, Height );

          Graphics graphics = Graphics.FromImage(bitmap as Image);
          graphics.CopyFromScreen(0, 0, Width, Height, bitmap.Size);

          Image<Bgr, Byte> imageCV = new Image<Bgr, Byte>(bitmap);

          //  CvInvoke.BitwiseNot(imageCV1, imageCV2, null);
          Mat m = new Mat(Height, Width , DepthType.Cv8U , 4);
          m = imageCV.Mat;

          Image<Bgr, Byte> mToImage = m.ToImage<Bgr, Byte>();  //error line

          //   Bitmap btm = mToImage.ToBitmap();
          Bitmap btm = mToImage.ToBitmap(m.Height, m.Width);

          pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
          pictureBox1.Image = btm;

          imageCV.Dispose();
          mToImage.Dispose();
     }
}

I know similar questions have been asked, and maybe I should have been able to put the pieces together, but I ran out of ideas. I tried to set the size of the Mat too, so the number of the rows cannot get too high, I also tried to invert my bitmap before passing it to an image. If anyone could help me to understand the concept behind them and this problem, I would be glad.

A: I've got to solve the problem with simply creating a new project and re-adding the necessary libraries again. The problem was I didn't added them correctly to my project. ( Emgu.CV.World.dll, Emgu.CV.UI.dll and the other dlls, which can be found in EmguCV's build folder.)