Q: Wrap wkhtmltoimage to xvfb-run How can I use wkhtmltoimage to run by default with xvfb?
/usr/bin/xvfb-run --server-args="-screen 0, 1024x1024x24"

I've to create bash file like this wkhtmltoimage
/usr/bin/xvfb-run --server-args="-screen 0, 1024x1024x24" /usr/local/bin/wkhtmltoimage-64 $*

But in this case, other programs (gem imgkit) do not work correctly with wkhtmltoimage. It put addition debug info to the file.

A: You can create a wrapper script as I done that:
wkhtmltoimage:
xvfb-run --server-args="-screen 0, 1024x680x24" wkhtmltoimage.bin -q --use-xserver $*

where wkhtmltoimage.bin is original binary.


Q: Hausdorff Spaces Subsets open? 'Given a Hausdorff space $X$ with finitely many elements, show all subsets of $X$ are open in $X$.'
I let $U$ be an arbitrary subset of $X$
Since every subset of a Hausdorff space is a Hausdorff space, then $U$ is also Hausdorff.
This means that any two points in $U$ $x \ne y$ have disjoint neighbourhoods.
Does this imply every point of $U$ has a neighbourhood lying in $U$ hence prove open? This seems trivial. Where does finitely many elements come into it?

A: Let $X=\{x_1,...,x_n\}$. Given $x_i$, for $j\ne i$ let $U_{i,j}$ be an open neighborhood of $x_i$ that doesn't contain $x_j$. Then $U_i = \bigcap_{j\text{:  } j\ne i}U_{i,j}$ is a finite intersection open neighborhood of $x_i$ that contains no other $x_j$, so it's open. But $U_i = \{x_i\}$.
So all singletons $\{x_i\}$ are open. Every subset of $X$ is a union of singletons, so every subset is open.

A: In a finite Hausdorff $X=\{x_1, \ldots, x_n\}$ space you can show that every singleton $\{x_i\}$ is open. Hence every subset is open since it is union of open sets.
To see that $\{x_i\}$ is open, we know that for every $j\neq i$, we have disjoint neighborhoods $U_j, V_j$ of $x_i, x_j$ respectively.
Take $$U = \bigcap_{j\neq i} U_j$$
Then $U = \{x_i\}$, which is open since it is finite intersection of open sets.

A: We only need that singletons are closed (because then all finite sets are closed, and so all sets are open)...

A: Just for interest, here is a simpler solution to the question I asked.
We want to prove any subset $U$ in a Hausdorff space with finitely many elements is open.
If $X$ is Hausdorff, then by definition every finite subset of $X$ is closed. Take $X-U$. Since $X$ has finitely many elements, then so does $X-U$, which implies $X-U$ is closed. Therefore $U$ is open.

A: Let $X$ be a finite topological space with a hausdorff topology. Observe that the topology must be discrete, and consequently, every subset is both, open and closed.


Q: How do I stop sound on mouseout when hovering over an image?
var Start = new Audio("MySound.mp3");

When hovering over the image the sound plays correctly but when I mouseout the sound continues playing? Not too sure why that is.

A: Change from onmouseout="Start.pause;"> to onmouseout="Start.pause();">. You missed the parenthesis in the pause function


Q: Persisting data on disk using Hazelcast I have installed HazelCast 2.5. I want to persist my records into disk. I learned that MapStore does this job. However i'm not sure how to implement MapStore.
Code I've written so far:
public class MyMaps implements MapStore<String,String> {

    public static Map<Integer, String> mapCustomers = Hazelcast.getMap("customers");

    public static void main(String[] args) {
        {
            mapCustomers.put(1, "Ram");
            mapCustomers.put(2, "David");
            mapCustomers.put(3, "Arun");

        }
    }
}

How do i put all these entries into disk.
Is it necessary to have a back-end like MySQL or PostgreSQL to use this class?
I believe the following function can be used:
public void delete(String arg0);
public void deleteAll(String arg0);
public void store(String arg0);
public void storeAll(String arg0);

I need a sample snippet of how to implement MapStore.
Please provide me with sample code.

A: Yes, you can use MapStore and MapLoader to persist file to local storage. Read official documentation here.
https://docs.hazelcast.org/docs/latest/manual/html-single/#loading-and-storing-persistent-data

A: Hazelcast has two types of distributed objects in terms of their partitioning strategies:

*

*Data structures where each partition stores a part of the instance, namely partitioned data structures.

*Data structures where a single partition stores the whole instance, namely non-partitioned data structures.
Partitioned Hazelcast data structures persistence data to local file system is not supported,need a centralized system that is accessible from all hazelcast members,like mysql or mongodb.
You can get code from hazelcast-code-samples.


Q: In C#, Loading large file into winform richtextbox I need to load a - 10MB range text file into a Winform RichTextBox, but my current code is freezing up the UI. I tried making a background worker do the loading, but that doesnt seem to work too well either.
Here's my several loading code which I was tried. Is there any way to improve its performance? Thanks.
    private BackgroundWorker bw1;
    private string[] lines;
    Action showMethod;
    private void button1_Click(object sender, EventArgs e)
    {
        bw1 = new BackgroundWorker();
        bw1.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw1.RunWorkerCompleted += bw_RunWorkerCompleted;
        string path = @"F:\DXHyperlink\Book.txt";
        if (File.Exists(path))
        {
            string readText = File.ReadAllText(path);
            lines = readText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            bw1.RunWorkerAsync();

        }
    }

    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        Invoke((ThreadStart)delegate()
        {
            for (int i = 0; i < lines.Length; i++)
            {
                richEditControl1.Text += lines[i] + "\n";
            }
        });
    }

I Also Try:
Action showMethod = delegate()
            {
                for (int i = 0; i < lines.Length; i++)
            {
                richEditControl1.Text += lines[i] + "\n";
            }
            };

A: It's about how you're invoking the UI update, check the AppendText bellow.
private BackgroundWorker bw1;

private void button1_Click(object sender, EventArgs e)
{
    bw1 = new BackgroundWorker();
    bw1.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw1.RunWorkerCompleted += bw_RunWorkerCompleted;
    bw1.RunWorkerAsync();
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    string path = @"F:\DXHyperlink\Book.txt";
    if (File.Exists(path))
    {
        string readText = File.ReadAllText(path);
        foreach (string line in readText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
        {
            AppendText(line);
            Thread.Sleep(500);
        }
    }
}

private void AppendText(string line)
{
    if (richTextBox1.InvokeRequired)
    {
        richTextBox1.Invoke((ThreadStart)(() => AppendText(line)));
    }
    else
    {
        richTextBox1.AppendText(line + Environment.NewLine);
    }
}

In addition to that reading the whole file text is very inefficient. I would rather read chunk by chunk and update the UI. i.e.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    string path = @"F:\DXHyperlink\Book.txt";
    const int chunkSize = 1024;
    using (var file = File.OpenRead(path))
    {
        var buffer = new byte[chunkSize];
        while ((file.Read(buffer, 0, buffer.Length)) > 0)
        {
            string stringData = System.Text.Encoding.UTF8.GetString(buffer);

            AppendText(string.Join(Environment.NewLine, stringData.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)));
        }
    }
}

A: You don't want to concatenate strings in a loop.

A System.String object is immutable. When two strings are
  concatenated, a new String object is created. Iterative string
  concatenation creates multiple strings that are un-referenced and must
  be garbage collected. For better performance, use the
  System.Text.StringBuilder class.

The following code is very inefficient:
for (int i = 0; i < lines.Length; i++)
{
    richEditControl1.Text += lines[i] + "\n";
}

Try instead:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    // Cpu intensive work happens in the background thread.
    var lines = string.Join("\r\n", lines);

    // The following code is invoked in the UI thread and it only assigns the result.
    // So that the UI is not blocked for long.
    Invoke((ThreadStart)delegate()
    {
        richEditControl1.Text = lines;
    });
}

A: why do you want to split lines and join them again?
strings  are immutable witch means cant be changed. So every time you do Text+= "..." it has to create new string and put it in Text. So for 10 mb string its not ideal way and it may take Centuries To complete such task for Huge strings.
You can see What is the difference between a mutable and immutable string in C#?
If you really want to split Them and Join them again. then StringBuilder is the right option for you.
        StringBuilder strb = new StringBuilder();

        for (int i = 0; i < lines.Length; i++)
        {
            strb.Append(lines[i] + "\n");
        }

        richEditControl1.Text = strb.ToString();

You can see String vs. StringBuilder
Structure of StringBuilder is List of characters. Also StringBuilder is Muttable. means can be changed.
Inside Loop you can do any extra task with string and Add the final result to the StringBuilder. Finally after the loop Your StringBuilder is Ready. You have to convert it to string and Put it in Text.

A: It took me a while to nail this one..
Test one & two:
First I created some clean data:
string l10 = " 123456789";
string l100 = l10 + l10 + l10 + l10 + l10 + l10 + l10 + l10 +l10 + l10;
string big = "";
StringBuilder sb = new StringBuilder(10001000);
for (int i = 1; i <= 100000; i++)
    // this takes 3 seconds to load
    sb.AppendLine(i.ToString("Line 000,000,000 ") + l100 + " www-stackexchange-com ");
     // this takes 45 seconds to load !!
    //sb.AppendLine(i.ToString("Line 000,000,000 ") + l100 + " www.stackexchange.com ");
big = sb.ToString();

Console.WriteLine("\r\nStringLength: " + big.Length.ToString("###,###,##0") + "  ");

richTextBox1.WordWrap = false;
richTextBox1.Font = new System.Drawing.Font("Consolas", 8f);
richTextBox1.AppendText(big);
Console.WriteLine(richTextBox1.Text.Length.ToString("###,###,##0") + " chars in RTB");
Console.WriteLine(richTextBox1.Lines.Length.ToString("###,###,##0") + " lines in RTB ");

Displaying 100k lines totalling in around 14MB takes either 2-3 seconds or 45-50 secods.
Cranking the line count up to 500k lines brings up the normal text load time to around 15-20 seconds and the version that includes a (valid) link at the end of each line to several minutes.
When I go to 1M lines the loading crashes VS.
Conclusions:

*

