text:
Q: Using recursion to reverse an integer without trailing 0's in C++ I am stuck on how to omit trailing zeros, on a recursive call to reverse an integer. If you could just guide me to the right path I'd appreciate it. I am stuck and do not know how to do it. I have came this far, but am struggling to complete it. Thanks.
int main() {
    int numToReverse;

    cout << "Please enter in a number: " << endl;
    cin >> numToReverse;

    cout << reverseIntRecursion(numToReverse) << endl;

}

int reverseIntRecursion(int n) {
    if (n < 10)  //Base Case
        return n;
    else
        cout << n % 10; // Prints out the last number
        return reverseIntRecursion(n / 10); // General Case, Recursive Function
}

A: Maybe easiest way is parse int to string (array of chars) and print as array?

A: Here is some code that works just fine as long as you enter true for the second parameter:
int ReverseIntRecursion(int, bool);

int main(int argc, const char * argv[]) {

    std::cout << ReverseIntRecursion(30400, true);
    std::cout << std::endl;

    return 0;
}

int ReverseIntRecursion(int N, bool FirstIter)
{
    if (N < 10)
        return N;
    else if (N % 10 == 0 && FirstIter)
        return ReverseIntRecursion(N/10, true);
    else
        std::cout << (N % 10);
    return ReverseIntRecursion(N/10, false);
}
// prints 403

A: Your function isn't reversing an integer. It just prints digits in a reverse order.
This is why you are getting your trailing zeros problem. If you wrote a function which actually reversed the integer - your problem would disappear.
For example:
// Helper function for reversing an integer.
int reverseIntRecursionBase(int n, int& base) {
    if (n < 10) // trivial case. If n consists of a single digit - reversed n is equal to n.
        {
        return n;
        }

    int result = reverseIntRecursionBase (n/10, base); // recurse until you hit a trivial case.
    /*
       The leftmost digits in the original number should be the
       rightmost digits in the reversed number.
       This code will be first executed, after trivial case has been hit:
       e.g. given number 1234, this line will be first reached when n = 12; result = 1.
    */
    base *= 10;
    result = (n % 10)*base + result;
    return result;
}

int reverseIntRecursion(int n) {
    int base = 1;
    return reverseIntRecursionBase (n, base);
}

Live demo.


text:
Q: Spring event/notification on application loading failure Is there a way in Spring to be notified when application startup ends with failure (due to the missing bean, missing property, invalid configuration, etc...).
I would like to be able to notify other parts of the stack (namely Jenkins server) that the application has failed to deploy correctly.
I've noticed that ...
SpringApplication.handleRunFailure(ConfigurableApplicationContext context,
            SpringApplicationRunListeners listeners, Throwable exception)

...is called if the app failed to start. I also noticed that the method
private int getExitCodeFromException(ConfigurableApplicationContext context,
            Throwable exception)

is invoked during context shutdown/error handling, so I tried to register bean of type ExitCodeExceptionMapper, but the defined beans' method is never called because the target error (the one which I want to be notified of) occurred before the bean is loaded.
The application is deployed on Tomcat and started via SpringBootServletInitializer.
Is there another way to catch context startup failure error in Spring Boot application?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What JS design pattern is this? I'm looking at the source code of connect js library and they do something interesting. They merge all of the methods from proto into the app object. Does this design pattern have a name?
function createServer() {
  function app(req, res, next){ app.handle(req, res, next); }
  utils.merge(app, proto);
  utils.merge(app, EventEmitter.prototype);
  app.route = '/';
  app.stack = [];
  for (var i = 0; i < arguments.length; ++i) {
    app.use(arguments[i]);
  }
  return app;
};

A: I think the closest thing to call it would be a mixin. That is, you take an existing definition of an object (in this case a function) and then copy properties from another object onto it.
You can tell from reading the source that the method simply copies properties from the source object to the target object.


text:
Q: Save nearest establishment to google user account in Swift2 The purpose for this portion of the app is for the user (signed in with Google sign in) to locate the nearest place to them and save it automatically to the user's google account.
The below method works fine, grabbing the most likely place the user is located at (first object in the array of placeLikelihoods). Now what I need to do is save it to the user's google account (the one they signed in with).
Any lead or ideas on how to do this or if it's even possible? Thank you for the help like always.
func getInfoViaPlacesClient() {

let placesClient = GMSPlacesClient.sharedClient()

placesClient.currentPlaceWithCallback { (likelihoodlist, error) -> Void in

    if error != nil {
        print("Current Place error: \(error!.localizedDescription)")
        return
    }

    let nearestPlace : GMSPlaceLikelihood = likelihoodlist!.likelihoods.first as! GMSPlaceLikelihood
        print(nearestPlace.likelihood)
        self.nearestPlace = nearestPlace.place

        self.saveNearestPlace()

  }
}

Save method... I think I'm on the right track but I keep getting this error in the placesClient.addPlace block...

Add Place error: The operation couldn't be completed.
  (com.google.places.server.ErrorDomain error -1.)

func saveNearestPlace() {

//to app(core data)
let placesClient = GMSPlacesClient.sharedClient()

let name = self.nearestPlace!.name
let address = self.nearestPlace!.formattedAddress

LocationController.sharedInstance.addLocationWithName(name!, address: address!)

//to google

let addedPlace = GMSUserAddedPlace()
addedPlace.name = self.nearestPlace?.name
addedPlace.coordinate = (self.nearestPlace?.coordinate)!
addedPlace.types = self.nearestPlace?.types
addedPlace.address = self.nearestPlace?.formattedAddress

placesClient.addPlace(addedPlace, callback: { (place: GMSPlace?, error: NSError?) -> Void in

    if let error = error {
        print("Add Place error: \(error.localizedDescription)")
        return
    }

    if let place = place {

        self.nearestPlace = place

        print("Added place with placeID \(place.placeID)")
        print("Added Place name \(place.name)")
        print("Added Place address \(place.formattedAddress)")
    }
})

}


