Playing Counter Strike 1.6 on Wirless LAN

Question: We have a LAN made up of multiple computers connected via Wifi and we use to play CS on this LAN, there is a proxy server (SQUID) between us and internet.
We are unable to play CS multiplayer any more now. Have they blocked the ports with proxy server? If so what can we do? Search for open ports https://superuser.com/questions/421030/find-ports-not-blocked-by-proxy-server ?
Answer: You can play on Wireless LAN even if ports are blocked .
If "they" have blocked ports then you cannot play online or on Steam.
Use local IP of Local Server(on LAN) to connect.
Answer: SQUID can't interfere in your LAN gaming there must be some WiFi connection problem, you must check the  connection properly and If you are still having problem then there must be some game error. For this solution you must download Steam as a solution. You can download it from here.


How to define title text and subtitle text in VBA for PowerPoint 2010

Question: I have the following code (VBA for PowerPoint 2010) to create a slide at the end of a presentation and insert title text:
longSlideCount = ActivePresentation.Slides.Count

With ActivePresentation.Slides
    Set slideObject = .Add(longSlideCount + 1, ppLayoutTitleOnly)
End With

slideObject.Shapes.Title.TextFrame.TextRange.Text = "This is the Main Title Text"

I would like to know how to:

Insert 'Subtitle' text (smaller font, on a new line immediately below the main title text)
Change the font and size of the main title text and the subtitle text

Thanks in advance!!!
Answer: You can do it in several ways depending on how you want the slide to look. The easiest may be to use the ppLayoutTitle instead of ppLayoutTitleOnly. It has two textframes instead of one, so you could update the text by using something like the following:
slideObject.Shapes(2).TextFrame.TextRange.Text = "This is the subtitle."

If you need a more custom layout, you could add a new textbox by using adding the following at the bottom of your code example:
Set oShp = slideObject.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 200, 300)
oShp.TextFrame.TextRange.Text = "Row #2: subtitle."

The numeric parameters to the AddTextbox function set the position and size of the new textbox.
You can update the font the same way for both of the above examples (just change the reference to the textbox):
oShp.TextFrame.TextRange.Font.Bold = msoTrue


How to avoid Pycharm inspection error in multiline SQL literals

Question: I recently discovered that PyCharm complains about " expected, unexpected end of file" when I write a SQL Query, that spans multiple lines (using parantheses):

It looks like it detects that this is a SQL statement, but only parses the first line.
Any idea how to correctly write this without disabling inspections or writing very long lines ?
Comment: I'd suggest opening a ticket in PyCharm's [issue tracker](http://youtrack.jetbrains.com/issues/PY). The IDE should know that those literals are joined by the compiler and act accordingly.
Comment: Seems to be reported already http://youtrack.jetbrains.com/issue/PY-10983
Answer: you need a python multi line string
string = """select * from table
              where x=1
              limit 10"""

if you want to avoid the new lines you can do this:
x = "select * from t " \
    "where x = 1 " \
    "limit 1"

doc

with sql dialect on:
Comment: The second one would of course be a valid multi-line string if enclosed by parantheses.
I previously used the first method you mentioned (triple-quotes), but i dislike that this would also include additional newlines and whitespace.
Comment: @powo theres another way that you can avoid new lines, see the updated answer
Comment: if i use the \ one doesn't give me an error. i'm on pycharm 3.0 but i used strings with \ on 2.7 as well and it was fine. what version do you have.
Comment: @powo attached an image it looks ok for me.
Comment: I'm using 3.0 ... in your example the statement in the first line is valid SQL, try for example to put the "where" up to the first line.
Comment: ok i added it and it gave me a warning that i dont have sql dialect, i selected sql dialect and it highlights the where, it gives an error but i dont get the same error as you
Comment: using \ it gives me an error that my sql is wrong when i move the where up, but i dont get `expected, unexpected end of file`
Comment: sorry for bad crop, hover over where says its not expected there, hover over sql says no data source defined. the where becomes red (correctly since its wrong)


Remote Switch wiring for a gas log fire place

Question: I have a remote switch outside my gas log fireplace to turn the fireplace  burner on and off. I've been having problems with the standard thermostat wiring that was supplied with my remote switch. The wiring is melting. Should I be using a "heat resistant" wiring to run from my wall switch thru my fire place to control the ignition of the burners?  The answer seem obviously "yes" but do you have a recommended type of wire for this application?
Again the wall switch simply "jumpers" two terminals on my gas valve, thus allowing the gas valve to open and thus the burners to ignite off the pilot. I was thinking of going to my local electrical supply house for some "heat/temperature" resistant low voltage capable wiring and trying that. Also should I run that wiring under the burner pan or behind the burner pan and under the sand/stones provided for aesthetics for the fire place?  .
Comment: The wires shouldn't be close enough to the flame to melt.
Answer: I thought any time you came within 18" of a stove or insert (fireplace type) you were supposed to use "glass" or high temp appliance wire (but this may be an Oregon thing).  It is about a buck a foot here in the pacific northwest. You only need a small gauge to control your gas valve; 18 would probably do just fine but it may be easier to find 14awg.  The wire I am talking about has a glass braid on the outside and some type of plastic inner insulation, this type of wire can handle the heat unlike standard AWM/NM/THHN. Plumbing and electric stores usually have it; I'm not sure about the big box stores.
Comment: Wow not sure what happened there , but when I typed Romex maybe I should have said NM , as that is in 99% of all house wiring nothing else I had changed a few things , it doubled everything don't have a better answer ? Humm


What is the best way to display time related to a video?

Question: What is the best way to display a start time in a video that is greater than the one hour mark? It looks good as 34:57, but not so much as 01:08:54. Should I instead just write 68:54 or is it not intuitive to go over the hour mark?
Also, to clarify--there is a list of chapter titles and the related times. For example
Chapter 1 0:00
Chapter 2 3:44
Chapter 3 55:38
Chapter 4 1:05:08
Comment: Where are these videos hosted?
Comment: On our own servers for now. AWS.
Answer: It depends on how your video renders times longer than an hour.
If your video rendering site is something like youtube and renders times longer than one hour as something like 1:05:36 then I would recommend going with the hour:mm:sec approach as users can quickly see the start time and get the particular point by hovering over the video bar as shown in the example given below

However, if it for some reason renders time as 68:34 then you might be better off going the route of showing the total sum of minutes as users will use that as the reference point to define the start point and will scan across the video play bar to determine where to click.
However be careful not to mix the both time options i.e. showing time as 68:43 when your video shows the time in hh:mm:ss format and vice versa as that would put a mental load on your user to translate the times from one format to another.
Comment: This, imo, is the correct answer, as you want consistency.
Answer: In addition to Mervin Johnsingh's method you could consider writing out the time using time units:
Chapter 1: 1 hr 45 min
Chapter 2: 23 min
Chapter 3: 2 hr 01 min
Chapter 4: 3 hr 56 min
Benefits:

You have the units clearly written so user don't have to guess if 02:34 is 2 hour 34 minutes or 2 minutes and 34 seconds
Users don't need to make calculations in their head to convert 68:54 to 1 hour 8 minutes and 54 seconds.

Hulu.com

Amazon Prime


Easy way to change axis limits in subplots

Question: How do I change the limits on the axes in matplotlib subplots?
For example if I have
x = np.linspace(0,4*np.pi,100)

plt.figure(1)
plt.subplot(121)
plt.plot(x,np.sin(x))
plt.xlim([0,4*np.pi])
plt.ylim([-1,1])
plt.axis('equal')

plt.subplot(122)
plt.plot(x,np.cos(x))
plt.xlim([0,4*np.pi])
plt.ylim([-1,1])
plt.axis('equal')

I tried using plt.xlim and plt.ylim but these didn't work.
Answer: What you have works if you just remove the plt.axis('equal') lines.
EDIT: To answer your comment considering scales, this is the code that should work:
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,4*np.pi,100)

plt.figure(1)
plt.subplot(121)
plt.plot(x,np.sin(x))
plt.xlim([0,4*np.pi])
plt.ylim([-1,1])
plt.gca().set_aspect('equal', adjustable='box')

plt.subplot(122)
plt.plot(x,np.cos(x))
plt.xlim([0,4*np.pi])
plt.ylim([-2*np.pi,2*np.pi])
plt.gca().set_aspect('equal', adjustable='box')

Solution courtesy of How to equalize the scales of x-axis and y-axis in Python matplotlib?
Comment: Is there a way to set the limits on both axes and to have the scales on both axes equal at the same time?


linux cat: No such file or directory

Question: I have a peculiar problem in Linux2.4, C and using gcc.
There is a small program to retrieve information from a file using cat & grep cmd.
#define tmpFile "/tmp/cli_tmp_file.txt"
#define MAX_CMD 50

void getRange()
{
        char cmd[MAX_CMD+1];

        // remove the temp file first
        snprintf(cmd, MAX_CMD, "rm -f %s", tmpFile);
        system(cmd);
        // create temp file
        snprintf(cmd, MAX_CMD, "touch %s",tmpFile);
        system(cmd);
        // execute the command
        snprintf(cmd, MAX_CMD, "echo \"Range:Max val 500\" > %s",tmpFile);
        system(cmd);
        // dump out the temp file so user could see
        snprintf(cmd, MAX_CMD, "cat %s|grep \"Range\"", tmpFile);
        system(cmd);
        // remove the temp file
        snprintf(cmd, MAX_CMD, "rm -f %s", tmpFile);
        system(cmd);
}

when i execute this code, i get output as
cat: /tmp/cli_tmp_file.txt: No such file or directory
However, the file is created in the tmp folder with the contents
# pwd
/tmp
# ls -l
-rw-r--r--    1 root     root           68 Oct 10 12:54 cli_tmp_file.txt

#more /tmp/cli_tmp_file.txt
Range:Max val 500

On manual execution of the same cmd, it displays the intended output
# cat /tmp/cli_tmp_file.txt|grep Range
Range:Max val 500