*It takes a 10+ times longer to load a text with links in it and during that time the UI is freezing.

*Loading 10-15MB of textual data is no real problem as such.
Test three:
string bigFile = File.ReadAllText("D:\\AllDVDFiles.txt");
richTextBox1.AppendText(bigFile);

(This was actually the start of my investigation..) This tries to load a 8 MB large file, containing directory and file info from a large number of data DVDs. And: It freezes, too.
As we have seen the file size is not the reson. Nor are there any links embedded.
From the first looks of it the reason are funny characters in some of the filenames.. After saving the file to UTF8 and changing the read command to..:
string bigFile = File.ReadAllText("D:\\AllDVDFiles.txt", Encoding.UTF8);

..the file loads just fine in 1-2 seconds, as expected..
Final conclusions:

*

*You need to watch out for wrong encoding as those characters can freeze the RTB during loading.

*And, when you add links you must expect for the loading to take a a lot (10-20x) longer than the pure text.  I have tried to trick the RTB by preparing a Rtf string but it didn't help. Seems that analyzing and storing all those links will always take such a long time.

So: If you really need a link on every line, do partition the data into smaller parts and give the user an interface to scroll & search through those parts.
Of course appending all those lines one by one will always be way too slow, but this has been mentionend in the comments and other answers already.


Q: Custom contour plot in MATLAB I want to create a contour plot in MATLAB, as in the second example on this page:
ContourPlot[Cos[x] + Cos[y] == 1/2, {x, 0, 4 Pi}, {y, 0, 4 Pi}]

As you can see, they are plotting only the lines for which f(X, Y) == some_value. Another issue I have is that I do not really have the function f, but only a collection of points of type [x, y, z] (read from a file), and some_value of course.
Is it possible to do such a plot in MATLAB?

A: Simply use the contour function with a 2nd argument of desired values (it is a vector of 2 elements instead of a scalar, to distinguish the function call from another mode):
some_value = .5;
[x y] = meshgrid(linspace(0,4*pi,30),linspace(0,4*pi,30));
z = cos(x)+cos(y);
contour(x, y, z, [some_value, some_value])

A: It helped me.
contourf(aX, aY, NM(:, :, k+1), 'ShowText','on', 'LevelStep', 0.4);


Q: Stripping text from one point to another in python I have a file textfile.txt:
[X:Y:Z]

How would I strip "X:" and ":Z" so that I am left with "Y"?

A: Using str.strip and str.split:
>>> '[X:Y:Z]'.strip('[]')
'X:Y:Z'
>>> '[X:Y:Z]'.strip('[]').split(':')
['X', 'Y', 'Z']
>>> '[X:Y:Z]'.strip('[]').split(':')[1]
'Y'

UPDATE
As Blender commented, stripping the brackets off is not necessary.
>>> '[X:Y:Z]'.split(':')
['[X', 'Y', 'Z]']
>>> '[X:Y:Z]'.split(':')[1]
'Y'

A: Y = "[X:Y:Z]".split(':')[1]
That's a quick one liner for it.

A: There are dozens of ways you could achieve this for the single example you've posted, e.g.:
full_string = '[X:Y:Z]'
first, middle, last = full_string.split(':')
print(middle)
Out[5]: 'Y'

To narrow down what will or won't work, you may have to post some more examples that make clearer how your data format looks, and what pieces of information you need to extract from it.


Q: Two arrays defining 2D coordinates, as array indices I have a 2D array, call it A.  I have two other 2D arrays, call them ix and iy. I would like to create an output array whose elements are the elements of A at the index pairs provided by ix and iy.  I can do this with a loop as follows:
for i=1:nx
    for j=1:ny
        output(i,j) = A(ix(i,j),iy(i,j));
    end
end

How can I do this without the loop?  If I do output = A(ix,iy), I get the value of A over the whole range of (ix)X(iy).

A: This is the one-line method which is not very efficient for large matrices
reshape(diag(A(ix(:),iy(:))),[ny nx])

A clearer and more efficient method would be to use sub2ind. I've incorporated yuk's comment for situations (like yours) when ix and iy have the same number of elements:
newA = A(sub2ind(size(A),ix,iy));

Also, don't confuse x and y for i and j in notation - j and x generally represent columns and i and y represent rows.

A: A faster way is to use linear indexing directly without calling SUB2IND:
output = A( size(A,1)*(iy-1) + ix )

... think of the matrix A as a 1D array (column-wise order)


Q: ClassCastException when try to use loaded class Java Version: 6
I have build an aotuloader which loads Classes out of a JAR and instances them. SO i get an ArrayList of all Instances which match to the specific path and Abstract Class.
package com.geNAZt.RegionShop.Util;

import com.geNAZt.RegionShop.RegionShopPlugin;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Loader {
    public static <T> ArrayList<T> loadFromJAR(RegionShopPlugin plugin, String path, Class interf) {
        ArrayList<T> returnObjects = new ArrayList<T>();

        try {
            String pathToJar = Loader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            JarFile jarFile = new JarFile(pathToJar);
            Enumeration e = jarFile.entries();

            URL[] urls = { new URL("jar:file:" + pathToJar +"!/") };
            ClassLoader cl = URLClassLoader.newInstance(urls);

            while (e.hasMoreElements()) {
                JarEntry je = (JarEntry) e.nextElement();

                if(je.isDirectory() || !je.getName().endsWith(".class") || !je.getName().substring(0,je.getName().length()-6).replace("/", ".").contains(path +".")){
                    continue;
                }

                try {
                    String className = je.getName().substring(0,je.getName().length()-6);
                    className = className.replace('/', '.');
                    Class<?> c = cl.loadClass(className);

                    if(!c.getSuperclass().getName().equals(interf.getName())) {
                        continue;
                    }

                    Constructor[] cons = c.getDeclaredConstructors();

                    for(Constructor con : cons) {
                        try {
                            returnObjects.add((T)con.newInstance(plugin));
                            break;
                        } catch (InvocationTargetException e1) {
                            e1.printStackTrace();
                            continue;
                        } catch (InstantiationException e1) {
                            e1.printStackTrace();
                            continue;
                        } catch (IllegalAccessException e1) {
                            e1.printStackTrace();
                            continue;
                        } catch (IllegalArgumentException e1) {
                            e1.printStackTrace();
                            continue;
                        }
                    }
                } catch(ClassNotFoundException er) {
                    er.printStackTrace();
                    continue;
                }

            }
        } catch(IOException e) {
            e.printStackTrace();

            return null;
        }

        return returnObjects;
    }
}

It works fine an i get the right Objects with:
private ArrayList<ShopCommand> loadedCommands = new ArrayList<ShopCommand>();
loadedCommands = loadFromJAR(pl, "com.geNAZt.RegionShop.Command.Shop", ShopCommand.class);

If i make a log all Objects seem to be fine:

12:24:40 [INFO] [RegionShop] Loaded ShopCommands: [com.geNAZt.RegionShop.Command.Shop.ShopAdd@3b39c41d, com.geNAZt.RegionShop.Command.Shop.ShopBuy@4d7a6a4b, com.geNAZt.RegionS
  hop.Command.Shop.ShopDetail@1fd889aa, com.geNAZt.RegionShop.Command.Shop.ShopEquip@4136083b, com.geNAZt.RegionShop.Command.Shop.ShopList@42567aef, com.geNAZt.RegionShop.Comman
  d.Shop.ShopName@3ba102ef]

But then i want to use them. In case to use them i wanted to cast them into the ShopCommand Class. But then i get this error:

12:24:40 [SCHWERWIEGEND] Error occurred while enabling RegionShop v1.1.0b3 (Is it up to date?)
  java.lang.ClassCastException: com.geNAZt.RegionShop.Command.Shop.ShopAdd cannot be cast to com.geNAZt.RegionShop.Command.ShopCommand
          at com.geNAZt.RegionShop.Command.ShopExecutor.(ShopExecutor.java:40)
          at com.geNAZt.RegionShop.RegionShopPlugin.onEnable(RegionShopPlugin.java:80)
          at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
          at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:457)
          at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:383)
          at org.bukkit.craftbukkit.v1_5_R3.CraftServer.loadPlugin(CraftServer.java:305)
          at org.bukkit.craftbukkit.v1_5_R3.CraftServer.enablePlugins(CraftServer.java:287)
          at net.minecraft.server.v1_5_R3.MinecraftServer.j(MinecraftServer.java:310)
          at net.minecraft.server.v1_5_R3.MinecraftServer.e(MinecraftServer.java:289)
          at net.minecraft.server.v1_5_R3.MinecraftServer.a(MinecraftServer.java:249)
          at net.minecraft.server.v1_5_R3.DedicatedServer.init(DedicatedServer.java:152)
          at net.minecraft.server.v1_5_R3.MinecraftServer.run(MinecraftServer.java:388)
          at net.minecraft.server.v1_5_R3.ThreadServerApplication.run(SourceFile:573)

Is it possible to cast the Objects into the abstract class so i get the api from the Class ? Or is there another way to get the API from the Class ?

A: This exception is the result of class identity crisis . You cannot cast between class loaders. As mentioned this site:

Other types of confusion are also possible when using multiple class
  loaders. Figure 2 shows an example of a class identity crisis that
  results when an interface and associated implementation are each
  loaded by two separate class loaders. Even though the names and binary
  implementations of the interfaces and classes are the same, an
  instance of the class from one loader cannot be recognized as
  implementing the interface from the other loader.

EDIT
Although the solution is found out by the OP but I would like to give my two cents.
The confusion which is leading to the nonrecognition of instance of the class from other ClassLoader could easily be resolved if that class is moved into the System class loader's space. And making System Class Loader to be the parent of newly created ClassLoaders. This would cause the different ClassLoaders to share the same class. This could be achieved by URLClassLoader(URL[] urls,ClassLoader parent) in following way:
URL[] urls = { new URL("jar:file:" + pathToJar +"!/") };
ClassLoader cl = new URLClassLoader(urls,ClassLoader.getSystemClassLoader());


Q: Listing subgroups of a group I made a program to list all the subgroups of any group and I came up with satisfactory result for $\operatorname{Symmetric Group}[3]$ as
$\left\{\{\text{Cycles}[\{\}]\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 2 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 2 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 2 & 3 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 3 & 2 \\
\end{array}
\right)\right]\right\}\right\}$