text:
Q: Exception NullPointer, suggestions? I am following the ebook Big Java Late Objects - and I have problem resolving on of the tasks. It is about inheritance. There is Question class and one sub ChoiceQuestion class that extends it.
But when I run the code in my testclass it calls the null exception and I don't know why.
Exception in thread "main" java.lang.NullPointerException
at ChoiceQuestion.addChoice(ChoiceQuestion.java:12)
at TestClass.main(TestClass.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at                  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Here are my classes:
public class Question {
private String text;
private String answer;

/**
 *  Constructs a queston with empty question and answer.
 */
public Question(){
    text = "";
    answer = "";
}
//=============Setter methods============
public void setText(String questionText){
    text = questionText;
}

public void setAnswer(String correctResponse){
    answer = correctResponse;
}
//==============Getter Methods=============
public boolean checkAnswer(String response){
    return answer.equals(response);
}
public void display(){
    System.out.println(text);
}
}

And here is my subclass:
class ChoiceQuestion extends Question {
private ArrayList<String> choices;

//=========Methods==============
public void addChoice(String choice,boolean correct){
    choices.add(choice);
    if(correct){
        //convert choices.size() to string
        String choiceString = "" + choices.size();
       this.setAnswer(choiceString);
    }
}

public void display(){
    // Display the question text
    super.display();
    // Display the answer choices
    for(int i=0;i<choices.size();i++){
        int choiceNumber = i + 1;
        System.out.println(choiceNumber + ": " + choices.get(i));
    }
}
}

And my test Class:
import java.util.Scanner;

public class TestClass {
public static void presentQuestion(Question q){
    q.display();
    System.out.println("Your answer: ");
    Scanner in = new Scanner(System.in);
    String response = in.nextLine();
    System.out.println(q.checkAnswer(response));
}
public static void main(String[] args) {
    Question first = new Question();
    first.setText("James Gosling");
    first.setAnswer("James Gosling");

    ChoiceQuestion second = new ChoiceQuestion();
    second.setText("In which country was the inventor of Java born? ");
    second.addChoice("Austria", false);
    second.addChoice("Canada",true);
    second.addChoice("Denmark",false);
    second.addChoice("United States",false);
    presentQuestion(first);
    presentQuestion(second);

}
}

A: Object choices is never initialized.
In Java, objects must be initialized before you can use them. That's why an attempt to call choices.add(choice) yields such an exception.
It is often a good idea to initialize member objects in constructors.
In this case, it looks like you should write a constructor for ChoiceQuestion and initialize your choices ArrayList there.
class ChoiceQuestion extends Question {
    private ArrayList<String> choices;

    ChoiceQuestion(){
        choices = new ArrayList<>();
    }

   //...

A: Write private ArrayList choices = new ArrayList();
In the class when you declared it.

A: You need to initialize your list before use:
private List<String> choices = new ArrayList<String>();

A: The choices member is never initialized, so the first time you try to access it, you fail with a NullPointerException. You could, for example, initialize it in the class definition:
class ChoiceQuestion extends Question {
    private ArrayList<String> choices = new ArrayList<>();
    // Rest of the class


text:
Q: code coverage for oe-core doesn't work, show 0% mesured I use
export LANG=en_US.UTF-8
coverage run  --source=$path-to/oe-core/meta/lib/oe --debug=trace $path-to/bin/bitbake -C do_rootfs core-image-minimal

it shows oe-core measurement is 0%, and --debug=trace doesn't show any info about oe-core/meta/lib/oe
......
......
/oe-core/meta/lib/oe/package_manager/__init__.py         345    345     0%
/oe-core/meta/lib/oe/package_manager/deb/__init__.py     322    322     0%
/oe-core/meta/lib/oe/package_manager/deb/manifest.py      15     15     0%
/oe-core/meta/lib/oe/package_manager/deb/rootfs.py       133    133     0%
/oe-core/meta/lib/oe/package_manager/deb/sdk.py           55     55     0%
/oe-core/meta/lib/oe/package_manager/ipk/__init__.py     298    298     0%
/oe-core/meta/lib/oe/package_manager/ipk/manifest.py      49     49     0%
/oe-core/meta/lib/oe/package_manager/ipk/rootfs.py       204    204     0%
/oe-core/meta/lib/oe/package_manager/ipk/sdk.py           58     58     0%
/oe-core/meta/lib/oe/package_manager/rpm/__init__.py     293    293     0%
/oe-core/meta/lib/oe/package_manager/rpm/manifest.py      33     33     0%
/oe-core/meta/lib/oe/package_manager/rpm/rootfs.py        89     89     0%
/oe-core/meta/lib/oe/package_manager/rpm/sdk.py           57     57     0%
/oe-core/meta/lib/oe/packagedata.py                       75     75     0%
.....
.....
TOTAL                                                                                8130   8130     0%


text:
Q: How to handle inputs in a C shell program during exec I am currently writing my own shell program. This simple shell can just execute commands.
When executing commands like vi or calc which require input from the terminal , the command is getting executed and is waiting for the input from the user. But I am unable to give any input on the screen.
How should the input be handled during the fork and exec.
Here is the piece of code which is executing commands:
    if((pid = fork()) < 0)
    {
            perror("Fork failed");
            exit(errno);
    }
    if(pid == 0)
    {
            // Child process
            if(execvp(arguments[0], arguments) == -1)
            {
                    child_status = errno;
                    switch(child_status)
                    {
                            case ENOENT:
                                    printf(" command not found \n");
                                    break;
                    }
                    exit(errno);
            }
    }
    else
    {
            // parent process
            int wait_stat;
            if(waitpid(pid , &wait_stat, WNOHANG) == -1)
            {
                    printf(" waitpid failed \n");
                    return;
            }
    }

}
~
Thanks,

A: The WNOHANG is causing the parent process not to wait and therefore (depending on platform) the child process will be detached from terminal IO or die.
Remove the WNOHANG.


text:
Q: Reweighting importance-weighted samples in Bayesian bootstrap Typically, in Bayesian bootstrap, you have samples {$x_1,...,x_n$} of a random variable $X$.
Choose $\{p_1,...,p_n\}$ from a Dirichlet distribution, by sorting $\{0,1,u_1,...,u_{n-1}\}$ where $u_i$ are independent samples from $U \sim Uniform(0,1)$, and taking differences of sorted neighbors.
Use $\{p_1,...,p_n\}$ as weights for $\{x_1,...,x_n\}$ to calculate a sample from the statistic of interest $\theta$; i.e.
$$\hat\theta_j = \sum_{i=1}^n f(x_i) \cdot p_i$$
for bootstrap iteration $j$.
I already have weights $\{w_1,...,w_n\}$ from importance sampling, from which I compute
$$\hat\theta = \frac{\sum_{i=1}^n f(x_i) \cdot w_i}{\sum_{i=1}^n w_i} $$
With a new set of weights computed as $w_i' = w_i \cdot p_i$, computing
$$\hat\theta_j = \frac{\sum_{i=1}^n f(x_i) \cdot w_i'}{\sum_{i=1}^n w_i'} $$
doesn't work: the distribution of bootstrapped statistics is too narrow.
Resampling from the weighted samples to get unweighted $\{x_1',...,x_n'\}$ and applying Bayesian bootstrap to these also doesn't work: the distribution of bootstrapped statistics is too wide. (This is also true if I resample anew for each Bayesian bootstrap iteration.)
I think I need to reweight differently. How is this done?
EDIT: Actually, using weights $w_i' = w_i \cdot p_i$ was the right solution. I was comparing my bootstrap results against the results of using a bad, too-high Monte Carlo variance estimate. I'm not ready to call this foobar my fault, though, because it's stupidly hard to find the correct formula for Monte Carlo variance of expected values computed using "ratio" or "self-normalized" importance samples. For the record, I finally found it here, on page 63:
http://www.rni.helsinki.fi/~pek/test/mcmbc10.pdf
So thanks very much to Petri Koistinen. This is the formula for an unbiased Monte Carlo variance estimate, in case the link goes stale:
$$Var[\widehat\theta] \approx \frac{n}{n-1} \frac{\sum_{i=1}^n \left(f(x_i)-\widehat\theta\right)^2 w_i^2}{\left(\sum_{i=1}^n w_i\right)^2}$$
I think this is right because 1) Monte Carlo variance of expected values computed using unweighted samples is a special case; 2) changing the importance distribution induces the expected changes to it; 3) all the bootstrap methods I've implemented agree with the values I compute from it (finally); 4) it's invariant to weight scaling; and 5) it seems to have a decent proof behind it, in Koistinen's notes and another place I found it. (Though in the other place it was followed up by a bogus formula for computing a confidence interval, with a spurious multiplication by $\sqrt{n}$.) As a bonus, the leading term is the standard bias correction term for variance estimates.
You would think that, given that importance sampling is so often presented and used as a variance reduction technique, estimating the variance would be common.
Sorry for the noise, but at least it might help someone else in the future.

