text:
Q: PHP Countdown Timer Is it possible to create a timer using PHP so that after 60 seconds it does something. So it actually shows you a countdown from 60 to 0. I would refresh the div so it actually looks like it's counting down. I don't mind using JavaScript but I want to run the timer only when the $_GET variable is = to something.
For either option, can anyone help?
For now, I'm using this code I got from EpicSoftworks on Youtube but the problem with this code is that you have to specify the timestamp you want to use.
$future = -2211753540;
$current = time();
$difference = $future - $current;

$minutes = floor($difference/60);
$r_seconds = floor($difference - ($minutes = 60) );

echo '<h2>' . $minutes . ' - ' . $r_seconds . '</h4>';

A: use PHP to get the variable from the URL and then use javascript for the rest. Create a function that will run a loop 60 times. Inside that loop create a setTimeOut that will do something with a 1000 (1 second) timeout.


text:
Q: How do I take a file a submit it as blob into my db using java servlet? I have a post method that takes a Blob as one of its parameters.
My jsp has this
<input type='file' class='form-control' name ='receipt'/>

In my Servlet I have this
     */
@WebServlet("/upload")
@MultipartConfig
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
    if(req.getParameterMap().containsKey("receipt")){
//      String receipt = req.getParameter("receipt");
        Part receipt =req.getPart("receipt");
        System.out.println("reciept: " + receipt);
        return;
}

receipt returns null for me.
I need to convert receipt to a blob.
I'm using import javax.servlet.http.Part;
and javax-servlet version 3.1

A: If you are on Servlet 3.0 or later then before using HttpServletRequest#getParts() method , you must annotate your servlet with @MultipartConfig.
I believe you are missing @MultipartConfig tag in your servlet class
@MultipartConfig  annotation must be used to indicate that servlet or a form is receiving the Multi Part request from the client.

redpajama_set_name: RedPajamaStackExchange


text:
Q: grepl in R: matching impeded by intra-word dashes I have 3 words: x, y, and z, from which two compound words can be built: x-y, and y-z.
In naturally occuring text, x, y, and z can follow each other.
In the first case, I have:
text="x-y z"

And I want to detect: "x-y" but not "y z".
If I do:
v=c("x-y","y z")
vv=paste("\\b",v,"\\b",sep="")
sapply(vv,grepl,text,perl=TRUE)

I get c(TRUE,TRUE). In other words, grepl does not capture the fact that y is already linked to x via the intra-word dash, and that therefore, "y z" is not actually there in the text. So I use a lookbehind after adding whitespace at the beginning of the text:
text=paste("",text,sep=" ")
vv=paste("(?<= )\\b",v,"\\b",sep="")
sapply(vv,grepl,text,perl=TRUE)

this time, I get what I want: c(TRUE, FALSE).
Now, in the second case, I have:
text="x y-z"

and I want to detect "y-z" but not "x y". Adopting a symmetrical approach with a lookahead this time, I tried:
text=paste(text,"",sep=" ")
v=c("x y","y-z")
vv=paste("(?= )\\b",v,"\\b",sep="")
sapply(vv,grepl,text,perl=TRUE)

But this time I get c(FALSE,FALSE) instead of c(FALSE,TRUE) as I was expecting.
The FALSE in first position is expected (the lookahead detected the presence of the intra-word dash after y and prevented matching with "x y"). But I really do not understand what is preventing the matching with "y-z".
Thanks a lot in advance for your help,

A: I think this matches the description in your comment of what you want to accomplish.
spaceInvader <- function(a, b, text) {
  # look ahead of `a` to see if there is a space
  hasa <- grepl(paste0(a, '(?= )'), text, perl = TRUE)
  # look behind `b` to see if there is a space
  hasb <- grepl(paste0('(?<= )', b), text, perl = TRUE)

  result <- c(hasa, hasb)
  names(result) <- c(a, b)
  cat('In: "', text, '"\n', sep = '')
  return(result)
}

spaceInvader('x-y', 'y z', 'x-y z')
# In: "x-y z"
#   x-y   y z
#  TRUE FALSE
spaceInvader('x y', 'y-z', 'x y-z')
# In: "x y-z"
#   x y   y-z
# FALSE  TRUE
spaceInvader('x-y', 'y z', 'x y-z')
# In: "x y-z"
#   x-y   y z
# FALSE FALSE
spaceInvader('x y', 'y-z', 'x-y z')
# In: "x-y z"
#   x y   y-z
# FALSE FALSE

Is this a problem?
spaceInvader('x-y', 'y-z', 'x-y-z')
# In: "x-y-z"
#   x-y   y-z
# FALSE FALSE


text:
Q: I want to give a timer to the session and end it <?php

function saveUsers($onlineusers_file){
    $file_save=fopen("onlineusers.txt","w+");
    flock($file_save,LOCK_EX);
    for($line=0;$line<count($onlineusers_file);$line++){
        fputs($file_save,$onlineusers_file[$line]."\n");
    };
    flock($file_save,LOCK_UN);
    fclose($file_save);
}

$onlineusers_file=file("onlineusers.txt",FILE_IGNORE_NEW_LINES);
if (isset($_POST['user'],$_POST['oper'])){
    $user=$_POST['user'];
    $oper=$_POST['oper'];
    $userexist=in_array($user,$onlineusers_file);
    if ($userexist)$userindex=array_search($user,$onlineusers_file);

    if($oper=="signin" && $userexist==false){
        $onlineusers_file[]=$user;
        saveUsers($onlineusers_file);

        echo "signin";
        exit();
    }

    if($oper=="signin" && $userexist==true){
        echo "userexist please enter other name";
        exit();
    }

    if($oper=="signout" && $userexist==true){
        array_splice($onlineusers_file,$userindex,1);
        saveUsers($onlineusers_file);
        echo "signout";
        exit();
    }

    if($oper=="signout" && $userexist==false){
        echo "usernotfound";
        exit();
    }
}
$olu=join("<br>",$onlineusers_file);
echo $olu;

?>

I have taken this script from online and I wanted to start and end session timeout here.

A: Firstly you want to store the time when the sessions started
<?php
  $_SESSION['timeout'] = time();
?

Then on another request check their session time (below example is based on 10 minutes) so if their initial session was requested more then 10 minutes the session is invalidated. Otherwise its still valid
<?php
  if ($_SESSION['timeout'] + 10 * 60 < time()) {
     // session timed out
  } else {
     // session ok
  }
?>

Also point to note: The session timeout is also dependant on your php.ini. If the value in ini file is i.e 5 minutes then the session will be invalidated after 5 minutes - regardless of what you specify in your code.


text:
Q: max-width not working on div.container-fluid [This image 1 is my desired outcome but my result is image 2]
How can you make your png to fit in the div.container-fluid like image 1?
HTML Code:

        available for contact on

        saturdays and sundays

        EST GMT -05:00

        contact

Manila City, Philippines

        albaalecxavier@gmail.com

        social

        dribble

        linkedin

        twitter

        instagram

    **   **

CSS Code:
#redwave {
    max-width: 100%;
    max-height: 100%;
    object-fit: none;
}

A: What is the CSS for the parent div of #redwave?  Unless it has a declared width and height, there would be nothing for #redwave's 100% to calculate against.  If you're wanting to use a percentage of the viewport, you can use vh instead of %, where a width of 1vh == 1% of the viewport's width.  If you're wanting it to take up a percentage of the parent container then you'd need to give the parent container an absolute value for the percentages to be calculated.

A: These are the styling i wrote.

ul {
  margin: 0 auto;
  text-align: center;
}

ul li {
  list-style: none;
  display: inline-block;
  padding: 4px 50px;
}

ul li a {
  text-decoration: none;
  text-transform: uppercase;
  color: #000;
}

@media only screen and (max-width: 700px) {
  ul li {
  padding: 4px 20px;
  }
}

This is the complete code

.wrapper{
  margin: 0;
  background-color: #fff;

}

header{
  height: 120px;
  padding: 4px;
}
header h1{
  font-family: "Amatic Sc";
  text-transform: uppercase;
  font-size: 50px;
  text-align: center;
  color: #000;
}

.btn {

  width: 10;
  height: 2px;
    padding: 1.375rem 2.625rem 1.375rem 2.625rem;
    border: 0.125rem solid #B49DF1;
    border-radius: 2rem;
    background-color: #B49DF1;
    color: #fff;
    font: 700 0.75rem/0 'Open Sans', arial, sans-serif;
    text-decoration: none;
    transition: all 0.2s;
}

.btn:hover {
    background-color: #9876F3;
    border: 0.125rem solid #9876F3;
}

ul {
  margin: 0 auto;
  text-align: center;
}

ul li {
  list-style: none;
  display: inline-block;
  padding: 4px 50px;
}

ul li a {
  text-decoration: none;
  text-transform: uppercase;
  color: #000;
}

@media only screen and (max-width: 700px) {
  ul li {
  padding: 4px 20px;
  }
}

Novaturient

Home

Content

Features

About

Contact


text:
Q: UTF-8 issue in html file after java out.println JSP I made a small java ee app, and a login in html, with a form post method to a java class verification.
UTF-8 is respected at the beginning, as we can see on this:

When the login or password is not good, we have this message at the top

And as you can see, there is a problem with accent. here is the source code after ctrl+u :

And this is the class that checks the login, and send a out.print.ln :

I don't understand why there is a problem with utf-8 after the out.print.ln ? How can I solve this ?
I could have used a jsp page, but I used this tag lib in my web.xml file :
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <include-prelude>include/taglibs.jsp</include-prelude>
        </jsp-property-group>
    </jsp-config>

, that doesn't give me the possibility to use my index page as a jsp , which is in a different folder from others jsp, (because it tries to include taglibs.jsp, but it is in a different folder from the include prelude, I think you understood).
Thanks for your help


text:
Q: C# Cannot convert type 'String' to 'AreaCal.VolumeSphere' I am new to C# and trying to make a volume cal that allows you to choose the shape you want to find the volume of I am trying to do that with read line. I am getting Cannot convert type 'String' to 'AreaCal.VolumeSphere' at the read line in static void main
using System;

namespace AreaCal
{

    class VolumeSphere
    {
        double pi = 3.14159265359;
        double ft = 1.333333333333333333333333333333333333;
        double r;
        public void Details()
        {
            Console.WriteLine("Volume of a Circle");
            Console.WriteLine ("Type Radius");
            r = Convert.ToInt32 (Console.ReadLine ());

        }
        public double GetVolume()
        {
            return ft * pi * r * r * r;
        }
        public void Display()
        {
            Console.WriteLine ("Volume: {0}", GetVolume());
        }

    }
    class MainClass
    {
        public static void Main (string[] args)
        {
            VolumeSphere Sphere = new VolumeSphere ();
            Sphere = (Console.ReadLine ());
            if (Sphere != null)
                Console.WriteLine ("awwww");

        }
    }
}

A: Sphere is an object of class VolumeSphere but you are assigning a string Console.ReadLine here that is wrong. Probably you wanted to do something like:
VolumeSphere Sphere = new VolumeSphere();
Sphere.Details();
Sphere.Display();

But your requirement is not clear. So please provide more details on it. And also consider using constructor to pass radius value to your VolumeSphere class.

A: VolumeSphere Sphere = new VolumeSphere();
Sphere = (Console.ReadLine ());

This is throwing the error.  Console.Readline() returns a string read in from standard input.    You are trying to assign this to the variable Sphere, which you declared to be of type VolumeSphere.  I am not sure what you are reading from standard input, but I assume it is radius.
You need to do this instead;
string radius = Console.ReadLine();
VolumeSphere Sphere = new VolumeSphere(Convert.ToDouble(radius));