Any help would be appreciated.
Thanks in advance.
Comment: You should check the return value of `system` to see if the commands succeed. Also, try printing the `cmd` buffer after each `snprintf` to see if it contains the intended command.
Comment: Is there a reason you aren't just writing this as a shell script? It would be a bit simpler...
Comment: remove the file, try again.
Comment: Avoid using `system` with `rm`; consider calling [remove(3)](http://man7.org/linux/man-pages/man3/remove.3.html) function. And to create a file, just `fopen` it for writing and `fclose` it just after. Don't forget to test against failure of every function.
Answer: It's a (managed, but ignored) buffer overrun, the echo command is more than 50 characters. The command is truncated by snprintf() but you run it anyway. Check return values!
Comment: it's doesn't seem to be more in his example. but definitely dangerous.
Comment: Thanks, adding sleep of 1 sec after touch resolved this issue.

linux cat: No such file or directory


Open twitter/instagram page on app

Question: I am looking for a method to open a twitter/instagram link on the native app.
For example :
This link
https://mobile.twitter.com/become90
Should be opened in Twitter app.
And this link:
http://instagram.com/become90#
Should be opened in available instagram app
Answer: INSTAGRAM
Instagram://user?username=insertyourusername
TWITTER
Twitter://user?screen_name=insertyourusername

Open twitter/instagram page on app


Using statement on RSA class causes 401 / object being disposed prematurely?

Question: I'm currently running into an issue with decrypting jwts using a public key. When I use the RSA class with a using declaration (I did try the older syntax too just to be safe), I get 401s every time. Removing the using keyword fixes the problem, but I'm sure that's poor practice as RSA is an IDisposable. Any ideas on how to make this work the proper way?
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
{
    var publicKey = tokenSettings.PublicKey.ToByteArray();

    // removing "using" makes it work
    using var rsa = RSA.Create();
    rsa.ImportSubjectPublicKeyInfo(publicKey, out _);
    var key = new RsaSecurityKey(rsa);

    opt.TokenValidationParameters = new TokenValidationParameters
    {
        IssuerSigningKey = key,
        ValidAudience = tokenSettings.TargetAud,
        ValidIssuers = new[] { tokenSettings.Issuer },
        RequireSignedTokens = true,
        RequireExpirationTime = true,
        ValidateLifetime = true,
        ValidateAudience = true,
        ValidateIssuer = true,
        ClockSkew = TimeSpan.Zero,
    };
});

I did find a self-answer here RSA Disposed Object Error - every other test, but isn't omitting "using" an incorrect use of IDisposable objects?
I'll also note this is not the same as the caching issue in which it returns 200 once and 401 after that. The code currently returns 401 every time.
Answer: using var rsa = RSA.Create();
rsa.ImportSubjectPublicKeyInfo(publicKey, out _);
var key = new RsaSecurityKey(rsa.exportParameters(false));

Source: https://www.reddit.com/r/dotnet/comments/ihno7b/-/g31aze8
Comment: That is still wrong, you're using the rsa object after it has been disposed.
Comment: This is actually the correct answer.  When you create the `RsaSecurityKey` object using RSA parameters, it will retain a copy of the parameters in lieu of an `RSA` object, leaving you free to dispose your `rsa` instance (and avoiding storing any disposable objects in the `RsaSecurityKey`).  https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/9938b0fcf08dfcc82da82081e526a8f69b6a3440/src/Microsoft.IdentityModel.Tokens/RsaSecurityKey.cs
Answer: How about setting the using-clause in curly brackets, so it doesn't get disposed after the next instruction ?
services.AddAuthentication(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
{
    System.ReadOnlySpan<byte> publicKey = tokenSettings.PublicKey.ToByteArray();

    // removing "using" makes it work
    using (System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create())
    {
        rsa.ImportSubjectPublicKeyInfo(publicKey, out _);
        Microsoft.IdentityModel.Tokens.RsaSecurityKey key = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsa);

        opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            IssuerSigningKey = key,
            ValidAudience = "tokenSettings.TargetAud",
            ValidIssuers = new[] { "tokenSettings.Issuer" },
            RequireSignedTokens = true,
            RequireExpirationTime = true,
            ValidateLifetime = true,
            ValidateAudience = true,
            ValidateIssuer = true,
            ClockSkew = System.TimeSpan.Zero,
        };
    }
});

But most-likely, this is because RsaSecurityKey has the instance of the RSA-Provider contained, and uses that to encrypt and decrypt the JWT-Bearer. Which is a bit of a problem if the RSA instance is disposed ...
//
// Zusammenfassung:
//     Represents a Rsa security key.
public class RsaSecurityKey : AsymmetricSecurityKey
{
    public RsaSecurityKey(RSAParameters rsaParameters);
    public RsaSecurityKey(RSA rsa);

    [Obsolete("HasPrivateKey method is deprecated, please use PrivateKeyStatus.")]
    public override bool HasPrivateKey { get; }
    public override PrivateKeyStatus PrivateKeyStatus { get; }

    public RSA Rsa { get; }
}

Just remove the using, the RSA-provider probably has application-lifetime scope. However that works with MultiThreading...
Comment: The using line is actually syntactic sugar added in c#8, although I did try the vanilla syntax just to be safe. I'll haven't done a lot of study on multithreading in dotnet, so I'll have to research that, thanks!
Answer: You Dispose objects when you're sure you no longer require them.
Here, you may be issuing tokens at any time that your application is running. So Dispose-ing of the object whilst still configuring the application is wrong.
I'd suggest, here, that you don't Dispose the object. The only time you actually know that it's no longer required is when the application is shutting down - but in that case, you know that everything in the process is about to be destroyed - there's no point delaying that just to do a bit of tidying that nobody will benefit from.


Why does Dirac's delta distribution have an infinite energy?

Question: My Fourier analysis materials define the energy of a function to be its $L^2$ norm over the real numbers. So far the reader has been lead to believe that if something does not belong to the $L^2$ space, then its energy is infinite. The reference gives a quick argument on why the Dirac's delta distribution does not belong to any $L^p$ space: Elements of $L^p$ spaces are functions in the classical sense and Dirac's delta is not a function. Hence $\delta \not\in L^p(\mathbb{R})$.
Later on the reference says casually that: *The signal $f \equiv \delta(b)$ (Dirac's delta at $b \in \mathbb{R}$) has an infinite energy.*At this point norm has not been defined for Schwartz's tempered distributions.
(Question:) Therefore, do you think that it is reasonable to assume that the reason for the comment that $\delta(b)$ has an infinite energy is that $\delta \not\in L^2(\mathbb{R})$, or is there a compelling argument why $\delta$ has an infinite norm in some sense?
Comment: One way I like to think about this, convolutions with a mollifier converges in a suitable topology to the delta distribution. The mollifier is an sequence of element of $L^1(\mathbb{R})$ of norm 1 but of unbounded norm in $L^2(\mathbb{R})$. One thinks of the delta distribution as the limit of the sequence, which has unbounded energy.
Answer: There is an unfortunate issue in that to calculate the $L^2$ norm of $\delta$ one would have to somehow integrate its square, but there is no (obvious) way to make sense of $\delta^2$. We can instead try to approximate $\delta$ by a sequence of, say, smooth functions, and then we'll find that no matter what sequence we choose the $L^2$ norm of the sequence diverges.
But here is maybe a cleaner and more conceptual argument: the Fourier transform of $\delta$ is the constant function $1$, and the Fourier transform ought to be unitary. So the $L^2$ norm of $\delta$ ought to be the $L^2$ norm of the constant function $1$, which clearly diverges.


Sin and Cos function incorrect in python

Question: I am trying to make a top down shooter in pygame. I when I added the code to make the player move in the direction they are facing. The player would move in weird directions. This is the code I am using:
        if pygame.key.get_pressed()[K_UP]:
            playerX = playerX - math.cos(playerFacing)
            playerY = playerY - math.sin(playerFacing)
        if pygame.key.get_pressed()[K_DOWN]:
            playerX = playerX + math.cos(playerFacing)
            playerY = playerY + math.sin(playerFacing)

I tried just typing in math.cos(90) and it equaled -0.299515394756 but my calculator is telling me it equals 0. I am probably just making a stupid mistake, but can anyone tell me what I am doing wrong.
Thanks
Xeno
Comment: The math functions expect radians rather than degrees. Use `math.radians` to convert degrees to radians.
Answer: math.sin, math.cos, etc. take angles in radians.
You can use math.radians to convert degrees to radians. So:
math.sin(math.radians(90)) == 0

And you could just fix it in the posted snippet like that:
if pygame.key.get_pressed()[K_UP]:
            playerX = playerX - math.cos(math.radians(playerFacing))
            playerY = playerY - math.sin(math.radians(playerFacing))
        if pygame.key.get_pressed()[K_DOWN]:
            playerX = playerX + math.cos(math.radians(playerFacing))
            playerY = playerY + math.sin(math.radians(playerFacing))

However I advise to just use radians everywhere.
Comment: Beat me to it. :). But add some code for the guy, got to earn those points...
Comment: multiply your angle by (pi/180)
Answer: math.sin() and math.cos() take angles in Radians and not in Degrees.
The same would be the case with numpy.sin() and numpy.cos()
>>> import math
>>> math.sin(90)
0.8939966636005579
>>> math.sin(1.57)
0.9999996829318346

You can see that math.sin(90) should be 1, but instead we get 0.89. But math.sin(1.57) gives us the correct answer, because 90 degrees is 1.57 in radians.
Here is a WEBSITE that explains you the conversion between radians<-->degrees.


JSON at line 1 column 3

Question: Here's the command, formatted what I thoughtwas correctly...
/tellraw @p ["",{"text":"This map is based off of 1.9 features such as detecting when you pick up items,","color":"green"},{"text":" [HINT] ","color":"dark_green","bold":true,"clickEvent":{"action":"run_command","value":"/tellraw @p {{\"text\":\"[HINT]\",\"color\":\"dark_blue\"},{\"text\":\"This pickaxe cannot break lit glowstone lamps.\",\"color\":\"light_purple\"}}"},"hoverEvent":{"action":"show_text","value":{"text":"","extra":[{"text":"Click For Hint"}]}}},{"text":"so you may need to think outside of the box for some levels. good Luck!","color":"green"}]