It excludes the whole set itself though it can be added seperately. But in case of $SymmetricGroup[4]$ I am getting following
$\left\{\{\text{Cycles}[\{\}]\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 2 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 2 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 2 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 3 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 2 \\
 3 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 3 \\
 2 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 4 \\
 2 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 2 & 3 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 3 & 2 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 2 & 4 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 4 & 2 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 3 & 4 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 4 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 2 & 3 & 4 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 2 & 4 & 3 \\
\end{array}
\right)\right]\right\}\right\}$
The matrix form shows double transposition. Can someone please check for me if I am getting appropriate results? I doubt I am!!

A: By using GAP, you can make them all so easier and visible.
  gap> LoadPackage("sonata");;
  gap> s4:=SymmetricGroup(IsPermGroup,4);;
  gap> g:=Subgroups(s4);;
  gap> List([1..Size(g)],k->g[k]);

A: I have the impression that you only list the cyclic subgroups.
For $S_3$, the full group $S_3$ ist missing as a subgroup (you are mentioning that in your question).
For $S_4$, several subgroups are missing. In total, there should be $30$ of them. $14$ of them are cyclic, which are exactly the ones you listed. To give you a concrete example, the famous Klein Four subgroup
$$\{\operatorname{id},(12)(34),(13)(24),(14)(23)\}$$
is not contained in your list.


Q: Converting floats to and displaying Binary Numbers in C So I'm just diving into C during my first few days of classes. My professor proposed a question/ more of a challenge for us so I thought I'd propose it here.
float x,y,z;
x = 0.0;
y = 1.0;
z = -2.5;

He wanted us to display these numbers in binary and hexadecimal without using %x etc. He also hinted to use a union:
union U {
float y;
unsigned z;
};

Thank you for your time in advance. I'm just looking for help/ an explanation on how to develop such conversion.

A: The correct way, not violating the strict aliasing rule would be to alias the float with a char array, which is allowed by the C standard.
union U {
  float y;
  char c[sizeof (float)];
};

This way you will be able to access the individual float y; bytes using the c array, and convert them into binary/hex using the very simple algorithm that can be easily found around (I will leave it up to you, as it is your assignment).


Q: Qt: How to know when a QMdiSubWindow is closed? Is there any way I can get notified when a user closes a QMdiSubWindow? I cannot find any signal in QMdiArea nor in QMdiSubWindow that suggests I can.
I think my only chance is by subclassing QMdiSubWindow and overriding the close event, but is there any other way?

A: Yes, there is another way : you can install an event-filter on the QMdiSubWindow you create :
MdiSubWindowEventFilter * p_mdiSubWindowEventFilter;

...

QMdiSubWindow * subWindow = mdiArea->addSubWindow(pEmbeddedWidget);
subWindow->installEventFilter(p_mdiSubWindowEventFilter);
subWindow->setAttribute(Qt::WA_DeleteOnClose, true); // not mandatory, depends if you manage subWindows lifetime

with
bool MdiSubWindowEventFilter::eventFilter(QObject * obj, QEvent * e)
{
    switch (e->type())
    {
        case QEvent::Close:
        {
            QMdiSubWindow * subWindow = dynamic_cast<QMdiSubWindow*>(obj);
            Q_ASSERT (subWindow != NULL);

            //
            // do what you want here
            //

            break;
        }
        default:
            qt_noop();
    }
    return QObject::eventFilter(obj, e);
}

A: I had the same trouble, but in my case the task was more specific: "How to hide a subwindow when I press the close button instead of closing". So I solved this with the following:
subwindow->setAttribute(Qt::WA_DeleteOnClose, false);

Perhaps it's not a relevant answer but it may be useful for someone.

A: I don't think there is any other way than as you describe (overriding the close event) to do precisely what you're asking.
There might be other ways of achieving what you want without doing that depending on why you want to know when its closed.  Other options could be the use of the destroyed signal, checking QApplication::focusWidget(), or perhaps having the parent inspect its children.
Edit in response to comment:
Signals and slots are disconnected automatically upon destruction of QObjects, and I would suggest looking at using QSharedPointers or QScopedPointers to handle your QObjects' lifespans instead.  By applying these techniques, you shouldn't need a signal from a closed window.

A: Here is what I ended coding.
#ifndef __MYSUBWINDOW_H
#define __MYSUBWINDOW_H

#include <QMdiSubWindow>
#include <QCloseEvent>
#include <QDebug>

class MyQMdiSubWindow : public QMdiSubWindow
{
    Q_OBJECT

signals:
    void closed( const QString );

protected:
    void closeEvent( QCloseEvent * closeEvent )
    {
        emit closed( this->objectName() );
        closeEvent->accept();
    }
};
#endif

Note that for my problem I need a way to identify which subwindow user is closing, and objectName does the work for me.

A: You can create QWidget based class like:
class CloseWatcher : public QWidget
{
  Q_OBJECT

private:
  QString m_name;

signals:
  void disposing( QString name );

public
  CloseWatcher( QWidget * p )
    : QWidget( p )
    , m_name( p->objectName() )
  {}

  ~CloseWatcher()
  {
    emit disposing( m_name );
  }
};

and just use it:
// anywhere in code
QMdiSubWindow * wnd = getSomeWnd();
CloseWatcher * watcher = new CloseWatcher( wnd );

connect( watcher, SIGNAL( disposing( QString ) ), reveiver, SLOT( onDispose( QString ) ) );


Q: Unexpected parameter: id While writing the Python code for Twitter extraction in Jupyter notebook I am getting the error as Unexpected parameter: id. Can anyone please help me with it?

A: You need to provide the relevant code and/or full traceback for anyone to know what exactly is going on, but that's likely just a warning that you're passing an id parameter to an API method that doesn't expect it.
Tweepy v4.0.0 changed many API methods to no longer accept id parameters.

A: You need to use screen_name instead of id parameter.


Q: Chef Configuration setting I am trying to configure for copying  files  through chef.However,we have a requirement to push  configuration only  for couple of servers. Is there any parameter or setting for that ?
Elaborated a little more .....
Our standard deployment through Chef requires that the latest build be deployed to all servers.
However, individual developers also submit experimental builds that are deployed to 1-2 servers per developer only as opposed to the entire stack.
Our objectives are as follows:
1.  Be able to deploy experimental builds through Chef to a specified set of servers.
2.  Prevent experimental builds from being deployed to the servers that already host experimental builds – perhaps have the Chef server mark those servers as unavailable somehow(?)
3.  Be able to deploy full builds to either all servers or only those servers that are not used for experimental builds at the moment.
I’m sure it’s a fairly common scenario and would  like to know if there is an elegant/effective/dynamic  way to keep Chef server informed of where each build/experiment should be  deployed to.

A: If you use a cloud provider, the answer is to use Packer to create an image for each build, and then deploy images as needed.  If you use bare metal, then you can easily use either normal attributes or roles to setup the versions.  I'd suggest attributes.

*

*Set node['myapp']['test_version'] = 'some version' on the nodes to be updated

*In your recipe, check the value of that attribute.  If set, then install that version, otherwise install your master version.

To remove a node from the experiment, you can just reset that attribute to nil on the node.  The next chef run will result in that node going back to the master version.
If you want a way to install the master version on ALL nodes, including ones that are in experiments, you can either write a second recipe that ignores the setting, or you can add an override attribute like node['myapp']['force_master'] or such.  You could then set that on the environment to override the experiments.  But you'd need to remember to reset it at a later time.


Q: ModelForm and Model validation playing together I have the following Model :
class Advertisement(models.Model):

    slug = models.UUIDField(default=uuid4, blank=True, editable=False)

    advertiser = models.ForeignKey(Advertiser)
    position = models.SmallIntegerField(choices=POSITION_CHOICES)
    share_type = models.CharField(max_length=80)
    country = CountryField(countries=MyCountries, default='DE')
    postal_code = models.CharField(max_length=8, null=True, blank=True)

    date_from = models.DateField()
    date_to = models.DateField()

Based on Advertiser, position, type country and postal code this stores adverisements with range date_from and date_to.
advertiser, position, share_type, country and postal_code

are coming from the request and are fetched in
class CreateAdvertisment(LoginRequiredMixin, CreateView):

    # Some usefull stuff

    def dispatch(self, request, *args, **kwargs):

        self.advertiser = Advertiser.objects.get(user=self.request.user)
        self.share_type = self.kwargs.get('share_type', None)
        self.country = self.kwargs.get('country', None)
        self.postal_code = self.kwargs.get('postal_code', None)
        self.position = int(self.kwargs.get('position', None))
        self.position_verbose = verbose_position(self.position)

        ret = super(CreateAdvertisment, self).dispatch(request, *args, **kwargs)

        return ret

Without any validation for checking date_from, date_to. I can simply do
def form_valid(self, form):

    form.instance.advertiser = self.advertiser
    form.instance.share_type = self.share_type
    form.instance.country = self.country
    form.instance.postal_code = self.postal_code
    form.instance.position = self.position

    ret = super(CreateAdvertisment, self).form_valid(form)
    return ret

and I am done. Unfortunatly I cannot do this as I do have to check for valid time Frames for the Advertisment to avoid Double Bookings of the same time. I do this in the model with the following :
def clean(self):
    ret = super(Advertisement, self).clean()
    print ("country [%s] position [%s] share_type [%s] postal_code [%s]" % (self.country,
           self.position, self.share_type, self.postal_code))
    if self.between_conflict():
        raise ValidationError("Blocks between timeframe")
    elif self.end_conflict():
        raise ValidationError("End occupied")
    elif self.during_conflict():
        raise ValidationError("Time Frame complete occupied")
    elif self.start_conflict():
        raise ValidationError("Start Occupied")
    return ret

def start_conflict(self):

    start_conflict = Advertisement.objects.filter(country=self.country,
                                                  position=self.position,
                                                  share_type=self.share_type,
                                                  postal_code=self.postal_code).filter(
        date_from__range=(self.date_from, self.date_to))

    return start_conflict