This passes the string parameter converted to a double to the VolumeSphere constructor, which you are going to define like this inside of class VolumeSphere:
public VolumeSphere(double r)
{
   this.r = r;
}

You should also remove the Details method and put its writelines in the main before you read your input because it is better to encapsulate your models and user interface.

A: In reading your question you mention that you are trying to select multiple calculators, in your example you are trying to assign your keyboard input to your VolumeSphere Object. Here is a quick and dirty implementation of a menu for your calculator, you can play with it and expand it to meet your needs.
class MainClass
{
    static void Main(string[] args)
    {
        int value;
        bool run;

        run = true;
        while(run)
        {
            Console.WriteLine("Calculator Menu");
            Console.WriteLine("1: Compute Volume of a Sphere");
            Console.WriteLine("2: Compute Something else");
            Console.WriteLine("etc,etc,etc");

            if (int.TryParse(Console.ReadLine(), out value))
            {
                switch (value)
                {
                    case 1:
                        VolumeSphere Sphere = new VolumeSphere();
                        Sphere.Details();
                        Console.WriteLine(Sphere.GetVolume());
                        Sphere.Display();
                        break;
                    case 2:
                        break;
                    case 3:
                        break;

                    default:
                        Console.WriteLine("GoodBye");
                        run = false;
                        break;

                }

            }
        }
        Console.WriteLine("Press Any Key to Exit");
        Console.ReadLine();
    }
}


text:
Q: Как в SELECT перебрать двумерный массив в Postgres кто может подсказать, как в Postgres перебрать массив в select'e?
Например, есть массив
{{1,2,3,4,10,12},{1,4,3,3,25,14},{1,6,3,3,11,14}}

Мне нужно получить сумму 5 и 6 элементов, и вывести строки в порядке убывания, то есть получиться вот такое должно
1,2,3,4,22
1,6,3,3,25
1,4,3,3,39

Уточнение, это отдельные столбцы, а не строка целиком
Можно ли это сделать как-то оконной функцией, но не через функцию и цикл, а именно select'ом?
Через функцию у меня нормально все. Тут именно понять, можно ли селектом перебирать массив.
Уточнение, изначально количество элементов неизвестно, то есть жестко делать выборку array[1:1], array[1:2] и тд не получится.

A: SELECT
    columns ->> 0 AS col1,
    columns ->> 1  AS col2,
    columns ->> 2  AS col3,
    columns ->> 3  AS col4,
    (columns ->> 4)::int + (columns ->> 5)::int  AS col5
FROM
    json_array_elements(array_to_json('{{1,2,3,4,10,12},{1,4,3,3,25,14},{1,6,3,3,11,14}}'::int[])) columns
ORDER BY col5;


text:
Q: readline() returns bracket I wrote some codes to get some lines from .txt like below and its keep returning lines with brackets which I did not intend. Could you help me?
codes:
#!/bin/python
i=1
f=open("name.txt","r")
while(i<=225):
 x=f.readline().splitlines()
 print("mol new %s.bgf"%(x))
 i+=1
f.close()

name.txt
02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c
04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c
09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c
17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c
18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c

And it returns
mol new ['02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c'].bgf
mol new ['04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c'].bgf
mol new ['09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c'].bgf
mol new ['17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c'].bgf
mol new ['18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c'].bgf

A: Making minimal changes to your code, try:
i=1
f=open("name.txt","r")
while(i<=225):
 x=f.readline().rstrip('\n')
 print("mol new %s.bgf"%(x))
 i+=1
f.close()

This produces output like:
mol new 02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c.bgf
mol new 04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c.bgf
mol new 09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c.bgf
mol new 17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c.bgf
mol new 18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c.bgf

Further improvements:
with open("name.txt","r") as f:
    for i, line in enumerate(f):
        if i >= 225:
            break
        print("mol new %s.bgf"%(line.rstrip('\n')))

Notes:

*

*You want to use with open("name.txt","r") as f to assure that the file f gets closed regardless.

*Looping over i as a counter as in i=1; while(i<=225): i+=1 is not pythonic.  Use enumerate instead.

*readline reads in a line.  There is no need for splitlines.

*By looping over the lines in the file with for i, line in enumerate(f):, we eliminate the need to read the whole file in at once.  This makes the program suitable for handling very large files.

*In python, when a line is read from a file, it still has the newline at the end of it.  We use rstrip('\n') to safely remove it.

A: The readline function reads a single line from the file. Then you ask to split the line into a list of lines (which will give you a list of only one line since that's what you have).
Don't split the single line. Instead strip the string (to remove leading and trailing "white-space").
Please read the string reference for more information about both splitlines and strip.

A: This is because f.readline().splitlines() returns the line in a list form containing a single element.
Try this instead:
x = f.readline().splitlines()
x = x[0]

A: You don't need to call the splitlines() method on the results of readline()
file.readline() returns one line of the file, including the trailing newline.

.splitlines() is getting rid of the newline by using it as a delimiter and giving you a LIST of lines with only 1 item.  The brackets are coming from the str representation of that 1 item list
you want this:
x = f.readline().rstrip()

to remove the newline or you could also slice off the newline like this
x = f.readline()[:-1]

another thing you might consider is changing your code to use the file object as an iterable.  It is more idiomatic in Python to write
for line in fileobject:
    print line[:-1]

than to use a while loop and .readline()


text:
Q: Any good alternative to qgis libraries in python I would like to be able to visually graph coordinates just like you can do with qgis but without all the hassle of using that python library, something more straight forward maybe?

A: What exactly is your problem with QGIS? Daniel J. Lewis has prepared a nice writeup about Python mapping: http://danieljlewis.org/2010/09/15/drawing-maps-with-python/ As your focus seems to be just to graph things, especially descartes might to be worth a look: http://pypi.python.org/pypi/descartes/1.0

A: You can use a combination of shapely and the Matplotlib pylab module as Sean Gillies does in this post. Shapely can be found on pypi.
x, y = geom.xy
pylab.plot(x, y)

Make sure to also checkout Fiona (nicer ogr byndings for Python).
You might also want to ask the same question on http://gis.stackexchange.com


text:
Q: How to test ClamAV service for potential threats As part of an enterprise software project, our application connects to an antivirus service backed by ClamAV, using ICAP as communication protocol. I would like to test the antivirus service response to malicious documents but, of course, I cannot use a document which is actually infected with something malicious. I found EICAR Anti Malware Testfile, but it only seems to come as either a .txt or a .zip and the system only allows upload of Word or PDF. The antivirus service only recognizes EICAR if it is send to it "as-is" but not when embedded inside a Word or PDF.
My question is: how can I create a Word and/or PDF document that is recognized by ClamAV as a threat despite it is actually not harmful at all?

A: I initially suggested
Since docx is a zip you could try rename eicar.zip as eicar.docx it proves only that a docx is reviewed/scanned similar to a zip, not that the AV can detect malicious VBA macros which would be a different payload.
However, the uploading step, involving Apache Tika file verification, blocked that simplistic approach, as the file type was not as expected.
My second suggestion was
Take a valid docx rename to zip drop the eicar text into it with explorer (or use zip add) and rename to docx as that's likely to bypass Tika checking.
Apparently that worked.
Likewise it should be possible to embed eicar.txt inside a PDF however detection again would not mean the av is scanning for JavaScript exploitation, just that the plain text signature is seen in a PDF file, thus only hints that a PDF is scanned.
This is more difficult due to PDF encryption, but with a hand crafted text file attachment in an editor, it may not be encoded, simply stored as plain text, sufficient basic for the eicar trigger to be seen.
It could look something like this but cut and pasting this binary shown as text will likely fail storage as eicar.pdf due to ansi line endings encoding. so grab a binary copy from link below
%PDF-1.4
%µ¶

1 0 obj
<</Pages 2 0 R/Type/Catalog>>
endobj

2 0 obj
<</Count 1/Kids[3 0 R]/Type/Pages>>
endobj

3 0 obj
<</Contents 4 0 R/MediaBox[0 0 500 800]/Parent 2 0 R/Resources<</Font<</F1 5 0 R>>>>/Type/Page>>
endobj

4 0 obj
<</Length 57>>
stream
q BT /F1 24 Tf 1 0 0 1 50 720 Tm (Hello World!) Tj ET Q

endstream
endobj

5 0 obj
<</BaseFont/Courier/Subtype/Type1/Type/Font>>
endobj

xref
0 6
0000000000 65536 f
0000000016 00000 n
0000000062 00000 n
0000000114 00000 n
0000000227 00000 n
0000000333 00000 n

trailer
<</Size 6/Root 1 0 R/ID[<89311A609A751F1666063E6962E79BD5><FDDAE606D8247DFCBA7D13E1833DEDE3>]>>
startxref
395
%%EOF
%X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*
%%EOF

temporarily available from https://gofile.io/d/53fylg should look like this
assuming your antivirus allows download :-) try save download as text otherwise I will need to upload as RAR

However those two "Positives" would be just as good a detection as telltales that any AV is searching those file types for current known exploits.
I recommend download the live script running version bottom of this article for deeper testing.
https://blog.didierstevens.com/2015/08/28/test-file-pdf-with-embedded-doc-dropping-eicar/


text:
Q: What happens if sscanf() is fed with incomplete string? I have a certain message protocol in which 4 values are sent in ascii format. They are separated by commas and are terminated by a newline character.
To process a received message I use sscanf()
    if( messageReceived() )
    {
        sscanf( message, "%d,%d,%d,%d",
            &SLAVE_ID, &COMMAND, &DATA1, &DATA2 ) ;

        processMessage() ;
    }

This works fine.
Depending on what value goes into COMMAND, the values of DATA1 or DATA2 may or may not be used inside the function processMessage()
The messages do have a fixed format, meaning that there are always 4 values in a message like: 1,23,123,213
I want to start with variable sized messages and I am wondering if my line with sscanf() is going to do strange things (undefined behaviour) if I for instance would send 2,23. Obviously I would not be interested in the values of DATA1 or DATA2 in this example.
I do know how that I can calculate the message size by simply counting the amount of commas + 1 and do something like:
switch (messageSize)
{
case 2:
    sscanf( message, "%d,%d",
                &SLAVE_ID, &COMMAND ) ;
    break;
case 3:
    sscanf( message, "%d,%d,%d",
                &SLAVE_ID, &COMMAND, DATA1 ) ;
    break;
case 4:
    sscanf( message, "%d,%d,%d,%d",
                &SLAVE_ID, &COMMAND, DATA1, DATA2 ) ;
    break;
// etc
}

However I would still like to know if this...
    sscanf( message, "%d,%d,%d,%d",
                &SLAVE_ID, &COMMAND, DATA1, DATA2 ) ;

... is going to give undefined behaviour if message only contains 1,2?

A: No, that behavior is well-defined. Quoth the C standard:

The sscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the sscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

So you can just use one format string, but you should check sscanf's return value to see if the expected number of values was read:
  if(messageSize == sscanf( message, "%d,%d,%d,%d",
                            &SLAVE_ID, &COMMAND, &DATA1, &DATA2 ))
  {
    // everything is fine.
  }


text:
Q: Convergence of a sequence with lots of powers A problem from "Problems in Real Analysis - Advanced Calculus on the Real Axis":