However it's giving me Invalid json: malformed JSON at line 1 column 3 Please help!
Comment: Possible duplicate of [How do I fix 'Invalid JSON' errors?](https://gaming.stackexchange.com/questions/304990/how-do-i-fix-invalid-json-errors)
Answer: Your clickEvent value starts with two curly brackets instead of a square followed by a curly.
However, when a player clicks a clickEvent via /tellraw, they are running the value as if they have manually typed it into the chat themselves. This means that the player is subject to chat limitations, such as requiring OP to run commands as well as a 100-character limit. The command being run exceeds that character limit, so it is trimmed (causing an error due to invalid format as a result of the trim).
The solution is to either use a shorter command or to use a different command altogether. For example, /scoreboard for OP'd players or /trigger for non-OP'd players while using an external mechanism to target players with a changed score.
Example using /scoreboard:
The /tellraw command becomes:
/tellraw @p ["",{"text":"This map is based off of 1.9 features such as detecting when you pick up items,","color":"green"},{"text":" [HINT] ","color":"dark_green","bold":true,"clickEvent":{"action":"run_command","value":"/scoreboard players set @a[c=1] OBJ 1"},"hoverEvent":{"action":"show_text","value":{"text":"","extra":[{"text":"Click For Hint"}]}}},{"text":"so you may need to think outside of the box for some levels. good Luck!","color":"green"}]

(clickEvent value specifically being):
/scoreboard players set @a[c=1] OBJ 1

External command sending a new /tellraw command to players with an OBJ score of 1:
/tellraw @a[score_OBJ_min=1] [{"text":"[HINT]","color":"dark_blue"},{"text":"This pickaxe cannot break lit glowstone lamps.","color":"light_purple"}]

Afterwards, set the player to have an OBJ score of 0 to prevent constant spam:
/scoreboard players set @a[score_OBJ_min=1] OBJ 0

JSON at line 1 column 3


Java object instantiation reading a file

Question: I am new to java. I have a class as following
import java.io.*;
class Lexer
{
     private static final int KEYWORDS = 11;
     private StreamTokenizer tokenizer;
     private String punctuation = ",:;.()";
     private Token[] punctuationTokens =
    {
    Token.COMMA, Token.COLON, Token.SEMICOLON, Token.PERIOD, Token.LEFT_PAREN, Token.RIGHT_PAREN
};

// Constructor that creates a lexical analyzer object given the source file

     public Lexer(String fileName) throws FileNotFoundException
    {
    tokenizer = new StreamTokenizer(new FileReader(fileName));
    tokenizer.ordinaryChar('.');
    tokenizer.quoteChar('"');
    }
}

I wrote the following code to instantiate an object:
Lexer test = new Lexer("C:\\Users\\Kris\\Desktop\\test.txt");

It returns me this error: Uncompilable source code - unreported exception java.io.FileNotFoundException. Could anyone let me know how to instantiate this object give the class and the file "test.txt"? I really appreciate your help.
Answer:
unreported exception java.io.FileNotFoundException.

You also need to Surround your Object creation call with try-catch as it may throw FileNotFoundException or add the throws in the method from where you are doing this.
 Lexer test = new Lexer("C:\\Users\\Kris\\Desktop\\test.txt");

Moreover go for the suggestion of Elliott Frisch for FilePath.

It may be possible your IDE not allowed to access files of C: drive due to User Access Control in Windows so better to run your IDE as an Administrator and Execute code again and please double check the path.
Comment: I retried the try-catch block. Now it's working. Thanks for all your help.
Comment: Thanks for you reply. I did wrote double slash. I did not format my question very well when I posted. Sorry about that. Even I specify the correct path, it still returned an error. The IDE suggested use try and catch block. After adding it, it still not working.
Comment: Great Glad TO Help You!! You should Accept One of the answers which you feel the one which solved the problem! Thanks.
Answer: If I understand your question, this
Lexer test = new Lexer("C:\Users\Kris\Desktop\test.txt");

Should be
Lexer test = new Lexer("C:/Users/Kris/Desktop/test.txt");

You could also use (the less readable, to me anyway)
Lexer test = new Lexer("C:\\Users\\Kris\\Desktop\\test.txt");

Because "\" starts an escape sequence,

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.
Comment: Thanks for you reply. I did wrote double slash. I did not format my question very well when I posted. Sorry about that. Even I specify the correct path, it still returned an error. The IDE suggested use try and catch block. After adding it, it still not working.
Comment: Are you sure you have a file "C:\Users\Kris\Desktop\test.txt"?


Showing that the sum of any 1-cycle and its opposite orientation is a 1-boundary

Question: Suppose that $\phi$ is a $1-cycle$ in a topological space $X$, and that $\phi^*:= \phi r$ is its opposite orientation where $r(t,1-t)=r(1-t,t)$. How should one show that there is a $2-chain$ whose boundary is $\phi+\phi^*$?
I know a proof for a more general fact (given any 1-simplex, the sum of it and its opposite orientation is a 1-boundary), but for this simple case is there any simple solution?
Comment: I didn't talk about homotopy, it's about homology
Comment: I think you need more information about  $X$ If you mean a loop  homotopic to its inverse, there may not be any, for example if $X= S^1$, there are no such loops.
Comment: Well, other than any loop homotopic to the constant loop.
Comment: @AleksandarMilivojevic: indeed.
Comment: If a cycle and its inverse are not homotopic, there isn't much you can say about them except that they are simplices: $\Delta_1\to X$. If they are homotopic, then you can use the homotopy $H$ to produce a simplex $\sigma:\Delta_2\to X.\ \sigma $ is obtained in the following way: take $I\times I$ and define a quotient map $q$ that collapses the square to a triangle. Then, $H$ factors through the quotient as $H=\sigma\circ q$, and then $\partial \sigma =\phi+\phi^*.$ It's a good exercise to fill in the details. So,bottom line; without more information, your question is ambiguous.
Answer: I am going to assume that you are asking about the singular chain complex of $X$, so in this answer a "simplex" means a "singular simplex in the topological space $X$".
Suppose at first that one knows how to find a solution for each 1-simplex $\sigma$, i.e. one knows how to find $\tau$ so that $\partial\tau = \sigma + \sigma^*$.
Consider any $1$-chain $\phi$ (not just a 1-cycle). We may write $\phi$ as a finite linear combination of 1-simplices,
$$\phi = \sum_i a_i \sigma_i
$$
where each $\sigma_i$ is a 1-simplex and each $a_i$ is a coefficient. Using your proof for a 1-simplex, it follows that for each $i$ there is a 2-chain $\tau_i$ such that $\partial \tau_i = \sigma_i + \sigma^*_i$. From this we obtain
$$\phi + \phi^* = \sum_i a_i \sigma_i + \sum_i a_i \sigma^*_i = \sum_i a_i (\sigma_i + \sigma^*_i) = \partial \left( \sum_i a_i \tau_i \right)
$$
and so $\sum_i a_i \tau_i$ is the required 2-chain.
So to complete the answer, I'll describe $\tau$ in the special case of a single 1-simplex $\sigma$ (which does not have to be a cycle). I'll follow the standard notations in many algebraic topology books, for example Hatcher's book. By definition, $\sigma$ is a continuous function $\sigma : \Delta^1 \to X$. Let $c : \Delta^2 \to \Delta^1$ be the affine map that maps the first and third vertices of $\Delta^2$ to the first vertex of $\Delta^1$, and maps the second vertex of $\Delta^2$ to the second vertex of $\Delta^1$. Let $d : \Delta^2 \to \Delta^1$ be the constant map which take $\Delta^2$ to the first vertex of $\Delta^1$. Then we just take $\tau = \sigma \circ c + \sigma \circ d$. A short computation shows that $\partial \tau = \sigma + \sigma^*$.
Comment: Thanks, However I wanted to know if there is an easy solution independent of the general fact that you used in the answer
Comment: Your use of the term "general" is unclear to me. The "1-simplex" statement is a special case of the "1-chain" statement, not a general case. Namely, it is the special case where the sum $\phi = \sum_i a_i \sigma_i$ has only one term, and the coefficient of that term is $a_i=1$.
Comment: I mean forget about chains and consider a simplex which is itself a cycle. Is there any routine solution in this case?
Comment: Okay, I thought that was the case you said you could do, but I added a description anyway.
Comment: Thank you, now it is exactly what I wanted


Using an angular expression in an ng-src with google maps embed api

Question: I am trying to load a map on each page that is specific to the values from an api, but I am getting this error message:
Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required.  See http://docs.angularjs.org/api/ng.$sce
http://errors.angularjs.org/1.2.15/$interpolate/noconcat?
Here is the markup:

and here is the controller:
.controller('EventsCtrl', function($scope, EventsFactory, $routeParams, $sce){
    EventsFactory.async().then(function(data){
        $scope.events = data.data;
        $scope.event= findEvent(eventId, $scope.events);
        console.log($scope.event);
        $scope.trustedHtml = $sce.trustAsHtml($scope.event);

Answer: Instead of using $sce.trustAsHtml(), try using $sce.trustAsResourceUrl(). Place your whole URL as parameter for $sce.trustAsResourceUrl(). The link below worked for me.
How to set an iframe src attribute from a variable in AngularJS


Starting a personal UX project?

Question: So, I am an aspiring UX Designer and I want to start building up my portfolio and getting some UX design experience. But, the problem is, I don't know where to start.
A lot of people have told me that I should just start making my own projects to get experience but I don't know where to begin.
Like, if I was making a website, I know how to design it. I can code HTML/CSS etc. But, I don't know the actual UX Design way of going about it. Like, creating wire-frames and prototypes or creating personas. I know about these things but I don't know how to actually incorporate them in my projects.
So, basically, what is the UX process for creating a personal project?
Comment: Perhaps you can consider looking at design challenges, such as the ones listed at TopCoder http://www.topcoder.com/active-challenges/design/ . At the very least, it will give you some real-world material to work with, even if you don't submit anything.
Comment: So is your question how to use a user centered design process ?
Answer: There are many paths you can take to follow a design process (I think most of the paths follow the basic structure I posted below, but each are nuanced in terms of what tools and techniques they implement for any given project). Choosing what to do will depend on what is most appropriate for your project.
Most importantly, I suggest you pick a topic area you are interested in for your project! (By that, I mean if you are already part of an organization that you love, maybe there is an opportunity to improve something in it... basically, start with something you enjoy, and work from there to find a problem to solve.)
Also, in your case, you should consider if there is a particular skill set in the design process you want to focus on (for example, do you want to focus on prototyping, research, UI design...?).
In general, I would outline the UX Design Process as:
Definition: Defining the problem that and understanding what it is you want to solve.
Research: Research should ideally be happening throughout the entire process. After the definition phase, you can do research to gather information that will help define the problem further and help generate ideas and potential solutions.
Ideation & Prototyping: Create possible solutions through sketches, prototyping, wireframing, etc. You should be iterating on your designs through this process to improve usability, UI, etc. Put your designs in front of your target users so you can figure out which areas of your design you may need to improve. You can do many types of user research on your designs.
Launch, Learn, Improve: Launch your solution, gather insights about it, and iterate!
There are a lot of resources available online to learn about each one of these areas. For example, what are different types of research methods? How do you run a usability tests? How do you create prototypes? etc... Good luck! :)
Comment: Perfect, thanks! This really helped give me some kind of direction because I was little lost haha. As for a skill, I want to focus more on UI and visual design part of it. I've done some graphic design stuff before and I really like "making things pretty" :)
Comment: That's awesome! I'm glad you found it helpful :)
Answer: Full disclosure, I do not have UX or design anything as my job title. I am a developer but I am very concerned with the user experience of what I produce. I try very hard to follow the ideas of the User Experience Team of One. I hope others might come forward with a more detailed or more complete answer for you.
www.Usability.gov has a very good infographic on this topic. I would suggest that you get started there.

But beyond just learning about the process you need to get some practical experience in. You could actually do this by volunteering and working with local charities, small businesses, and open source projects. Of course, you are going to have a lot more questions as you progress. Try and make some connections in your area. There should be professional associates associated with usability/UX in your area. It might be a users group like http://utah-ux.groups.adobe.com/ or a User Experience Professionals Association branch.
Comment: +1 for the book link. The step-by-step guide is a bit "waterfall"y but gives a nice overview. I guess that in an agile team the analyze, design and test/refine steps would be executed more in parallel for various users tasks.
Comment: yes, that would be a concentric loop that would connect back up to plan. Although all the components in plan and analyze phases would not necessarily be needed.

Starting a personal UX project?


Opening a URL in using JavaScript in self window

Question:

Open the JavaScript Window Example 1

This is an example that opens a URL in new window. How can I make it open in same window? Something similar to target=self.
Answer: simply use an Anchor for what it is for:
Open the link

no javascript needed ;)
however, the settings (menubar, scrollbars etc..) of the current window cannot be changed by javascript. THis is only possible in a new window on creation.
if you really need Javascript use window.location
 function openLink()
 {
     window.location.href = "http://www.javascript-coder.com";
 }

Answer: Just do this:

This will assign the url to the current window's location. Something like self=target.


Is there a "true" ending to Dishonored, or just 2 equivalent endings?

Question: What I mean is : if I end the game killing most ppl using all the tools and gameplays for what they are built, will it prevent me to reach the "true" ending, and I will have to play again the full thing in "stealth" mode ?
Comment: Related: [What are the different endings in Dishonored?](https://gaming.stackexchange.com/questions/88864/what-are-the-different-endings-in-dishonored)
Answer: It depends what you mean by "true ending".
There is a set of choices that is considered canon by the developers, and is reflected by certain assassination targets surviving and appearing in Dishonored 2. Most of these imply a low chaos Corvo (and Daud, in his DLCs).
Whether you get the "good" or one of the "bad" endings is decided at the beginning of the final mission, based on your Chaos, though it's possible to have such high/low chaos a few missions before then that you can't change it.
However, there's no reason you have to stick with those decisions. Nobody's going to ban you from playing Dishonored 2 just because you didn't do what they wanted. Enjoy your rampage.


How to take snapshots with LVM?

Question: This time when I installed Ubuntu off my LiveUSB I ticked the option to also install LVM for easier snapshot taking and partition resizing. But now even after looking in the LVM man page, I am still unsure of how to take a snapshot with it. So that is really my question, how do you use LVM to take snapshots on Ubuntu GNOME 15.04?
Answer: Use the lvcreate command along with the --snapshot option to take a snapshot.
To define the size add the --size option and to set a name add the --name option.
Select drive/partition/directory/folder where you want to store the snapshot.
Find more command line options from the Ubuntu lvcreate manual here.
And I found an excellent guide on to how use lvm snapshots for backups on tutonics
Comment: That site doesn't seem to like my machine, nor my machine it... So could you please put its contents into your answer. :) Also link-only answers are normally detect by the system as low quality and then deleted.
Comment: By the way, putting it into your own words is good, but you can also quote the tutorial and give a link back to it...
Comment: Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: @RolandiXor - I couldn't have explained it better without copying something from the tutorial. I followed your suggestion and added details in my own words - Thank you !
Comment: What would it mean to define the size?
Comment: The size the snapshot will have - e.g. --size 5GB (has to be large enough to not run out of space). :)

How to take snapshots with LVM?


Why is the content of an irreducible polynomial not a unit?

Question: I'm reading a corollary in my book, but I don't follow one sentence.

Corollary: Let $D$ be a UFD with quotient field $F$. If $f$ is a nonconstant polynomial in $D[X]$, then $f$ is irreducible over $D$ if and only if $f$ is primitive and irreducible over $F$.
Proof: If $f$ is irreducible over $D$, then $f$ is irreducible over $F$. If $f$ is not primitive, then $f=c(f)f^*$ where $f^*$ is primitive and $c(f)$ is not a unit...

Here $c(f)$ is the content of $f$, the $\gcd$ of the coefficients. Why is it necessarily not a unit? I thought it had something to do with the fact that if $c(f)$ is a unit, then $c(f)^{-1}f=f^*$, so $c(f)^{-1}$ divides every coefficient of $f^*$, but maybe this is impossible since $f^*$ is primitive, but I'm not too sure.
Would this prove $c(f)^{-1}=1$ up to associates (if so, I don't see why), and then $c(f)=1$, so $f=f^*$, contradicting the fact that $f$ is not primitive? Thanks.
Answer: "$f$ is not primitive"  means precisely that the content of $f$ is not a unit. Your definition of primitivity seems to be that no nonunit divides all the coefficients of $f$, but this is equivalent since the content is the greatest common divisor of the coefficients.
Comment: The content is the gcd of the coefficients, and gcds are only defined up to associates. Thus "the content is 1" and "the content is a unit" are both sloppy ways of saying that the gcd$\bf{s}$ are exactly the units.
Comment: Thanks, Chris. Does this then mean if $c(f)$ is a unit, then $f$ is primitive? Because my text stated that a primitive polynomial is one whose content is $1$, not just any unit. Am I missing something?
Comment: Thanks for the clarafication. I think that's been a block in my understanding so far, of what it means for two elements to be the same up to associates. So two elements $a$ and $b$ are associates if $a=ub$ for $u$ a unit. But it's not just a safeguard against something trivial like $u=cc^{-1}d^{-1}de^{-1}e$, where $c,d,e$ are all units, correct?
Comment: I don't know what your "safeguard" question means, but there are rings where there are lots of units and where, for purposes of divisibility, there is no point in distinguishing among $17, 17i, 17(\sqrt2-1),\dots$ - they're all associates.


Spring mvc, update data in database using AJAX

Question: I'm coming again with the same concern that have not get answer before. Excuse me for repetition.
I'm trying to enable user already registered in my database from a jsp using AJAX. unfortunately I'm getting the below error code.
POST http://localhost:8081/spring_gestionobjetsvolesouperdus_webapp/activerutilisateur/ 405 (Method Not Allowed)    jquery-3.2.1.js:9566

Here's my code
Model class
@Entity
@Table(name="utilisateur")
public class Utilisateur implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="username")
    @NotEmpty(message="Veuillez saisir le nom d'utilisateur")
    @UsernameAlreadyExists
    private String username;

    @Column(name="password")
    private String password;

    @Transient
    private String confirmPassword;

    @Column(name="nom_utilisateur")
    private String nomUtilisateur;

    @Column(name="prenom_utilisateur")
    private String prenomUtilisateur;

    @Column(name="date_naissance_utilisateur")
    @DateTimeFormat(pattern="dd-MM-yyyy")
    private Date dateNaissanceUtilisateur;

    @Column(name="lieu_naissance_utilisateur")
    private String lieuNaissanceUtilisateur;

    @Column(name="enable")
    private boolean enable;

    //Getters and Setters

}

Dao Implementation
public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
    sessionFactory.getCurrentSession().update(utilisateur);
    return utilisateur;
}