This works well and I filter out any Conflict for the given period. Problem is that I do not have the instance variables as they are set in view.form_valid() and model.clean() is called by the form validation process.
I do have an chicken egg problem here. I am thinking about setting the requests parameters to the form kwargs in
def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()
    kwargs['advertiser'] = self.advertiser
    kwargs['position'] = self.position
    ....

and then putting them into the form instance in form.init()
def __init__(self, *args, **kwargs):
    advertiser = kwargs.pop('advertiser')
    position = kwargs.pop('position')
    # .. and so on
    super(AdvertismentCreateForm, self).__init__(*args, **kwargs)

For some reasons I do not think this is very pythonic. Does anybody have a better idea? I will post my solution.

A: I think that overriding get_form_kwargs is ok. If all the kwargs are instance attributes, then I would update the instance in the get_form_kwargs method. Then you shouldn't have to override the form's __init__, or update the instance's attributes in the form_valid method.
def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()
    if kwargs['instance'] is None:
        kwargs['instance'] = Advertisement()
    kwargs['instance'].advertiser = self.advertiser
    ...
    return kwargs

In the model's clean method, you can now access self.advertiser.

A: alasdairs proposal works fine I have the following now :
def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()

    if kwargs['instance'] is None:
        kwargs['instance'] = Advertisement()

    kwargs['instance'].advertiser = self.advertiser
    kwargs['instance'].share_type = self.share_type
    kwargs['instance'].country = self.country
    kwargs['instance'].postal_code = self.postal_code
    kwargs['instance'].position = self.position

    return kwargs

def form_valid(self, form):

    ret = super(CreateAdvertisment, self).form_valid(form)
    return ret

Of course there is no need to override form_valid anymore. I have just included here in order to display that we do not set the instance fields anymore as this is done in get_form_kwargs() already


Q: Redirect specific IP using htaccess I am trying to figure out if it is possible to do a 301 redirect for a particular IP address (in this case brute force password bot).  I want to send this guy to a project honeypot link rather than just banning the IP.  Something like the following?
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^xxx\.xxx\.xxx\.xxx
Redirect 301 ^/adminlogin/$ http://www.example.com/honeypotlink.php

A: The RewriteCond has to be followed by a RewriteRule. And your RewriteCond has an ! which is a negation. It should look more like this:
RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^xxx\.xxx\.xxx\.xxx
RewriteRule ^/adminlogin/$ http://www.example.com/honeypotlink.php [R=301,L]


Q: Driven oscillation with negligeable damping problem The problem : A car's suspension system rolling on the pavement can be viewed as a driven oscillation system. The car's natural frequency is $100$ $ rad/s $. It has also a mass of $800$ $kg$. We know that when the car is going such that the driving frequency is equal to $150$ $rad/s$, the amplitude of the vibrations is equal to $0.1$ $mm$. Damping can be neglected.
The question : What is the amplitude of the vibrations at resonance?
The answer is  $0.8$ $mm$ but I have no idea how to get there. If I use the formula for the amplitude of a driven oscillation $A = \frac{F_0/m}{\sqrt{(\omega_0^2 - \omega^2)^2 + (\frac{\omega \beta}{m}})^2}$, the natural frequency $\omega_0$ and driving frequency $\omega$ are equal at resonance and $\beta$ approches 0 and so I divide by zero...

A: Your corrected data probably makes more sense. You can calculate the force for 0.1 mm and 150 rad/s: 1000 N. The answer (0.8mm) corresponds to a force that is 8 times larger, i.e. 8000N, which is roughly the weight of the car. I am not sure the force can grow above that, even at resonance and without damping, as the car will probably lose contact with the road.


Q: How to check if items repeat in pandas column with multiple lists? I have this pandas df:
                                               Name
0                      [MARCIO, HAMILTON, FERREIRA]
1                    [NILSON, MARTINIANO, FERREIRA]
2                         [WALTER, MALIENI, JUNIOR]
3                  [CARLOS, ALBERTO, ARAUJO, NETTO]

If one of the items appear in another list I want to tag it. In this case the output should be like this:
                                               Name       Check
0                      [MARCIO, HAMILTON, FERREIRA]        True
1                    [NILSON, MARTINIANO, FERREIRA]        True
2                         [WALTER, MALIENI, JUNIOR]       False
3                  [CARLOS, ALBERTO, ARAUJO, NETTO]       False

Is there a pythonic way to do that or I will need to apply a set of for sentences? (for i in object: for k in list...). Since my file is quite large I'm afraid it will be very heavy.

A: We can do explode then do transform with nunqiue find the index duplicated with same value
s=df.Name.explode().reset_index()
v=(s.groupby('Name')['index'].transform('nunique')>1).groupby(s['index']).any()
Out[465]:
index
0     True
1     True
2    False
3    False
Name: index, dtype: bool
df['Check']=v

A: Similar to Ben's answer but using duplicated instead of groupby().nunique():
s = series.explode().reset_index()
df['Check'] = (s.drop_duplicates()
                .duplicated('Name', keep=False)
                .groupby(s['index']).any()
              )

Output:
                               Name  Check
0      [MARCIO, HAMILTON, FERREIRA]   True
1    [NILSON, MARTINIANO, FERREIRA]   True
2         [WALTER, MALIENI, JUNIOR]  False
3  [CARLOS, ALBERTO, ARAUJO, NETTO]  False


Q: how to reload the current page when twitter bootstrap modal's cancel button clicked? Is it possible to reload/refresh the current page when clicking on the twitter bootstarp modal popup window?

A: Assuming you're using the standard Bootstrap modal markup, you could handle the modal 'hidden' event like this..
$('#myModal').on('hidden', function () {
  document.location.reload();
})

Demo: http://www.bootply.com/62174

A: For BS3 it Should be something like
$('body').on('hidden.bs.modal', '.modal', function () {
   document.location.reload();
});


Q: How to logging all queries after execution in codeigniter? I have try to insert all codeigniter queries after execute the mysql query. Unable to insert all query anyone can help me resolve this issue

A: Try this for logging specific query in log file:
Create a logFile.log file then write your query in this file.
$sql_query = "insert into tablename (column1, column2) values(value1, value2)";
file_put_contents('logFile.log', json_encode($sql_query , true), FILE_APPEND);

Hope this will help you a bit.
Or you can follow the duplication question here: logging all queries after execution in codeigniter


Q: No JWT created from JSON Web Tokens using Spring Security I'm using spring security and JSON Web Tokens for email verification.
I noticed that there is no JWT created when I register a new employee.
I use email for login, not username. I don't know if that problem with the Userdetalis interface.
when I'm trying to login into Postman, I get this error.

My code :
EmployeeController :
@CrossOrigin(origins = {"http://localhost:3000"})
@Tag(name = "Employee", description = "Employee API")
@RestController
@RequestMapping(EmployeeController.BASE_URL)
public class EmployeeController {
    public static final String BASE_URL = "/api/v1/employees";
    private final EmployeeService employeeService;
    private final ConfirmationTokenService confirmationTokenService;

@Autowired
AuthenticationManager authenticationManager;

@Autowired
RoleRepository roleRepository;

@Autowired
PasswordEncoder encoder;

@Autowired
JwtUtils jwtUtils;

public EmployeeController(EmployeeService employeeService, ConfirmationTokenService confirmationTokenService) {
    this.employeeService = employeeService;
    this.confirmationTokenService = confirmationTokenService;
}

@GetMapping
@ResponseStatus(HttpStatus.OK)
public EmployeeListDTO getEmployeeList() {
    return employeeService.getAllEmployees();
}

@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody EmployeeDTO loginRequest) {
    System.out.println("Hei");

    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));

    System.out.println("Hei2");

    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);
    System.out.println(jwt);

    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
    List<String> roles = userDetails.getAuthorities().stream()
            .map(item -> item.getAuthority())
            .collect(Collectors.toList());

    return ResponseEntity.ok(new JwtResponse(jwt,
            userDetails.getId(),
            userDetails.getEmail(),
            roles));
}

@GetMapping({"/{id}"})
@ResponseStatus(HttpStatus.OK)
public EmployeeDTO getEmployeeById(@PathVariable Long id) {
    return employeeService.getEmployeeById(id);
}

@PostMapping("/signup")
@ResponseStatus(HttpStatus.CREATED)
public EmployeeDTO createNewEmployee(@RequestBody EmployeeDTO employeeDTO) {
    return employeeService.createNewEmployee(employeeDTO);
}

@PutMapping({"/{id}"})
@ResponseStatus(HttpStatus.OK)
public EmployeeDTO updateEmployee(@PathVariable Long id, @RequestBody EmployeeDTO employeeDTO){
    return employeeService.saveEmployeeByDTO(id, employeeDTO);
}

@DeleteMapping({"/{id}"})
@ResponseStatus(HttpStatus.OK)
public void deleteEmployee(@PathVariable Long id){
    employeeService.deleteEmployeeDTO(id);
}

}
> package com.tietoevry.bookorabackend.security.jwt;
>
> import com.tietoevry.bookorabackend.services.UserDetailsServiceImpl;
> import org.slf4j.Logger; import org.slf4j.LoggerFactory; import
> org.springframework.beans.factory.annotation.Autowired; import
> org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
> import
> org.springframework.security.core.context.SecurityContextHolder;
> import org.springframework.security.core.userdetails.UserDetails;
> import
> org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
> import org.springframework.util.StringUtils; import
> org.springframework.web.filter.OncePerRequestFilter;
>
> import javax.servlet.FilterChain; import
> javax.servlet.ServletException; import
> javax.servlet.http.HttpServletRequest; import
> javax.servlet.http.HttpServletResponse; import java.io.IOException;
>
>
> public class AuthTokenFilter extends OncePerRequestFilter {

@Autowired
private JwtUtils jwtUtils;

@Autowired
private UserDetailsServiceImpl userDetailsService;

private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)

        throws ServletException, IOException {

    try {
        String jwt = parseJwt(request);

        if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
            String username = jwtUtils.getUserNameFromJwtToken(jwt);

            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            System.out.println("No JWT yet");
        }
    } catch (Exception e) {
        logger.error("Cannot set user authentication: {}", e);
    }

    filterChain.doFilter(request, response);
}