Let $p$ be a nonnegative real number. Study the convergence of the sequence $(x_n)_{n\ge1}$ defined by $$x_n=\left(1^{1^p}\cdot2^{2^p}\cdots(n+1)^{(n+1)^p}\right)^{1/(n+1)^{p+1}}-\left(1^{1^p}\cdot2^{2^p}\cdots n^{n^p}\right)^{1/n^{p+1}}.$$

If $p=0$, it is already proved in the book that $x_n$ converges to $\dfrac1e$. So just consider the case that $p>0$. If the sequence converges, I can prove by Stolz-Cesàro Theorem that the sequence must converge to $0$. But I don't know how to determine which $p$ gives convergent sequences.
Please don't give complete solution, just helpful hints. Thanks in advance.

A: HINT : Let $ a_n = \left( 1^{1^p} \cdot 2^{2^p} \cdots n^{n^p} \right)^{1/n^{p+1}}$ so that $x_n = a_{n+1}- a_n $. Now study the asymptotics of $\log a_n$ using the Euler-Maclaurin formula.

A: Use $\sum_{k=1}^n k^p \log(k) = \frac{\mathrm{d}}{\mathrm{d} p} H_n^{(-p)}$, as well as series expansion for harmonic numbers $H_n^{(-p)}$ of order $-p$, using $H_n^{(-p)} = \zeta(-p) - \zeta(-p, n+1)$.
I am getting zero value for the limit, as you claimed.


text:
Q: isChecked() method always returns false for react-native screen - UIAUTOMATOR As mentioned in various blogs The UiObject.isChecked() method works for checkbox verification for property like - if it is checked already or not but it seems to be working for android native screens only, as I tried it on react-native screen in my app and it always returns .isChecked as false.

I have tried with UiObject2 class as well as UiObject class but it is not working!

So the problem is - UiObject.ischecked() is not working on react-native screens in android app. Can someone help ? or confirm if it works for you than how it is working ?

code below:
try {
UiObject checkBox_toggle = mDevice.findObject(new UiSelector().description("toggle_checkbox"));   if (checkBox_toggle.isChecked()) {
         checkBox_toggle.click();
          }    } catch (UiObjectNotFoundException e) {
          e.printStackTrace();
        }
         UiObject2 checkBox_toggle =
         mDevice.findObject(By.desc("toggle_checkbox"));
            if (checkBox_toggle.isChecked()) {
               checkBox_toggle.click();
             }

Thanks!


text:
Q: Problem hosting server behing personal router I recently bought a domain name lucidcontraptions.com and want to host the website from home. I have a D-LINK router in which I have set up my personal virtual server correctly. My application server is apache2.2
The server works perfectly with the following settings:
external ip: 207.172.xx.xx public port:8888
internal ip: 192.168.xx.xx private port:80
if I go to 207.172.xx.xx:8888/ the server works perfectly and my apache page shows up without any issues, both from inside the intranet as well as outside.
This setting would not work out for me as I am not allowed port numbers in my DNS management.
Now when I tweak the settings to the following:
external ip: 207.172.xx.xx public port:80
internal ip: 192.168.xx.xx private port:80
if I go to 207.172.xx.xx/ the server works perfectly and my apache page shows up without any issues BUT ONLY FROM INSIDE THE INTRANET
this page does not show up for people outside the intranet.
On the other hand, an ssh to lucidcontraptions.com works perfectly. so i am guessing port 22 is working flawlessly..
SOMEONE PLEASE!, help me out!

A: Many consumer ISPs block port 80 so that consumers can't do their own web hosting.  You might want to check with your ISP to see if they are blocking it.

A: If you are doing this from say comcast,time warner,$other_isp then they could be filtering port 80..You'd probably have to upgrade to a business acct to get 80 opened up

A: Greetings ...
I advise third party hosting if possible .. it is ridiculously inexpensive.  DreamHost is doing a deal today (17-June-2009); less than US$10 for a year of hosting on a shared server with unlimited space and bandwidth.  It is probably cheaper than the difference between residential and business ISP broadband.
You know about the ISP port blocking problem .. there is not likely a way around it, certainly not a way that doesn't break your contract.  If that is indeed the problem I wouldn't mess with it.
You could possible have issues with the router config.  Set the web server to another port and see if you can get it all to work on that port.  You could also try it at another location (friend or relative?) with a different ISP -- easily done with DynDNS -- and see if that works.

A: According to http://www.dslreports.com/faq/12111, RCN blocks incoming port 80 for customers who do not have static IPs.  This suggests that you can get it unblocked by signing up for the static IP service ($19.95/mth according to http://www.rcn.com/boston/high-speed-internet/extras/home-networking)
A cheaper alternative may be to sign up for a URL redirection service from one of the dynamic dns providers.  Zoneedit.com provides such a service for $1/mth.  You would be looking for their ManagedDNS and WebForward service.  How this might work is that you could set lucidcontraptions.com and www.lucidcontraptions.com to do a webforward to web.lucidcontraptions.com:8888.  Other service providers may be cheaper or provide variants of this service, such as an iframe that hides the forwarded url so that visitors don't see the ugliness.
Not sure if you had anonymized your domain name, but according to [link in the comment below], the lucidcontraptions.com domain has not in fact been registered.
I'm also not sure whether hosting websites is against your T&C and AUP.  You will have to find out and consider this risk.


text:
Q: ExceptionFilterAttribute may not be logging exceptions in ApplicationInsights Do exceptions that are filtered with a custom ExceptionFilterAttribute logged to Application Insights?
I want to return a custom DTO in my custom ExceptionFilterAttribute filter, but I think exceptions are no longer logged into ApplicationInsights after that. This is for .NET Core 3.0.
I added a line with:
this.telemetryClient.TrackException(context.Exception);

to make sure I can see the exception but I'm not sure if my exceptions are logged twice now.
Does anyone know if ApplicationInsights will log exception if they enter ExceptionFilterAttribute? I can't find documentation for this.
I'm calling just in case also:
base.OnException(context);

A:
Does anyone know if ApplicationInsights will log exception if they
  enter ExceptionFilterAttribute?

Yes, it will log the exceptions, so you do not need to add this line of code this.telemetryClient.TrackException(context.Exception);. Just using base.OnException(context); is ok.
You can see this GitHub issue for the similar issue, the reason is that "With new Ilogger enablement by default, exceptions are automatically reported by application insights.".
I also check it via a simple test, the test result as below:


text:
Q: How can I launch the iOS Clock app using a a URL scheme? How do I redirect to home screen clock on click button event in my app?
I am trying with this code, but it redirects to Settings page, whereas I want to redirect to clock page.
This is my code which I used in my project:-
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General&path=Clock"]]

please give some ideas.thanks in advance.

A: UPDATE: it is not possible to do this.
There are URL schemes for the various parts of the Clock app (see below) but for some reason they do not work.
ORIGINAL ANSWER:
As far as I know the Clock app has several URL schemes depending on the part of the app to launch to.
Try this:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"clock-worldclock://"]]

clock-alarm:// and clock-stopwatch:// should also work.


text:
Q: javax.jms.JMSException: maximum connections (50) reached error while configuring more than 50 resource adapters - MDB We are getting the below exception when we try to configure more than 50 MDB (each MDB to a different MQ). I have tried changing the standalone.xml configuration as below, but still it didnt help. Could someone help us on this ?
standalone.xml
<short-running-threads>
    <core-threads count="90"/>
    <queue-length count="90"/>
    <max-threads count="90"/>
    <keepalive-time time="10" unit="seconds"/>
</short-running-threads>
<long-running-threads>
    <core-threads count="90"/>
    <queue-length count="90"/>
    <max-threads count="90"/>
    <keepalive-time time="10" unit="seconds"/>
</long-running-threads>

Stacktrace:

ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 185)
  MSC000001: Failed to start service
  jboss.deployment.subunit."test.ear"."testAppMDB.jar".component.TESTMDB.START:
  org.jboss.msc.service.StartException in service
  jboss.deployment.subunit."test.ear"."TestAppMDB.jar".component.TESTMDB.START:
  java.lang.RuntimeException:
  com.ibm.mq.connector.DetailedResourceAdapterInternalException:
  MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011
  An internal error caused an attempt to allocate a connection to fail.
  See the linked exception for details of the failure. at
  org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:57)
  [jboss-as-ee-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] at
  java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
  [rt.jar:1.8.0_102] at
  java.util.concurrent.FutureTask.run(FutureTask.java:266)
  [rt.jar:1.8.0_102] at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  [rt.jar:1.8.0_102] at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  [rt.jar:1.8.0_102] at java.lang.Thread.run(Thread.java:745)
  [rt.jar:1.8.0_102] at
  org.jboss.threads.JBossThread.run(JBossThread.java:122) Caused by:
  java.lang.RuntimeException:
  com.ibm.mq.connector.DetailedResourceAdapterInternalException:
  MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011
  An internal error caused an attempt to allocate a connection to fail.
  See the linked exception for details of the failure. at
  org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.activate(MessageDrivenComponent.java:209)
  at
  org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.start(MessageDrivenComponent.java:181)
  at
  org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:54)
  [jboss-as-ee-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] ... 6
  more Caused by:
  com.ibm.mq.connector.DetailedResourceAdapterInternalException:
  MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011
  An internal error caused an attempt to allocate a connection to fail.
  See the linked exception for details of the failure. at
  com.ibm.mq.connector.services.JCAExceptionBuilder.buildException(JCAExceptionBuilder.java:134)
  at
  com.ibm.mq.connector.services.JCAExceptionBuilder.buildException(JCAExceptionBuilder.java:105)
  at
  com.ibm.mq.connector.inbound.ConnectionHandler.allocateConnection(ConnectionHandler.java:165)
  at
  com.ibm.mq.connector.inbound.MessageEndpointDeployment.acquireConnection(MessageEndpointDeployment.java:284)
  at
  com.ibm.mq.connector.inbound.MessageEndpointDeployment.(MessageEndpointDeployment.java:233)
  at
  com.ibm.mq.connector.ResourceAdapterImpl.endpointActivation(ResourceAdapterImpl.java:393)
  at org.jboss.jca.core.rar.EndpointImpl.activate(EndpointImpl.java:191)
  at
  org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.activate(MessageDrivenComponent.java:207)
  ... 8 more Caused by: javax.jms.JMSException: maximum connections (50)
  reached at com.ibm.mq.connector.in

A: This exception
Caused by: javax.jms.JMSException: maximum connections (50) reached at com.ibm.mq.connector.inbound.ConnectionHandler.allocateConnection

is a result of default setting (50) of the maxConnection property in the WebSphere MQ Resource adapter. Check this page for more details Configuring properties for the IBM MQ resource adapter.
You need to change this property in the resource adapter configuration. I dont know how you configure it in JBoss, but in WebSphere you do it via Resources > JMS > JMS providers > Resource adapter properties.

A: It's hard to tell from the formatting of the stack-trace, but it appears to me that the exception is coming from the WebSphereMQ JCA Resource Adapter which indicates that the problem is with the configuration of the WebSphereMQ server which appears to be limiting the number of possible connections to 50.  Changing thread-pool configurations in the JBoss application server isn't going to resolve the issue.  You need to change the WebSphereMQ server to allow more than 50 connections.

A: You can increase the number number of available connections (defaults to 50):
    <subsystem xmlns="urn:jboss:domain:resource-adapters:5.0">
        <resource-adapters>
            <resource-adapter id="wmq-jmsra.rar" statistics-enabled="true">
                <archive>
                    wmq-jmsra.rar
                </archive>
                <config-property name="maxConnections">
                    100
                </config-property>


text:
Q: Not working, How to push random variables to array and output total of array Javascript First function produces a random number. Each time the second function is called it should output the total number of array values added together. why does this only output one variable value?