Controller
@RequestMapping(value = "/activerutilisateur/", method = RequestMethod.POST)
@ResponseBody
public Utilisateur activerUtilisateur(@RequestBody Utilisateur utilisateur) {
    utilisateur.setEnable(true);
    service.updateUtilisateur(utilisateur);
    return utilisateur;
}

JSP with AJAX Request
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <link rel="stylesheet" type="text/css" href="<c:url value="/resources/css/datatables.min.css"/>"/>
        <link rel="stylesheet" type="text/css" href="<c:url value="/resources/bootstrap-3.3.7/dist/css/bootstrap.min.css"/>" />
        <link rel="stylesheet" type="text/css" href="<c:url value="/resources/css/style.css"/>" />

        <title>Liste des utilisateurs</title>

Liste des utilisateurs

                                    Username

                                    Nom et prénoms
                                    Date de naissance
                                    Lieu de naissance
                                    Actif
                                    Action

                                <c:forEach items="${listUtilisateur}" var="u">

                                        <%-- <c:out value="${u.idUtilisateur}"></c:out>	 --%>
                                        <c:out value="${u.username}"/>
                                        <%-- <c:out value="${u.password}"/>	 --%>
                                        <c:out value="${u.nomUtilisateur} ${u.prenomUtilisateur}"/>
                                        <%-- <c:out value="${u.dateNaissanceUtilisateur}"></c:out>	 --%>
                                        <fmt:formatDate value="${u.dateNaissanceUtilisateur}" pattern="dd-MM-yyyy"/>
                                        <c:out value="${u.lieuNaissanceUtilisateur}"/>

                                            <c:choose>
                                                <c:when test="${u.enable=='TRUE'}">

                                                      <input type="checkbox" checked="checked">

                                                </c:when>
                                                <c:otherwise>

                                                      <input type="checkbox" id="${u.username}" onclick="activerUtilisateur('${u}')">

                                                </c:otherwise>
                                            </c:choose>

                                </c:forEach>

                Nouvel utilisateur ? Inscription ici sinon <a href="<%request.getContextPath();%>"> retour