private String parseJwt(HttpServletRequest request) {
    String headerAuth = request.getHeader("Authorization");

    if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer")) {
        return headerAuth.substring(7, headerAuth.length());
    }

    return null;
} }

import java.util.List;

public class JwtResponse {
    private String token;
    private String type = "Bearer";
    private Long id;
    private String email;
    private List<String> roles;

    public JwtResponse(String accessToken, Long id, String email, List<String> roles) {
        this.token = accessToken;
        this.id = id;
        this.email = email;
        this.roles = roles;
    }

    public String getAccessToken() {
        return token;
    }

    public void setAccessToken(String accessToken) {
        this.token = accessToken;
    }

    public String getTokenType() {
        return type;
    }

    public void setTokenType(String tokenType) {
        this.type = tokenType;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<String> getRoles() {
        return roles;
    }
}

//generate Token
@Component
public class JwtUtils {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    @Value("${bezkoder.app.jwtSecret}")
    private String jwtSecret;

    @Value("${bezkoder.app.jwtExpirationMs}")
    private int jwtExpirationMs;

    public String generateJwtToken(Authentication authentication) {

        UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();

        return Jwts.builder()
                .setSubject((userPrincipal.getEmail()))
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    public String getUserNameFromJwtToken(String token) {
        return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
    }

    public boolean validateJwtToken(String authToken) {
        try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
            return true;
        } catch (SignatureException e) {
            logger.error("Invalid JWT signature: {}", e.getMessage());
        } catch (MalformedJwtException e) {
            logger.error("Invalid JWT token: {}", e.getMessage());
        } catch (ExpiredJwtException e) {
            logger.error("JWT token is expired: {}", e.getMessage());
        } catch (UnsupportedJwtException e) {
            logger.error("JWT token is unsupported: {}", e.getMessage());
        } catch (IllegalArgumentException e) {
            logger.error("JWT claims string is empty: {}", e.getMessage());
        }

        return false;
    }
}

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        // securedEnabled = true,
        // jsr250Enabled = true,
        prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/h2-console/**").permitAll();

        http.csrf().disable();
        http.headers().frameOptions().disable();
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/api/v1/employees/**").permitAll()
                .antMatchers("/api/test/**").permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

and in intellj I get :


Q: when a quasinilpotent is nilpotent In the case of an infinite-dimensional complex banach space X,
under what conditions can a quasinilpotent operator T\in B(X) be determined to be nilpotent?


Q: Loading array file with other numbering format I am trying to load a file in which the numbers are in the following form:
  0.0000000D+00 -0.1145210D-16  0.1262408D-16
  0.1000000D+00 -0.4697286D-06  0.1055963D-06
  0.2000000D+00 -0.1877806D-05  0.4220493D-06
  0.3000000D+00 -0.4220824D-05  0.9482985D-06

I am trying the numpy.loadtext function, but apparently it's not in its recognized numbering format as I'm getting the following error:
ValueError: could not convert string to float: b'0.0000000D+00'
Any idea?
Thanks

A: You can use a converter with numpy.loadtxt that converts the value to a parsable float. In this case we trivially replace Dwith E;
import numpy as np

numconv = lambda x : str.replace(x.decode('utf-8'), 'D', 'E')
np.loadtxt('test.txt', converters={0:numconv, 1:numconv, 2:numconv}, dtype='double')

# array([[  0.00000000e+00,  -1.14521000e-17,   1.26240800e-17],
#        [  1.00000000e-01,  -4.69728600e-07,   1.05596300e-07],
#        [  2.00000000e-01,  -1.87780600e-06,   4.22049300e-07],
#        [  3.00000000e-01,  -4.22082400e-06,   9.48298500e-07]])


Q: If - Else on Pirates Un-resolved Could you someone show me how to create an if - else statements with two sets of R.drawable.images pirates?
I've tried, but I got an error code saying pirates is un-resolved.
Bitmap icon = BitmapFactory.decodeResource(getResources(),pirates[i]);
This is what I have in the preferences:

xmlns:android="http://schemas.android.com/apk/res/android"
android:key="wallpaper_settings"
android:title="@string/wallpaper_settings" >  <!--must be the same callout from
values->strings-->

<ListPreference
    android:key="speed"
    android:title="@string/speed_title"
    android:entries="@array/timelist"
    android:entryValues="@array/actualtime"
    android:summary="@string/speed_summary" >
</ListPreference>

  <CheckBoxPreference
    android:key="checkbox"
    android:title="Nature Pictures"
    android:summary="For Nature Pictures Option"
    android:defaultValue="false" />

Main Activity:
     public class main_activity extends WallpaperService {

     public static final String SHARED_PREFS_NAME="settings_menu";

   @Override
  public void onCreate() {
    super.onCreate();
}

   @Override
public void onDestroy() {
    super.onDestroy();
}

   @Override
public Engine onCreateEngine() {
    return new wallpaperEngine();
}

class wallpaperEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener{

    private final Handler mhandler = new Handler();

    //defines variables

    private final Runnable drawrunnable = new Runnable()
    {
        public void run() {
            drawFrame();
        }
    };
    private int i = 0;
    private boolean mVisible;
    private SharedPreferences mPrefs;
    private boolean mcheckbox = false;
    public int mSpeed = 10;

         int[] pirates = {
            R.drawable.image_1,
            R.drawable.image_2,
            R.drawable.image_3,
            R.drawable.image_4

    };

       //For Nature Pictures
         int[] pirates = {
            R.drawable.image_a1,
            R.drawable.image_a2,
            R.drawable.image_a3,
            R.drawable.image_a4

    };

  .......
  ......

   Bitmap icon = BitmapFactory.decodeResource(getResources(),pirates[i]);

        i++;

        if (i == 14) {
            i = 0;

Thank you very much

A: Seems like you are trying to create two arrays of int, holding different set of images. But you are using the same variable name pirates. I would suggest you define two different variables int[] pirates and int[] piratesNatural and then switch between those two arrays when you need one and the other.
Bitmap icon;
if(natural)
  icon = BitmapFactory.decodeResource(getResources(),piratesNatural[i]);
else
  icon = BitmapFactory.decodeResource(getResources(),pirates[i]);

A: you doing animation?
int frame=0;
int frametime=24;

Bitmap icon1 BitmapFactory.decodeResource(getResources(), R.drawable.image_1,);
Bitmap icon2 BitmapFactory.decodeResource(getResources(), R.drawable.image_2,);
Bitmap icon3 BitmapFactory.decodeResource(getResources(), R.drawable.image_3,);
Bitmap icon4 BitmapFactory.decodeResource(getResources(), R.drawable.image_4,);

//in update
frametime--;
if(frametime<=0){
frame++;
frametime=24;
}
if(frame>3){
frame=0;
}

//in onDraw

switch(frame){

case 0:
canvas.drawBitmap(icon1,x,y,null);
break;
case 1:
canvas.drawBitmap(icon2,x,y,null);
break;
case 2:
canvas.drawBitmap(icon3,x,y,null);
break;
case 3:
canvas.drawBitmap(icon4,x,y,null);
break;
default:
canvas.drawBitmap(icon1,x,y,null);
break;}


Q: Method Swizzling - How to assure methods are swizzled before they are called I'm method swizzling a third party applications creation of NSMenuItems with SIMBL, but 50/50 of the time the menu-items are created before my method swizzling is initialized.
What is a clean way to make sure my swizzling always comes first? I guess I could swizzle applicationDidFinishLaunching: and continue my swizzling there. But I'm afraid I'm going to run in to the same error there, where applicationDidFinishLaunching will be called before my actual swizzle is in place.
John

A: You'd want the swizzle to happen as soon as the libraries are loaded.  You can do that via +initialize, +load, or a constructor function.
@bbum's answer to this question has a bit more information, along with one of his blog posts on the caveats of using these special class methods.
(And I'm purposely not questioning the wisdom of what you're doing ;) )

A: You can use constructor functions like this:
__attribute__((constructor)) static void do_the_swizzles()
{
    // Do all your swizzling here.
}

From GCC documentation:

The constructor attribute causes the function to be called
  automatically before execution enters main().

Note: Although this is originally from GCC, it also works in LLVM.


Q: Multiple Timers counting down are not working properly | SwiftUI I have an auction app running. I need several timers counting down in the UI, these timers have different end Dates, and the end seconds can be updated when SignalR receives a new value.
I have implemented running timers in my current solution, but sometimes and suddenly, they start having delays between counting down a second.
The timers are inside these components called LotCard within the ForEach
ForEach($lotService.getLotListDto) { $item in
    LotCard(lotCardViewModel: $item.lotCardViewModel,
            lotDto: item,
            fnStartLotConnection: { value in lotService.initSingleLotCard(uID: value)})

}

This is the necessary code within these components:
//MARK: Timer
@State var timeRemaining = 9999
let timerLotCard = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

HStack(spacing: 3){
    Image(systemName: "stopwatch")
    if(lotCardViewModel.showTimer){
        Text("\(timeRemaining.toTimeString())")
            .font(.subheadline)
            .onReceive(timerLotCard){ _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1

                    if(self.timeRemaining <= 0){
                        self.timerLotCard.upstream.connect().cancel()
                    }
                }else{
                    self.timerLotCard.upstream.connect().cancel()
                }
            }
    }
}

I guess it's a problem with threads and using many timers simultaneously with the same Instance but I am not an experienced developer using SwiftUI/Swift.
This is how my interface looks like:

Thanks for your help.

A: I came up with this approach thanks to the comments in my question.
I hope it works and suits your problems.
First, I created a Published Timer, meaning every component will run the same Timer.
import Foundation
import Combine

class UIService : ObservableObject {

    static let shared = UIService()

    //MARK: Timer to be used for any interested party
    @Published var generalTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

}

Finally, I am using that Timer wherever I want to use it. In this case, I use it in every LotCard component.
struct LotCard: View {

//MARK: Observable Class
@EnvironmentObject var UISettings: UIService

//MARK: Time for the counting down
@State var timeRemaining = 9999

var body: some View {
    HStack{

        Text(timeRemaining.toTimeString())
            .onReceive(UISettings.generalTimer){ _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                }
            }
    }
}
}


Q: Override a method and make it behave static I have an existing framework, which I can't change, it reads 2 properties

*

*ClassA=somepackage.AnImplementationOfInterfaceA

*ClassB=somepackage.AnImplementationOfInterfaceB
Which calls public methodA on a new ClassA(), public methodB on a new ClassB() in that order
I want to make a class C which implements interfaces A, B and provides hooks methodC1, methodC2 for class D to override (methodA & methodB contain a lot of boilerplate and complex to implement - methodC1 & methodC2 would encapsulate the business logic) . Then my properties would be

*

*ClassA=somepackage.classD

*ClassB=somepackage.classD
The problem is that the person who implements class D might be tempted to write something like:
class D extends class C
{
   private int foo; //must be non-static due to multi-threaded new Class D() calls going on
   int methodC1() {this.foo = read number from network}
   methodC2(int x) {y = this.foo;} //methodC2 is always called after methodC1

   //methodA, methodB implementation inherited from C
}

But this wouldn't work as expected since the framework would actually create a new object of class D each time before invoking methodA, methodB and thus can't rely on using the "this" reference.
Defining methodC1, methodC2 as static wouldn't work either because then the call to methodC1 is tied to the implementation in C, not the overriden one in D.
When really what ought to be written is:
class D extends class C
{
   int methodC1() {return number from network;}
   methodC2(int x) {y = x}  //here y is using the return value of methodC1

   //methodA, methodB implementation inherited from C
}

I would also like only methodC1, methodC2 to be overridable i.e. programmers working on D can't mess with methodA
The ideal design would have

*

*the properties refer to one class only

*methodC1, methodC2 to be in that class

Summary of challenges

*

*no this in methodC1, methodC2

*can't make methodC1, methodC2 static

*properies takes only a instantiable class

How do I design this framework? Is this even solvable? You can change the signature of methodC1, methodC2.

A: Composition! Establish an interface that you are okay with people extending.
This class would contain the logic for MethodD1 and D2, and for everything else just a simple call to the other methods in your currently existing class. People won't be able to modify the calls to change the underlying logic.

A: The static methods can not be overridden!
If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding has important implications.


Q: Set counting javascript program to two decimal places Please see this code:

What it does is take a piece of html like this:

10

And it will count by 10 every second.  How do I make the following code work:

10.02

Basically, I want to have this program count by up to two decimal places.

A: Use parseFloat instead of parseInt. And toFixed(2) for limiting two decimal points.
setInterval(function() {
    var counters = document.getElementsByClassName("count");

    for (var i = 0; i < counters.length; i++) {
        counters[i].innerHTML = parseFloat(counters[i].innerHTML).toFixed(2) + parseFloat(counters[i].dataset.increment).toFixed(2);
    }
}, 1000);

A: JSFIDDLE
 You need to use parseFloat to covert string to float.
  and toFixed on float to truncate extra decimal. toFixed return string you need to use parseFloat again so that it became float addition not string concatenation.

var counters = document.getElementsByClassName("count");

    setInterval(function () {
        for(var i = 0 ; i < counters.length ; i++) {

            counters[i].innerHTML = (parseFloat(parseFloat(counters[i].innerHTML).toFixed(2)) + parseFloat(parseFloat(counters[i].dataset.increment).toFixed(2))).toFixed(2);
        }
    }, 1000);

10

10.02

A: Try wrapping addition within String() , .innerHTML , .dataset within Number() , Number() within expression () chained to .toFixed(2) ; set counters[i].innerHTML to result derived within String((Number(/* innerHTML */) + Number(/* dataset *)).toFixed(2))

var interval = setInterval(function() {
  var counters = document.getElementsByClassName("count");

  for (var i = 0; i < counters.length; i++) {
    counters[i].innerHTML = String((Number(counters[i].innerHTML)
                            + Number(counters[i].dataset.increment)).toFixed(2));

  }
}, 1000);

10.02


Q: How to get the fingers count in the InkCanvas? I am trying to zoom the InkCanvas when the finger counts greater than 1, but I can't get the finger count in the InkCanvas.Anyone Please help me how to get the finger count in InkCanvas.

A: I don't have touch screen to test but maybe this will work:
    int count;

    private void InkCanvas_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
    {
        count++;
    }

    private void InkCanvas_PointerExited(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
    {
        count--;
    }

If it doesn't help. Try to use PinterPressed and PointerReleased. You may grab point Id from event args and handle them.


Q: React Native init Project which ruby
outputs -> /Users/User/.rbenv/shims/ruby
ruby -v
outputs -> ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21]
which bundle
outputs -> /Users/User/.rbenv/shims/bundle
bundle -v
outputs -> Bundler version 2.1.4
but the problem is that npx react-native init MyProject
outputs -> ✖ Installing Bundler
error Bundler::RubyVersionMismatch: Your Ruby version is 2.6.10, but your Gemfile specified 2.7.5

A: What's likely happening is that npx react-native init MyProject is sub-shelling into Bash where you do not have rbenv configured. When it tries to run ruby from Bash it looks in $PATH and finds the default macOS version of Ruby -- 2.6.10 -- and errors out.
This is discussed thoroughly in the react-native repo where there are many solutions, but what it boils down to is react-native init is not finding the right version of Ruby, for whatever reason. You can bypass that by completing the failing part of the init process yourself with:
cd MyProject
bundle install
cd ios && bundle exec pod install

The longer version of the solution is to configure rbenv for Bash as well, but this isn't necessary as you can likely use just the workaround above:
echo 'eval "$(~/.rbenv/bin/rbenv init - bash)"' >> ~/.bash_profile


Q: Assign  to specific characters within CSS style I am new to CSS and web development in general. Hopefully there is a way to accomplish what I am trying to do. What I am trying to do is simple to explain, but I need to give some background info first, sorry for the length of the post.
I have created a webpage that is in the Tibetan language. Tibetan does not have spaces between words, it only has a character called a "tsheg" (་ - U+0F0B) that is used to separate every syllable. It also has a mark called a "shey" (། - U+0F0D) that comes at the end of phrases and clauses and sentences. Although sometimes it is doubled, after a shey is generally a space before the next line of text. When typing in Tibetan this space is represented not as a normal space (U+0020) but instead U+00A0, however when it comes to browsers and HTML/coding in general these two seem to behave the same.
In any Tibetan writing, the ideal aesthetic is for full justification. Traditionally there would be slight spaces placed between the tsheg marks and the shey marks to achieve a perfectly flush left and right alignment. (The exception would be the last line of a text, or a paragraph in contemporary formatting, does not need to be justified). It is acceptable for lines to break mid-word or mid-sentence, but never mid syllable. So the last character on any line is going to be either a tsheg or a shey. It is also not acceptable to start a line with a shey. In the last few years this has been easy to achieve for desktop publishing using MS Word, using "Thai Justification." However that option is not available even in other Office products, never mind outside of the Office environment. Other work-arounds have been to add invisible width characters after every tsheg and shey, allowing for wrapping at any point.
Now comes the question and difficulty. I am using distributed justification, and that seems to be the best option. It does not break syllables up, which is important. But it only wants to break at those spaces after shey marks, and it breaks elsewhere when there is a long string of text without a space, but if there is a space then it breaks there, sometimes stretch one or two syllables across an entire line, which is obviously not ideal.
Now, when coding the HTML of the text I can use the same work-around that is used for desktop publishing pre "Thai justification," I can add a <wbr> after every single tsheg, and this will not be visible to the end user and should allow cleaner breaking. However, there are two problems with this. But inserting that many <wbr> characters I am essentially doubling, or close to doubling, my character count, which can make the page take twice as long to load, even if half of those characters are invisible. However, more important is that it disrupts search functionality. Although you may see the word that has the syllables "AB" for instance, if you tried searching for AB you wouldn't find it, because the HTML sees "AB". And being able to search is kind of critical. Enough so that an ugly formatting is preferable to losing the ability to search and to be indexed properly. Obviously, since I need the site to be responsive and I do not know what size screens will be used I cannot have forced line breaks, either, another trick used when publishing.
So, finally, my question. Is there a way I can define a style or function or some sort of element that automatically associates a certain character--in my case the tsheg character--as having a <wbr> command after it without actually needing to input that command into my HTML? So when the text is justified it treats every tsheg as a <wbr>? I have a class .Tibetan in my stylesheet that defines the font and the justification and so forth, is there some way I can add some code there that achieves what I am looking for?
The one other thing I tried was replacing all of the spaces with   which gave a beautiful justified appearance but it also caused the browser to disregard the tsheg marks entirely and it allowed for the cutting in half of syllables.
If you want to see an example of what I am talking about you can visit this page of my site: http://publishing.simplebuddhistmonk.net/index.php/downloads/critical-editions/ and next to the word "English" click the Tibetan characters and that will bring up a paragraph of prose, or you can look here: http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/essence-of-dispelling-errors-tib/ (though the formatting on that latter page is less egregious than the former, at least on my screen).
EDIT It looks like the solution this person used might be able to be adapted for my use: Dynamically add <wbr> tag before punctuation however I do not actually understand what I would need to add, and where, to make that work for me. Anyone think that might apply to this scenario? And if so, what code would I add where?
NEW EDIT So, I think the problem might be with the search function that comes from my WordPRess theme. I used my workaround as mentioned above, adding the tag  after every tsheg, on this page: http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/essence-of-dispelling-errors-tib/ and as you can see, it displays perfectly. But if you search for any phrase from that page using the search function that is up in my header, it will not find it. If you do a Ctrl+F and search on the page, though it will find it. Even if you copy the text from the page and paste it into the search box it still does not find it. Copy the text into a word editor doesn't reveal any hidden or invisible characters. However, if you search for a term from this page http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/beautiful-garland-ten-innermost-jewels-tib/ which I have not added the  tags to, you will see that it finds it no problem.
So, that leads me to believe the error is in the search function. Any experience with this? Because search is important but I can quite possibly find alternative earch widgets to replace the one that comes with the theme. What is most important though is if you search for a line of text on Google it needs to be found. My site has not been indexed fully by any search engine so I cannot yet confirm if this does or does not affect them.
So.... At this point I wil take any advice I can get. Any advice regarding the original question (is there a way to tell the style guide "if your are displaying X then treat it like X" ) or any idea about this issue with the search functionality, and how the  tag may or may not affect search, both from within the site and also from search engines.


Q: Trying to add an alert to detection model "ssd_mobilenet_v2", throws an error Using "ssd_mobilenet_v2_fpn_keras" i am trying to add an alert system
The detection model is loaded in to the below function
 def detect_fn(image):
    image, shapes = detection_model.preprocess(image)
    prediction_dict = detection_model.predict(image, shapes)
    detections = detection_model.postprocess(prediction_dict, shapes)
    return detections

The image is converted to a tensor
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)

The the tensor is fead to the detection model
detections = detect_fn(input_tensor)
The output of the detection model is a dictionary, with the following keys:
dict_keys(['detection_boxes', 'detection_scores', 'detection_classes', 'raw_detection_boxes', 'raw_detection_scores', 'detection_multiclass_scores', 'detection_anchor_indices', 'num_detections'])

detections[detection_classes], gives the following output ie 0 is ClassA, 1 is ClassB
[0 1 1 0 0 1 0 0 1 0 1 1 0 0 1 0 1 1 0 1 0 1 1 0 0 1 0 0 1 0 1 0 0 1 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 1 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 1 0 1]

detections['detection_scores'] gives the score for each box detected (a few shown below)
[0.988446 0.7998712 0.1579772 0.13801616 0.13227147 0.12731305 0.09515342 0.09203091 0.09191579 0.08860824 0.08313078 0.07684237

I am trying to Print("Attention needed"), if detection classB ie 1 is observed
for key in detections['detection_classes']:
if key==1:
    print('Alert')

When i try to do that i get an error
`ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How do make it work?
I want the code to print "Attention needed" is Class =1 or A and detection_scores >= 14
Code Explained, a bit further

links for the complete code are below :

*

*Tutorial on YouTube

*GitHub sources repository

A: As mentioned in the error message, you should use .any(). like:
if (key == 1).any():
  print('Alert')

As key == 1 will be an array with [False, True, True, False, ...]
You might also want to detect ones that exceeds certain score, say 0.7:
for key, score in zip(
  detections['detection_classes'],
  detections['detection_scores']):
  if score > 0.7 and key == 1:
    print('Alert')
    break


Q: Android - How to open an associated file to an application from main activity
Possible Duplicate:
Android intent filter: associate app with file extension

I've associated an XML file with extensions .x to my application. I would like to click on .x file, my associated application should start, and I would like to open the file, passed in some way, from inside onCreate() of activity. There is a way to do this ?
Thanks in advance.

A: Add this intent filter in your manifest to your activity
<intent-filter>
 <action android:name="android.intent.action.VIEW" />
 <category android:name="android.intent.category.DEFAULT" />
 <data android:mimeType="application/xml" />
 <data android:pathPattern=".*\\.x" />
</intent-filter>

on your onCreate files are passed on as:
Uri uri = this.getIntent().getData();
if(uri!=null){
 Log.v(getClass().getSimpleName(), "importing uri:"+uri.toString());
}


Q: как сделать темную тему в sublime text 3? я лазил в настройках sublime text и он решил как то переключится с темной темы на светлую,глаза режет,помогите(не шрифт,а фон)
и я искал насчет этого и на стеке, и в гугле,ничего не нашел если че


Q: Crop raster plot in r I am trying to read a hospital floor plan map (a higher resolution version than the one here in .PNG form) http://www.alfredicu.org.au/assets/Miscellaneous-Downloads/newicufloorplan.pdf
So that I can then place points onto it representing OHS incidents. My problem is that I need to be able to cut down the map so that I am only looking at a subset of the area so the x-axis (which represents mm of the A2 page) is 10:300 and the y axis is 10:380.
I have read in the array and plot but do not know how to subset this plot. If you can advise how to change the dimensions of the plot so that I can 'zoom in' on the relevant part of the map that would be greatly appreciated.
#Read PNG into raster array
r <- readPNG("ICU-map.png")

#Set up the plot area as A2 with mm as the dimensions
icu <-plot(0, type='n', main="ICU", xlab="x", ylab="y", xlim=c(0, 594), ylim=c(0, 420))

#Get the plot information so the image will fill the plot box, and draw it
lim <- par()
rasterImage(r, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
grid()
lines(c(1, 1.2, 1.4, 1.6, 1.8, 2.0), c(1, 1.3, 1.7, 1.6, 1.7, 1.0),     type="b", lwd=5, col="white")


Q: Broken Adobe Air Installers, Do I Need a Certificate This is a multi-part question, but all to resolve the same issue.
I'm trying to publish a project I've been working on but get intermittent problems with .air files that are generated.
I always get the following warning when publishing my project:
"There was an error connecting to the timestamp server. You may not have a connection to the network, or the server itself may have a problem.
If you choose to disable timestamping, the AIR application will fail to install when the digital signature expires."
So I have had no choice but to disable timestamping.
I do have a working internet connection, but I'm working from my company network, could this be an issue, and if so, is there a work around (Opening a specific port or something)? Also, how long do the above-mentioned digital signatures have before expiring?
Also, I am creating my own certificate. Do I need to purchase some kind of certificate/license to install my application on another computer? I've done some research, but the information is hard to find, and what I do find is kind of cryptic at best. Currently, I only need to deploy to machines within the company.
Sometimes the installer works fine and without issue (on the computer that generated it at least), other times I get "The application could not be installed because the installer file is damaged. Try obtaining a new installer file from the application author." as an error message. Other times I get an error stating that certificates or signatures or something do not match (Sorry, I couldn't replicate the error so am paraphrasing).I have yet to get an install to work on a separate machine.
I've tried using Air 2.5 and 2.6.
Also, as an extra while I'm here: Can I embed AIR applications to be run INSIDE a browser like a traditional Flash project?

A: About certificate, you can use a self signed certificate, the only difference is that the users will see a big warning when installing that the publisher is unknown.
About timestamping, I only know that the adt tool that packages the app is attempting to connect to a timestamping server, I am not sure what protocol is used, you will need to check this and unblock this.
If the installer is not timestamped then the issue is that after the certificate expires you can continue using this installer and need to do a new one with a certificate that is not expired.
As an example, if I use a certificate that expires tomorrow today and the installer is not timestamped then it will not work after tomorrow but if it was timestamped then it will continue to work after the certificate expired because it was created  before the expiration
I seen the installer is damaged erors a few times on our customers machine, usually on Windows, sometimes uninstalling and reinstalling AIR helped but not always, the problem is that the error message is not detailled enough to fix this, in rare cases I had to create .exe installers for those customers but I suggest to try the installers on a few machines first and use the native .exe installers if anything else is not working.


Q: Javascript variable inside qoute (double inside single qoute) I am trying to use a variable in nodejs. It giving me errors whatever I try.
How can I use a variable in this string
 let txt= 'some unknown texts'
 "MATCH (productName) AGAINST ('txt')"

Here I need to replace txt.
Note: I cannot use ``
Edit
Here is the query I am using
await Product.query().whereRaw("MATCH (productName) AGAINST ('txt')").select('productName')

Thank you.

A: In ES6 you need to do the following to use a var in string
`MATCH (productName) AGAINST ${txt}`

IF you cannot use ``
Just go for the old way with string concatanation,
"MATCH (productName) AGAINST '" +txt + "'"


Q: How to make past date unselectable in fullcalendar? Problem is, how to disable selectable on PAST DATES in fullcalendar's month/week view.
I want to user not allowed to click/select the on past dates.

Here is some googled code snippet I am trying to implement on event rendering:
selectable: true,
selectHelper: false,
select: function(start, end, allDay) {
        var appdate = jQuery.datepicker.formatDate('<?php echo $DPFormat; ?>', new Date(start));
        jQuery('#appdate').val(appdate);
        jQuery('#AppFirstModal').show();
    },
    eventRender: function(event, element, view)
    {
        var view = 'month' ;
       if(event.start.getMonth() !== view.start.getMonth()) { return false; }
    },

But its not working though.
I tried bellow CSS too and this help me to hide past date text only, but selectable is still working on pastdate box.
.fc-other-month .fc-day-number {
     display:none;
}

I am really stuck with this problem. Please someone help me out.
Thanks...

A: The old answers to this question are ok...
However, the official documentation suggests a new, more concise solution:
First set the day you want to be the lower bound
 var today = new Date().toISOString().slice(0,10);

Then include the range using validRange. Simply omit the end date.
 validRange: {
    start: today
 }

A: In FullCalendar v3.0, there is the property selectAllow:
selectAllow: function(info) {
    if (info.start.isBefore(moment()))
        return false;
    return true;
}

A: In fullcalendar 3.9, you might prefer the validRange function parameter :
validRange: function(nowDate){
    return {start: nowDate} //to prevent anterior dates
},

Drawback: this also hides events before that datetime

A: You can combine:
-hide text by CSS as mentioned in question
-disable PREV button on current month
-check date on dayClick/eventDrop etc:
dayClick: function(date, allDay, jsEvent, view) {
    var now = new Date();
    if (date.setHours(0,0,0,0) < now.setHours(0,0,0,0)){
        alert('test');
    }
    else{
         //do something
    }
}

A: I have done this in my fullcalendar and it's working perfectly.
you can add this code in your select function.
 select: function(start, end, allDay) {
    var check = $.fullCalendar.formatDate(start,'yyyy-MM-dd');
    var today = $.fullCalendar.formatDate(new Date(),'yyyy-MM-dd');
    if(check < today)
    {
        // Previous Day. show message if you want otherwise do nothing.
        // So it will be unselectable
    }
    else
    {
        // Its a right date
        // Do something
    }
  },

I hope it will help you.

A: I like this approach:
select: function(start, end) {
    if(start.isBefore(moment())) {
        $('#calendar').fullCalendar('unselect');
        return false;
    }
}

It will essentially disable selection on times before "now".
Unselect method

A: This is what I am currently using
Also added the .add() function so the user cannot add an event at the same hour
select: function(start, end, jsEvent, view) {
               if(end.isBefore(moment().add(1,'hour').format())) {
               $('#calendar').fullCalendar('unselect');
               return false;
             }

A: You can use this:
var start_date= $.fullCalendar.formatDate(start,'YYYY-MM-DD');

var today_date = moment().format('YYYY-MM-DD');

if(check < today)
{
    alert("Back date event not allowed ");
    $('#calendar').fullCalendar('unselect');
    return false
}

A: Thanks to this answer, I've found the solution below:
$('#full-calendar').fullCalendar({
    selectable: true,
    selectConstraint: {
        start: $.fullCalendar.moment().subtract(1, 'days'),
        end: $.fullCalendar.moment().startOf('month').add(1, 'month')
    }
});

A: I have tried this approach, works well.
$('#calendar').fullCalendar({
   defaultView: 'month',
   selectable: true,
   selectAllow: function(select) {
      return moment().diff(select.start, 'days') <= 0
   }
})

Enjoy!

A: below is the solution i'm using now:
        select: function(start, end, jsEvent, view) {
            if (moment().diff(start, 'days') > 0) {
                $('#calendar').fullCalendar('unselect');
                // or display some sort of alert
                return false;
            }

A: No need for a long program, just try this.
checkout.setMinSelectableDate(Calendar.getInstance().getTime());
Calendar.getInstance().getTime()

Gives us the current date.

A: I have been using validRange option.
validRange: {
  start: Date.now(),
  end: Date.now() + (7776000) // sets end dynamically to 90 days after now (86400*90)
}

A: In Fullcalendar i achieved it by dayClick event. I thought it is the simple way to do it.
Here is my code..
 dayClick: function (date, cell) {
              var current_date = moment().format('YYYY-MM-DD')
              // date.format() returns selected date from fullcalendar
              if(current_date <= date.format()) {
                //your code
              }
            }

Hope it helps past and future dates will be unselectable..

A: if any one of answer is not work for you please try this i hope its work for you.
 select: function(start, end, allDay) {

              var check = formatDate(start.startStr);
              var today = formatDate(new Date());

              if(check < today)
              {
                 console.log('past');
              }
              else
              {
                console.log('future');
              }
}

and also create function for date format as below
function formatDate(date) {
      var d = new Date(date),
          month = '' + (d.getMonth() + 1),
          day = '' + d.getDate(),
          year = d.getFullYear();

      if (month.length < 2) month = '0' + month;
      if (day.length < 2) day = '0' + day;

      return [year, month, day].join('-');
  }

i have tried all above question but not work for me
you can try this if any other answer work for you.
thanks

A: just add this if statement

 select(info) {
      if (moment(info.start).format() > moment().format()) {
       //your code here
      } else {
        toast.error("Please select valid date");
      }
    },

A: For FullCalendar React (Disable past day completely):
selectAllow={c => (moment().diff(c.start, 'hours') <= 0)}


Q: How to catch when user close a console application via “X” button I have to write data in memory to in a file to close my console application. How can i detect console closing event ?

A: When the terminal is closed, your program will get a SIGHUP, which kill it by default. add a signal handler to handle the SIGHUP do whatever you want. and if you program write to the console after it has been close, you may also get SIGPIPE, handle it properly


Q: How will you design memory for 1GB memory with each page size being 4K I was asked this question in a job interview recently. I answered that I wud use a hash data structure to begin with designing the system. But couldn't answer that well. I think the interviewer was looking for answers like how will i design a page table for this.
I would like to know how to answer this question. Like for each page size being 4K how many pages would be needed for 1Gb? Also, what other considerations I should keep in my mind to design it efficiently.

A: This question makes sense in the context of CPUs where the TLBs are
"manually" loaded and there are no predetermined page table
structures, like some models of MIPS, ARM, PowerPC.
So, some rough thoughts:
1G is 2^30 bytes or 2^18 = 256K 4K pages
Say, 4-byte entry per page, that's 1M for a single level page
table. Fast, but a bit wasteful on memory.
What can we do to reduce memory and still make it reasonably fast.
We need 18 bits per page frame number, cannot squeeze it in 2 bytes,
but can use 3-bytes per PTE, with 6 bits to spare to encode - access
rights, presence, COW, etc. That's 768K.
Instead of the whole page frame number we can keep only 16-bits of it,
with the remaining two determined by a 4-entry upper level page table
with a format like this:

*

*2 MSB of the physical page number

*21 bits for second level page table (30 bit address, aligned on 512K
boundary)

*spare bits

No place for per-page bits though, so lets move a few more address
bits to the upper level table to obtain
Second level page table entry (4K 2-byte entries = 8K)

*

*4 bits for random flags

*12 LSB of the page frame address

First level page table entry format (64 4-byte entries = 256 bytes):

*

*6 MSB of the page frame address

*17 bits for second level page table address (30-bit address aligned
at 8K)

*spare bits

A: Looks like an open end question to me. The main idea may be to know how much you know about memory and how much deep you can think of the cases to handle. Some of them could be:

*

*Pagination - How many pages you want to keep in memory for a process and how many on disk to optimize paging.

*Page Tables

*Security

*Others, if you can relate and think Of


Q: How to override span-columns at different breakpoint in SUSY I think I must be missing something fundamental with how susy works, and the documentation has too few examples to understand how this works.
I want different layouts at different breakpoints.  I can make it that far, but I want my elements to span different number of columns depending on what breakpoint is triggered.  So if I have a general stylesheet for mobile ('mobile-first') like:
 .wrapper{
        .element1{
            @include span-columns(4);
        }

        .element2{
            @include span-columns(2 omega);
        }
}

But once the width changes to my 'tablet' and it changes to an 8 column layout, I want to be able to change this to:
     @include at-breakpoint($tablet-break $tablet-layout){
         .wrapper{
        @include set-container-width;
            .element1{
                @include span-columns(5);
            }

            .element2{
                @include span-columns(3 omega);
            }
    }
}

It seems like this not only doesn't 'overwrite' the mobile settings, but it appears, upon firebug inspection, that the elements do not match up with my new tablet columns.  I think it is still using a 6 column layout.  Adding @include set-container-width doesn't seem to fix the problem; however, if I comment out the mobile layout it works.  So it's almost as if these include statements don't overwrite, so I think I'm not understanding how susy works.  Here's an example of firebug showing the element not matching the layout:

(Also I'm not sure of any SUSY best practices (except for don't nest more than 4 deep).  I could define all my sass with nested @at-breakpoint statements for all my changes, or I could define my default (mobile) css and then create a separate sass block all nested within at-breakpoint.  I don't know if this is causing a problem.)
UPDATE
It appears, that if I include at-breakpoint includes after the original (mobile) declaration, it seems to work.  Though it does seem to require code repetition:
        .element1{
        @include span-columns(2 omega);
        text-indent: -1em;
        text-align: center;
        @include at-breakpoint($tablet-break $tablet-layout){
            @include span-columns(3 omega);
            text-indent: 0;
            text-align: left;
        }
        @include at-breakpoint($desktop-break $desktop-layout){
            @include span-columns(3 omega);
            text-indent: 0;
            text-align: left;
        }
    }


Q: fftw shift zero-frequency to image center I am struggling on the result of FFTW applied on image.
I can do the Fourier transform and inverse Fourier transform on image, I am sure the two functions are working. Now I am trying to analyze the result of Fourier transform and try to apply a filter on it, etc.
Currently I am confusing on the FT result. As I know the the zero-frequency should be on the top-left corner. I should shift it to the image center if I want to check frequency friendly. There are at least two way I have tested. one method is described on the FFTW FAQ webpage, all the pixels in the image were multiplied by (-1)^(i + j) before Fourier transform, where i, and j are the pixel's index.
image was multiplied by (-1)^(i+j), then its magnitude is

but actually ,it should be like this (which I did in imagej) Fourier transform in imagej:

I also tried using my code to switch them after calculating its magnitude, but got the similar wrong result.
void ftShift2D(double * d, int w, int h)
{

    int nw = w/2;
    int nh = h/2;
    if ( w%2 != 0) {nw++;}
    if ( h%2 != 0) {nh++;}

        printf("%d, %d\n", nw, nh);
        for (int i = 0; i < nh ; i++)
        {
                for(int j = 0; j < nw; j++)
                {
                        int t1 = i * w + j;
                        int t2 = (i + nh + 1) * w + j + nw;
                        swapXY<double>(d[t1], d[t2]);
                }

                for (int k = nw; k < w; k++)
                {
                        int t1 = i  * w + k;
                        int t2 = (i + nh　＋ 1 ) * w + k - nw;
                        swapXY<double>(d[t1], d[t2]);
                }
        }
}

I understood the layout of FT result in FFTW, as is described in their website.
I also checked the output, this layout can be confirmed, only top half have data, the rest is 0. therefore, it seems explain why the two methods used above cannot work. I am trying to design new method to shift the zero-frequency to image center. could you give me a better way to do it?
I insist on this, aim to use the filter, it will be easier to understand. if the zero-frequency did not be shifted to center, could you guys give me another suggestion that I can, for example, apply a high Gaussian filter on it in frequency domain.
thanks a lot.
the input image is:

The FT and IFT code are
    void Imgr2c(double * d, fftw_complex * df, int w, int h)
{
        fftw_plan p = fftw_plan_dft_r2c_2d(h, w, d, df, FFTW_ESTIMATE);
        fftw_execute(p);

        fftw_destroy_plan(p);

}

void Imgc2r(fftw_complex * in, double * ftReverse, int w, int h)
{
        fftw_plan p = fftw_plan_dft_c2r_2d(h, w, in, ftReverse, FFTW_ESTIMATE);
        fftw_execute(p);

        int l = w * h;
        for (int i = 0; i < l; i++)
        {
                ftReverse[i] /= l;
        }

        fftw_destroy_plan(p);
}

[Edit by Spektre]
This is how it should more or less look like:

A: You may want to check out how I did it here:
https://github.com/kvahed/codeare/blob/master/src/matrix/ft/DFT.hpp
The functions doing the job are at the bottom. If there are any issues, feel free to contact me personally.

A: I found what is my problem! I did not understand the output layout of DFT in FFTW deeply. After some tests, I found the the dimension in width should w/2 +　1, and the dimension in height did not changed. the code to do FT, IFT, and shift the origin have no problem. what I need to do is changing the dimension when try to access it.
magnitude after DFT
magnitude after shifting the origin
Cheers,
Yaowang