function random() {
  return Math.floor((Math.random() * 10) + 1);
}

var addtime = [];
function totalArray() {
  var newCell3 = random();
  var Value = '';
  var total = 0;

  value = newCell3;
  addtime.push(value);

  for (var i in addtime) {
    total += addtime[i];
  }

  console.log(total);
}

totalArray();

A: I guess this is what you are looking for:

const random = () => Math.floor((Math.random() * 10) + 1);

var addTime = [];

document.getElementById('button').addEventListener('click', totalArray);

function totalArray() {
  const newValue = random();
  let total;

  addTime.push(newValue);

  total = addTime.reduce((x, y) => x + y, 0);

  console.log(total);
}
<button id="button">Click Me!</button>


text:
Q: What do I do with Pickaxes in the nightly builds? In the stable builds, pickaxes and drills are the main methods of mining out things (apart from the Matter Manipulators). However, this has changed in the nightly builds.
I've noticed that Pickaxes and drills are no longer the main progression in mining; they're not in the workbench anymore!
Instead, I've noticed that you're meant to use the Matter Manipulator more often, and that you can't repair picks with ores like in the Stable builds.
Questions:

*

*What do I do with pickaxes?

*Is there any faster mining methods (apart from using the Matter Manipulator or a pickaxe^)?

*How do I get them?

^Because that would just be very expensive (in terms of ores).

A: *

*You can still use them for mining. IMO the diamond drill is a bit faster than the fully upgraded MM but only mines 2x2.

*No. I don't know if you can destroy blocks with some kind of explosives.

*/

A: *

*Pickaxes are now used as a short-term method to mining slightly faster than the Matter Manipulator. They can no longer be repaired but are now much cheaper to craft. They also have a much more limited range than the Matter Maniplator

*It seems 2 handed weapons of higher rarity, that shoot projectiles can damage nearby blocks (the projectiles won't damage farther away blocks, only the swing from the weapon itself). They can hit many more blocks than a pickaxe will, but take more hits to mine. You will also not be able to collect any blocks destroyed in this manner, so highly non-recommended.
You can use both the projectile or weapon's swing to destroy background objects like plants and the destructible white chests, these you will be able to collect. This doesn't work on farm-able plants, just things like reeds in desert oasis' or jungle plants.

*They can be crafted at an Iron anvil, or found in containers in some dungeons.


text:
Q: Unexpected Response code 301 when calling Image from Url In my app i am calling image from url,its working in simulator but in device it shows tunnel failure probelm. I then appended "deviceside=true" if i test it in simulator and "interface=wifi" if i test it in device both shows "Unexpected Response code 301" error. Why it is so ? Guide me.

A: 301 is a "Moved Permanently" code. The actual body you receive will probably say where its actual location is. The browser gets this and can make sense of it, knowing to just forward itself to the new URL, but a normal connection is just grabbing the contents of whatever is at that location.
You can add some logic in there to follow the redirect, or just figure out what the actual URL is.


text:
Q: why use each when creating a jquery plugin Im a bit confused with the use of each when creating plugins.  Ive created a simple plugin with a callback as a test.

Click me 1

Click me 2

Without each :-
(function($){
    $.fn.TestCallBack = function(options){
        var defaults = {
            onClicked :function(){}
        }

        var settings = $.extend({}, defaults, options);

        function DoSomething(){
            settings.onClicked.call(this);
        }

        $(this).bind("click", DoSomething);

        return this;
}
})(jQuery);

$("div").TestCallBack({onClicked:function(){
    console.log($(this).html());
}});

This produces the results
Click me 1
Click me 2

With each :-
(function ($) {
    $.fn.TestCallBack = function (options) {
        var defaults = {
            onClicked: function () {}
        }

        var settings = $.extend({}, defaults, options);

        function DoSomething() {
            settings.onClicked.call(this);
        }

        this.each(function(){
            $(this).bind("click", DoSomething);
        });

        return this;
    }
})(jQuery);

$("div").TestCallBack({
    onClicked: function () {
        console.log($(this).html());
    }
});

this produces the results
Click me 1
Click me 2

i thought using each would iterate over the divs found but why does the code not using each provide the same results.  Im obviosuly missing something here.  Any ideas?

A: The only thing you do to this is calling jQuery's bind on it.
This internally does that operation for all elements of the set this.
You would need to iterate over all elements with each when doing something with them that is not automatically applied to all items of the set.

A: You use each to be able to follow jQuery convention of returning the original set of jQuery objects, which in turn enables chaining.
The way you are using each doesn't make it. It should be used like this:
 $.fn.extend({
        TestCallBack : function () {
            return this.each(function () {
                // write your code here
            });
        }
});

Now you can code like this:
$('div').TestCallBack().stop().show(). .....

Without each returning, you will not be able to chain further jQuery methods on the original set.
More information here: http://learn.jquery.com/plugins/basic-plugin-creation/
Scroll down on that page to the section: "Using the each() Method"


text:
Q: R coding for ROC I am having a hard time translating the example command for an ROC to my dataset. This is for the pROC package
This is the example using data (aSAH)
roc(aSAH$outcome, aSAH$s100b)
roc(outcome ~ s100b, aSAH)

So...
aSAH should be replaced with the name of my data set or data subset. Correct?
outcome should be replaced by my outcome variable name. Correct?
s100b should be replaced with my predictor variable name. Correct? What if I do not have a single predictor variable but instead I am trying to determine the ROC of a tree? I did try to replace s100b with the name of my tree but that didn't work either.

A: In the roc command in R, the first argument is the real observed response and the second the scores of your model. In order to draw the ROC-curve, it's easiest to apply the roc curve and store the results in some other variable - let's call it analysis. Then, one needs to extract the sensitivity and 1-specificity from the variable analysis because that's what you need for the ROC-curve. This can be done in the plot command:
plot(1-analysis$specificities,analysis$sensitivities,type="l")

Please have look at the picture and how an outcome could look like in R. Below the picture, you can find the R-code for this curve and apply it to your problem. Please note, at the beginning I simulated data.

rm(list = ls()) # clear work space
##Simulate Data
set.seed(123456)
n <- 10000
q <- 0.8

#Simulate predictions
Real <- c(sample(c(0,1), n/2, replace = TRUE, prob = c(1-q,q)),
    sample(c(0,1), n/2, replace = TRUE, prob = c(0.7,0.3)))

#Simulate Response
p <- c(rep(seq(0.4,0.9, length=100), 50),
rep(seq(0.2,0.6, length=100), 50))
p <- data.frame(cbind(Real, p))

#install and load package
install.packages("pROC")
library(pROC)

#apply roc function
analysis <- roc(response=p$Real, predictor=p$p)

#Plot ROC Curve
plot(1-analysis$specificities,analysis$sensitivities,type="l",
ylab="Sensitiviy",xlab="1-Specificity",col="black",lwd=2,
main = "ROC Curve for Simulated Data")
abline(a=0,b=1)
abline(v = opt_t) #add optimal t to ROC curve


text:
Q: using and consuming typescript npm modules So I want to write shared code in typescript, make an npm package of it and be able to install it..
So I tried writing an external lib like this :
export class Lib {
   constructor(){

   }

   getData(){
      console.log('getting data from lib');
   }

}
Running npm link on external lib
And running npm link "package" in consuming apps directory, to have it appear in it's node_modules
consuming-app
   index.ts
   node_modules/
       external-package-with-typescript

index.ts is simple it just looks like :
import { Lib } from 'external-package-with-typescript'

var l = new Lib();

Then I try to bundle it all with
browser index.ts -p tsify --global --debug > bundle.js

This results in an error from the external package
'import' and 'export' may appear only with 'sourceType: module'

I can get it to work with https://github.com/basarat/ts-npm-module-consume
But that produces an output that looks like
consuming-app/ index.ts
external-package-with-typescript/ index.ts

Which is of no value to me as I want one .js file that I can include in index.html
Ideas anyone?

A: Have you tried using declare instead of export?


text:
Q: C++ choose overloaded constructor for a stack object by condition I want something like this:
if (customLocation.isEmpty())
{
    KUrl url;
}
else
{
    KUrl url(customLocation);
}
/* use url */

A: Any reason you can't do
KUrl url;
if (!customLocation.isEmpty())
{
    url = KUrl(customLocation);
}
/* use url */

or
KUrl url = customLocation.isEmpty() ? KUrl() : KUrl(customLocation);

A: The usual C++ constructs intentionally create a very tight coupling between allocation and initialization. Thus, ordinarily you would need to use dynamic allocation to be able to dynamically specify the constructor to use. And dynamic allocation is probably some orders of magnitude more inefficient than the slight overhead that you're trying to avoid…
However, with C++11 you can use aligned storage and placement new.
The catch is that the KUrl class will most likely use dynamic allocation internally, and then all that the optimization accomplishes is to waste programmer's time: both your time initially, and the time of anyone later maintaining the code.

A: Here you have no copy of KUrl being done
boost::optional<KUrl> ourl;
if(customLocation.isEmpty()) {
  ourl = boost::in_place();
} else {
  ourl = boost::in_place(customLocation);
}

KUrl &url = *ourl;

Fun aside, I would recommend Jacks solutions (if it works with your type) :)

A: Any reason why this won't work?
KUrl url;
if (!customLocation.isEmpty())
    url = customLocation;

A: KUrl url;

if (!cusomLocation.isEmpty())
{
    url = KUrl( customLocation );
}


text:
Q: Sum of two maximum patterns in linux file I am a newbie in linux. Need help for a command.
I have file in linux with following values:
2-1
2-10
2-11
2-12
2-2
2-3
1-1
1-10
1-11
1-2
1-3
1-9

Needed output needed is 23. Sum of maximum from 1- & 2- pattern i.e. 11 from 1-11 & 12 from 2-12

A: awk -F"-" 'BEGIN{a=0; b=0;} {if(int($1)==1 && int($2)>a){a=int($2)}; if(int($1)==2 && int($2)>b){b=int($2)}}END{print a+b}' file

output:
23

A: Another awk using ternary operator
awk -v FS='-' '{m1=($1==1?(m1>$2?m1:$2):m1);m2=($1==2?(m2>$2?m2:$2):m2)}END{print m1+m2}' file

A: sort + awk pipeline:
sort -t- -k2 -n file | awk -F'-' '{a[$1]=$2}END{ print a[1]+a[2] }'

The output:
23

A: $ awk -F'-' '{max[$1] = ($2 > max[$1] ? $2 : max[$1])} END{for (key in max) sum+=max[key]; print sum}' file
23

A: $ awk -F- 'a[$1]<$2{a[$1]=$2}END{for(i in a)s+=a[i]; print s}' infile
23


text:
Q: Redirect returns "Object moved to" I have a problem. When I try to redirect user to non-http URL from MVC action, it returns:

Object moved to here.

Full response (from Fiddler):
HTTP/1.1 301 Moved Permanently
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: myGame-app://test.somespecificdata
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcUGlvdHJcRGVza3RvcFxUYWtlc0NhcmVcVGFrZXNDYXJlXERvY3RvcnNcRWRvY3RvclxDb25zdWx0YXRpb25cMTkx?=
X-Powered-By: ASP.NET
Date: Thu, 18 Jun 2015 18:19:35 GMT
Content-Length: 457

<title>Object moved</title>

Object moved to here.

My action (with pseudo code):
[HttpGet]
public ActionResult Consultation(int id)
{
      //.. specific business logic
      if(IsMobile()){
          return RedirectPermanent("myGame-app://test.somespecificdata");
      }
      else{
          return View("AboutGame", SomeSpecificModel);
      }
}