I also have spring security config in the project and find down the config code:
Spring security config
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/editermarque**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/supprimermarque**" access="hasRole('ROLE_ADMIN')"/>
        <access-denied-handler error-page="/403"/>
        <form-login login-processing-url="/j_spring_security_check" login-page="/login" default-target-url="/" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
        <logout logout-url="/j_spring_security_logout" logout-success-url="/"/>
        <csrf/>
    </http>

    <authentication-manager>
        <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username, password, enable from utilisateur where username=?" authorities-by-username-query="select username, role from utilisateurrole where username=?" role-prefix="ROLE_"/>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

Please help me to find what I did wrong and once more I'm apologizing for the repetition.
Thanks
Comment: what issue do you met,you need describe it!
Comment: I have this WARNING : Request method 'POST' not supported in my tomcat console, and POST http://localhost:8081/my_project/activerutilisateur/my_username 405 (Method Not Allowed) in my browser console.
Comment: in your controller method,try to use `/activerutilisateur` instead of `/activerutilisateur/`
Comment: No change, I get the same issue
Comment: also check your ajax url,the ajax url and the controller url need to keep the same.
Answer: I finally found the answer here :
https://matthewbusche.com/blog2/2016/08/06/using-csrf-with-spring-security-and-ajax-calls/
It's due to csrf


Check how many matching keys in the object

Question: I have a following data in JavaScript:
{
  '0.Title': 'Title 1',
  '0.Detail': 'Detail 1',
  '1.Title': 'Title 2',
  '1.Detail': 'Detail 2',
  '2.Title': 'Title 1',
  '2.Detail': 'Detail 1'
}

I want to count how many times the .Title exist in the key. No matter its 0.Title or 1.Title.
I did like:
let count = 0;
while ('.Title' in fields) { // <--- fields is the above object
  count++;
}
console.log(count); // <--- gives 0

Comment: Do you want to count Title in key or value.
Comment: In the Key......
Answer: You can use a reducer:

const data = {
  '0.Title': 'Title 1',
  '0.Detail': 'Detail 1',
  '1.Title': 'Title 2',
  '1.Detail': 'Detail 2',
  '2.Title': 'Title 1',
  '2.Detail': 'Detail 1'
}

console.log(Object.keys(data).reduce((acc, curr) => {
  if(curr.indexOf(".Title") !== -1) acc += 1;
  return acc;
}, 0))
Answer: You can use Object.keys which will give an array of keys then use map to return an array of keys only but changing the case just to make sure that title
or Title or TITLE all considered same. Following that you can use filter to take out keys which have title keyword. This will return an array then you can use length

let data = {
  '0.Title': 'Title 1',
  '0.Detail': 'Detail 1',
  '1.Title': 'Title 2',
  '1.Detail': 'Detail 2',
  '2.Title': 'Title 1',
  '2.Detail': 'Detail 1'
};

let k = Object.keys(data).map(e => e.toLowerCase()).filter(e => e.includes('title'));
console.log(k.length)


How do I complete Challenge 1-18?

Question: I cannot for the life of me figure this level out.
I figure I have to use the white and blue rectangular blocks as stepping stones to the top, but I can't seem to make it work.
How do I complete this challenge?
Answer: Here's my solution:

Pull pink block twice
stand in font of the blue block and pull it once
Jump to the small gap in front of the white block, side pull the blue block twice (you'll have to move back once)
Pull the white block once
Jump diagonally to the small protruding blue block
Push the pink block all the way back
Side pull the white block once or twice
Pull the pink block once and use the white block to get on top of it

How do I complete Challenge 1-18?


Functions with same Signature in derived class but inherited as Protected

Question: Base class function and derived class function having the same signature but inherited as protected .In main i have assigned derived class object to a base class pointer and i am trying to access the function .It causes error. Is it because of Protected?
 class base{

    public:
    void test(){
    cout<<"test in base\n";

    }
    };
    class derived:protected base{

    public:

     void test(){
    cout<<"test in derived\n";

    }

    };

    int main(){

    base *ptr;
    derived obj;
    ptr=&obj;
    ptr->test();

    return 0;
    }

error:
In function 'int main()':

error: 'base' is an inaccessible base of 'derived'

     ptr=&obj;

          ^~~

Comment: Maybe, but you've not posted any code so can't say for sure.
Comment: Maybe you are missing a `;` on line 42. Please include the error and the code in the question.
Comment: Have you tried making test() in the base class virtual?
Comment: sorry i forgot to add the protected in derived class access specifier
Comment: thats how protected inheritance works, why did you choose to use protected inheritance?
Comment: Did you notice which line gives you the error? The line that calls the `test` function is not necessary to reproduce the error.
Comment: you can remove the function call and still get the same error. Please pay attention to the line numbers included in the error message
Comment: the line ptr=&obj causes error. why does it cause ?
Comment: "the line ptr=&obj causes error. why does it cause ?"  Because ptr is a `base*` and obj is-a `derived` which is-not-a `base` (because `protected` inheritance means that obj is-not-a base).
Comment: Why does it is not working with protected inheritance?
Comment: That's how protected inheritance works.  You are telling the compiler that doing `ptr = &obj` is not allowed, so the compiler prints out an error.
Comment: @SelvaBharathi Now that you see which line causes the error, do you see how the focus of your question is misplaced? You spent so much space discussing the function, yet that is irrelevant. You could remove that function from your example code and still have the error. A well-focused question can save everyone time and effort.
Answer: Edit
The code in the question changed so I change the whole answer:
both Private and protected inheritance allow overriding virtual functions in the private/protected base class, neither claims the derived is a kind-of its base. So ptr=&obj doesn't work because they are not the same type.

protected inheritance allows derived classes of derived classes to
  know about the inheritance relationship. Thus your grand kids are
  effectively exposed to your implementation details. This has both
  benefits (it allows derived classes of the protected derived class to
  exploit the relationship to the protected base class) and costs (the
  protected derived class can't change the relationship without
  potentially breaking further derived classes).
Comment: nope. The error is not due to calling the function but due to `ptr=&obj`. Doesnt work with protected inheritance
Comment: @formerlyknownas_463035818 seems the question changes a lot :)
Comment: "You have public inheritance not protected." op first posted the wrong code
Comment: why does it is not working with protected inheritance? due to compile time binding it must bind with type of pointer so base function must be called.
Comment: @SelvaBharathi read about the purpose of protected inheritance in the link I cited.
Answer: As you are using protected inheritance to the outside world derived is not derived from base, only derived and its subclasses know that it is derived from base.
Therefore:
base *ptr;
derived obj;
ptr=&obj;

Is assigning derived* to the completely unrelated type base*. If you want derived to be convertible to base you need to use public inheritance, protected inheritance deliberately hides your base class from the outside world.


Cordova iOS Go Back To Previous Page

Question: I am not very familiar with iOS. I have a Cordova app that I built and it runs fine on Android. However when I run it on an iPad running iOS 9 there are no back buttons to travel back to the previous page like any browser I have ever used in my life. I'm assuming its loaded into a UIWebView so how am I supposed to travel back to the previous page when there is no back button?
Answer: You will need to create a custom "backButton" equivalent to Android or Windows Phone native back buttons.
In my case, I created an "Arrow to Left" button in left top corner of the screen to work as backButton. After, I linked my backButton function for Android e WP to it. Look:
HTML:
 Back

JS:
//Android and WP cordova handle
//document.addEventListener('backbutton', backButtonActions, false);

//Only iOS
$scope.iosBackButtonEvent= function() {
        try {
            backButtonActions();
        }
        catch (error) {
            console.log(error);
        }
    };

PS: I use AngularJS.
Answer: You'll have to add your own.
If you use a framework like Ionic this is already baked in.
Answer: This would work 100 % of times. Add $ionicViewSwitcher and $ionicHistory to your controller or function. and then ng-click="goBackState()"
$rootScope.goBackState = function(){
  $ionicViewSwitcher.nextDirection('back');
  //console.log($ionicHistory.backView())
  $ionicHistory.goBack();
}

Cordova iOS Go Back To Previous Page


Beginner: How to store data in Ruby on Rails?

Question: I have a rails 4 app ,where I'd like to store questions and answers in some form of a document or in the database and then display them on a specific webpage and have users answer these questions.
For example: I would have a webpage called /questions and there would be a question such as "Do you like Math or Science" -> If the user chose Math for the answer it would lead them to a different question than if they had chosen Science.
 Question: How can I store questions or any piece of data in my rails app and then display them in my view if need be?
Comment: So, what's your question? ^^
Comment: How can I store questions or any piece of data in my rails app and display them in my view?
Comment: http://guides.rubyonrails.org/getting_started.html
Answer: Okay look - you really need to focus on asking specific questions on here. People get paid to provide opinionated answers (consultants) - SO is mainly for providing specific information about specific questions
Nonetheless, I will help you out as I'm guessing you're new:

Ror
Saving data is one of the most elementary functions of Rails - it's an MVC (model view controller) framework, which means that it can take any input (from your view), configure it in your controller, and finally save it in your model (to your database):

Rails is one of the most efficient, simple & extensible platforms for creating, storing & associating data; and is designed around that functionaliy
--
MVC
To get started with Rails, there are several things you need to consider.
Firstly, you need to appreciate that Rails is built on Ruby, which makes it object orientated. This means that everything you do with Rails has to revolve around objects, including everything from your routes to your controller actions
This is important because so many newbies don't know about Rails' OOP capabilities, and consequently create application-flows which are disjointed & broken. The right way to create Rails-based applications is to put the object at the center of the flow, which will be apparent in a second
-
Secondly, as Rails is an MVC framework, it handles requests somewhat differently than "normal" applications. It does this by taking your request, sending it to your routes & then processing a controller action. This action then allows you to build data from the model, which you can then display in the view
You can read great beginner resources for Rails here:

Rails official beginners' guide
Getting started with Rails Railscast

Question
In regards to your question, here is what you need to do:
#config/routes.rb
root to: "questions#index"
resources :question do #-> domain.com/questions
   resources :answers
end

Here is what you need
#app/models/question.rb
Class Question < ActiveRecord::Base
   has_many :answers
end

#app/models/answer.rb
Class Answer < ActiveRecord::Base
   belongs_to :question
end

#app/controllers/questions_controller.rb
Class QuestionsController < ApplicationController
   def index
      @questions = Question.all
   end

   def new
      @question = Question.new
   end

   def create
      @question = Question.new(question_params)
      redirect_to @question if @question.save
   end

   def show
      @question = Question.find params[:id]
   end

   private

   def question_params
       params.require(:question).permit(:your, :question, :attributes)
   end
end

#app/views/questions/index.html.erb
<% @questions.each do |question| %>
   <%= link_to question.title, question %>
<% end %>

#app/views/questions/new.html.erb
<%= form_for @question do |f| %>
    <%= f.text_field :title %>
    <%= f.submit %>
<% end %>

--
Flow
This will give you the ability to access the route domain.com/questions/new to create a new question, and if you want, you can then add some nested functionality to accommodate answers for those questions
I would highly recommend firstly thinking about what you want to achieve, rather than how you are going to do it. This will give you clarity on how you're meant to create the structure, consequently making it much simpler to implement
Answer: When you created your Rails application, it created a config/database.yml file. This file tells Rails where to store your data. By default, it stores the data in a sqlite database. This is a fine option for learning how to use Rails.
Rails uses database migrations to create the structure of the database.
The easiest way I can think of to get you started would be to use a scaffold. A scaffold creates a Rails model, a database migration, and all the views and controllers you'll need to get started. On the command line, run:
bin/rails generate scaffold Question question:string category:string

The will show a list of all the files it created, and the files are worth looking into.
Now that the files are generated, run:
bin/rake db:migrate

This will migrate your database. The database migration will add a questions table to your database, with two string columns, question and category, and a a few Rails-specific columns. You can see the structure of the table it created in db/schema.rb.
After you migrate your database, you'll be able to run the rails server with:
bin/rails server

Once the server is running, you can see your list of questions in a browser at localhost:3000/questions. Of course, you start with no questions, but the scaffold added code that will let you add, edit, and delete questions.
There are a lot of good tutorials for the next steps, such as associating answers with questions.
Comment: I appreciate you writing this answer but it's not what I'm looking for. My question is how do I store and retrieve data such as questions? Not have a possible user create a question.
Comment: Is your question how to restrict users so they can only view questions? Usually, as the site admin, you'd want the ability to add/edit/delete in the UI so you can manage the questions. Or, are you asking about how to structure the questions in the database? How to populate the questions without a UI?
Answer: You should check out the Ruby on Rails Guides. They are an excellent resource for learning how to create Rails applications
http://edgeguides.rubyonrails.org/
Answer: I am quite new to rails too and found taking some time out to really get my head around the MVC framework and how it works really helped be to then take a step forward and apply things in the way i needed to. The rails guide listed above is great. It really helped me to break down the MVC into the three individual aspects and understand how they worked individually before putting them together. There are some really good projects with screencasts out there which helps put this into practice. I particularly like base rails and the odin project.


Testing primary task

Question: I would like to solve the following testing problem. If there is an error i.e. (=1/0) in a cell, the additional tests will not run after that. I would like to know how to solve this issue in the testing primary task part.
Private Sub ts_NoBlank(TsCn, STST, LsSt, LsIn, TsRw, MsCo, MsIC, MsSt)
    Dim TsCl, StRw, LsRw, TsSh

    TsCl = ColNrOfField(TsCn)
    StRw = FsRwOfField(TsCn) + 1
    LsRw = LsRwOfField(TsCn)
    TsSh = SheetOfField(TsCn)

' Setting up Status Updates
    PLcSt = -1 'Starting previous local status is set to -100% to show eitherways
    rws = LsRw - StRw
    'this part has to be copied to whenever showing the status (Value of LcSt has to be added each time by function)
    LcSt = 0
    If LcSt - PLcSt >= LsIn Then
        Call ShowStatus(MsSt & " (" & Application.WorksheetFunction.Text(LcSt, "0%") & ")", ThisWorkbook.Worksheets("Calculations Running").Range("Started"), STST + (LsSt - STST) * LcSt)
        PLcSt = LcSt
    End If

' Testing primary task
    ErrNr = 0
    For Rw = StRw To LsRw 'ToDo speed up with fromrow torow
        If Len(ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl)) = 0 Then
            ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl).Interior.ColorIndex = 46
            ErrNr = ErrNr + 1
        End If

        'Showing Local Status
        LcSt = 0.1 + ((Rw / LsRw) * 0.75)
        If LcSt - PLcSt >= LsIn Then
            Call ShowStatus(MsSt & " (" & Application.WorksheetFunction.Text(LcSt, "0%") & ")", ThisWorkbook.Worksheets("Calculations Running").Range("Started"), STST + (LsSt - STST) * LcSt)
            PLcSt = LcSt
        End If

    Next Rw
' Updating Test Results on 'Testing' Page

    TRRg = "test" & TsRw & "_results"
    If ErrNr = 0 Then 'If Results are Positive
      ThisWorkbook.Worksheets("Testing").Range(TRRg) = MsCo
      ThisWorkbook.Worksheets("Testing").Range(TRRg).Interior.ColorIndex = 51
    Else 'If Errors are found
      ErrMS = NumberizeMessage(MsIC, "SP_textvers", "S_textvers", "P_textvers", ErrNr)
      ThisWorkbook.Worksheets("Testing").Range(TRRg) = ErrMS
      ThisWorkbook.Worksheets("Testing").Range(TRRg).Interior.ColorIndex = 3
    End If

    'Showing Local Status
    LcSt = 0.1
    If LcSt - PLcSt >= LsIn Then
      Call ShowStatus(MsSt & " (" & Application.WorksheetFunction.Text(LcSt, "0%") & ")", ThisWorkbook.Worksheets("Calculations Running").Range("Started"), STST + (LsSt - STST) * LcSt)
      PLcSt = LcSt
    End If

    ' Highlighting erroneous cells (if not done during testing)
    If ErrNr > 0 Then

    End If
'Showing Local Status 100%
    LcSt = 1
    If LcSt - PLcSt >= LsIn Then
      Call ShowStatus(MsSt & " (" & Application.WorksheetFunction.Text(LcSt, "0%") & ")", ThisWorkbook.Worksheets("Calculations Running").Range("Started"), STST + (LsSt - STST) * LcSt)
      PLcSt = LcSt
    End If

End Sub

Comment: Please put question clarifications in the question itself, not in comments. Your question can be edited by clicking the "edit" link.
Comment: Not sure exactly what you're after. Is your code failing? If so where? Is there an additional task that your code needs to do but you don't know how to do it? You will probably find it valuable to declare types on your `Sub` parameters, and at the very least, it will help us understand something more about your code.
Comment: My code in:
 'Testing primary task
    ErrNr = 0
        For Rw = StRw To LsRw 'ToDo speed up with fromrow torow
            If Len(ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl)) = 0 Then
                ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl).Interior.ColorIndex = 46
                ErrNr = ErrNr + 1
            End If

Here it works as it colors the cells if there is a formula which is not accepted, but the rest of the tests are not running after that. I would like to solve this, so if there is a cell with a wrong formula, just I want to mark it, and go on with the next processes.
Answer: Since you indicate that the ' Testing primary task section seems to work, but nothing after that seems to execute, I'd suggest that when you get here:
'Showing Local Status
LcSt = 0.1
If LcSt - PLcSt >= LsIn Then

this condition is false, so the code is never executed.
Then you get here:
' Highlighting erroneous cells (if not done during testing)
If ErrNr > 0 Then

End If

and there is no code to execute, no matter the value of ErrNr.
Then you get here:
'Showing Local Status 100%
LcSt = 1
If LcSt - PLcSt >= LsIn Then

and it's still evaluating False, so again it never executes.
Have you gone through in the debugger to look at the values and ensure everything is as you expect it to be?

Testing primary task


Not seeing windows 10 when i trying to dualboot Ubuntu 20.04