A: Think of the importance sampling as defining a new $f^*(x_i) = f(x_i)w_i/\sum w_i$.  Then, when you do your Bayesian bootstrap, as in your formula for $\hat{\theta}_j$, do it with respect to $f^*$ instead of the original $f$.
The concept behind this is that the importance sampling "corrects" for a misspecified probability of observing the $x_i$ (misspecified because it isn't $1/n$.)  This correction should be the same regardless of the weights generated for a particular bootstrap sample, because it's due to the underlying probability model.  So you shouldn't combine the correction weights with the bootstrap weights to form new weights (your first approach).  On the other hand, your second approach adds randomness by sampling according to the importance sampling weights rather than doing the importance sampling calculation, thus adding randomness to your results and causing the resulting distribution to be too wide.  Your third approach adds randomness for the same reason, but to a different degree, and therefore has the same effect.


text:
Q: Errors Message for Validation I'm working on authorization system for Kohana. I'm doing it just for education...
This is how looks my controller that checks submitted fields:
$validation =
  Validation::factory( $_POST )
    ->rule( 'username', 'not_empty' )
    ->rule( 'username', 'max_length', array( ':value', 32 ) )
    ->rule( 'username', 'alpha_dash', array( ':value', true ) )
    ->rule( 'password', 'not_empty' )
    ->rule( 'password', 'min_length', array( ':value', 6 ) )
    ->rule( 'password', 'max_length', array( ':value', 255 ) )
    ->rule( 'passwordRepeatedly', 'not_empty' )
    ->rule( 'passwordRepeatedly', 'matches', array( ':validation', 'passwordRepeatedly', 'password' ) )
    ->rule( 'email', 'not_empty' )
    ->rule( 'email', 'email' );

I'm looking for the way to display different error message for each added rule. My goal is then pass it (one or all (if occurs)) to view and display them there.
Pseudo-code:
errorFor( 'username', 'not_empty' ) => 'Username is required! Try again...';

How to define different error for each rule? I can't find anything understandable for me in the docs...

A: You have:
$validation = ...

So, first you should check if variables pass validation:
if($validation->check())
{
  // no errors
}
else
{
    $errors = $validation->errors('user');
}

Then you should have user.php file in application/messages
<?php defined('SYSPATH') or die('No direct script access.');

  return array
  (
     'input_name' => array
     (
        'rule' => 'your message',
        'default' => 'default message'
     ),
     'username' => array
     (
        'not_empty' => 'your message',
        'max_length' => 'your message',
        'alpha_dash' => 'your message',
        'default' => 'default message'
     ),

  );

?>

To display errors:
foreach($errors as $input_field => $message)
    echo $message;

A: Validation rules make use of messages folder in your application directory.
Check this: http://kohanaframework.org/3.1/guide/orm/examples/validation for full validation example, where the messages file is at the very bottom of the page.
The things to note are the directory and the filename of the message file.
In KO3.1 (I believe) the Validation throws an exception whenever if fails. If you catch it with catch (ORM_Validation_Exception $e) you can use $e->errors('some_directory') to catch error messages, which are then pulled from messages/some_directory/model_name.php in the form of array, just like in the example from the link above.


text:
Q: django_filters returns True is not a valid field when filtering through rest api Got in my model serializer such field like is_favorited and others
is_favorited = serializers.SerializerMethodField()
def get_is_favorited(self, obj):
    user = self.context['request'].user
    if user.is_anonymous:
        return False
    qs = Favorite.objects.filter(user=user, recipe=obj)
    return len(qs) > 0

my model viewset contains
queryset = Recipe.objects.all()
filter_backends = [DjangoFilterBackend]
filterset_fields = (
    'is_favorited',
        )

in Postman i get this bad request when trying to filter by this boolean field

A: decided to use get_queryset in order to filter simple queries.


text:
Q: Trigger SBT assembly from other subproject I have a root project containing 3 subprojects plus sbt config files and nothing else. 2 main subprojects are called server and backend, the other is called common and is dependency of both main projects. server is PlayFramework project. backed project is configured to generate assembly jar into resources directory of server.
The jar is generated correctly and server is able to see it, but I don't know how to run assembly task from backend when server is compiled(i.e. I want the server to depend on assembly of backend.jar)
/* [...] */

lazy val commonSettings = Seq(
  version := "0.1",
  organization := "org.example",
  scalaVersion := "2.11.7"
)

lazy val server = (project in file("server")).enablePlugins(PlayJava).settings(commonSettings: _*).settings(
  name := """example""",
  libraryDependencies ++= Seq(
    /* [...] */
  ),
  /* [...] */
  unmanagedResourceDirectories in Compile += { baseDirectory.value / "resources" }
).dependsOn(common)

lazy val backend = (project in file("backend")).settings(commonSettings: _*).settings(
  assemblyJarName in assembly := "backend.jar",
  assemblyOutputPath in assembly := server.base / "resources/backend.jar",
  libraryDependencies := Seq(

  )
).dependsOn(common)

lazy val common = (project in file("common")).settings(commonSettings: _*)

onLoad in Global := (Command.process("project server", _: State)) compose (onLoad in Global).value

A: Thanks to comment by @pfn I got it working. One thing I needed to do was to insert this line in server subproject settings and change server to Compile, so it is now:
(compile in Compile) <<= (compile in Compile) dependsOn (assembly in backend)


text:
Q: Proving an evenness property for the nth power map for a finite (not necessarily commutative) group $G$ In the course of proving some properties about an algorithm to pick an element of prime order $p$ from a finite group $G$ such that $p ∥ \lvert G \rvert$ ($p \mid \lvert G \rvert$ but $p^2 \not\mid \lvert G \rvert$), I needed the following lemma:
Lemma: Let $G$ have order $m$ with prime $p ∥ m$, and let
  $f(x) = x^{m/p}$. If $y$ is a non-identity element in the
  image of $f$, then $\lvert f^{-1}(\{ y \}) \rvert = C$ for some
  constant $C$ independent of $y$. In other words, each
  non-identity element in the image of $f$ has an equal number of
  elements of $G$ mapping to it.
This lemma becomes easy if we can assume that $G$ is commutative, since then $f(x)$ is a group homomorphism, and thus each $y$ in the image is isomorphic to a coset of $\ker f$.
I've managed to prove this myself for arbitrary finite groups, but was wondering if it was correct, and if there's a better way to prove it. Here's my proof (take as given that any non-identity element in the image of $f$ has order $p$):
Proof:   Let $A_{m/p}$ be the set of elements of $G$ with order a factor
  of $m/p$, and let $k$ be an integer such that
  $k(m/p) ≡ 1 \pmod p$. If $y$ is a non-identity element in the
  image of $f$, then we want to show that
  $$
    f^{-1}(\{y\}) = \{ xy^k \mid x ∈ A_{m/p} ∩ C_G(y) \}\text{,}
  $$
  where $C_G(y)$ is the centralizer of $y$.
Let $xy^k$ be in the set on the right-hand side. $x$ commutes
  with $y$, so it must also commute with $y^k$, and
  $(xy^k)^a = x^a y^{ka}$ for any $a$. Therefore,
  $$
    (xy^k)^{m/p} = x^{m/p} y^{k(m/p)} = y\text{.}
  $$
Going the other way, let $z ∈ f^{-1}(\{ y \})$. Since $y$ has
  order $p$, $z$ had order $pn$ where $n \mid m/p$. $p$ and
  $n$ are coprime, so there exists $z_1, z_2 ∈ G$ such that
  $z = z_1 z_2 = z_2 z_1$, $\operatorname{ord}(z_1) = p$, and $\operatorname{ord}(z_2) =
  n$. (Let $ap + bn = 1$. Then $z_1 = z^{bn}$ and
  $z_2 = z^{ap}$.) $z_1$ must be in the subgroup generated by
  $y$, so $z_1 = y^k$, and $z_2 ∈ A_{m/p} ∩ C_G(y)$.
Then let $y_1$ and $y_2$ be non-identity elements in the image
  of $f$. If $y_1$ and $y_2$ are in the same cyclic subgroup,
  then $y_2 = y_1^a$ for some $a$, and thus $C_G(y_1) = C_G(y_2)$.
  Therefore, the map
  $$
    g(xy_1^k) = xy_2^k
  $$
  is a bijection from $f^{-1}(\{ y_1 \})$ to $f^{-1}(\{ y_2 \})$.
Otherwise, if $y_1$ and $y_2$ are not in the same cyclic
  subgroup, then they're in different $p$-Sylow subgroups of
  $G$. By the second Sylow theorem, there is some $w$ such that
  $y_2 = wy_1'w^{-1}$ for some $y_1'$ in the cyclic subgroup
  generated by $y_1$. Then we want to show that the map
  $g(x) = wxw^{-1}$ is a bijection from $f^{-1}(\{y_1'\})$ to
  $f^{-1}(\{y_2\})$.
Let $xy_1'^k ∈ f^{-1}(\{y_1'\})$. Then
  $$
    g(xy_1'^k) = g(x)y_2^k\text{.}
  $$
  Conjugation preserves order, and it also commutes with taking the
  centralizer. Therefore, $g(x) ∈ A_{m/p}$ and $g(x) ∈ C_G(y_2)$,
  so $g(xy_1'^k) ∈ f^{-1}(\{ y_2 \})$, and thus
  $g(f^{-1}(\{ y_1' \})) ⊆ f^{-1}(\{ y_2 \})$. The other inclusion
  holds similarly. In particular, both inverse images have the same
  size, and by the first part above $f^{-1}(\{y_1\})$ has the same size as
  $f^{-1}(\{y_2\})$. $∎$
(Note that, unlike the commutative case, the exclusion of the identity is necessary. If $G = S_3$
  and $p = 2$, then each transposition has exactly one element in
  the preimage of $f(x) = x^3$ (itself), but $e$ has three
  elements in the preimage of $f$; $e$ itself and the two
  $3$-cycles.)

A: Here's a shorter way (without finding an explicit description of $f^{-1}(y)$).
Note that each $y$ in the image of $f$ has $y^p = 1$, so each such $y$ is in a cyclic subgroup of order $p$, i.e. a $p$-Sylow subgroup.
Suppose first that $y_1$ and $y_2$ are in the same $p$-Sylow subgroup, so $y_2 = y_1^r$ for some $r$ not divisible by $p$. Let $s$ be such that $s \equiv r \text{ (mod $p$)}$ and $s$ is coprime to $m/p$ (this can be done via the CRT, for example), so that $y_2 = y_1^s$ and $s$ is coprime to $m$. Also, let $t$ be such that $st \equiv 1 \text{ (mod $m$)}$. Then $x \mapsto x^s$ defines a map $f^{-1}(y_1) \to f^{-1}(y_2)$, since if $x^{m/p} = y_1$, then $(x^s)^{m/p} = (x^{m/p})^s = y_1^s = y_2$. Similarly, $x \mapsto x^t$ defines a map $f^{-1}(y_2) \to f^{-1}(y_1)$, and clearly these maps are inverse, hence bijections, so $|f^{-1}(y_1)| = |f^{-1}(y_2)|$.
Now suppose that $y_1$ and $y_2$ are in different $p$-Sylow subgroups, so since these subgroups are conjugate by the second Sylow theorem, there is some $y_2'$ in the cyclic subgroup generated by $y_2$ with $wy_1w^{-1} = y_2'$. Note that by the previous paragraph we have $|f^{-1}(y_2')| = |f^{-1}(y_2)|$. But $x \mapsto wxw^{-1}$ clearly defines a bijection $f^{-1}(y_1) \to f^{-1}(y_2')$ (with inverse $x \mapsto w^{-1}xw$), since $x^{m/p} = y_1$ implies $(wxw^{-1})^{m/p} = wx^{m/p}w^{-1} = wy_1w^{-1} = y_2'$, hence $|f^{-1}(y_1)| = |f^{-1}(y_2')|$ as well. It follows that $|f^{-1}(y_1)| = |f^{-1}(y_2)|$.


text:
Q: Why is there an error java.lang.ExceptionInInitializerError when using an ImageSlider in a recyclerView in Kotlin? I am trying to show images in an ImageSlider in a recyclerView. What I have done is, as the images to be fetched from Firebase storage, I created an array of SlideModel within the adapter class. There will be a minimum of 1 and a maximum of 5 images. Following is how I have done this.
My code seems to work as I can see data in the remoteImages (SlideModel ArrayList) in the Logcat. But, when I add the last line of code, which is holder.itemView.image_slider.setImageList(remoteImages, ScaleTypes.FIT), my app crashes with the  following error. Without it, the app works fine but there are no images in the slider.
    java.lang.ExceptionInInitializerError
    at okhttp3.internal.platform.Platform.get(Platform.java:85)
    at okhttp3.OkHttpClient.newSslSocketFactory(OkHttpClient.java:263)
    at okhttp3.OkHttpClient.<init>(OkHttpClient.java:229)
    at okhttp3.OkHttpClient$Builder.build(OkHttpClient.java:1015)
    at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:71)
    at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:50)
    at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:40)
    at com.squareup.picasso.Picasso$Builder.build(Picasso.java:848)
    at com.squareup.picasso.Picasso.get(Picasso.java:683)
    at com.denzcoskun.imageslider.adapters.ViewPagerAdapter.instantiateItem(ViewPagerAdapter.kt:71)
    at com.denzcoskun.imageslider.adapters.ViewPagerAdapter.instantiateItem(ViewPagerAdapter.kt:25)
    at androidx.viewpager.widget.ViewPager.addNewItem(ViewPager.java:1010)
    at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1158)
    at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
    at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
    at android.view.View.measure(View.java:27131)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:735)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:481)
    at android.view.View.measure(View.java:27131)

I have implementation 'com.github.denzcoskun:ImageSlideshow:0.1.0' in my build.gradle
Following is the XML code for the ImageSlider which is a part of my itemlayout for the recyclerView.
    <com.denzcoskun.imageslider.ImageSlider
    android:id="@+id/image_slider"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:iss_auto_cycle="true"
    app:iss_period="2500"
    app:iss_delay="0"/>