The same situation is with return Redirect() instead of return RedirectPermanent().
My main goal is to redirect a user who uses the mobile browser to URL with special protocol (not http). This special protocol (myGame-app://) runs my mobile app according to this Stack discussion. How can I achieve this, without information Object moved to here?
Regards

A: The Redirect/RedirectPermanent methods add a body to the response containing the "moved here"-HTML.
If you want an "empty" response just set the response yourself:
HttpContext.Current.Response.Redirect("url", false);
HttpContext.Current.Response.StatusCode = 301;
HttpContext.Current.ApplicationInstance.CompleteRequest();

Be aware that the rest of your logic after this will be executed, so make sure nothing else (filters etc) that might redirect the response again happens after setting this.


text:
Q: Finding the angular velocity of a rod hit at a distance from its pivot A 1m long, 2kg stick is nailed to the wall with a single nail, allowing it to pivot and freely rotate at the end. A 1kg ball, with speed 3m/s makes contact with the stick at some distance x (unknown) below the pivot point. The ball collides elastically with the stick, and stops dead after collision.

*

*Find the stick's resulting initial angular velocity.

*Find the distance x. (Hint: conserve L)

I'm having a lot of difficulty with this problem and I don't know what I'm missing. I know that kinetic energy is conserved so $\ \Delta KE=\frac{1}{2}mv^2-\frac{1}{2}I\omega^2=0$ and that $\ I_{end}=\frac{1}{3}Ml^2$ which in this case is $\ \frac{1}{3}*2kg*1m^2=\frac{2}{3}$, but yet i'm still missing something crucial to figure out how to caculate $\omega$ and $x$.
Any help would be greatly appreciated.

A:
I know that kinetic energy is conserved so $\ \Delta
 KE=\frac{1}{2}mv^2-\frac{1}{2}I\omega^2=0$ and that $\
 I_{end}=\frac{1}{3}Ml^2$ which in this case is $\
 \frac{1}{3}*2kg*1m^2=\frac{2}{3}$

You are looking for $\omega (= y)$
from conservation of $KE = (1*3^2/2)$you know that $\frac{1}{2}mv^2-\frac{1}{2}I\omega^2=0\rightarrow 1*3^2 = y^2 2/3\rightarrow y^2 =3*3^2/2$,
therefore you already know the value of the angular velocity $\omega= y$

Now, if you know the rules of elastic collision you know that the cue ball stops dead when the object ball has same mass (in this case = 1Kg)
You can find the distance x considering that the point of the rod hit by the ball will rotate with angular velocity $\omega = 3.67423$ r/s but with velocity of $v=\omega*r (=x) $ m/s and that it will have the same Ke*(2) = 9 , therefore $x^2= 2mv_0^2/\omega^2$ $$x =\sqrt{2Ke/y^2}$$

A: Use the hint in your second bullet point. The ball has angular momentum about the pivot point before it strikes the stick.

A: Your conservation of kinetic energy equation should help you solve the for the stick's initial angular velocity.
Think of it this way:  the tennis ball has initial momentum since it is moving, right?  And the stick is not moving, so it has no momentum.  At the end of the collision, the tennis ball stops completely, so it has no momentum, but the stick is now moving, so it has angular momentum.
Thus, your equation solves it perfectly.  Energy of ball at beginning = energy of rod at end.


text:
Q: how to automatically escape the path I have a path string like c:\user\test\test.jpg, how can I make it c:\\user\\test\\test.jpg?

A: you would only require escaping if you are using string literal in the code. why would you require automatic escaping anyways. you can use @ before the literal that requires no escaping.

A: Try this:
string path = @"c:\user\test\test.jpg";

A: string s = s.Replace(@"\", @"\\");

A: You can always try something like: System.Text.RegularExpressions.Regex.Unescape, of course that will do all escaped characters.


text:
Q: How to capitalize the last character of a string vector? I just started using R and I wanted to know how to create a function that will capitalize the last character of a string vector.

A: Base R regex:
words <- c("hello", "world")

# Last character of last word in vec element:
gsub("(\\w$)", "\\U\\1", words, perl = TRUE)

sentences <- c("hello world", "hello friend")

# Last character of sentence:
gsub("(\\w$)", "\\U\\1", sentences, perl = TRUE)

# Last character of each word in the sentence:
gsub("(\\w\\s+|\\w$)", "\\U\\1", sentences, perl = TRUE)


text:
Q: Attempts to get path of a resource result in NullPointerExceptions Changing path to hardcoded string - works, however this is not an option.
Test fails because it cannot find the resource, even though it's there.
Cities.java
    /*
This Singleton Class loads cities.json into an ArrayList and by using a boolean method isCity can tell if passed
String is city or not.
 */
public class Cities
{
    private static Cities single_instance = null;
    ArrayList<City> cityArrayList;

    private Cities() throws IOException
    {
        String path = new ClassPathResource("cities.json").getFile().getAbsolutePath();
        Gson gson = new Gson();
        Type cityListType = new TypeToken<ArrayList<City>>()
        {
        }.getType();
        cityArrayList = gson.fromJson(new FileReader(path), cityListType);
    }

    public static Cities getInstance() throws IOException
    {
        if (single_instance == null)
            single_instance = new Cities();
        return single_instance;
    }

    public boolean isCity(String cityToLookFor)
    {
        for (City city : cityArrayList)
        {
            if (city.getName().strip().equalsIgnoreCase(cityToLookFor))
            {
                return true;
            }

        }
        return false;
    }
}

CitiesTest.java
class CitiesTest
{
    Cities cities = Cities.getInstance();

    CitiesTest() throws IOException {}

    @Test
    void isCityTest2()
    {
        assertFalse(cities.isCity("USA"), "City not found in localDbase");
    }

    @Test
    void isCityTest3()
    {
        assertEquals(true, cities.isCity("Paris"), "City not found in localDbase");
    }
}

pom.xml
https://pastebin.com/fMQNknM1

java.io.FileNotFoundException: class path resource [cities.json] cannot be resolved to URL because it does not exist

at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:195)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:150)
at gr.serresparc.palantir.repository.Cities.<init>(Cities.java:24)
at gr.serresparc.palantir.repository.Cities.getInstance(Cities.java:35)
at gr.serresparc.palantir.repository.CitiesTest.<init>(CitiesTest.java:12)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at

A: Remove the <targetPath>..</targetPath> from the resources section of the pom.xml. You might as well remove the whole resources section.
The executed test code is not looking for the file in within src/main/resources but within target/classes. The classpath resource cities.json needs to appear there.
Please be also aware that if the application is shipped as a spring boot jar file then it is not possible to read a classpath resource as file.

A: Try to change the code as below,
String path = new ClassPathResource("classpath:cities.json").getFile().getAbsolutePath();

Please, note I have added classpath: in front of cities.json.
EDIT
You can also get the InputStreamReader like below, First, inject ResourceLoader.
@Autowired
ResourceLoader resourceLoader;

Then load json file just like below:
cityArrayList = gson.fromJson(new JsonReader(resourceLoader.getResource("classpath:cities.json").getInputStream()), cityListType);


text:
Q: SMTP Error could not authenticate and SMTP Error failed to connect to server(0) I'm getting this SMTP error when using the newest PHPMailer release:
SMTP Error: Could not authenticate.

I've tried using SSL instead of TLS with port number 465. OpenSSL is already loaded in the config file, and I've looked through the troubleshooting guide none of this has made a difference, what exactly is wrong with my code? One thing I'm not sure of is including the OAuth2 provider class with this :
use League\OAuth2\Client\Provider\Google;

There's no file path for that, should I change this? Also, when I change encryption to $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; and now I get this : SMTP ERROR: Failed to connect to server: (0).
Here's the code:
    class gmail_xoauth

    {
        public static function sendMail($subject,$body,$address)
        {

    $mail = new PHPMailer();
    $mail->isSMTP();

    $mail->SMTPDebug = SMTP::DEBUG_CLIENT;
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->SMTPAuth = true;
    $mail->AuthType = 'XOAUTH2';

    //Fill in authentication details here
    //Either the gmail account owner, or the user that gave consent
    $email = 'myemail@gmail.com';
    $clientId = 'clientid';
    $clientSecret = 'clientSecret';
    //Obtained by configuring and running get_oauth_token.php
    //after setting up an app in Google Developer Console.
    $refreshToken = 'refreshToken';
    //Create a new OAuth2 provider instance
    $provider = new Google(
        [
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
        ]
    );
    //Pass the OAuth provider instance to PHPMailer
    $mail->setOAuth(
        new OAuth(
            [
                'provider' => $provider,
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
                'refreshToken' => $refreshToken,
                'username' => $email,
            ]
        )
    );
    //Set who the message is to be sent from
    //For gmail, this generally needs to be the same as the user you logged in as
    $mail->setFrom($email, 'me');
    //Set who the message is to be sent to
    $mail->addAddress($address, 'John Doe');
    //Set the subject line
    $mail->Subject = $subject;
    //Read an HTML message body from an external file, convert referenced images to embedded,
    //convert HTML into a basic plain-text alternative body
    $mail->CharSet = PHPMailer::CHARSET_UTF8;
    $mail->msgHTML(file_get_contents('PHPMailer/PHPMailer-master/examples/contentsutf8.html'), __DIR__);
    //Replace the plain text body with one created manually
    $mail->AltBody = 'This is a plain-text message body';
    //Attach an image file

    $mail->addAttachment('PHPMailer/PHPMailer-master/examples/images/phpmailer_mini.png');
    //send the message, check for errors
    if (!$mail->send()) {
        echo 'Mailer Error: '. $mail->ErrorInfo;
    } else {
        echo 'Message sent!';
    }
    }
    }

This is the full error

    SERVER -> CLIENT: 220 smtp.gmail.com ESMTP w67sm7347917yww.16 - gsmtp
    CLIENT -> SERVER: EHLO localhost
    SERVER -> CLIENT: 250-smtp.gmail.com at your service, [108.203.6.59]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
    CLIENT -> SERVER: STARTTLS
    SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
    CLIENT -> SERVER: EHLO localhost
    SERVER -> CLIENT: 250-smtp.gmail.com at your service, [108.203.6.59]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
    SMTP Error: Could not authenticate.
    CLIENT -> SERVER: QUIT
    SERVER -> CLIENT: 221 2.0.0 closing connection w67sm7347917yww.16 - gsmtp
    SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
    Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/TroubleshootingEmail sent!


text:
Q: The view from inside of a mirrored tetrahedron Suppose you were standing inside a regular tetrahedron $T$ whose
internal face surfaces were perfect mirrors.
Let's assume $T$'s height is $3{\times}$ yours, so that your
eye is roughly at the centroid,
and that you look perpendicular to a face:

My question is:

Q. What do you see? Either qualitatively; or if anyone can find an image, that would be revealing.

Asking the same question for the view inside a mirrored cube is
easier to visualize: the opposing parallel square-face mirrors would produce
a "house of mirrors" effect (in three perpendicular directions).

(Image from this link.)

Addendum 1 (21Nov2014).
To respond to Yoav Kallus' (good) question, here is a quote from
Handbook of Dynamical Systems, Volume 1, Part 1.
(ed. B. Hasselblatt, A. Katok), 2010, p.194:

Addendum 2 (24Nov2014).
Now that we have Ryan Budney's amazing POV-ray images,
I would appreciate someone making an attempt to describe
his $32$-reflection image qualitatively.
I find it so complex that this may be an instance
where a thousand words might be superior to one picture.