Question: I have a problem, I think? when trying to dual boot windows on a spearate hard drive. When i get to the installation menu I do not see the "Install Ubuntu alongside windows 10" and when i partion the drive in the "something else"-menu it do not recognice windows 10 on my C-drive.
Is this a problem? Im worried that if I install ubuntu on my F-drive I won't be able to access windows again.
Answer: great question!
When installing Ubuntu (or it's derivatives) alongside Windows 10, as long as you don't change the existing EFI partition, or create a new one, (UEFI systems only), or destroy the Windows 10 boot loader/partition, you should be fine.
During install, Ubuntu looks for other supported operating systems, and their boot loaders. When Grub is installed during this process, it will automatically configure boot options for Ubuntu, and most (if not all) other operating systems, but will set Ubuntu as the default boot option.
All modern versions of Windows are considered supported, so with Windows 10, you should be perfectly fine.
I've installed Ubuntu, and Kubuntu alongside Windows 10 on MANY occasions in the last 3 years.
UEFI based BIOS also have the option of selecting which boot loader to run on startup. If you have this kind of system, you can always switch which boot loader runs by default (Windows, or Grub for Linux)
One thing to note is that Windows does not add Linux to it's list of operating systems to choose from on startup, so you will want to use Grub (Linux boot loader) if you want to be able to easily, and quickly switch your OS on boot.
Comment: Thank you so much for your answer!
I'm pretty new to Ubuntu, does Grub install automatically or is that something i have to install myself?
Comment: Grub is part of Ubuntu, so it gets installed automatically.


Trouble inserting date from select statement Error Code: 1292 MySQL

Question: I'm reconciling two different sources of data.  I am trying to insert from one of them into another based on a bunch of conditions, using a statement like so
INSERT INTO `tab`.`listsalesorders`
(`number`,
`name`,
`status`,
`parentProjectID`,
`dateEntered`,
`individualId`,
`taxable`,
....
SELECT
m.number as `number`,
m.name as `name`,
3 as `Status`,
-1 as `individualId`,
m.parentProjectID as `parentProjectID`,
m.dateEntered as `dateEntered`,
m.taxable as `taxable`,
...
FROM (SELECT si.number as `number`,
si.description as `name`,
si.date as `dateEntered`,
p.idx as `parentProjectID`,
si.date as `Date`,
IF(si.salesTaxID='NJ',2,1) as `taxable` FROM listsoli si
JOIN listprojects p ON LEFT(si.number,LOCATE('-',si.number) - 1)=p.number
GROUP BY si.number) as m;

and I am getting Error Code: 1292. Incorrect datetime value: '498' for column 'dateEntered' at row 1.
I looked through my SELECT statement data in another tab, adding on a HAVING dateEntered LIKE '%498%' as well as HAVING dateEntered IS NULL and HAVING dateEntered = '' as I've read both of those can cause problems, but not a single row appears.  Just looking at the data and ordering it by dateEntered, I see no issues at either tail end.
What is causing this and how can I fix it or work around it?
Comment: Why are you inserting `m.parentProjectID` into `dateEntered`?
Comment: Move `-1 as individualId,` after `m.dateEntered as`dateEntered,`
Comment: No, it's the order of the column definitions that decide what values get put in which columns, not the names.
Comment: You thought wrong :-)
Comment: Yea I see the 498 now in the parentID first row of my select query, but I don't see how I am doing it in my insert with `m.parentProjectID as `parentProjectID`,
m.dateEntered as `dateEntered`, ` and `si.date as `dateEntered`,
p.idx as `parentProjectID`,`.  Can you explain where I am going wrong/what needs to change?
Comment: Oh I see the order between my INSERT and my SELECT being off caused this?  I thought just by explicitly naming them I'd be ok.
Comment: Good to know, thanks.
Answer: For INSERT ... SELECT statements the column names (or aliases) don't matter. The order of the columns in INSERT and in SELECT must match. Example:
INSERT into test_table (a, b, c)
SELECT
  'c' as c,
  'b' as b,
  'a' as a

is the same as
INSERT into test_table (a, b, c)
SELECT 'c', 'b', 'a'

or
INSERT into test_table (a, b, c)
VALUES ('c', 'b', 'a')

In the table you will have
a   | b   | c
----|-----|----
'c' | 'b' | 'a'

In other words: The columns are matched not by their names but by their position.


How to prove that $A$ surjective $\iff \ker (A^*) = \{0\}$ and $\operatorname{Im}(A^*)$ is closed?

Question: Let $A$ be a linear densely defined closed operator on a Hilbert space $A: D(A) \subseteq H \to H$. I have to show that $A$ surjective $\iff \ker (A^*) = \{0\}$ and  $\operatorname{Im}(A^*)$ is closed. I know that $\operatorname{Im}(A)$ is closed $\iff \operatorname{Im}(A)=\ker(A^*)^\perp$. So I know that if $A$ is surjective, then $A^*$ is injective. However, I don't know how to prove the rest. Any hints ?
Comment: I take it that $A$ is an operator on a Hilbert space?
Answer: Suppose $A$ is surjective. Lets show that the image of $A^*$ is closed.
Let $x_n\in D(A^*)$ so that $A^*x_n$ converges to some $y$. Then for all $z\in H$ there is some $z'\in D(A)$ with $z= Az'$ and:
$$\langle x_n, z\rangle =  \langle A^*x_n ,z'\rangle \to \langle y, z'\rangle$$
It follows that $\langle x_n, z\rangle$ is bounded as $n\to\infty$. Since $z$ is arbitrary uniform boundedness shows that $x_n$ is a bounded sequence. By passing to a subsequence assume that $x_n$ converges weakly to some $x\in H$. Then for all $z\in D(A)$:
$$\langle x, A z\rangle = \lim_n \langle x_n, Az\rangle=\lim_n\langle A^*x_n,z\rangle = \langle y, z\rangle$$
and $x\in D(A^*)$ with $A^*x=y$. This shows the image is closed.

Now suppose that $\ker(A^*)=0$ and the image of $A^*$ is closed. A standard calculation shows that $\ker(A^*)=0$ implies that the image of $A$ is dense.
Let $x_n\in D(A)$ so that $Ax_n$ converges to some $y$. Since $\mathrm{Im}(A^*)$ is closed let $p$ be the projection to this subspace. One has for all $z\in D(A^*)$:
$$\langle Ax_n,z\rangle=\langle x_n, A^*z\rangle = \langle px_n, A^*z\rangle$$
and so $px_n\in D(A^{**})=D(A)$ (since $A$ is closed). Additionally $px_n$ is bounded since for all $z\in H$ you have a $z'\in D(A^*)$ so that
$$\langle p x_n, z\rangle = \langle x_n, pz\rangle = \langle x_n, A^* z'\rangle\to \langle x, z'\rangle$$
and you apply uniform boundedness as above. Then there is a weak limit $x$ of $px_n$ and for all $z\in D(A^*)$:
$$\langle x, A^*z\rangle = \lim_n\langle px_n,A^*z\rangle =\lim_n \langle x_n A^*z\rangle =\lim_n \langle Ax_n,z\rangle=\langle y,x_n\rangle$$
and so $x\in D(A^{**})=D(A)$ (since $A$ is closed) and $Ax =A^{**}x=y$.
Comment: See https://loss.math.gatech.edu/17SPRINGTEA/7334/NOTES/section3closedoperators.pdf (Theorem 0.9) for a proof about $A^{**}=A$ iff $A$ closed. About reflexivity: Hilbert spaces are always reflexive! This is a consequence of Riesz
Comment: Thanks for the answer. In both parts, how can you pass to a weakly converging subsequence without assuming reflexivity of the Hilbert space ?
Comment: Also, is the statement $A^{**}=A$ for closed operators an easy lemma or does it rely on a nontrivial theorem ?


Mysql add NULL to cols that skipped in insert and that col is unique

Question: I'm trying to add the flowing insert:
INSERT INTO `user`
(`name`, `family`, `status`, `mobile`,  `ip`, `lastIp`, `seenTime`, `createTime`, `updateTime`)
VALUES
('Mehdi Abbasi', NULL, 4, '989197659980',  '184.108.40.206', '220.127.116.11', 1507650436, 1507650436, 1507650436)

And in database i have this:

Null value for family save as null in database and there is no problem about that but skipped cols like email filled by NULL and when trying to add another user whiteout  email get duplicate key error from database.

Note: email field has unique key.

This problem is strange because it's worked in the past.
Table schema is:
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `passwordResetToken` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `family` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `email` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `mobile` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `status` smallint(1) NOT NULL DEFAULT '1',
  `ip` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `lastIp` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `seenTime` int(20) DEFAULT NULL,
  `updateTime` int(20) DEFAULT NULL,
  `createTime` int(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`),
  ADD UNIQUE KEY `mobile` (`mobile`),
  ADD UNIQUE KEY `passwordResetToken` (`passwordResetToken`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

For example passwordResetToken and  email give NULL but family not.
Value in family col make no problem but email make.
Comment: please, add the create code of the table to the question.
Comment: As `NULL` is not equal to, nor not inequal to `NULL`, uniqueness constraints do not apply.
Comment: could you add the table schema?
Comment: @IvoP, I am edited the question.
Answer: The most likely answer is that you created the user.email column as NOT NULL with a default value.
If you truly want to have a unique index on the user.email column and allow multiple rows without an email value, then you need to alter your table to make the user.email column allow NULL values.
Here's an example using your schema to show how you can successfully add multiple rows with NULL email values despite the unique index:
mysql > CREATE TABLE `user` (
    ->   `id` int(11) NOT NULL,
    ->   `password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
    ->   `passwordResetToken` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    ->   `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
    ->   `family` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    ->   `email` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    ->   `mobile` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    ->   `status` smallint(1) NOT NULL DEFAULT '1',
    ->   `ip` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    ->   `lastIp` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    ->   `seenTime` int(20) DEFAULT NULL,
    ->   `updateTime` int(20) DEFAULT NULL,
    ->   `createTime` int(20) DEFAULT NULL
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Query OK, 0 rows affected (0.02 sec)

mysql > alter table user add unique index email (email);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql > insert into user (id,password,name) values (1,'foo','foo');
Query OK, 1 row affected (0.02 sec)

mysql > insert into user (id,password,name) values (2,'foo','foo');
Query OK, 1 row affected (0.01 sec)

mysql [localhost] {msandbox} (test) > select * from user;
+----+----------+--------------------+------+--------+-------+--------+--------+------+--------+----------+------------+------------+
| id | password | passwordResetToken | name | family | email | mobile | status | ip   | lastIp | seenTime | updateTime | createTime |
+----+----------+--------------------+------+--------+-------+--------+--------+------+--------+----------+------------+------------+
|  1 | foo      | NULL               | foo  | NULL   | NULL  | NULL   |      1 | NULL | NULL   |     NULL |       NULL |       NULL |
|  2 | foo      | NULL               | foo  | NULL   | NULL  | NULL   |      1 | NULL | NULL   |     NULL |       NULL |       NULL |
+----+----------+--------------------+------+--------+-------+--------+--------+------+--------+----------+------------+------------+
2 rows in set (0.00 sec)

Comment: I allowed `email` accept null but its make duplicate index problem.
Comment: Yes i want absolutely this but i'm wondered why mysql not working correct and make this problem.
Comment: @Amin MySQL allows multiple NULL values in a unique index. What version of MySQL are you using? Can you post your _actual_ `CREATE TABLE` statement? The one you posted does not have a unique index, so its you are getting duplicate key errors then that is not the right `CREATE TABLE` statement.
Answer: I finally resolve my problem by doping database and create it again and insert backup rows to that.
I don't know why this problem happens at all.
Answer: The cause of your problem is in two things:
1) you do allow NULL values inserted for the email.
That alone is no reason for an error, as you can see with the column Family not having any problems.
2) you on the other hand require the column email to have unique values.
And that is contracticting with allowing null values.
I am not sure if you were able to insert at least 1 record with NULL in email, but multiple inserts with NULL will trigger an error on those "values"  being duplicates.
So: don't let your application insert null into email
Comment: I inserted multi record by email null whit this schema.


Commutant of a C*-subalgebra of B(H)

Question: In operator theory, we can prove that the commutant of $B(H)$ is $\mathbb{C} I$, where $I$ is the identity map. But a book states that every $C*$-subalgebra of $B(H)$ that contains the compact operators also has the commutant $\mathbb{C} I$. In the proof for $B(H)$, we don't need to use the properties of compact operators. What is the process of proof for every $C*$-subalgebra of $B(H)$ that contain the compact operators?
In the proof for $B(H)$, we use of the operator $T$ with this form: for fixed $x,y$ in $H$, $T_{x,y}(z)=\langle z,x\rangle y$. Is this operator compact?
Answer: Yes. Every finite-rank operator is compact.
More precisely, a closed and bounded set in a finite-dimensional vector space is compact (this is basically Heine-Borel). A finite rank operator is necessarily bounded, and so it maps closed balls into pre-compact sets, making it a compact operator.
Comment: I want to show  the commutant of $B(H)$ is a Hilbert space.May be $B(H)'=\mathbb{C}I \cong \mathbb{C}$ is a better method.

Commutant of a C*-subalgebra of B(H)


How do I learn recipes?

Question: I have unlocked the Tavern in Littlewood, and I discovered one recipe just by trial and error, but honestly, that's going to take forever if that's the only way for me to learn to cook.
Are there other ways to learn to cook other than me just randomly trying combinations? Failing that, is there a list of recipes somewhere?
Answer: I've never played the game, but there's a pretty comprehensive Wiki for it.
Main Wiki
I would include a list of the recipes to prevent link rot, but 1) I don't see this link rotting without the game dying, 2) All the recipes are listed in a grid with pictures.
Cooking Wiki