Following is part of my ItemListAdapter.kt.
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val model = list[position]

        val numOfImages = model.image_count
        val remoteImages: ArrayList<SlideModel> = ArrayList()

        if (holder is MyViewHolder) {

            when (numOfImages) {
                1 -> {

                    remoteImages.add(
                        SlideModel(
                            model.image,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    Log.d("TAG", remoteImages.toString())
                    Log.d("TAG", remoteImages.size.toString())
                }
                2 -> {

                    remoteImages.add(
                        SlideModel(
                            model.image,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image2,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    Log.d("TAG", remoteImages.toString())
                    Log.d("TAG", remoteImages.size.toString())
                }
                3 -> {
                    remoteImages.add(
                        SlideModel(
                            model.image,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image2,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image3,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    Log.d("TAG", remoteImages.toString())
                    Log.d("TAG", remoteImages.size.toString())
                }
                4 -> {
                    remoteImages.add(
                        SlideModel(
                            model.image,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image2,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image3,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image4,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    Log.d("TAG", remoteImages.toString())
                    Log.d("TAG", remoteImages.size.toString())
                }
                5 -> {
                    remoteImages.add(
                        SlideModel(
                            model.image,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image2,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image3,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image4,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    remoteImages.add(
                        SlideModel(
                            model.image5,
                            model.title,
                            ScaleTypes.FIT
                        )
                    )

                    Log.d("TAG", remoteImages.toString())
                    Log.d("TAG", remoteImages.size.toString())
                }
                else -> {
                    Log.d("TAG", "There are no images")
                }
            }

holder.itemView.image_slider.setImageList(remoteImages, ScaleTypes.FIT)

    }


text:
Q: Physical to Virtual on same hardware? I'd like to convert a physical machine to a virtual.  Its an SBS2008 server.  The catch is I have just the one server hardware to use.  Is it possible to create VHDs for the system drive as well as a volume on the RAID drive saving the images to a network share, reformat the server and install hyper-v then bring the images in as part of the guest OS?
EDIT:  Many answers have also asked why.  These are my goals:
One goal is to get more than one server going, so that I can leave the SBS as it is, and install other services on a non-sbs running server. Also, I think it would make migration to sbs2011 easier, since I can install that into a clean virtual and migrate, then shut down the sbs2008 server (while leaving the services on the second server alone). In short, I think running virtuals will give me more options... one long term one includes moving to new hardware. I imagine it'd be easier to move to new hardware if you just transfer virtuals.
I'm currently running this out of my home office, so space is at a premium, and since I'm very small, price is as well.  That's why only one server, and why when I do get a new server it'd be a replacement.  However as my business grows I'd like to make it as easy as possible to expand out, and it seems like virtuals are a great way to make transitions easier.
Another goal is that I'm looking to have the option to run multiple servers (many are servers I'll setup to mimic client environments, but most of those won't be running until I'm actively doing development.  I'll stop and start as needed).
I appreciate all the answers, and someone telling me this is a bad idea is fine as well.  A virtual SBS2008 IS a supported MS configuration though, I've found documents telling you how to acomplish just that.  Sadly I didn't come across these until recently, while I built the server a few years ago.

A: It should be possible, but it's difficult without knowing for sure that your hardware is is supported. I'm not going to say that it will work only to have you hit a snag and have it not work, then complain...in some circumstances it might.
The smarter thing to do is get a newer server dedicated to virtualization, then migrate your existing server over and decommission it.
Especially since your server is your only one. SBS will potentially die in the process, and leave your business high and dry.
Here's the options as I see it. One, make sure you have known-good backups, and verify that your p2v migration will support sparse disks, since if it will create the same size volumes you're going to have a size crunch. Then you can allocate a few days to trying it, and if it fails horribly, restore the computer back to the previous state.
Two, which I'd say would be safer, get a server with tons of storage dedicated to being a VM server, migrate your server to that, then decommission it once it's working well. Then turn your old server into a backup domain controller. Even for small business, it doesn't hurt to have 2 DC's.
Three, don't do this, unless you really have a compelling reason to move to a virtual system structure. What are you doing that you are running with SBS, but want to virtualize on that server? Especially if you don't have extra hardware for availability/redundancy? If you do idea two, you could migrate your server, make sure it works, and then turn the old server into another virtual server and install a backup DC and...something else you're trying to virtualize.
Depends on what exactly you're trying to achieve as an end goal (for what reason...?)

A: I did this at a church that had zero budget for hardware, but wanted to migrate to SBS2011 on the same server. It was risky, but it worked.

*

*I installed the Hyper-V role on the SBS2008 Box

*I used disk2vhd to make a copy of all the disks on the server, onto the same server. It uses snapshots, so you can have the source and destination be the same disk

*I mounted the virtual SBS2008 on the same machine as the real SBS2008. The important thing I did here was I did not give it a network adapter. The only reason I did this was to ensure that my copy did in fact work.

*I did a Hyper-V "Export" onto an external drive, and completely wiped the SBS2008 server

*I did a Hyper-V "Import" back to the main machine after I had a fresh 2008 R2 installation with Hyper-V added to it

*I booted the new Hyper-V machine and have been happy ever since. I should have virtualised it in the first place.

I was then able to install SBS2011 in a second VM on the same hardware, migrate everything over, and then just turned off and disabled the original SBS2008 VM. It took a fair bit of time, but it meant that we didn't have to spend a single dollar on hardware.
Important things to note:

*

*This only works if you have a single domain controller (the SBS machine). Because your AD will effectively go backwards during this (from the snapshot), if you have more than one AD they will complain about "Invalid restoration" (same as if you rolled back to a previous snapshot of a VM). Then the "old" DC will then just sit there being useless forever. I did ours on a weekend when almost all the computers in the office were shut down. We only had an issue with one network printer that (still) refuses to re-join the domain.

*You might have licensing issues. We did this on an educational license, which is not OEM, and thus we were allowed to virtualise. My work also donated the 2008 R2 license that we used as a hypervisor, but the vanilla Hyper-V hypervisor is free if you don't want a fully functioning OS underneath it.

*The first import of the VM is important, because you don't want to nuke your SBS2008 host without making 100% sure that your copy is in a good enough state to work.

A: KEY question #1: Did you buy SBS preinstalled on the server?  If so, you CANNOT virtualize it.  OEM copies cannot be virtualized.  If you bought a volume license or retail copy, you CAN do this - those can be virtualized.
Assuming you don't have an OEM copy then I ask KEY question #2: Are you suggesting you have NO other computer with at least the capability to have 8 GB of RAM and a virtualization capable processor?  Almost EVERY new computer sold in the last couple years and MANY in the last 5 support this configuration.  At worst, you could build one for $400.
You can migrate using third party software like ShadowProtect or DoubleTake among others... these are not inexpensive solutions.
If your TIME is not valueable, then you can do this the by doing a swing migration to a temporary server.  It's like an upgrade only you're staying on the same version.  You install another system with Hyper-V, migrate to that server, then reload the physical server with Hyper-V and export the VM from the temporary server and import into the newly installed physical server running Hyper-V.
I did basically this exact same thing for a client in October (only difference, is we upgraded them to SBS 2011 Standard from SBS 2008 Standard.  But logically, it wouldn't have been different to migrate to SBS 2008 (the same version).


text:
Q: incoming call to the server from WAN drop after some sconds i use Elastix 2.4.0 with a static public IP
all call on LAN no problem
any out call from any extension on the LAN To any extension on WAN(internet) no problem
any call from any extension on WAN(internet) to any other extension the call drop off after some seconds.
when i change sip.config to:
localnet=192.168.1.20/255.255.255.0
calls not drop off but no voice

A: It is not programming question, but debug question
You have ensure
1) you provided external ip to asterisk via externaddress= param
2) your firewall not block sip protocol nor change it(sip alg or similar algorithm not enabled on firewall)


text:
Q: Java ServerSocket and HttpServer I want to implement a client server communication involving decent amount of data being passed.       (~ 50MB)
Should I implement the back end using the ServerSocket or HttpServer?
What are the pointers to decide?
Thanks.

A: Mainly it depends if you want to communicate to the client using the HTTP protocol or you want to set up a simple TCP/IP connection and than use the another application protocol.
Netty simplify the implementation of both the solution, Ratpack focuses on HTTP.

A: you give too little details about what the backend would be. Standard approaches use a Tomcat at the back (if you are in Java) or apache webserver and a REST based data exchange mechanism between the client and server.


text:
Q: Simple packet capturing I've got a GPS tracker which is sending two packets to my server. First of them contains OBD data, in the second one we can find coordinates. I have an application which is listening on specific port (Traccar) however it is capturing only the second packet (support for packets without coordinates is not implemented yet).
I'd like to capture these packets, read the OBD data and insert them to an SQL database. I can do that manually by using tcpdump, but of course this is not the solution. What is the best and most efficient way to solve this problem? Should I use popen() to open a pipe to tcpdump? Is there any other way?

A: Piping' tcpdump: in my experience it's always risky to parse the output of a command/program. Output format may change depending on the version of the program, the platform it's running on, and the LOCALE used. These surprises come out when you're deploying the software.
For a bit more of coding, the second option would be to embed the gut of tcpdump, that is to says libpcap. It's not that hard, a quick introduction here:
http://www.tcpdump.org/pcap.html
...it would be cleaner, but still, like with tcpdump, you will be "naked on the wire", just seeing Ethernet frames, without the IP, TCP, UDP etc layers that you may need.
But these (tcpdump or libpcap) are workaround.
Since Traccar is open source, did you investigate the amount of work to add the feature you require? In this situation, I'd spend a couple of hours investigating that.


text:
Q: Stop output from drools when starting OptaPlanner from a JAR How to stop the drools logger when executing OptaPlanner from a compiled JAR?
In the logback.xml file the drools output is commented out and when i run the project directly from Eclipse everything is ok the only output is the one from OptaPlanner (either debug or trace) , but when i compile everything into a JAR and run it from the JAR for some reason i also get the drools output.

A: I solved this with turning off the Drools logger through the Java API.
Logger droolsLogger = (Logger) LoggerFactory.getLogger("org.drools");
droolsLogger.setLevel(Level.OFF);


text:
Q: Sincronizacion python Me podrían ayudar con este código, necesito hacer el "faneuil Hall problem" este dice lo siguiente:

"There are three kinds of threads: immigrants, spectators, and a one
  judge. Immigrants must wait in line, check in, and then sit down. At
  some point, the judge enters the building. When the judge is in the
  building, no one may enter, and the immigrants may not leave.
  Spectators may leave. Once all immigrants check in, the judge can
  confirm the naturalization. After the confirmation, the immigrants
  pick up their certificates of U.S. Citizenship. The judge leaves at
  some point after the confirmation. Spectators may now enter as before.
  After immigrants get their certificates, they may leave."

La cosa es que al momento de sincronizar los hilos, el hilo del inmigrante no desbloquea al juez por lo que en el if me toma como juez = 0
No se que estoy haciendo mal si pudieran echarme una mano y explicarme en que me equivoque. Muchas gracias..
import threading
import time

condition = threading.Semaphore(1)
mutex = threading.Semaphore(1)
confirmar = threading.Event()

entrar = 0
registrar = 0
juez = 0

class Inmigrante(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global entrar, registrar
        print ("comenzar inmigrante\n")

        condition.acquire()
        print("[%s]Inmigrante: Entrar\n" % time.strftime("%H:%M:%S"))
        entrar += 1
        print("[%s]Inmigrante: Entrar: %d\n" % (time.strftime("%H:%M:%S"), entrar))
        print ("aaa\n")
        condition.release()
        mutex.acquire()

        print("[%s]Inmigrante: Registar\n" % time.strftime("%H:%M:%S"))
        registrar += 1
        print("[%s]Inmigrante: Registar: %d\n" % (time.strftime("%H:%M:%S"), registrar))

        print ("valor de juez es: %d\n" % juez )
        if(juez == 1 and entrar == registrar):
            mutex.notify()

        else:
            mutex.release()

        print("[%s]Inmigrante: Sentarme\n" % time.strftime("%H:%M:%S"))
        confirmar.wait()

        print("[%s]Inmigrante: Jurar\n" % time.strftime("%H:%M:%S"))
        print("[%s]Inmigrante: Obtener certificado\n" % time.strftime("%H:%M:%S"))

        condition.acquire()
        print("[%s]Inmigrante: Salir\n" % time.strftime("%H:%M:%S"))
        condition.release()

class Juez(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global entrar, registrar
        print ("comenzar juez\n")
        condition.acquire()
        mutex.acquire()

        print("[%s]Juez:Entrar\n" % time.strftime("%H:%M:%S"))
        juez = 1
        print ("valor juezzzz: %d \n" % juez)
        print("[%s]Juez: Juez: %d\n" % (time.strftime("%H:%M:%S"), juez))

        if(entrar > registrar):
            mutex.release()

        print("[%s]Juez:Confirmando a inmigrante\n" %   time.strftime("%H:%M:%S"))
        confirmar.set()
        entrar = registrar = 0
        print("[%s]Juez: Entrar: %d Registrar: %d\n" % (time.strftime("%H:%M:%S"), entrar, registrar))

        print("[%s]Juez:Salir\n" %   time.strftime("%H:%M:%S"))
        juez = 0
        print("[%s]Juez: Juez: %d\n" % (time.strftime("%H:%M:%S"), juez))

        mutex.release()
        condition.release()

class Espectador(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        print ("comenzar espectador\n")
        condition.acquire()

        print("[%s]Espectador: Entrar\n" % time.strftime("%H:%M:%S"))
        condition.release()

        print("[%s]Espectador: Espectear\n" % time.strftime("%H:%M:%S"))

        print("[%s]Espectador: Salir\n" % time.strftime("%H:%M:%S"))

inmigrante = Inmigrante()
judge = Juez()
espectador = Espectador()

inmigrante.start()
espectador.start()
judge.start()

inmigrante.join()
espectador.join()
judge.join()


text:
Q: How do I look up a value in a hash based on an array of keys? With Ruby (2.4), I want to extend the core hash functionality to search for keys based on an array and return the value from the first element that can be found from that array.  I have this in my lib/core_ext/hash_with_indifferent_access.rb file ...
class CaseInsensitiveHash < HashWithIndifferentAccess
  # This method shouldn't need an override, but my tests say otherwise.
  def [](key)
    if key.kind_of?(Array)
      find_by_arr(arr)
    else
      super convert_key(key)
    end
  end

  protected

  def convert_key(key)
    key.respond_to?(:downcase) ? key.downcase : key
  end

  def find_by_arr(arr)
    arr.inject(self){|h, k| h.to_h[k]}
  end

end

However, it is not working as expected. In my code below, the search 'h[["a", "b"]]' should produce "1", because the first element, "a", is a key in my hash.
2.4.0 :001 > h = {"a" => 1, "b" => 2}
 => {"a"=>1, "b"=>2}
2.4.0 :002 > h["a"]
 => 1
2.4.0 :003 > h[["a", "b"]]
 => nil

How do I modify my code so that I can pass in an array as a key to a hash and it will start searching for values iteratively by each element in the array?

A: You've almost got it, but the problem is that h = { ... } creates a plain-old Hash, not the kind you've added these methods to.
The first fix is to do this:
h = CaseInsensitiveHash["a" => 1, "b" => 2]

Then you get the right type of object and your method actually runs.
There's a typo in your [] method which can be corrected:
def [](key)
  case key
  when Array
    find_by_arr(key)
  else
    super convert_key(key)
  end
end

Your reference to arr doesn't work because that's not defined.
The find_by_arr method also returns the last match, not the first. This can be fixed:
def find_by_arr(arr)
  self[arr.first { |key| self[key] }]
end


text:
Q: Merging 2 sorted files(with similar content) based on Timestamp in shellscript I have 2 identical files with below content:
File1:
1,Abhi,Ban,20180921T09:09:01,EmpId1,SalaryX
4,Bbhi,Dan,20180922T09:09:03,EmpId2,SalaryY
7,Cbhi,Ean,20180923T09:09:05,EmpId3,SalaryZ
9,Dbhi,Fan,20180924T09:09:09,EmpId4,SalaryQ

File2:
11,Ebhi,Gan,20180922T09:09:02,EmpId5,SalaryA
12,Fbhi,Han,20180923T09:09:04,EmpId6,SalaryB
3,Gbhi,Ian,20180924T09:09:06,EmpId7,SalaryC
5,Hbhi,Jan,20180925T09:09:08,EmpId8,SalaryD

I want to append all File1's content in Files (based on the date in ascending order)
Outcome:
1,Abhi,Ban,20180921T09:09:01,EmpId1,SalaryX
11,Ebhi,Gan,20180922T09:09:02,EmpId5,SalaryA
4,Bbhi,Dan,20180922T09:09:03,EmpId2,SalaryY
12,Fbhi,Han,20180923T09:09:04,EmpId6,SalaryB
7,Cbhi,Ean,20180923T09:09:05,EmpId3,SalaryZ
3,Gbhi,Ian,20180924T09:09:06,EmpId7,SalaryC
9,Dbhi,Fan,20180924T09:09:09,EmpId4,SalaryQ
5,Hbhi,Jan,20180925T09:09:08,EmpId8,SalaryD

A: You can use below AWK construct to do this :-
awk -F "," 'NR==FNR{print $4, $0;next} NR>FNR{print $4, $0;}' f1.txt f2.txt | sort | awk '{print $2}'

Explanation :-
Prefix date column ($4) before every line ($0) for both the files.
sort it. And Then print $2 which is whole line.
These printed lines will be in sorted order by date.
f1.txt and f2.txt are two file names.

A: You can try the following command
awk 'FNR==NR{a[FNR]=$0;next}{print a[FNR]"\n"$0}' file1 file2

with an array a store file1's datas, FNR is a's key.


text:
Q: Firebase onAuthStateChanged and Redux state I have a loading screen component in React Native. Whenever Auth state changes, i navigate to the desired screen.
 When user is in process of registration i flag the redux state as isRegistering = true. This is because after registration is completed with firebase, i still want to show registration completed screen and hold off the automatic navigation from loading screen based on auth state.
The problem seems to be that when the event is called on auth change, the redux state is empty. That is eventho i know from debugging that the redux state had data before and it has them right after them event. But during the event and checking on isRegistration in Redux, the state is completely empty ( reset to default state ).
I checked on all my actions, reducer etc. There is nothing called, the redux stated is just being checked at the moment of authstatechanged event and at that moment it has no data, eventho the data were there right before it.
componentDidMount() {
        firebase.auth().onAuthStateChanged(user => {
            if (this.props.userObject.isRegistering === false) {
                this.props.navigation.navigate(user ? 'MainScreen' : 'LandingPage')
            }
        })
    }

const mapStateToProps = (state) => {
    return {
        userObject: state.user
    }
}

A: Try this,
componentDidMount() {
     var that = this;
        firebase.auth().onAuthStateChanged(user => {
            if (that.props.userObject.isRegistering === false) {
                that.props.navigation.navigate(user ? 'MainScreen' : 'LandingPage')
            }
        })
    }


text:
Q: How can I compile function with Apply? For example, I tried to compile this function but Mathematica gives "The only function arguments supported are Times, Plus, or List", I have no a way to compile this.
isPrime = Compile[{{n, _Integer}},
  And @@ (Mod[n, #] != 0 & /@ Range[2, Sqrt@N@n])
  ]

A: To check whether the sentence is False or True, the And function is not appropriate, but FreeQ works best by J.M.:
isPrime =
 Compile[{{n, _Integer}},
  And @@ (Mod[n, #] != 0 & /@ Range[2, Sqrt@N@n])]

Compile::cpapot: Compilation of And@@(n mod #1!=0&)/@Range[2,Sqrt[N[n]]] is not supported for the function argument And. The only function arguments supported are Times, Plus, or List. Evaluation will use the uncompiled function. >>

But:
isPrime =
 Compile[{{n, _Integer}}, FreeQ[Mod[n, Range[2, Sqrt[n]]], 0]]


text:
Q: Bootstrap Mega Menu with Yamm Center and make full width I am using the Yamm 3 mega menu for bootstrap.
I am having problems making the the menu go full width right across the whole screen outside of the container, then having the menu options centered in the middle.
For example on the link below, click on the navigation on PICTURES > this is exactly what i want but for the white background to carry on across the full width of the screen:
http://geedmo.github.io/yamm3/
I would like to similar to the auto trader. co . uk website.
I cannot figure it out at all, hope one of you CSS ninjas can help me!
Here is an example of what i want:
http://jsfiddle.net/5G845/1/
Here is what i am getting > click on PICTURES. Using the same markup:
http://geedmo.github.io/yamm3/

    nav sub menu here

Thanks

A: Since it is within the container of the page, you will need to remove the "max-width" from the container, doing that will allow the width of the drop-down to span across the page.


text:
Q: Do I need a swap space to use Hybrid-sleep? Battery levels setting is now handled by UPower on latest Ubuntu and other systems. Instead of using gsettings, one should now edit the file /etc/UPower/UPower.conf.
As specified by that file:
# The action to take when "TimeAction" or "PercentageAction" above has been
# reached for the batteries (UPS or laptop batteries) supplying the computer
#
# Possible values are:
# PowerOff
# Hibernate
# HybridSleep
#
# If HybridSleep isn't available, Hibernate will be used
# If Hibernate isn't available, PowerOff will be used

That is, normal Suspend is not possible at critical battery level, but only HybridSleep. (That was posted as a bug here.)
But Hybrid Sleep doesn't seem to be available on my system.
Could it be because I don't have a swap space? (That's what I think the bug reporter says: "PowerOff is the only option for machines lacking a swap partition".)

A: The answer is 'Yes'.
After creating a swap partition both hibernation and hybrid sleep are available.
Hybrid Sleep is both hibernation and sleep/suspend, but to the user it looks more like suspend. Like hibernation, it 'swaps' RAM data to the hard disk and can restore it even in case of power failure. It acts like sleep/suspend in that it refreshes RAM constantly and therefore (if the battery is not fully depleted) can wake up as quickly as normal suspend.


text:
Q: How to convert date format containing timezone CEST in Java I get a dateformat from wicket which Java can't convert:
Mon Apr 20 00:00:00 CEST 2020
The problem is that CEST is not a timezone Java supports. I've tried CST what should work but it doesn't.  Error is:

Unparseable date: "Mon Apr 20 00:00:00 CST 2020"

Code:
DateFormat dateFormat = new SimpleDateFormat(
        "yyyy-MM-dd", Locale.GERMANY);
dateFormat.parse("Mon Apr 20 00:00:00 CST 2020");
System.out.println(dateFormat.format(new Date()));

I need to convert this date in a JSON-Format so yyyy-MM-dd.
How can I do this?

A: This works for me:
        String dateStr = "Mon Apr 20 00:00:00 CEST 2020";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM d H:mm:ss zzz yyyy", Locale.ENGLISH);
        ZonedDateTime parsedDate = ZonedDateTime.parse(dateStr, formatter);
        System.out.println(parsedDate);
        System.out.println(parsedDate.format(DateTimeFormatter.ISO_LOCAL_DATE));

The output from the above is: 2020-04-20T00:00+02:00[Europe/Paris] and 2020-04-20
I think the trick is that you need a formatter to parse this date because it's a pretty strange format using the year at the end of the string with the hours/minutes/seconds in between that and the rest of the date. Default date/time parsing isn't going to work.


text:
Q: How to get a Response from other web site, using Jquery or PHP? I have a query
I need to make a login form, where I have to get a Response from other web site, i know there is HttpResponseMessage, but I think this is to consume a web API, so I really wanna know how to get the response of the web site, cause I need to get a success login or if there is a fail with the logon
Is there any ways to make it?
and the code:

Inicio de Sesión

      <form action="http://us.mzoneweb.net/Scope.MZone.Web/Logon.ashx" method="post" target="TheMZoneFrame">

<input name="Username" id="User" type="text" placeholder="Usuario">

<input name="Password" id="Pass" type="password" placeholder="Contraseña">

<input name="LogoutUrl" type="hidden" value="">

<input name="ErrorUrl" type="hidden" value="">

<input name="Version" type="hidden" value="">

       <input type="checkbox" name="remember_me" id="remember_me">
       Remember me on this computer

<input name="Submit1" id="btnSub" type="submit" value="Iniciar Sesión" >

      </form>

 <noframes>Your browser does not support IFRAME elements.</noframes>

A: Use cURL.
Here's a sample function that will get a response from another site:
/*
 * Makes an HTTP request via GET or POST, and can download a file
 * @returns - Returns the response of the request
 * @param $url - The URL to request, including any GET parameters
 * @param $params - An array of POST values to send
 * @param $filename - If provided, the response will be saved to the
 *    specified filename
 */
function request($url, $params = array(), $filename = "") {
    $ch = curl_init();
    $curlOpts = array(
        CURLOPT_URL => $url,
        // Set Useragent
        CURLOPT_USERAGENT =>
            'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0)
                    Gecko/20100101 Firefox/29.0',
        // Don't validate SSL
        // This is to prevent possible errors with self-signed certs
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true
    );
    if(!empty($filename)){
        // If $filename exists, save content to file
        $file2 = fopen($filename,'w+')
            or die("Error[".__FILE__.":".__LINE__."]
                    Could not open file: $filename");
        $curlOpts[CURLOPT_FILE] = $file2;
    }
    if (!empty($params)) {
        // If POST values are given, send that shit too
        $curlOpts[CURLOPT_POST] = true;
        $curlOpts[CURLOPT_POSTFIELDS] = $params;
    }
    curl_setopt_array($ch, $curlOpts);
    $answer = curl_exec($ch);
    // If there was an error, show it
    if (curl_error($ch)) die(curl_error($ch));
    if(!empty($filename)) fclose($file2);
    curl_close($ch);
    return $answer;
}


text:
Q: unable to refer app module classes in dynamic feature module when running unit test cases Our project has dynamic feature module with a dependency on the app module. The classes in the dynamic feature module have a dependency on app module.
We also have unit test cases in the dynamic module testing individual classes of the dynamic module. The unit tests run fine when run through android studio. Got an error running unit tests using gradlew.
Below is the error:
./gradlew :dynamic_feature1:testDebugUnitTest
Getting the following error:
15:40:13.225 [DEBUG] [TestEventLogger]
15:40:13.225 [DEBUG] [TestEventLogger] com.example.dynamic_feature1.DynamicPresenterTest > testXyz FAILED
15:40:13.225 [DEBUG] [TestEventLogger]     java.lang.NoClassDefFoundError: com/example/dynamicfeature/AppBase
15:40:13.225 [DEBUG] [TestEventLogger]         at java.lang.ClassLoader.defineClass1(Native Method)
15:40:13.225 [DEBUG] [TestEventLogger]         at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
15:40:13.225 [DEBUG] [TestEventLogger]         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)```

A: To fix the java.lang.NoClassDefFoundError: com/example/dynamicfeature/AppBase issue, try this command:
./gradlew test

see  Android jUnit Test java.lang.NoClassDefFoundError: android/database/sqlite/SQLiteOpenHelper


text:
Q: How can we initialize a parametrized constructor as default for a string? For an integer we can do it as
class A{
  int a;
public:
  A(int x = 0){ a = x; }
};

A: It is difficult to understand exactly what you are asking.  I think you are asking how to specify a default value for a std::string parameter.  If that is the case, you can do it like this:
class A{
  string a;
public:
  A(string x = ""){ a = x; }
};

or:
class A{
  string a;
public:
  A(const string &x = string()){ a = x; }
};

Though, in either case, you should be initializing the a member using the constructor's member initialization list instead of the constructor's body:
class A{
  string a;
public:
  A(string x = "") : a(x) { }
};

class A{
  string a;
public:
  A(const string &x = string()) : a(x) { }
};


text:
Q: Ldapsearch and base64 encoding of non ASCII values If the database contains non ASCII data like (Lehtelä) , the Ldapsearch returns it as an base64 encoded (:: TGVodGVsw6Q=) .
I followed this blog, for decoding it(https://lurchi.wordpress.com/2009/11/03/ldapsearch-and-base64-encoding/)
It only helps if the base64 is a single line value, how to handle it if value spans across multiple lines.
 ldapsearch -x -H ldap://76.656.23.56 -D cn=admin -w abc -b "o=my_comp" -s sub -LLL 'mail=mail@gmail.com'  sn nrfAssignedResources | un64

dn: cn=SBOSTRO2,ou=Employees,ou=Active,ou=Identities,ou=Meta,o=VCC
base64: invalid input
nrfAssignedResources:: "cn=VCCBIZ GPO 0100 account,cn=ResourceDef"
 zLGNuPVJvbGVDb25maWcsY249QXBwQ29uZmlnLGNuPVVBLGNuPURyaXZlclNldCxvdT1TeXN0ZW0s
 bz1WQ0MjMiM8YXNzaWdubWsjdfahgsgacgfacxfg sahhagsvgcagjMyMzZaPC9zdGFydF90bT48c
 mVxX3RtPjIwMTQwMTI3MDYzMjM2WjwvcmVxX3RtPjxpbnN0LWd1aWQ+ZGM5M2ZkODRjYmQ3NGY3MG
 JjM2VmZjRlODAyZDdlMjE8L2luc3QtZ3VpZD48cmVxPmNuPUpBU1BMVU5ELG91PUVtcGxveWVlcyx
 W50Pg==
sn:: "Boström "

As you can see here, because sn has only single  line its complete("Boström") and nrfAssignedResources value is multiple line, only first line is decoded not the rest.
the AWK code is available in the link above.

A: You can pass your ldapsearch the option -o ldif-wrap=no which should avoid the wrapping.


text:
Q: Add rows on table on button click using spring mvc and bind added rows to modelAttribute I have a table for which I am passing list of student objects from my spring controller method, On page load  3 rows are populated. I want the user to be able to add more rows delete existing rows on button click. Can anyone tell me how to achieve this. See below my controller and jsp code. On clicking add I want to add 3 more rows selecting check box and clicking delete row should delete the row. i want the the added columns to be binded
I am very new to jQuery is this possible without jQuery. If not please tell me in detail how to achieve this using jQuery

Student Entity
@Entity
@Table(name="STUDENT_REGISTRATION")
public class Student {

    private int studentId;
    private String firstName;
    private String lastName;
    private Date dob;
    private String sex;
    private String status;
    private Date doj;
    private int deptId;
    private String deptName;
    private int batchId;
    private String batchName;
    private int roleId;
    private String roleName;
    private String regNo;
    public Student(){

    }

    public Student(int studentId, String firstName, String lastName, Date dob,
            String sex, String status, Date doj, int deptId,
            String deptName, int batchId, String batchName, int roleId,
            String roleName, String regNo) {
        super();
        this.studentId = studentId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
        this.sex = sex;
        this.status = status;
        this.doj = doj;
        this.deptId = deptId;
        this.deptName = deptName;
        this.batchId = batchId;
        this.batchName = batchName;
        this.roleId = roleId;
        this.roleName = roleName;
        this.regNo = regNo;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="STUDENT_ID")
    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }
    @Column(name="STUDENT_FIRST_NAME")
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    @Column(name="STUDENT_LAST_NAME")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    @Column(name="DOB")
    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }
    @Column(name="SEX")
    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
    @Column(name="STATUS")
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    @Column(name="DOJ")
    public Date getDoj() {
        return doj;
    }

    public void setDoj(Date doj) {
        this.doj = doj;
    }

    @Column(name="DEPT_ID")
    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }
    @Column(name="DEPT_NAME")
    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
    @Column(name="BATCH_ID")
    public int getBatchId() {
        return batchId;
    }

    public void setBatchId(int batchId) {
        this.batchId = batchId;
    }
    @Column(name="BATCH_NAME")
    public String getBatchName() {
        return batchName;
    }

    public void setBatchName(String batchName) {
        this.batchName = batchName;
    }
    @Column(name="ROLE_ID")
    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }
    @Column(name="ROLE_NAME")
    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    @Column(name="REG_NO")
    public String getRegNo() {
        return regNo;
    }

    public void setRegNo(String regNo) {
        this.regNo = regNo;
    }

}

Student DTO
public class StudentDTO {

    private int studentId;
    private String firstName;
    private String lastName;
    private Date dob;
    private String sex;
    private String status;
    private Date doj;
    private int deptId;
    private String deptName;
    private int batchId;
    private String batchName;
    private int roleId;
    private String roleName;
    boolean select;
    private String regNo;

    public StudentDTO(){

    }

    public StudentDTO(int studentId, String firstName, String lastName,
            Date dob, String sex, String status, Date doj, int deptId,
            String deptName, int batchId, String batchName, int roleId,
            String roleName, boolean select, String regNo) {
        super();
        this.studentId = studentId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
        this.sex = sex;
        this.status = status;
        this.doj = doj;
        this.deptId = deptId;
        this.deptName = deptName;
        this.batchId = batchId;
        this.batchName = batchName;
        this.roleId = roleId;
        this.roleName = roleName;
        this.select = select;
        this.regNo = regNo;
    }

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Date getDoj() {
        return doj;
    }

    public void setDoj(Date doj) {
        this.doj = doj;
    }

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public int getBatchId() {
        return batchId;
    }

    public void setBatchId(int batchId) {
        this.batchId = batchId;
    }

    public String getBatchName() {
        return batchName;
    }

    public void setBatchName(String batchName) {
        this.batchName = batchName;
    }

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public boolean isSelect() {
        return select;
    }

    public void setSelect(boolean select) {
        this.select = select;
    }

    public String getRegNo() {
        return regNo;
    }

    public void setRegNo(String regNo) {
        this.regNo = regNo;
    }

}

Here I am adding 3 Student Objects
    public List<StudentDTO> addStudentToList(){
        List<StudentDTO> studentList = new ArrayList<StudentDTO>();
        StudentDTO stud = new StudentDTO();
        for(int i=0; i<3; i++){
            studentList.add(stud);
        }

        return studentList;

    }

Student Controller class

    @RequestMapping(value="/addStudent", method=RequestMethod.GET)
    public ModelAndView getStudentForm(ModelMap model)
    {   List<StudentDTO> studentList = studentService.getStudentAttributesList();
        //List<Integer> userIdForDropDown = userDAO.getAllUserIdForDropDown();
        //model.addAttribute("userIdDropDown",userIdForDropDown);

        List<String> deptList = configDAO.getDeptListForDropDown();
        model.addAttribute("deptlist",deptList);
        List<String> batchList = configDAO.getAllBatchForDropDrown();
        model.addAttribute("batchList", batchList);
        ModelAndView mav = new ModelAndView("add_student");
        Student stu = new Student();
        mav.getModelMap().put("add_student", stu);
        StudentForm studentForm = new StudentForm();
        studentForm.setStudentList(studentList);
        model.addAttribute("studentForm",studentForm);
        return mav;
    }

@RequestMapping(value="/addStudent", method=RequestMethod.POST)
    public String saveStudent(@ModelAttribute("add_student") StudentForm studenfForm, BindingResult result, SessionStatus status, ModelMap model) throws ParseException{
        /*if(result.hasErrors()){
            return "add_student";
        }*/
        List<StudentDTO> newList = (List<StudentDTO>) studenfForm.getStudentList();
        List<Student> newList1 = new ArrayList<Student>();
        for(StudentDTO stud:studenfForm.getStudentList()){
            Student student = new Student();
            student.setBatchId(stud.getBatchId());
            student.setBatchName(stud.getBatchName());
            student.setDeptId(stud.getDeptId());
            student.setDeptName(stud.getDeptName());

            SimpleDateFormat sdf = new SimpleDateFormat("DD/MM/YYYY");
            Date dateWithoutTime = sdf.parse(sdf.format(new Date()));

            student.setDob(stud.getDob());
            student.setDoj(stud.getDoj());
            student.setFirstName(stud.getFirstName());
            student.setLastName(stud.getLastName());
            student.setRegNo(stud.getRegNo());
            student.setRoleId(stud.getRoleId());
            student.setRoleName(stud.getRoleName());
            student.setStatus(stud.getStatus());
            student.setSex(stud.getSex());
            student.setStudentId(stud.getStudentId());
            newList1.add(student);
        }
        Integer saveStatus = studentDAO.saveStudentInfo(newList1);
        //Integer res = roleDAO.saveRole(role);
        if(saveStatus!=null){
            status.setComplete();
            model.addAttribute("savedMsg", "Student record saved Successfully.");

        }
        return "redirect:addStudent";

    }

See my jsp page

    <form:form action="addStudent" method="post" commandName="add_student" modelAttribute="studentForm">

Add Student

                <input type="button" id="addrows" name="addrows" class="addperson" value="Add Rows">

                <input type="button" id="removerows" class="removerows" value="Delete Rows" />

                <input type="submit" value="Save" />

                        No

                        Select

                        Reg No

                        First Name

                        Last Name

                        Sex

                        DOB

                        DOJ

                        Dept Name

                        Role Name

                        Batch Name

                        Status

                <c:forEach var="rows" items="${studentForm.studentList}" varStatus="status">

                        ${status.count}

                        <form:checkbox path="studentList[${status.index}].select"/>

                    <form:input  path="studentList[${status.index}].regNo"/>

                    <form:input  path="studentList[${status.index}].firstName"/>

                    <form:input  path="studentList[${status.index}].lastName"/>

                    <form:select  path="studentList[${status.index}].sex">
                        <form:option value="NONE" label="--- Select ---"/>
                        <form:option value="M" label="Male"/>
                        <form:option value="F" label="Female"/>
                        </form:select>

                    <form:input  path="studentList[${status.index}].dob"/>

                    <form:input  path="studentList[${status.index}].doj"/>

                    <form:select  path="studentList[${status.index}].deptName">
                        <form:option value="NONE" label="--- Select ---"/>
                        <form:options items="${deptlist}" />
                        </form:select>

                    <form:select  path="studentList[${status.index}].roleName">
                        <form:option value="NONE" label="--- Select ---"/>
                        <form:option value="ROLE_STUDENT" label="Student"/>
                        <form:option value="ROLE_BATCHREP" label="Batch Rep"/>
                        </form:select>

                    <form:select  path="studentList[${status.index}].batchName">
                        <form:option value="NONE" label="--- Select ---"/>
                        <form:options items="${batchList}" />
                        </form:select>

                    <form:select  path="studentList[${status.index}].status">
                        <form:option value="NONE" label="--- Select ---"/>
                        <form:option value="E" label="Enable"/>
                        <form:option value="D" label="Disable"/>
                        </form:select>

                    </c:forEach>

                        ${savedMsg}

        </form:form>

A: Even though this thread is older, For the benefit of others who is in need of this.
Let me explain with a minimal code and User example with firstName, email, userName and gender fields so that people won't get confused with bigger code.
Consider you are sending 3 empty users in usersList from controller this will creates 3 empty rows. If you inspect/view page source you will see

*

*Rows(<input> tags) with different id's like list0.firstName
list1.firstName

*Rows(<input> tags) with different names like list[0].firstName
list[1].firstName
Whenever form is submitted id's are not considered by server(added for only for helping client side validations), but name attribute will be interpreted as request parameter and are used to construct your modelAttribute, hence attribute names are very important while inserting rows.
Adding row
So, How to construct/append new rows?
If i submit 6 users from UI, controller should receive 6 user object from usersList. Steps to achieve the same is given below
1. Right click -> view page source. You will see rows like this(you can see *[0].* in first row and *[1].* in second row)

    <input id="list0.firstName" name="list[0].firstName" type="text" value=""/>
    <input id="list0.email" name="list[0].email" type="text" value=""/>
    <input id="list0.userName" name="list[0].userName" type="text" value=""/>

            <input id="list0.gender1" name="list[0].gender" type="radio" value="MALE" checked="checked"/>Male

            <input id="list0.gender2" name="list[0].gender" type="radio" value="FEMALE"/>Female

    <input id="list1.firstName" name="list[1].firstName" type="text" value=""/>
    <input id="list1.email" name="list[1].email" type="text" value=""/>
    <input id="list1.userName" name="list[1].userName" type="text" value=""/>

            <input id="list1.gender1" name="list[1].gender" type="radio" value="MALE" checked="checked"/>Male

            <input id="list1.gender2" name="list[1].gender" type="radio" value="FEMALE"/>Female

*Copy first row and construct a javascript string and replace '0' with variable name index. As given in below sample

'
'+
    '<input id="list'+ index +'.firstName" name="list['+ index +'].firstName" type="text" value=""/>	'+
    '<input id="list'+ index +'.email" name="list['+ index +'].email" type="text" value=""/>	'+
    ...
'
';

*Append the constructed row to the
. Rows get added in UI also on submission of form newly added rows will be received in controller.

Deleting row
Deleting row is little bit complicated, i will try to explain in easiest way

*

*Suppose you added row0, row1, row2, row3, row4, row5

*Deleted row2, row3. Do not just hide the row but remove it from the
DOM by catching event.

*Now row0,row1,row4,row5 will get submitted but in the controller your
userList will have 6 user object but user[2].firstName will be null
and user[3].firstName will be null.

*So in your controller iterate and check for null and remove the
user.(Use iterator don't use foreach to remove user object)

Posting code to benefit beginners.
//  In Controller
@RequestMapping(value = "/app/admin/add-users", method = RequestMethod.GET)
public String addUsers(Model model, HttpServletRequest request)
{
    List<DbUserDetails> usersList = new ArrayList<>();

    ListWrapper userListWrapper = new ListWrapper();
    userListWrapper.setList(usersList);

    DbUserDetails user;
    for(int i=0; i<3;i++)
    {
        user = new DbUserDetails();
        user.setGender("MALE"); //Initialization of Radio button/ Checkboxes/ Dropdowns
        usersList.add(user);
    }

    model.addAttribute("userListWrapper", userListWrapper);
    model.addAttribute("roleList", roleList);

    return "add-users";
}

@RequestMapping(value = "/app/admin/add-users", method = RequestMethod.POST)
public String saveUsers(@ModelAttribute("userListWrapper") ListWrapper userListWrapper, Model model, HttpServletRequest request)
{
    List<DbUserDetails> usersList = userListWrapper.getList();
    Iterator<DbUserDetails> itr = usersList.iterator();

    while(itr.hasNext())
    {
        if(itr.next().getFirstName() == null)
        {
            itr.remove();
        }
    }

    userListWrapper.getList().forEach(user -> {
        System.out.println(user.getFirstName());
    });
    return "add-users";
}

//POJO
@Entity
@Table(name = "userdetails")
@XmlRootElement(name = "user")
public class DbUserDetails implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String  firstName;
    private String  userName;
    private String  email;
    private String  gender;

    //setters and getters
}

//list wrapper
public class ListWrapper
{
    private List<DbUserDetails> list;

    //setters and getters
}

In JSP
<form:form method="post" action="${pageContext.request.contextPath}/app/admin/add-users" modelAttribute="userListWrapper">

                <spring:message code="app.userform.firstname.label"/>
                <spring:message code="app.userform.email.label"/>
                <spring:message code="app.userform.username.label"/>
                <spring:message code="app.userform.gender.label"/>

            <c:forEach items="${userListWrapper.list}" var="user" varStatus="loop">

                    <form:input path="list[${loop.index}].firstName" />
                    <form:input path="list[${loop.index}].email" />
                    <form:input path="list[${loop.index}].userName" />

                            <form:radiobutton path="list[${loop.index}].gender" value="MALE" /><spring:message code="app.userform.gender.male.label"/>

                            <form:radiobutton path="list[${loop.index}].gender" value="FEMALE" /><spring:message code="app.userform.gender.female.label"/>

            </c:forEach>

        <button type="submit" class="btn btn-primary">SAVE ALL</button>

</form:form>

Javascript needs to be included in JSP
var currentIndex = 3; //equals to initialRow (Rows shown on page load)
function addRow()
{
    var rowConstructed = constructRow(currentIndex++);
    $("#tbodyContainer").append(rowConstructed);
}

function constructRow(index)
{
    return '
'+
    '<input id="list'+ index +'.firstName" name="list['+ index +'].firstName" type="text" value=""/>	'+
    '<input id="list'+ index +'.email" name="list['+ index +'].email" type="text" value=""/>	'+
    '<input id="list'+ index +'.userName" name="list['+ index +'].userName" type="text" value=""/>	'+
    ''+
        ''+
            '<input id="list'+ index +'.gender1" name="list['+ index +'].gender" type="radio" value="MALE" checked="checked"/>Male'+
        ''+
        ''+
            '<input id="list'+ index +'.gender'+ index +'" name="list['+ index +'].gender" type="radio" value="FEMALE"/>Female'+
        ''+
    '	'+
'
';
}


text:
Q: How to have "Copy To (My app)" on a UIDocumentInteractionController
How can I have a "Copy To MyExampleApp" in a UIDocumentationController.
The file types can be any : pdf,pptx,doc,txt ...
P.S : Objective-C code will be helpful.
Thank You !

A: //AppDelegate.m
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication (NSString *)sourceApplication annotation:(id)annotation {
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [fileURLFromLaunch path];
BOOL success = [fileManager copyItemAtPath:filePath toPath:finalFilePath error:&error];
if (success) {
    NSLog(@"success");
}}

A: Try Adding DocType Support to your App for the extension and then handle the delegates to do the needful.
Reference: Registering the filetypes your app supports


text:
Q: la ultima tabla que contiene la llave forania no me deja crear la tabla CREATE TABLE usuarios(
   id       int(7) unsigned AUTO_INCREMENT not null,
   nombre   varchar(100) not null,
   apellido varchar(100) not null,
   email    varchar(255) not null,
   pasword  varchar(255) not null,
   fecha    date not null,
   CONSTRAINT pk_usuarios PRIMARY KEY (id),
   CONSTRAINT uq_email UNIQUE (email)
)ENGINE=innoDB;

CREATE TABLE categorias (
   id          int(255) auto_increment not null,
   nombre      varchar(100) not null,
   CONSTRAINT pk_categorias PRIMARY KEY (id)
   ) ENGINE=innoDB;

CREATE TABLE entradas(
id int(255) auto_increment not null,
usuarioid int(255) not null,
categoriaid int(255) not null,
titulo varchar(255) not null,
fecha date not null,
CONSTRAINT pk_entradas PRIMARY KEY (id),
**constraint FK_usuario FOREIGN KEY (usuarioid) REFERENCES usuarios(id),
constraint FK_categoria FOREIGN KEY (categoriaid) REFERENCES categorias(id)
);**

A: Cuando agregas una clave foránea, tienes que fijarte que los tipos de datos de las columnas coincidan exactamente, o al menos que puedan almacenar el mismo conjunto de valores.
En tu caso eso no se cumple porque la columna id de usuarios es "unsigned" y la clave foránea no lo es. En resumen la PK no es capaz de almacenar todos los valores que la clave foránea podría producir. Para resolver el problema haz que los tipos de datos sean idénticos. Por ejemplo:
CREATE TABLE usuarios(
   id       int AUTO_INCREMENT not null,
   nombre   varchar(100) not null,
   apellido varchar(100) not null,
   email    varchar(255) not null,
   pasword  varchar(255) not null,
   fecha    date not null,
   CONSTRAINT pk_usuarios PRIMARY KEY (id),
   CONSTRAINT uq_email UNIQUE (email)
)ENGINE=innoDB;

CREATE TABLE categorias (
   id          int auto_increment not null,
   nombre      varchar(100) not null,
   CONSTRAINT pk_categorias PRIMARY KEY (id)
   ) ENGINE=innoDB;

CREATE TABLE entradas(
  id int(255) auto_increment not null,
  usuarioid int not null,
  categoriaid int not null,
  titulo varchar(255) not null,
  fecha date not null,
  CONSTRAINT pk_entradas PRIMARY KEY (id),
  constraint FK_usuarioxx FOREIGN KEY (usuarioid) REFERENCES usuarios(id),
  constraint FK_categoria FOREIGN KEY (categoriaid) REFERENCES categorias(id)
);

Ejemplo que se puede ver funcionando en DB Fiddle.


text:
Q: get element from Vec that tell me could not move in rust I am learning to using rust to do some work. I am using this code to find element from Vec in rust:
let filtered_music:Vec<Music> = musics.iter()
            .filter(|item| item.source_id == fav.source_id)
            .collect();

the next step I want to put he element to another object:
let curr_music = &filtered_music[0];
let fav_resp = FavMusicResponse{
    id: (&fav.id.to_string()).parse().unwrap(),
    song_id: None,
    created_time: 0,
    updated_time: 0,
    user_id: 0,
    source_id: fav.source_id.to_string(),
    like_status: 0,
    source: 0,
    playlist_id: 0,
    play_count: 0,
    fetched_download_url: None,
    downloaded: None,
    music: curr_music
};

but the compiler tell me expected Music, found &Music , what should I do to fix it? This is my minimal example about this problem that could run in https://play.rust-lang.org/ to reproduce this situation:
fn main() {
    println!("Hello, world!");
    let musics:Vec<Music> = Vec::new();
    let filtered_music:Vec<&Music> = musics.into_iter()
            .filter(|item| item.source_id == "1")
            .collect();
    let resp = MusicRes{
        music: filtered_music[0]
    };
}

pub struct Music {
    pub id: i64,
    pub name: String,
    pub artists: String,
    pub album_id: i64,
    pub publishtime: i64,
    pub status: i32,
    pub duration: i32,
    pub source_id: String,
    pub source: i32,
    pub created_time: i64,
    pub updated_time:i64,
    pub album: String,
    pub fetched_download_url: i32
}

pub struct MusicRes {
    pub music:Music
}

A: Here are the major changes
fn take<T>(mut vec: Vec<T>, index: usize) -> Option<T> {
    if index < vec.len() {
        Some(vec.swap_remove(index))
    } else {
        None
    }
}
fn main() {
    println!("Hello, world!");
    let musics: Vec<Music> = Vec::new();
    let filtered_music: Vec<Music> = musics
        .into_iter()
        .filter(|item| item.source_id == "1")
        .collect();
    let resp = MusicRes {
        music: take(filtered_music, 0).unwrap(),
    };
}

Edit
If you just want the first element of your music vector, consider using .next() after filtering. This would avoid the take function.
My answer is based on this answer
Here is a working example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6d4137ccb7f737fa6261ea8c27bd012b


text:
Q: Add namespace Prefix in Nusoap PHP I'm using nusoap v 1.123, I'm trying to add the prefixes urn in my generated request of nusoap
This is what I am expecting
<soapenv:Envelope  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:urn="urn:mnop:acceptor:contract">
       <soapenv:Header>
          <urn:authenticationHeader>
             <urn:name>abctest</urn:name>
             <urn:userid>dddd</urn:userid>
             <urn:pass>errerere</urn:pass>
          </urn:authenticationHeader>
       </soapenv:Header>

and this is what the code is generating
   <SOAP-ENV:Header>
          <authenticationHeader>
             <name>abctest</urn:name>
             <userid>dddd</urn:userid>
             <pass>errerere</urn:pass>
          </authenticationHeader>
     </SOAP-ENV:Header>

$header = new SoapHeader($wsdl, 'authenticationHeader',$headerParam);
$soapAction='urn:mnop:acceptor:contract';
$client = new  nusoap_client($wsdl);
$client->setHeaders($headerParam);
$data=$client->call('myoperation',$bodyParam,$namespace,$soapAction,null,null,'document', 'literal');

the urn prefix is missing and SOAP-ENV: need to be replaced with soapenv: , kindly tell me to resolve this issue.
Thanks

A: this is how I solved this problem
$bodyParam = array('urn:operationName'=>array(
    'urn:amount'=>'23232',
    'urn:automati'=>'monUrl',
    'urn:context'=>'',
    'urn:currencyCode'=>'978',
    'urn:customerId'=>'',
    'urn:customerIpAddress'=>'',
    'urn:customerLanguage'=>'fr',
));

A: Solved this problem, nusoap parameters must be configured
add global name space
$client->namespaces['tem'] = "http://tempuri.org/";
and add local namespace for elements
$responseService = $client->call(
            'CAV_GET_DATA',
            $param,
            $namespace = 'tem'
        );

Resolve
<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tem="http://tempuri.org/" xmlns:ns6704="tem"><SOAP-ENV:Body><tem:CAV_GET_DATA><tem:UsuarioID>example</tem:UsuarioID><tem:Password>example</tem:Password><tem:idEmpleado>000000</tem:idEmpleado></tem:CAV_GET_DATA></SOAP-ENV:Body></SOAP-ENV:Envelope>