A: There is a software by Jeff Weeks, Curved Spaces which allows for flying through various such spaces. It includes a mirrored tetrahedron but with $\pi/2$ dihedral angles. One can construct own spaces though, by providing a list of 4$\times$4 matrices generating the (linearized version of the) transformation group.
Snapshot:

(obviously not that inspiring, you have to see it in motion to really appreciate)
Addendum
After several unsuccessful attempts to realize the Euclidean tetrahedron in the program I contacted Jeff Weeks; it turned out that unfortunately Curved Spaces cannot handle noncompact groups.
Jeff also mentioned the spherical case - regular spherical tetrahedron with dihedral angles $2\pi/5$, whose face reflections fill up the 600-cell. It occurred to me that this is a rare situation when the Euclidean case (dihedral angle $\arccos 1/3$) is the most pathological between the nearest "non-pathological" cases - spherical case mentioned above and the hyperbolic case (dihedral angle $\pi/3$). A wonderful picture of the latter may be found in the Wikipedia chapter "Order-6 tetrahedral honeycomb"

An additional question then - is the Euclidean case in any sense a quotient of this?

A: Here are a couple pictures.  If you'd like to do more, I created this with a simple povray script.  Feel free to e-mail me and I'll send it to you.
With four reflections.

With 8 levels of reflections.

One with 24 reflections.

And one with 32 reflections, and each mirror having a slightly different tint, a red sphere, and a slightly wider viewing angle.

Here is the view from inside a mirrored tetrahedron, near one of the vertices, looking towards the opposite face.  Near the centre of each face is a number indicating which vertex the triangle is opposite.  The sequence shows the triangles becoming more reflective and less opaque. The field of view is 120 degrees so there is a little bit of lens distortion at the fringes of the image.

And here is the link to the scripts for the tetrahedra with the numbering and without the spheres.

A: I don't know why this question got bumped to the front page, but since it did, I might as well answer that I made a movie of this a long time ago, showing the view inside a (Euclidean) regular tetrahedron with reflective faces (tinted red, green, blue and white, and intrinsically luminous so we can see something!), as well as what it's like to move along a straight line "through" the mirrors (equivalently, a billiard ball path, but with the view flipped at each reflection so that we seem to go through the mirror).
In comparison, this video, made by my friend Vincent Nesme¹, shows a rendering of the 600-cell as a regular tiling of the constantly curved 3-sphere by 600 (spherical!) regular tetrahedra, and moving in a straight line (great circle) in this geometry.

*

*I had previously made such a video by using gnomonic projection to map the lines into Euclidean space and feeding the result into POVray, but while this correctly projects the lines, it does not correctly project their thickness.  Vincent was much more patient than I was and wrote his own raytracer for this.


text:
Q: How to compute CRC checksum in R compatible with output with Linux `cksum` command I am downloading files from a site that provides checksums (as decimals) computed with the Linux cksum command.
In R I can do a CRC-32 checksum in decimal format with:
library(digest)
strtoi(digest(file_path, algo="crc32", file=TRUE), base=16L)

Is there a similar command I can use to get a checksum for a file that is compatible with the Linux cksum command? I need a cross-platform approach that preferably does not require software external to R. The wikipedia page on cksum states that:
"The standard cksum command, as found on most UNIX-like OS (including GNU/Linux, *BSD, Mac OS X, and Solaris) uses a CRC algorithm based on the ethernet standard frame check and is therefore interoperable between implementations. It is not however compatible with the CRC-32 calculation."
I have also found cksum in the bitops package, but I am unclear how best to compute a checksum for a file using that function.

A: Get the file size, read into a raw vector, convert to char, use bitops' cksum:
cksumfile = function(f){
   size = file.info(f)$size
   c = file(f,"rb")
   csum = cksum(rawToChar(readBin(c,raw(),n=size)))
   close(c)
   csum
}

test:
> cksumfile("/etc/passwd")
[1] 1594741334
> system("cksum /etc/passwd")
1594741334 1953 /etc/passwd

This edited version opens and closes the connection explicitly to stop a warning.


text:
Q: Amazon Pay ignores javascript mixins from other modules When using Amazon Pay during the checkout process, seemingly any module that uses Javascript mixins to capture additional fields from the checkout page and pass them to the POST request for processing get skipped, resulting in the data never being sent to the server for processing.
For example, we're in the process of installing the GDPR module from Plumrocket and testing it on our development site.  We've added a Consent Checkbox for the Privacy Policy to the checkout process.  This adds a little checkbox just bellow the payment method to accept the Privacy Policy.  If it's not checked, it won't let you click the checkout button.  But when you check it and hit submit there's a server side check for the box, and that is throwing an error because the checkbox is never sent through the payment[extension_attributes][consent_ids] key during the POST.
So I opened up the console and started throwing some breakpoints in the javascript.  And from what I can tell, none of Plumrocket GDPR's mixins get ran after hitting the submit button.  In contrast, they work just fine when using PayPal, Auth.net/Credit Card, or Gift Card payment methods.
Now, I know what you might be thinking, that "It's probably just an issue with GDPR.", but we have another website where we are setting up Amazon Pay and it's causing issues with another module that tries to capture additional fields in the payment[extension_attributes] key.
This module adds a text box to capture a Delta SkyMiles account number and was built mostly following this stack answer.  It's a pretty straight forward little module that does what it needs to do and like the GDPR, works on every payment method except Amazon Pay.  And just like the GDPR, none of the mixins run, and the field ultimately is not added to the payment[extension_attributes] key during the POST.
So, my hope here is that someone has some insight as to what might be happening here.  Because I'm at a loss at this point.  This does not seem like the behavior I would expect from a proper payment method.
Edit 9/25
I've learned after some testing that this only happens to JS mixins applied to the payment_methods section of the checkout and are acting on Magento_Checkout/js/action/place-order.  We recently added a checkbox to the shipping_methods section of checkout that acts on Magento_Checkout/js/action/set-shipping-information and that one works fine when using Amazon Pay and the checkbox is properly captured for the order.

A: I can't believe I didn't catch this sooner.  I'm going to blame my newness to Magento, but for everyone else who might be struggling with this issue and since I couldn't find it anywhere else on the greater internet...
The Amazon Payment module that comes included with Magento 2.2.x, overrides the javascript used in the place-order action.  So adding your mixin to the standard Magento_Checkout/js/action/place-order will not work with Amazon Pay.  You must also include you mixin with Amazon Pay's version of place-order like so:
/**
 * app/code/[vendor]/[module]/view/frontend/web/requirejs-config.js
 */

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/action/place-order': {
                'Vendor_Module/js/order/place-order-mixin': true
            },
            'Amazon_Payment/js/action/place-order': {
                'Vendor_Module/js/order/place-order-mixin': true
            }
        }
    }
};

That's it.  It's that easy to get everything working again.  I hope this helps someone else, because boy do I sure wish this was mentioned somewhere.


text:
Q: tokenizer or split string at multiple spaces in java I need to tokenize a string where ever there is more than one space.
for instance
"HUNTSVILLE, AL                   30   39.8   44.3   52.3"

becomes
"HUNTSVILLE, AL","30","39.8","44.3","52.3"

StringTokenizer st = new StringTokenizer(str, "   ");

just tokenizes any whitespace, and I can't figure out a regex to do what I need.
Thanks

A: Try this:
String s = "HUNTSVILLE, AL                   30   39.8   44.3   52.3";
String[] parts = s.split("\\s{3,}");
for(String p : parts) {
  System.out.println(p);
}

The \s matches any white space char, and {3,} will match it 3 or more times.
The snippet above would print:
HUNTSVILLE, AL
30
39.8
44.3
52.3

A: Can't you use split?
String[] tokens = string.split("  ");

You have to filter empty entries though.

A: Try this way:
String[] result = "HUNTSVILLE, AL                   30   39.8   44.3   52.3".split("[ ]{2,}");
     for (int x=0; x<result.length; x++)
         System.out.println(result[x]);

[ ] - Represents space
{2,} - Represents more than 2

A:  /*
 * Uses split to break up a string of input separated by
 * whitespace.
 */
import java.util.regex.*;

public class Splitter {
    public static void main(String[] args) throws Exception {
        // Create a pattern to match breaks
        Pattern p = Pattern.compile("[ ]{2,}");
        // Split input with the pattern
        String[] result =
                 p.split("one,two, three   four ,  five");
        for (int i=0; i<result.length; i++)
            System.out.println(result[i]);
    }
}


text:
Q: How to Merge Consecutive timeline in Array of Object JavaScript? I have got an array of objects where different objects has time slot, if there are consecutive time slot then I want to merge it as one and keep other the same and later the final result has to be sort as well, for better understanding please look at the input and output I want.
Input:
 const timeArray = [
      { timeValue: "10:00am-11:00am" },
      { timeValue: "11:00am-12:00pm" },
      { timeValue: "12:00pm-1:00pm" },

      { timeValue: "3:00pm-4:00pm" },
      { timeValue: "4:00pm-5:00pm" },
      { timeValue: "5:00pm-6:00pm" },
      { timeValue: "10:00pm-11:00pm" },
      { timeValue: "7:00pm-8:00pm" },
      { timeValue: "8:00pm-9:00pm" }
    ];

Output: I want
   const new = [
      { timeValue: "10:00am-1:00pm" },
      { timeValue: "3:00pm-6:00pm" },
      { timeValue: "7:00pm-9:00pm" },
      { timeValue: "10:00pm-11:00pm" }
    ];

What I did I just aligned the consecutive time slot I have trying from hours I got no clue, Please help I will be very thankful

A: In this case, i thing that just using recursive function, to  merging step by step.

const timeArray = [{
    timeValue: "10:00am-11:00am"
  },
  {
    timeValue: "11:00am-12:00pm"
  },
  {
    timeValue: "12:00pm-1:00pm"
  },

  {
    timeValue: "3:00pm-4:00pm"
  },
  {
    timeValue: "4:00pm-5:00pm"
  },
  {
    timeValue: "5:00pm-6:00pm"
  },
  {
    timeValue: "10:00pm-11:00pm"
  },
  {
    timeValue: "7:00pm-8:00pm"
  },
  {
    timeValue: "8:00pm-9:00pm"
  }
];

const recursiveFunction = (timeArray, stop) => {
  if (!stop) {
    return timeArray;
  }
  const output = [];
  let isLastAdd = false;
  let isHaveSome = false;

  for (let i = 1; i < timeArray.length; i++) {

    const currentTimeValue = timeArray[i].timeValue;
    const arrayCurrent = currentTimeValue.split("-");
    const currentFirTime = Number(arrayCurrent[0].split(":")[0]);
    const currentSecTime = Number(arrayCurrent[1].split(":")[0]);
    const currentSufixo = currentTimeValue.split("-")[0].split(":")[1];

    const prevTimeValue = timeArray[i - 1].timeValue;
    const arrayPrev = prevTimeValue.split("-");
    const prevFirTime = Number(arrayPrev[0].split(":")[0]);
    const prevSecTime = Number(arrayPrev[1].split(":")[0]);
    const prevSufixo = prevTimeValue.split("-")[1].split(":")[1];

    if (prevSecTime === currentFirTime) {
      output.push({
        timeValue: `${prevFirTime}:${prevSufixo}-${currentSecTime}:${currentSufixo}`
      });
      i++;

      if (!(i < timeArray.length)) {
        isLastAdd = true;
      } else {
        isLastAdd = false;
      }
      isHaveSome = true;

    } else {
      output.push({
        timeValue: prevTimeValue
      });
      isLastAdd = false;
    }

  }
  if (!isLastAdd) {
    output.push(timeArray.at(-1));
  }
  return recursiveFunction(output, isHaveSome);
}