How do I learn recipes?


facebook developer apps - cannot find page

Question: when I try to create the "like" app for my website,it says that it cannot find the page.
I even copied and pasted my name to it. I want to be able to post from it and it will show up on my website. http:/facebook.com/thevisalusbody is what I am trying to get an app for
Answer: You can't create like buttons for user pages.  You would have to convert your user profile to a fan page using Facebook's tool.


JSON to object issue with Jersey and Genson

Question: I'm running into the following problem when trying to execute a POST call using Jersey and Genson:
....
com.owlike.genson.JsonBindingException: No constructor has been found for type interface Animal
....
I have the following setup:
-> Animal.java
package com.test;

import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeInfo;

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes( {@JsonSubTypes.Type(value = Dog.class, name = "dog") })
public interface Animal
{  }

-> Dog.java
package com.test;

import org.codehaus.jackson.annotate.JsonTypeName;
import org.codehaus.jackson.annotate.JsonProperty;

@JsonTypeName("dog")
public class Dog implements Animal
{
   @JsonProperty
   public String name;

   public String getName() { return name; }
   public void setName(String n) { this.name = n; }
}

-> Zoo.java
package com.test;

import java.util.List;

public class Zoo
{
   private List<Animal> animals;
   public List<Animal> getAnimals()
   {
     return animals;
   }

   public void setAnimals(List<Animal> animals)
   {
    this.animals = animals;
    }
 }

-> GensonCustomResolver.java
package com.test;
import javax.ws.rs.next.ContextResolver;
import javax.ws.rs.next.Provider;

import com.owlike.genson.Genson;

@Provider
public class GensonCustomResolver implements ContextResolver<Genson>
{
   private final Genson genson = new      Genson.Builder().useRuntimeType(true).useClassMetadata(true).create();

   @Override
   public Genson getContext(Class<?> arg0)
   {
     return genson;
   }
}

-> JerseyService.java
package com.test;

import javax.ws.rs.*;
import org.codehaus.jackson.*;

@Path("/exampleservice")
public class JerseyService
{

   @POST
   @Path("somePath")
   @Consumer(MediaType.APPLICATION_JSON)
   @Produces(MediaType.APPLICATION_JSON)
   public Zoo createAnotherZoo(Zoo zoo) throws JsonParseException, JsonMappingException, Exception
   {
      Zoo newZoo = new Zoo();
      Collection<Animal> animals = zoo.getAnimals();
      List<Animal> newAnimals = new ArrayList<Animal>();

      for (Animal a : animals) {
          Dog dog_a = (Dog) a;
          Dog dog_b = new Dog();
          dog_b.setName(dog_a.getName() + "TEST");
          newAnimals.add(dog_b);
      }
      newZoo.add(newAnimals);
      return newZoo;
   }
}

The input JSON looks like this:
{
   "animals" : [
     {
       "name": "Unno"
     }
    ]
}

To summarize, I have a List and I'm trying to use one of the interface implementations when deserializing my objects.
Thank you in advance.
::::SOLUTION:::::
In case anyone runs into this:
I removed genson dependencies completely as suggested below. Only used jackson annotations and it seemed to work. Also I removed the @JsonProperty from the name attribute in the Dog.java.
Thank you :) :)
Answer: I think you mean "I'm trying to use one of the interface implementations when deserializing my objects."
Your problem
If it is what you mean, then the short answer is it can not work like that.

I see you are using Jackson annotations, Genson does not see/use those annotations (jackson and genson a two different libraries).
Based on the json stream (the sample input you provided) Genson has no way of knowing to which concrete class to bind.

Some possible solutions would be

If you use the same pojos (animal, dog, etc) and Genson on both ends (the code that will post the data to the server and the server), then using a Genson instance with useRuntimeType and useClassMetadata enabled on both ends should work. It would be the easiest solution.

The class metadata mechanism, during serialization writes in the json object as first entry the class name of the concrete type, during deserialization Genson looks for this first attribute with key @class to extract the concrete class name.
In your case if you are able to produce a json of the form {"animals":{"@class": "com.test.Dog", "name": "Unno"}}, then genson would deser it to the correct type. Note that you can also register aliases for types, so you could just write dog instead of the full class name. More details in the documentation.
As you have those Jackson annotations to give type hints, then you could also use jackson to handle the deser (note that the input json would not work with this configuration as it does not seem to contain the informations defined via the annotations). In this case you should not use Genson to handle the ser/de with jersey as jackson and genson do both the same job.
Comment: I guess it should contain some property named "type" and having as value "dog". Similar to the behaviour with @class in genson, except that maybe the order does not matter.
Comment: Yes I think so as you have set property="type" in JsonTypeInfo. You might also want to read jacksons documentation about those annotations as I am not 100% sure of the meaning.
Comment: Thanks eugen. I meant deserialization, I have corrected it. I would prefer to stay with Jackson only. For now I will remove the Genson stuff, and try using jackson. How would the JSON look like then, can you comment?
Comment: Do you mean this:                                                    {
   "animals" : [
     { "type" : "dog",
       "name": "Unno"
     }
    ]
}
Comment: eugen, that is "almost" working. Now I get a response back, however the response looks like this:  {"animals"{{"type":"dog","name":null}} even though I'm passing in the name in the input json. Any ideas on this one?
Comment: does the input json that you are sending contain also the type: dog? It should otherwise I don't jackson can know to what type to deser. Concerning the name I don't know, try to check that the input Dog has the expected name and make sure that it is jackson that is used during serialization. If none works you might also consider asking of jacksons mailing list.
Comment: This is the json I have : { "animals" : [ { "type" : "dog", "name": "Unno" } ] }  I will try to do some more research.


Dependencies for Spark-Streaming and Twiter-Streaming in SBT

Question: I was trying to use the following dependencies in my build.sbt, but it keeps giving "unresolved dependency" issue.
libraryDependencies += "org.apache.bahir" %% "spark-streaming-twitter_2.11" % "184.108.40.206.0.0-SNAPSHOT"
libraryDependencies += "org.apache.spark" %% "spark-streaming" % "2.2.0"

I'm using Spark 2.2.0. What are the correct dependencies?
Answer: The question was posted a while ago, but I ran into the same problem this week. Here is the solution for those who still have the problem :
As you can see here, the correct syntax of the artifact for importing the lib with SBT is "spark-streaming-twitter", while with Maven it is "spark-streaming-twitter_2.11". It is because, for some reason, when importing with SBT, the Scala version is appended later (the last number is truncated).
But the thing is that the only artifact that work is "spark-streaming-twitter_2.11". For example, with a Scala 2.12, you will have the error
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.apache.bahir#spark-streaming-twitter_2.12;2.3.2: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::

But if you use Scala 2.11, it should work fine. Here is a working sbt file :
name := "twitter-read"

version := "0.1"

scalaVersion := "2.11.12"

libraryDependencies += "org.apache.spark" %% "spark-core" % "2.4.2"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.4.2"
libraryDependencies += "org.apache.spark" %% "spark-streaming" % "2.4.2" % "provided"

libraryDependencies += "org.twitter4j" % "twitter4j-core" % "3.0.3"
libraryDependencies += "org.twitter4j" % "twitter4j-stream" % "3.0.3"

libraryDependencies += "org.apache.bahir" %% "spark-streaming-twitter" % "2.3.2"

Answer: Below are the dependencies you need to add for Spark-Twitter Streaming.
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming_2.11</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
   <groupId>org.apache.bahir</groupId>
   <artifactId>spark-streaming-twitter_2.11</artifactId>
   <version>2.0.0</version>
</dependency>
<dependency>
   <groupId>org.twitter4j</groupId>
   <artifactId>twitter4j-core</artifactId>
   <version>4.0.4</version>
  </dependency>
 <dependency>
   <groupId>org.twitter4j</groupId>
   <artifactId>twitter4j-stream</artifactId>
   <version>4.0.4</version>
   </dependency >
 <dependency>
  <groupId>com.twitter</groupId>
  <artifactId>jsr166e</artifactId>
  <version>1.1.0</version>
</dependency>

Comment: This actually didn't work out unfortunately. Could there be any other reason why I keep getting this ?