const result = recursiveFunction(timeArray, true);
console.log(result);
result.sort((a, b) => a.timeValue.split("-")[1].split(":")[0] - b.timeValue.split("-")[1].split(":")[0]);
console.log(result);

to sort use
result.sort((a, b) => a.timeValue.split("-")[1].split(":")[0] - b.timeValue.split("-")[1].split(":")[0])

A: This is the link to Codesandbox, You'll find the answer there.
you can merge different groups of time slots.


text:
Q: Preserving data more than once I am writing some code in Stata and I have already used preserve once. However, now I would like to preserve again, without using restore.
I know this will give an error message, but does it save up to the new preserve area?

A: No, preserving twice without restoring in-between simply throws an error:
sysuse auto, clear

preserve
drop mpg

preserve
already preserved
r(621);

However, you can do something similar using temporary files. From help macro:

"...tempfile assigns names to the specified local macro names that may be used as names for temporary files.  When the program or do-file concludes, any
  datasets created with these assigned names are erased..."

Consider the following toy example:
tempfile one two three

sysuse auto, clear
save `one'

drop mpg
save `two'

drop price
save `three'

use `two'
list price in 1/5

     +-------+
     | price |
     |-------|
  1. | 4,099 |
  2. | 4,749 |
  3. | 3,799 |
  4. | 4,816 |
  5. | 7,827 |
     +-------+

use `one'
list mpg in 1/5

     +-----+
     | mpg |
     |-----|
  1. |  22 |
  2. |  17 |
  3. |  22 |
  4. |  20 |
  5. |  15 |
     +-----+


text:
Q: foreign key constraint fails - hibernate I have problem when i try add data to table USERS. First my DB and classes.
DB structure:
CREATE TABLE IF NOT EXISTS `admins` (
  `ADMIN_ID` int(10) unsigned NOT NULL AUTO_INCREMENT ,
  `USERNAME` varchar(45) NOT NULL,
  `PASSWORD` varchar(45) NOT NULL,
  `AUTHORITY` varchar(45) NOT NULL,
  PRIMARY KEY (`ADMIN_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `lecturers` (
  `LECTURER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `SURNAME` varchar(45) NOT NULL,
  `TITLES` varchar(45) NOT NULL,
  `USERNAME` varchar(45) NOT NULL,
  `PASSWORD` varchar(45) NOT NULL,
  `AUTHORITY` varchar(45) NOT NULL,
  `LEC_DESCRIPTION` varchar(100) NOT NULL,
  PRIMARY KEY (`LECTURER_ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=40;

CREATE TABLE IF NOT EXISTS `roles_name` (
  `role_id` int(1) NOT NULL,
  `authority` varchar(45) NOT NULL,
  UNIQUE KEY `role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `roles_name` (`role_id`, `authority`) VALUES
(1, 'ROLE_ADMIN'),
(2, 'ROLE_USER'),
(3, 'ROLE_LECTURER');

CREATE TABLE IF NOT EXISTS `users` (
  `USER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT ,
  `NAME` varchar(45) NOT NULL,
  `SURNAME` varchar(45) NOT NULL,
  `username` varchar(45) NOT NULL,
  `PASSWORD` varchar(45) NOT NULL,
  `USER_DESCRIPTION` varchar(100) NOT NULL,
  `AUTHORITY` varchar(45) NOT NULL,
  `ENABLED` tinyint(1) NOT NULL,
  PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=50000;

CREATE TABLE IF NOT EXISTS `roles_map` (
  `rm_id` int(10) unsigned NOT NULL,
  `user_id` int(10) unsigned,
  `admin_id` int(10) unsigned,
  `lecturer_id` int(10) unsigned,
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `role_id` int(1) NOT NULL,
  PRIMARY KEY (`rm_id`),
  FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`),
  FOREIGN KEY (`lecturer_id`) REFERENCES `lecturers` (`lecturer_id`),
  FOREIGN KEY (`admin_id`) REFERENCES `admins` (`admin_id`),
  FOREIGN KEY (`role_id`) REFERENCES `roles_name` (`role_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

RolesMap.java
@Entity
@Table(name = "roles_map")
public class RolesMap {
    @Id
    @Column(name = "RM_ID", unique = true, nullable = false)
    private int rm_id;
    //@Column(name = "USER_ID", unique = true)
    //private int user_id;
    @Column(name = "ADMIN_ID", unique = true)
    private int admin_id;
    @Column(name = "LECTURER_ID", unique = true)
    private int lecturer_id;
    @Column(name = "USERNAME", unique = true, nullable = false)
    private String username;
    @Column(name = "PASSWORD", unique = true, nullable = false)
    private String password;
    @Column(name = "ROLE_ID", unique = true, nullable = false)
    private int role_id;
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name = "user_id")
    private User user;

     //getters and setters

}

User.java
@Entity
@Table(name = "users")
public class User {
    @Id
    @Column(name = "USER_ID", unique = true, nullable = false)
    private int user_id;
    @Column(name = "NAME", nullable = false)
    private String name;
    @Column(name = "SURNAME", unique = true, nullable = false)
    private String surname;
    @Column(name = "USERNAME", unique = true, nullable = false)
    private String username; // zamiast username
    @Column(name = "PASSWORD", unique = true, nullable = false)
    private String password;
    @Column(name = "USER_DESCRIPTION", nullable = false)
    private String userDescription;
    @Column(name = "AUTHORITY", nullable = false)
    private String authority = "ROLE_USER";
    @Column(name = "ENABLED", nullable = false)
    private int enabled;

    @OneToMany(mappedBy="user", cascade=CascadeType.ALL)
    private List <RolesMap> rolesMap;

      //getters and setters
}

adding method
public String addUser() {

    Session sess = null;

    try {
        sess = UserDao.getSessionFactory().openSession();
        sess.beginTransaction();
        RolesMap roles = new RolesMap();
        //roles.setrUser(user);
        User user = new User();
        roles.setPassword(getPassword());
        roles.setRole_id(2);
        roles.setUsername(getUsername());

        user.setName(getName());
        user.setSurname(getSurname());
        user.setUsername(getUsername());
        user.setPassword(getPassword());
        user.setUserDescription(getUserDescription());
        user.setAuthority(getAuthority());
        user.setEnabled(getEnabled());
        user.setRolesMap(new ArrayList<RolesMap>());
        user.getRolesMap().add(roles);
        sess.save(user);
        sess.getTransaction().commit();
        //getUserService().addUser(user);

        return SUCCESS;
    } catch (DataAccessException e) {
        e.printStackTrace();
    }

    return ERROR;
}

When I try use this method I have error:
Cannot add or update a child row: a foreign key constraint fails (soeOne2.roles_map, CONSTRAINT roles_map_ibfk_2 FOREIGN KEY (lecturer_id) REFERENCES lecturers (LECTURER_ID))
But I do not know why, because I'm trying to add data to the USER and ROLESMAP tables. I think when you add data to a table ROLESMAP/USER field lecturer_id and admin_id in ROLESMAP table shuld be NULL. Can anyone tell me what I'm doing wrong?

A: It is because lecturer_id=0 is NOT lecturer_id=null.
Your application try to save lecturer_id=0 and the database think that 0 is the ID of an item in table lecturers.
So the first workarround is to replace the int with Integer, so that you can assign lecturer_id = null
@Column(name = "LECTURER_ID", unique = true)
private Integer lecturer_id;

And I think you need this modification for all other references that work the same way.

The second point is, that the way you map references between entities is not the jpa (hibernate) way. I strongly recommend that you read something about mapping relations (OneToOne, OneToMany, ManyToOne, ManyToMany) For example the Hibernate Reference Chapter 7. Collection mapping and 8. Association Mappings


text:
Q: Расстояния в заголовке внутри колонки таблицы Есть файлы

* {
    margin: 0;
    padding: 0;
}

.hstyle {
    text-align: center;
}

.calltable tr td {
    border-spacing: 40px;
    padding-left: 5px;
    padding-right: 5px;
}

.calltable {
    margin: 15px;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Журнал вызовов</title>
    <link rel="stylesheet" type="text/css" href="calllog.css"></link>

Журнал вызовов

                №

                Дата/Время

                Входящий абонент

                Номер телефона

                Продолжительность

                Оператор абонента

                Стоимость вызова

*

*Почему border-spacing не срабатывает в шапке таблицы?

*Как выровнять содержимое ячеек шапки таблицы (1-я tr)?

A: Потому что это свойство таблицы, а не ячейки. Правда, не очень понятно, зачем Вам такие расстояния между ячейками - возможно, перед Вами какая-то другая задача стоит, а Вы не тем путём её решаете:

* {
    margin: 0;
    padding: 0;
}

.hstyle {
    text-align: center;
}

.calltable tr td {
    padding-left: 5px;
    padding-right: 5px;
    border: 1px solid red;
}

.calltable {
    margin: 15px;
    border: 1px solid black;
    border-spacing: 40px;
}

Журнал вызовов

            №

            Дата/Время

            Входящий абонент

            Номер телефона

            Продолжительность

            Оператор абонента

            Стоимость вызова


text:
Q: C# cannot get values from list of objects I have my main Program class that calls the StronyElementuStrukt procedure
List<object> monthlyPages = new List<object>();
monthlyPages =  StronyElementuStrukt(loginGuid, "8B35134E10A8432DB1A8C06A58427988");

Here is the procedure - a method that builds a list of xml nodes and returns it to the main Program class:
public static List<object> StronyElementuStrukt(string LoginGUID, string LinkGUID)
{
    List<object> listPages = new List<object>();

    XmlDocument document = new XmlDocument(); // tworzenie nowego obiektu - dokument xml z odpowiedzia serwera
    document.LoadXml(response.Result); //wczytywanie xmla z odpowiedzia serwera do obiektu
    XmlNode pageNode = document.SelectSingleNode("/IODATA/PAGES/PAGE"); //deklaracja noda xmlowego

    if (pageNode != null) //jeżeli PAGE node istnieje
    {
        XmlNodeList nodeList = document.SelectNodes("//PAGE");

        foreach (XmlNode node in nodeList)
        {
            listPages.Add(node);
        }
        return listPages;
    }
}

In the main Program Class I need to pick up value of xml id attribute, I'm trying to do it like this:
foreach (object monthlyPage in monthlyPages)
{
    Console.WriteLine(monthlyPage.Attributes["id"].Value);
}

The problem is that when I try to get the id I get the following error:

Error 6   'object' does not contain a definition for 'Attributes' and no
  extension method 'Attributes' accepting a first argument of type
  'object' could be found (are you missing a using directive or an
  assembly reference?)

Could you tell me how to reach to xml attributes in the foreach loop, please? Please ask if something is not clear enough.

A: Change the method to return a List<XmlNode>.
public static List<XmlNode> StronyElementuStrukt(string LoginGUID, string LinkGUID)
{
    List<XmlNode> listPages = new List<object>();

    XmlDocument document = new XmlDocument(); // tworzenie nowego obiektu - dokument xml z odpowiedzia serwera
    document.LoadXml(response.Result); //wczytywanie xmla z odpowiedzia serwera do obiektu
    XmlNode pageNode = document.SelectSingleNode("/IODATA/PAGES/PAGE"); //deklaracja noda xmlowego

    if (pageNode != null) //jeżeli PAGE node istnieje
    {
        XmlNodeList nodeList = document.SelectNodes("//PAGE");

        foreach (XmlNode node in nodeList)
        {
            listPages.Add(node);
        }
    }

    return listPages;
}

Then this will work.
List<XmlNode> monthlyPages = StronyElementuStrukt(
    loginGuid,
    "8B35134E10A8432DB1A8C06A58427988");

foreach (XmlNode monthlyPage in monthlyPages)
{
    Console.WriteLine(monthlyPage.Attributes["id"].Value);
}

Note that you could just change the foreach to declare monthlyPage as XmlNode instead of object and it will do a cast for you.  But it is better to be specific with the types you are putting into a generic collection.

A: I changed all occurences from List<object> to List<XmlNode>. So the code now looks like this:
Main Program:
List<XmlNode> monthlyPages = new List<XmlNode>();
monthlyPages =  StronyElementuStrukt(loginGuid, "8B35134E10A8432DB1A8C06A58427988");
foreach (XmlNodemonthlyPage in monthlyPages)
{
    Console.WriteLine(monthlyPage.Attributes["id"].Value);
}

Procedure:
    public static List<XmlNode> StronyElementuStrukt(string LoginGUID, string LinkGUID)
{
        List<XmlNode> listPages = new List<XmlNode>();

        XmlDocument document = new XmlDocument(); // tworzenie nowego obiektu - dokument xml z odpowiedzia serwera
        document.LoadXml(response.Result); //wczytywanie xmla z odpowiedzia serwera do obiektu
        XmlNode pageNode = document.SelectSingleNode("/IODATA/PAGES/PAGE"); //deklaracja noda xmlowego

        if (pageNode != null) //jeżeli PAGE node istnieje
        {
            XmlNodeList nodeList = document.SelectNodes("//PAGE");

            foreach (XmlNode node in nodeList)
            {
                listPages.Add(node);
            }
            return listPages;
        }
    }


text:
Q: Changing uitextfield return key type while editing I have 4 uitextfields that recognize when they are empty or complete. If complete they change their return key type to GO, else is the default one. The problem is the keyboard is not changing the key type even though i use the reloadinputview
- (void)viewDidLoad
{
    [super viewDidLoad];

    _fieldsArray = @[_nameField, _passwordField, _emailField, _usernameField];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    NSRange textFieldRange = NSMakeRange(0, [textField.text length]);

    //NSLog(@"%d", !(NSEqualRanges(range, textFieldRange) && [string length] == 0));

    [self signUpFieldsAreValid:(!(NSEqualRanges(range, textFieldRange) && [string length] == 0) && [self validateSignUpFields:textField])];
    [textField reloadInputViews];
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{

    [self signUpFieldsAreValid:NO];
    [textField reloadInputViews];
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    for (UITextField *aTextField in _fieldsArray) {
        if (aTextField.isFirstResponder) {

            aTextField.layer.borderWidth = 0.f;
            aTextField.layer.borderColor = nil;

        }
    }

    textField.layer.borderWidth = 1.f;
    textField.layer.borderColor = [UIColor colorWithRed:200.f/255.f green:0.f/255.f blue:4.f/255.f alpha:1.f].CGColor;

    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSUInteger fieldIndex = [_fieldsArray indexOfObject:textField];

    [_fieldsArray[(fieldIndex + 1) % 4] becomeFirstResponder];

    return YES;
}

- (BOOL)validateSignUpFields:(UITextField *)firstResponder
{
    for (UITextField *aTextField in _fieldsArray) {
        if (!aTextField.text.length && ![aTextField isEqual:firstResponder]) {
            return NO;
        }
    }

    return YES;
}

- (void)signUpFieldsAreValid:(BOOL)valid
{
    NSLog(@"%d", valid);
    for (UITextField *aTextField in _fieldsArray) {

        if (valid) {
            aTextField.returnKeyType = UIReturnKeyGo;
        }
        else {
            aTextField.returnKeyType = UIReturnKeyDefault;
        }
    }
}

A: Try this.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    NSString *newStr=[textField.text stringByReplacingCharactersInRange:range withString:string];
    if([newStr length] > 0)
    {
        textField.returnKeyType = UIReturnKeySearch;
    }
    else
    {
        textField.returnKeyType = UIReturnKeyDefault;
    }
    [textField resignFirstResponder];
    [textField becomeFirstResponder];
    return YES;
}

A: According to the docs, the reloadInputViews only affects custom input views, not the standard keyboard.
What I've done to solve this problem is to call resignFirstResponder then becomeFirstResponder. This will update the keyboard without any animation:
Instead of:
[textFiled reloadInputViews];

do:
[textField resignFirstResponder];
[textField becomeFirstResponder];

A: I used the following after changing the returnKeyType and it seemed to work very well in iOS7 and iOS6.1:
if ([self.textfieldOne isFirstResponder]) {
    [self.textfieldOne reloadInputViews];

}

A: In Swift 5
 // Change returnKeyType based on textField text
func textFieldDidChangeSelection(_ textField: UITextField) {
    // Change return key to Done when text entered
    if textField.text != "" {
        textField.returnKeyType = .done
        textField.reloadInputViews()
    }
    // Change back to default style if all text removed
    else {
        textField.returnKeyType = .default
        textField.reloadInputViews()
    }

A: I used the following after changing the returnKeyType and it seemed to work very well in iOS7 and iOS6.1:
if ([self.textfieldOne isFirstResponder]) {
    [self.textfieldOne reloadInputViews];

}


text:
Q: Destructuring array into an object I am trying to do array destructuring in javascript and encounter some very puzzling behavior
Here's the code I have --
 let res = {
            start: {},
            end: {},
        };
[res.start.hour, res.start.minute] = [7, 20]
[res.end.hour, res.end.minute] = [17, 30]
console.log(res)

The output is
{ start: { hour: 17, minute: 30 }, end: {} }

For some reason, [17, 30] were assigned to res.start, instead of res.end.
Furthermore, if I add a console.log statement like below
 let res = {
            start: {},
            end: {},
        };
[res.start.hour, res.start.minute] = [7, 20]
console.log(JSON.stringify(res));
[res.end.hour, res.end.minute] = [17, 30]
console.log(res)

Then it works. res.end would get the correct value.
Output --
{"start":{"hour":7,"minute":20},"end":{}}
{ start: { hour: 7, minute: 20 },
  end: { hour: 17, minute: 30 } }

I've searched, and read thru MDN page on destructure, but couldn't find an explanation to this.
Appreciate your help in advance.

A: Try this:

let res = {
  start: {},
  end: {}
};
[res.start.hour, res.start.minute] = [7, 20]; // Notice the semicolons.
[res.end.hour, res.end.minute] = [17, 30];
console.log(res);

I copy-pasted your code from the first block into VS Code and used 'Alt + Shift + F' (auto-formatting). It fixed the code to the following, indicating that something is clearly off:
let res = {
  start: {},
  end: {}
};
[res.start.hour, res.start.minute] = [7, 20][(res.end.hour, res.end.minute)] = [
  17,
  30
];
console.log(res);

As it turns out, semicolons do matter sometimes in JavaScript.


text:
Q: Gradle leftshift << operator with Task needed? (Is it superfluous) I am maintaining gradle code that sometimes uses the leftshift operator << in defining task.  It works fine, but so does omitting the << operator from the task.
I understand the purpose of the left shift operator as explained
What's the operator << (double less than) in gradle?
so... I get the purpose of leftshift operator <<.  It is to add to a set of actions for a task and when the task is ran it will execute the actions in the same order in which the the task were entered.  I Get it and I can see that it works properly.  However, omitting << will result in the same behavior.  I can see where using << in Gradle makes sense, but in the case of tasks it seems to be just superfluous and should be omitted.  Is that correct or does the leftshift operator serve a purpose.
Example:
task Foo
task Bar

Foo << {
  println "foo action 1"
}

Foo << {
  println "foo action 2"
}

Bar  {
  println "bar action 1"
}

Bar  {
  println "bar action 2"
}

Foo and Bar behave exactly the same.

A: Mark Vieira's answer is exactly right, but I would also add for clarification, that without the << operator, the code in your closure will be executed when the script is parsed, rather than when it is executed.
This is most obvious when you run the "clean" task.  If you don't use the << for all your tasks, then gradle clean will actually execute the code in all your tasks.
Try this:
build.gradle:
apply plugin: 'groovy'

task foo { println 'foo'}

and now try running the clean task
$>gradle clean
14:23:57: Executing external task 'clean'...
foo
:clean UP-TO-DATE

BUILD SUCCESSFUL

Total time: 0.216 secs
14:23:57: External task execution finished 'clean'.`

Now, if you add the <<,
build.gradle:
apply plugin: 'groovy'

task foo << { println 'foo'}

it will do this:
$>gradle clean
14:27:28: Executing external task 'clean'...
:clean UP-TO-DATE

BUILD SUCCESSFUL

Total time: 3.547 secs
14:27:32: External task execution finished 'clean'.

Note that the leftshift << operator was deprecated and is no longer in gradle versions 5.0 and up. You can replace the code above with:
build.gradle:
task foo { doLast { println 'foo' } }

A: The left shift (<<) operator is an alias to Task.doLast(), meaning that it adds an action to the task. A task action being some code that is evaluated when the task executes. Omitting the operator simply configures the task. The distinction being that one runs at configuration time (when Gradle runs your build script) and the other at execution time.
Essentially this example
task foo << {
    println 'bar'
}

is equivalent to
task foo {
    doLast {
        println 'bar'
    }
}


text:
Q: c# unicode chars in serialization I've got a list of dictionaries:
List<Dictionary<string, string>> list= new List<Dictionary<string, string>>();

I need to serialize this list to add it in another dictionary of strings, I did it in this way:
JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
string serializedArticles = javascriptSerializer.Serialize(list);
body.Add("Rows", serializedArticles);

It works but the char ' is stored as \u0027, how I can fix this?


text:
Q: Why does the new key show different when we use Object.defineProperty() in javascript? In this example bellow (source: W3school), when we put console.log('person',person); in the end, fullName is in a different color in the log of others (see the pic). Does it mean  that fullname is temporary? What should I do to make it become part of person?
P.s: I'm begginner and I'm not able to put pictures here. thanks for understanding!
<!DOCTYPE html>

JavaScript Object.defineProperty()

This example uses the defineProperty() method to add a getter and a setter.


text:
Q: Calculation detail of Batch Normalization I am implementing the BN algorithm in my CNN model using C++. But I am very confused because of its calculation of mean and standard deviation. Let's see the below pictures.

As far as I know, each pixel mean value has to be computed. but I don't know which of the equations is correct.
Let's assume that the BN's input is [B, H, W], where B is the batch size, (H, W) is the feature map size (Suppose to [3,2,2]).

*

*Mean of all pixels in one image
([0,0,0]+[0,0,1]+[0,1,0]+[0,1,1])/4
Mini-batch means are scalar

*Mean of the same location's pixel in multiple images (image num = batch num )
([0,0,0]+[1,0,0]+[2,0,0])/3 ,
  ([0,0,1]+[1,0,1]+[2,0,1])/3 ,
  ([0,1,0]+[1,1,0]+[2,1,0])/3 ,
  ([0,1,1]+[1,1,1]+[2,1,1])/3 )
Mini-batch means are an array
What calculation is right?

A: Neither is correct.  Method 1 merely normalizes each image; it has nothing to do with the batch as a whole.  Method 2 will almost certainly damage your training, as it decouples adjacent pixels from one another.
You need to compute the mean and variance of all pixels in the batch.  Then normalize each pixel with the scale and shift equation using those batch statistics.