text:
Q: How can I set a landscape layout just for tablets? Imagine I've a layout folder named layout-port. This layout contains the two-layouts you can see in the picture below (handset).
In the other hand, I've a layout folder which is used when the screen orientation is not in portrait mode, so it's in landscape.

However, when I rotate a device with a small screen, it's going to use the portrait layout, but as the screen is so small, its not optimal and it doesn't look good as the two fragments layout is mainly focused for atleast 600dp tablets.
So the question is,
Is there any way I can use a qualifier to set a Landscape layout for smallest width higher than 600?
I've been checking the docs http://developer.android.com/guide/practices/screens_support.html but it doesn't seem to be able to combine smallest width & orientation.

A: Put the tablet layout in your res/layout-w600dp or whatever smallest width you want to support for the two pane layout.

A: You could just ignore the -port qualifier.
Generally if the device has 600dp (or whatever number you choose), you could show the two-pane layout. Does it really matter if it is in landscape mode or portrait if there is enough space on the screen?
So in general you can put your layout for small screens in the layout folder and use layout-sw600dp for the larger layout.

A: I think what you really want is to declare a folder...
layout-w600dp-land

this will be invoked only if your tablet or w600dp device is in landscape mode.  Basically you can combine qualifiers w600dp with land.


text:
Q: Query in image size in android studio
Hello. There is a ball image of 640X480.In the image, as you can see I have specified layout_width as 849px and layout_height as 680 px.I have taken a background colour of blue.As layout_width specified is much more than 640px(width size of image), then why the image's left side and right side is not surrounded with blue background.Image's top and bottom is surrounded with blue background.
XML Code:
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="849px"
        android:layout_height="680px"
        android:background="#2196F3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ball_640x480" />
</androidx.constraintlayout.widget.ConstraintLayout>

What I cant understand is in the image,after setting wrap_content also why is still there white space below and above the image?
Below is the updated xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ball_640x480" />
</androidx.constraintlayout.widget.ConstraintLayout>

A: Your situation is given due to the fact that the image is not as big as the ImageView is. If you would like the image to completely fill the View you could use the property android:scaleType="centerCrop". You can follow along this visual guide on ImageView's different scale types and see how it behaves on different scale types.
If you would like to have a border along the ImageView I would not use the android:background property because your image is going to be drawn on top of the background and probably completely cover it.
My approach would be to have a parent view that is just a little bit bigger than the image view and that view hold the background property. You can easily do that with a FrameLayout and applying some android:layout_margin to the ImageView like the following example:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#2196F3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/imageView3"
            android:gravity="center"
            android:layout_margin="16dp"
            android:layout_width="849px"
            android:layout_height="680px"
            app:srcCompat="@drawable/ball_640x480" />
    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Screenshot related to the comments:

Code that works
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/ball_640x480"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fastest way to take screenShot of UIView I've searched a lot but only found two methods to take screen shot of UIView.
first renderInContext:
I've used it in a way
CGContextRef context = [self createBitmapContextOfSize:CGSizeMake(nImageWidth, nImageHeight)];
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, nImageHeight);
CGContextConcatCTM(context, flipVertical);
[self.layer setBackgroundColor:[UIColor clearColor].CGColor];
[self.layer renderInContext:context];
CGImageRef cgImage = CGBitmapContextCreateImage(context);
UIImage* background = [UIImage imageWithCGImage: cgImage];
CGImageRelease(cgImage);

Second drawViewHierarchyInRect: which I've used as
UIImage *background = nil;

UIGraphicsBeginImageContextWithOptions (self.bounds.size, NO, self.window.screen.scale);

if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
{
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
}
background = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

I know that the second one is faster than first and it work for me for iPhone because the view has low size. but when I capturing from iPad the video become jerky.
Can Any body tell me faster way of taking screen shot.
any help would be highly appreciated

A: Regarding performance, the Apple Docs state the following:

In addition to -drawViewHierarchyInRect:afterScreenUpdates:, UIView
  now provides another two snapshot related methods,
  -snapshotViewAfterScreenUpdates: and -resizableSnapshotViewFromRect:afterScreenUpdates:withCapInsets:. UIScreen also has -snapshotViewAfterScreenUpdates:.
Unlike UIView's -drawViewHierarchyInRect:afterScreenUpdates:, these
  methods return a UIView object. If you are looking for a new snapshot
  view, use one of
  these methods. It will be more efficient than calling
  -drawViewHierarchyInRect:afterScreenUpdates: to render the view contents into a bitmap image yourself. You can use the returned view
  as a visual stand-in for the current view/screen in your app. For
  example, you might use a snapshot view for animations where updating a
  large view hierarchy might be expensive.

A: There is a third method for taking a snapshot that is much much quicker than either of these but it returns a UIView.
- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates
If you are just using the snapshot to place as a background "image" etc... then I'd use this instead.
However, this is only available for iOS8.
To use it just do...
UIView *snapshotView = [someView snapshotViewAfterScreenUpdates:YES];

A: This Method will return you A snapshot images of particular view
-(UIImage *)createSnapShotImagesFromUIview
{
    UIGraphicsBeginImageContext(CGSizeMake(view.frame.size.width,view.frame.size.height));
    CGContextRef context = UIGraphicsGetCurrentContext();
    [mapView.layer renderInContext:context];
    UIImage *img_screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
     return img_screenShot;
}


text:
Q: How to search the minimum n that 10^n ≡ 1 mod(9x) for given x For given x, I need to calculate the minimum n that equates true for the formula 10^n ≡ 1 (mod 9x)
My algorithm is simple. For i = 1 to inf, I loop it until I get a result. There is always a result if gcd(10, x) = 1. Meanwhile if I don't get a result, I increase i by 1 .
This is really slow for big primes or numbers with a factorization of big values, so I ask if there is another way to calculate it faster. I have tried with threads, getting each thread the next 10^i to calculate. Performance is a bit better, but big primes still don't finish.

A: You can use Fermat's Little Theorem.
Assuming your x is relatively prime with 10, the following holds:
10 ^ φ(9x) ≡ 1 (mod 9x)

Here φ is Euler's totient function. So you can easily calculate at least one n (not necessarily the smallest) for which your equation holds. To find the smallest such n, just iterate through the list of n's divisors.

Example: x = 89 (a prime number just for simplicity).
9x = 801
φ(9x) = 6 * (89 - 1) = 528 (easy to calculate for a prime number)

The list of divisors of 528:
1
2
3
4
6
8
11
12
16
22
24
33
44
48
66
88
132
176
264
528

Trying each one, you can find that your equation holds for 44:
10 ^ 44 ≡ 1 (mod 801)

A: I just tried the example, it runs in less than one second:
public class Main {

    public static void main(String[] args) {
        int n = 1;
        int x =  954661;
        int v = 10;
        while (v != 1) {
            n++;
            v = (v * 10) % (9*x);
        }
        System.out.println(n);
    }
}

For larger values of x the variables should be of type long.

A: As you specified you are actually trying to get modulus with 1 that is 1mod(9x).
That will always give you 1.
And you don't have to calculate that part exactly which might reduce your calculation.
On the other hand for 10^n = 1, it will always be 0.
So can you exactly specify what you are trying to do


text:
Q: How to model optional inheritance in Java Is there a way optional inheritance as described in the following case?
Say start with this:

Note: there are can be more than 4 child classes.
Now there is an optional capability called "Autonomous Transport" as here.

Option 1: As in this picture above I can have all child classes inherit from "Autonomous Transport" but I don't want that. Say, there cannot be an autonomous Train.
Option 2: Not have "Autonomous Transport" strictly in between but have individual classes inherit (may be with interface) like "Car", "Autonomous Car", "Truck", "Autonomous Truck" as needed. But not an attractive option as there are way more than 4 child classes
Option 3: Possibly, I can use dependency injection and inject "Autonomous" capability where needed but I cannot add any framework like dagger etc.
Are there any other ways, it can be done cleanly with Java? Basically, if "Train" cannot be autonomous, I do not want any related business logic there.

A: To keep it simple:
Option 1
abstract class Transport {
   foo();
}

abstract class AutomonousTransport extends Transport {
   bar();
}

class Car extends AutonomousTransport {
   // inherits foo and bar
}

class Train extends Transport {
   //inherits only foo(), which is ok, since Train is still a transport
}

With this approach you'll have to decide from which class to inherit so that you'll get the desired capabilities.
The potential drawback of this method is if you have many different capabilities like this (and in java you can extend only from one class).
To overcome this issue, if you only inherit the capability (behavior) and not the state, consider using interfaces with default methods instead of abstract classes. This works somewhat like Traits in other languages with some restrictions:
interface Transport {
   default foo () {...}
}

interface AutonomousTransport extends Transport {
   default bar() {}
}
interface WheelSupportTransport extends Transport {
   default rotateWheelLeft() {...}
   default rotateWheelRight() {...}
}

class Car implements AutomonousTransport, WheelSupportTransport  {

}

class Train implements Transport {...}

Option 2
abstract class Transport {
   foo()
}

final class AutonomousStuff { // final to prohibit inheritance from it
   bar()
}

class Car extends Transport {
   AutonomousStuff autonomousStuff;
}

class Train extends Transport {
   // only foo
}

This approach is based on "prefere composition over inheritance" idea. You add the behavior to the required class as an internal data field and gain the access to the required set of methods (capabilities) through this field.
Option 3
abstract class Transport {
   foo()
}

abstract class AutonomousCapable extends Transport {
    private final Transport transport;
    public AutonomouseCapable(Transport transport) {
       this.transport  =  transport;
    }
    bar()

    foo() {
        transport.foo();
    }

}

class Car extends Transport {}

class Train extends Transport {}

When creating the car, use new AutonomousCapable(new Car())
This follows the idea of "decorator" (a.k.a. wrapper) pattern. You "decorate" the object (car) with additional set of behaviors in runtime.

A: If Autonomous is an optional capability then it is actually not a generalized property of all its subclasses.
In my opinion, it would be 4 abstract classes AbstractCar, AbstractTruck etc. And then you can have two concrete implementations of each of these Abstract classes, say AutonomousCar and NonAutonomousCar. One autonomous and the other not.
And you can have a marker interface for the Autonomous classes called IAutonomousTransport
Of course, the above assumes that you don't want a simple flag called isAutonomous within your class and handle your functionality based on that. But this method wouldn't be polymorphic.

A: You should use Decorator Pattern here:
public interface Transport {
    void foo();
}

public class AutonomousTransport implements Transport {
    public void foo() {
        // autonomous transport implementation
    }
}

public class Car implements Transport {
    private final Transport delegate;

    public Car(Transport delegate) {
        this.delegate delegate;
    }

    public void foo() {
        if(delegate == null)
            // car transport implementation
        else
            delegate.foo();
    }

}

P.S. This snippet shows you a brief solution. It could be many variants of implemnetation of this pattern.

Option 1: As in this picture above I can have all child classes
inherit from "Autonomous Transport" but I don't want that. Say, there
cannot be an autonomous Train.

Think about replace inheritance to delegation. In most of the cases, delegation is more preferable.

Option 2: Not have "Autonomous Transport" strictly in between but have
individual classes inherit (may be with interface) like "Car",
"Autonomous Car", "Truck", "Autonomous Truck" as needed. But not an
attractive option as there are way more than 4 child classes

Autonomous Transport look to me like behavior, but not property. I am sure, that it should not be in the Transport hierarhy.

Option 3: Possibly, I can use dependency injection and inject
"Autonomous" capability where needed but I cannot add any framework
like dagger etc.

Dipendency Injection is pattern but not a framework like Spring or Dagger. If your class contains linke to another class (does not matter via constructor or setter), de-facto this is DI already.


text:
Q: Using Jquery to return many values to be updated within html I could not think of a good title to describe what im trying to figure out, but i have this code here
$(document).ready(function() {
    setInterval(function(){
        $.get('/battleship/update_game/{{info.gameid}}/{{user.username}}', function(data){
           //All Html elements to be updated
        });
    },3000);
    });

the idea is that it sends a request for information, and then gets back multiple values ie an array of imformation. i cannot figure out how to do it. I am also using django, so my method of returning 'data' back is
return HttpResponse(myinformation)

what i want is to say
return HttpResponse([info1,info2,info3,info4])

and then be able to access those values from the javascript

A: When I need to do some operations and I don't want to reload the page I use a JQuery call to Ajax, I make the pertinent operations in AJAX and then receive the AJAX response in the JQuery function without leaving or reloading the page. I'll make an easy example here for you to understand the basics of this:
JQuery function, placed in the template you need
function form_post(){
    //You have to get the data from any tag in the template
    var var1 = $('#yourelement').val()
    //or get them using django variables
    var var2 = "{{django_variable}}"
    var data = []  // Create a list if you need to send multiple values
    data.push(var1)
    data.push(var2)
    $.ajax({  //Call ajax function sending the data you need
      url: "/ajax_url/",  //This is the url of the ajax view where you make the search
      type: 'POST',
      data: "data="+data
        success: function(response) {
            result = JSON.parse(response);  // Get the results sended from ajax to here
            if (result.error) { // If the function fails
                // Error
                alert(result.error_text);
            } else {  // Success

                    //Here do whatever you need with the result;
                }
            }
        }
    });
    }

You have to realize that I cannot finish the code without knowing what kind of results you're getting or how do you want to display them, so you need to retouch this code on your needs.
AJAX function called by JQuery
Remember you need to add an url for this Ajax function in your urls.py something like:
url(r'^/ajax_url/?$', 'your_project.ajax.ajax_view', name='ajax_view'),
your_project.ajax.ajax_view this meant you need a file called ajax.py in same folder as views.py
Then your AJAX function, it's like a normal Django View, but add this function into ajax.py
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.utils import simplejson

@csrf_exempt
def ajax_view(request):
    response = []
    #Here you have to enter code here
    #to receive the data you send here by POST
    data = request.POST['data']
    #Do the operations you need with the form information
    #Add the data you need to send back to a list/dictionary like response
    response = whatever you need
    #And return it to the JQuery function `enter code here`(simplejson.dumps is to convert to JSON)
    return HttpResponse(simplejson.dumps(response))

So, without leaving the page you receive via javascript a list of items that you sended from ajax view.
So you can update the any tag you need using JQuery
I know that this can be so confusing at the beginning but once you are used to AJAX this kind of operations without leaving or reloading the page are easy to do.
The basics for understanding is something like:

*

*JQuery function called on click or any event you need

*JQuery get some values on the template and send them to AJAX via
POST

*Receive that information in AJAX via POST

*Do whatever you need in AJAX like a normal DJango view

*Convert your result to JSON and send back to the JQuery function

*JQuery function receive the results from AJAX and you can do
whatever you need

Tip When you send variables to AJAX you need to know that the values you send are going to be converted to string. You'll received strings in the AJAX view via POST. When you create the response in the AJAX view to send it back to JQuery in the template, you need to convert the data to json too as you can see in the response of the ajax function return HttpResponse(simplejson.dumps(response)) simplejson.dumps() convert the data to json


text:
Q: Prime Knots and Prime Numbers I have heard that prime knots and prime numbers are somehow related. I can see the obvious relationship, that they are both defined similarly, but is there anything beyond this?

A: This is probably a comment about composition.  As is well known, every integer can be decomposed into its prime factorization.  So, $12 = 2\times 2 \times 3$.  In the same way, every knot can be decomposed into the simplest pieces that cannot be further decomposed.  We call these pieces prime knots.  The knots which can be decomposed we call composite knots and the operation to put them together is called the connected sum or knot sum.  See these links for images that will probably help.
The point here is that you can often get away with only looking at prime knots because every composite knot can be broken down.  Otherwise, I don't know of how you would "relate" prime knots and numbers.


text:
Q: Spring Jackson not converting class from interface I am posting the following JSON to a web server:
{
    "driver": "POSTGRES",
    "server": "teste",
    "port": "666",
    "sid": "teste",
    "schema": "teste",
    "datasource": {
        "name": "Novo datasource",
        "description": "",
        "type": "DATABASE",
        "user": "",
        "password": ""
    }
}

To this mapping:
@RequestMapping(
    method = RequestMethod.POST,
    consumes = MediaType.APPLICATION_JSON_VALUE,
    produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SomeInterface> save(SomeInterface object) {
    SomeInterface newObject = service.save(object);
    return new ResponseEntity<>(newObject, HttpStatus.CREATED);
}

And I'm getting a 400 status code, mapped to a org.springframework.http.converter.HttpMessageNotReadableException with no stacktrace at all.
I have 4 DB Entities that implement this SomeInterface, and what I want to do is to receive any of them in the controller, and pass it to Strategy on the Service.
Why is Jackson throwing that Exception instead of just converting the JSON?
---EDIT---
I'm running this from a Unit Test, and the only thing that shows up in the debug console is the assertion error exception as follows:
saveDatabaseDatasource(br.com.cds.connecta.presenter.DatasourceTest)  Time elapsed: 10.862 sec  <<< FAILURE!
java.lang.AssertionError: Content type not set
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:39)
    at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:72)
    at org.springframework.test.web.servlet.result.ContentResultMatchers$1.match(ContentResultMatchers.java:75)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:148)
    at br.com.cds.connecta.presenter.DatasourceTest.saveDatabaseDatasource(DatasourceTest.java:26)
    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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    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 org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

A: Unless you're using Jackson's polymorphic deserialization features, there's absolutely no way for Jackson to guess which of your four (or more) SomeInterface implementation to use as the target deserialization class. As such, Jackson fails to parse your JSON and throws up an exception to Spring.
If you turn your log level to DEBUG, you'll see a more specific reason.


text:
Q: create dynamically buttons to show dialog I have a button (create) and when it's clicked, it creates a new button (Change coordinates) that should be able to open dialog when it's clicked.
First of all I created body of dialog window, I created this via JavaScript, this is just how it looks like in HTML:

Both fields are required.

  <form>
    <fieldset>
    Longitude (decimal)
    <input type="text" name="lon" id="lon" value="" class="text ui-widget-content ui-corner-all">
    Latitude (decimal)
    <input type="text" name="lat" id="lat" value="" class="text ui-widget-content ui-corner-all">

    <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
    </fieldset>
  </form>

Now when create button is clicked I crate new button able to open dialog:
$( "#create" ).button().on( "click", function()
{
    var btn = document.createElement("BUTTON");
    btn.id = "change_coord";
    var t = document.createTextNode("Change coordinates");
    btn.appendChild(t);
    document.body.appendChild(btn);
});

And this is how my dialog looks like:
dialog = $( "#dialog-form" ).dialog({
          autoOpen: false,
          height: 300,
          width: 350,
          modal: true,
          buttons:{
                "Create an account": addUser,
                Cancel: function(){
                    dialog.dialog( "close" );
                }
          },
          close: function(){
                form[ 0 ].reset();
                allFields.removeClass( "ui-state-error" );
          }
});

Weird is that it works when I'm creating body of dialog and button to open it in
$(function()
{
....
});

But when I'm dynamically creating this button to open dialog it doesn't work at all.
HERE is my fiddle to show you my problem.

A: Per Charlietfl, who is correct "live" has been deprecated, but it does still remains a common solution to the problem.  The other method I've used, which also works is:
$(document).on("mouseenter","#lsTMFmenu", function() {

However, I cannot get JQuery to work against dynamically loaded HTML using just $("#selector").on(), I must use $(document).on statement shown above.
Thanks.


text:
Q: How do I include the wildcard in a returned expression with gsub in R? I have a string in R:
mystring <- "2 and 4"

I want to use gsub to put " hours" after every occurance of a number, so that the string looks like this:
"2 hours and 4 hours"

I have tried this, which matches the number, but I want the number returned in the output:
gsub("\\d{1}", "\\d{1} hours", mystring)
[1] "d{1} hours and d{1} hours"

How do I include the original number in the output?

A: We capture the digit (\\d) before the word boundary (\\b) as a group and in the replacement, specify the backreference (\\1) of the captured group followed by space and then the substring 'hours'
gsub("(\\d)\\b", "\\1 hours", mystring)
[1] "2 hours and 4 hours"

A: With stringr, we can use an R function on the match to construct the replacement:
library(stringr)
str_replace_all(
  mystring,
  "\\d",
  \(x) paste(x, "hours")
)
# [1] "2 hours and 4 hours"

A: You can use a non consuming look behind:
gsub("(?<=\\d)", " hours", mystring, perl=TRUE)
#[1] "2 hours and 4 hours"

In case there are more digits use a boundary in addition:
gsub("(?<=\\d)\\b", " hours", mystring, perl=TRUE)
#[1] "2 hours and 4 hours"


text:
Q: Preventing cracking of iOS apps I recently came across a link where a popular app that prevented itself from running on jailbroken devices was cracked to do so. The cracker highlighted that in the IDA tool they were looking for a string "jailbroken" or something like that and then trying to nail down the condition that caused the alert with "jailbroken" message to appear. I believe similarly any one can look for error messages in your app, find those message and hexedit the app using a tool like IDA and get to the condition that presented the error message and modify the condition to fail.
I already checked the following link for the methods for detecting cracked apps:
 http://www.iphonedevsdk.com/forum/iphone-sdk-tutorials/36330-iphone-piracy-protection-code-2-another-tutorial.html
Is there any way we can make it difficult for the app to be cracked like by encrypting the error messages and not having them in plain text in the app?

A: Well, for one, don't use plaintext "jailbroken" in your app. Another is to not throw up a dialog box, something that hackers could look for in your code and backtrace. The best is to just not allow certain features to be accessible, or better yet, randomly do weird things to make it harder for them to nail down a repro case.


text:
Q: Why does Swagger CodeGen 3.0.x generates classes with AllOf[Classname] I'm using swagger codegen 3.0.21 for generating a C# api client.
The generators creates for all referenced classes additional classes in /Model beginning with AllOf[Classname].
Why does Swagger CodeGen generate these classes? What is their porpuse? They also have multiple errors with my sepcification.
Relevant changed part of the generated json:
"components": {
  "schemas": {
    "MyClass": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int64"
          },
          "propertyTwo": {
            "type": "integer",
            "format": "int64"
          },
          "propertyThree": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MySecondClass"
              }
            ],
            "nullable": true
          },
          "propertyFour": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MyThirdClass"
              }
            ],
            "nullable": true
          },
          "propertyFive": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MyFourthClass"
            },
            "nullable": true
          },
          "propertySix": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
    },
  }
}

The constructor for MyClass is generated as following:
public MyClass(long? id = default(long?), long? propertyTwo = default(long?),  propertyThree = default(),  propertyFour = default(), List<MyThirdClass> propertyFive = default(List<MyFourthClass>), bool? propertySix = default(bool?))

As you can see the datatypes for propertyThree and propertyFour are just empty spaces.

A: We ran into the same issue. For generating a csharp client/models we actually use https://github.com/RicoSuter/NSwag/wiki/NSwagStudio which also provide you a lot of options and does generate the models properly
However for a client we needed a java generator as well and nswagstudio only supports csharp and typescript. I tried the suggestion of @NickSim  that worked as a charm.


text:
Q: How to try every possible permutation in Kotlin fun main () {
    var integers = mutableListOf(0)
    for (x in 1..9) {
        integers.add(x)
    }
    //for or while could be used in this instance
    var lowerCase = listOf("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
    var upperCase = listOf('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
    println(integers)
    println(lowerCase)
    println(upperCase)
    //Note that for the actual program, it is also vital that I use potential punctuation
    val passwordGeneratorKey1 = Math.random()*999
    val passwordGeneratorKey2 = passwordGeneratorKey1.toInt()
    var passwordGeneratorL1 = lowerCase[(Math.random()*lowerCase.size).toInt()]
    var passwordGeneratorL2 = lowerCase[(Math.random()*lowerCase.size).toInt()]
    var passwordGeneratorL3 = lowerCase[(Math.random()*lowerCase.size).toInt()]
    var passwordGeneratorU1 = upperCase[(Math.random()*upperCase.size).toInt()]
    var passwordGeneratorU2 = upperCase[(Math.random()*upperCase.size).toInt()]
    var passwordGeneratorU3 = upperCase[(Math.random()*upperCase.size).toInt()]
    val password = passwordGeneratorKey2.toString()+passwordGeneratorL1+passwordGeneratorL2+passwordGeneratorL3+passwordGeneratorU1+passwordGeneratorU2+passwordGeneratorU3
    println(password)
    //No, this isn't random, but it's pretty close to it
    //How do I now run through every possible combination of the lists //lowerCase, integers, and upperCase?
}

How do I run through every possible permutation to eventually solve for the randomly generated password? This is in Kotlin.

A: I think you should append all the lists together and then draw from it by random index, this way you ensure that position of numbers, lower cases and uppercases is random too. Also you don't need to write all the characters, you can use Range which generates them for you.
    fun main() {
        val allChars = mutableListOf<Any>().apply {
            addAll(0..9) // creates range from 0 to 9 and adds it to a list
            addAll('a'..'z') // creates range from a to z and adds it to a list
            addAll('A'..'Z') // creates range from A to Z and adds it to a list
        }
        val passwordLength = 9
        val password = StringBuilder().apply {
            for (i in 0 until passwordLength) {
                val randomCharIndex =
                    Random.nextInt(allChars.lastIndex) // generate random index from 0 to lastIndex of list
                val randomChar = allChars[randomCharIndex] // select character from list
                append(randomChar) // append char to password string builder
            }
        }.toString()

        println(password)
    }

Even shorter solution can be achieved using list methods
 fun main() {
    val password = mutableListOf<Any>()
        .apply {
            addAll(0..9) // creates range from 0 to 9 and adds it to a list
            addAll('a'..'z') // creates range from a to z and adds it to a list
            addAll('A'..'Z') // creates range from A to Z and adds it to a list
        }
        .shuffled() // shuffle the list
        .take(9) // take first 9 elements from list
        .joinToString("") // join them to string
    println(password)
}

A: As others pointed out there are less painful ways to generate the initial password in the format of: 1 to 3 digits followed by 3 lowercase characters followed by 3 uppercase characters.
To brute force this password, you will need to consider all 3-permutations of "a..z" and all 3-permitations of "A..Z". In both cases the number of such 3-permutations is 15600 = 26! / (26-3)!. In worst case you will have to examine 1000 * 15600 * 15600 combination, half of this on the average.
Probably doable in a few hours with the code below:

import kotlin.random.Random
import kotlin.system.exitProcess

val lowercaseList = ('a'..'z').toList()
val uppercaseList = ('A'..'Z').toList()

val lowercase = lowercaseList.joinToString(separator = "")
val uppercase = uppercaseList.joinToString(separator = "")

fun genPassword(): String {
    val lowercase = lowercaseList.shuffled().take(3)
    val uppercase = uppercaseList.shuffled().take(3)

    return (listOf(Random.nextInt(0, 1000)) + lowercase + uppercase).joinToString(separator = "")
}

/**
 * Generate all K-sized permutations of str of length N. The number of such permutations is:
 * N! / (N-K)!
 *
 * For example: perm(2, "abc") =  [ab, ac, ba, bc, ca, cb]
 */
fun perm(k: Int, str: String): List<String> {

    val nk = str.length - k

    fun perm(str: String, accumulate: String): List<String> {
        return when (str.length == nk) {
            true -> listOf(accumulate)
            false -> {
                str.flatMapIndexed { i, c ->
                    perm(str.removeRange(i, i + 1), accumulate + c)
                }
            }
        }
    }
    return perm(str, "")
}

fun main() {
    val password = genPassword().also { println(it) }

    val all3LowercasePermutations = perm(3, lowercase).also { println(it) }.also { println(it.size) }
    val all3UppercasePermutations = perm(3, uppercase).also { println(it) }.also { println(it.size) }

    for (i in 0..999) {
        println("trying $i")
        for (l in all3LowercasePermutations) {
            for (u in all3UppercasePermutations) {
                if ("$i$l$u" == password) {
                    println("found: $i$l$u")
                    exitProcess(0)
                }
            }
        }
    }
}


text:
Q: CSS: Compass Susy Grid is not aligning properly im trying to get susy correctly working within compass.
Look at the following html sample (body part):

Nav1

Nav2

Nav3

Nav4

Nav5

TEST

Section 1

Section 2

Section 3

Section 4

Section 5

Section 6

Section 7

Section 8

Section 9

Section 10

  Footer

... and the according sass code:
@import "compass"
@import "susy"

$total-columns : 6
$column-width  : 4em
$gutter-width  : 1em
$grid-padding  : $gutter-width

.page
    +container($total-columns)
    +susy-grid-background

.header
    +span-columns($total-columns)

.nav
    +span-columns($total-columns)

.test
    +span-columns($total-columns)

.footer
    +span-columns($total-columns)

.section
    +span-columns(3)
    &:last-child
        +span-columns(3 omega)

.border
    border: 1px solid black

2 "Section X" items should be on one line here (span-columns is set to 3, and 3 + 3 is the number of $total-columns?), but it looks like this (only stacked):
http://i.imgur.com/3LdJVX3.png
Removing the test-borders also doesnt work. What im doing wrong here?

A: Two things:

*

*Unless you are using the border-box model, you do need to remove those borders. Try using outline for testing instead - as it doesn't affect the flow:
.border
  outline: 1px solid black

*None of your sections actually match the .section:last-child selector. None of them are the last child of their parent element, and so none are getting the omega mixin added to them. First, you either need to wrap them so -child selectors work, or use -of-type. Then you need to use nth- instead of last-, because you don't just want to match the final one, you want to match all the even ones:
// without changing your markup
.section
  +span-columns(3)
  &:nth-of-type(even)
    +omega

// with a new wrapper around your sections
.section
  +span-columns(3)
  &:nth-child(even)
    +omega


text:
Q: Where to ask a question about computer science and programming study advice? What Stack Exchange site would a question like this be appropriate for?

I'm a student in my 3rd year of college studying computer science and programming. So far I have studied a lot of stuff, but I mostly "specialize" in Java web development and Android. I've done lots of projects with Android and Spring, and I'm even going to an internship for those fields.
Even though I like those things, I'm not sure if that's what I want to do for the rest of my life. During my 4th year, I will learn a bit more about data science and AI.
So the questions are:

*

*Do people transition from one technology and programming field to another during their careers, let's say from full stack developer to data science?

*How many things can I do at once. I know I can pretty much work on both Java web projects and Android. Should I even try to incorporate another language/technology, lets say should I try and incorporate data science as well?

A: Question 2 is likely to be off-topic on all Stack Exchange sites. It will depend mostly on you; on your experience, talent, motivation, etc. It's best to discuss this with the person in your college responsible for student's personal development.
Question 1: the answer is (obviously) yes, but I don't really think there's an appropriate site for it either. An extreme example: even if "What is 1+1?" is about Mathematics, it's not really appropriate for Mathematics Stack Exchange because it's too basic. If you have a specific example you want to ask about, it's already somewhat better: consider this question on Data Science Stack Exchange: Career switch to Big Data Analytics which is quite well-received.
See also Can I ask "Professional Careers and Advice" questions here? on The Workplace Meta - career questions generally aren't a good fit for Stack Exchange's Q&A format.


text:
Q: Prons and Cons of using relational Databases (like SQL) for real-time time series analysis? I know that the relational databases are not scalable to Big-Data. I also know that memcaching is a bit complicated in them. I also know that you may need to unnest and flatten data to prepare it for analysis.
However, I still think that for structured data, for some scenarios, it is better to apply them rather than time series databases like InfluxDB.
I do not think that sending queries causes latency and make relational databases inappropriate for time-series analysis. I could not find my answer [here]. So, my question is when we can use Relational databases for Time-Series analysis?


text:
Q: Teradata REGEXP_SPLIT_TO_TABLE Inserting Spaces between Numbers I am having trouble with Teradata's REGEXP_SPLIT_TO_TABLE.  It is separating the results correctly, but it is inserting spaces between each individual number.  I used CHAR2HEXINT and found the Hex of the space is 00.  Here is the statement I am using:
SELECT *
FROM TABLE(
       REGEXP_SPLIT_TO_TABLE('2625 1410', '2625 1410', '[ \t\r\n\v\f]' , 'i')
         RETURNS (outkey VARCHAR(250), token_ndx INTEGER, token VARCHAR(220) )
   ) AS t1;

It returns 2 6 2 5 as a row and 1 4 1 0 as a row.  I want the results to be 2625 as a row and 1410 as a row.  Is there something I am doing wrong that is adding the spaces?  Is there a way to get rid of the spaces?  Thanks in advance.

A: I had the same problem and found that REGEXP_SPLIT_TO_TABLE returns UNICODE strings :-)
But as you didn't specify the character set for the RETURN columns the parser assumes LATIN and this results in binary zeroes.
Simply add CHARACTER SET UNICODE:
SELECT *
FROM TABLE(
       REGEXP_SPLIT_TO_TABLE('2625 1410', '2625 1410', '[ \t\r\n\v\f]' , 'i')
         RETURNS (outkey VARCHAR(250) CHARACTER SET UNICODE
                 ,token_ndx INTEGER
                 ,token VARCHAR(220) CHARACTER SET UNICODE )
   ) AS t1;


text:
Q: How to update a constraint in a migration I need to add onDelete and onUpdate cascade to a constraint in a migration file.
So i did an alter table, selecting the foreign keys and chaining with the alter method in the end of each command.
class UpdateRecipientSchema extends Schema {
  up () {
    this.alter('deliveries', (table) => {
      table.integer('recipient_id')
        .unsigned()
        .references('id')
        .inTable('recipients')
        .onDelete('CASCADE')
        .onUpdate('CASCADE')
        .notNullable()
        .alter()
      table.integer('courier_id')
        .unsigned()
        .references('id')
        .inTable('couriers')
        .notNullable()
        .onDelete('CASCADE')
        .onUpdate('CASCADE')
        .alter()
    })
  }

  down () {
    this.alter('deliveries', (table) => {
      table.integer('recipient_id')
        .unsigned()
        .references('id')
        .inTable('recipients')
        .notNullable()
        .alter()

      table.integer('courier_id')
        .unsigned()
        .references('id')
        .inTable('couriers')
        .notNullable()
        .alter()
    })
  }
}

But i'm getting a error saying that the constraint of this relationship already exists. error: constraint "deliveries_courier_id_foreign" for relation "deliveries" already exists
How can i update a constraint of a table in a migration?

A: First i have to drop the foreign key column and then create it again.
We can do that with Arbitrary Code in migrations
await Database.raw('DROP FOREIGN KEY deliveries_courier_id_foreign')
// And now recreate it
await Database.raw('...')

We can also uso the this.schedule function to execute multiple things https://adonisjs.com/docs/4.1/migrations#_executing_arbitrary_code
Thanks to the guy that helped me in the Adonis forum https://forum.adonisjs.com/t/how-to-update-a-constraint-in-a-migration/5835


text:
Q: Trouble scraping a html table rvest Trying to scrape https://www.cefconnect.com/closed-end-funds-daily-pricing
using rvest into an R data frame.  Keep trying the various css and xpath selectors but cannot collect the main table of data.
Used the 'table', 'tbody', 'td', and 'tr xpath selectors without success. Two columns are hyperlinks and the rest are static text.
URL <- 'https://www.cefconnect.com/closed-end-funds-daily-pricing'
html <- read_html(URL)

html2 <- html %>%
html_nodes(xpath = '//table') %>%
html_nodes(xpath = '//td/a[1]/text()') %>%
html_text()
html3 <- as.data.frame(html2)

A: Try to analyze the requests that are transacted when you load the website in your browser. This can be accomplished by navigating through the following in the CHROME BROWSER.
Settings >> More Tools >>  Developer Tools (Shortcut : Ctrl + Shift + I)
On doing this, you can see that one of the requests as follows
https://www.cefconnect.com/api/v3/DailyPricing?props=Ticker,Name,DistributionRateNAV,LastUpdated,Discount,DistributionRatePrice,ReturnOnNAV,CategoryId,CategoryName,IsManagedDistribution,Price,PriceChange,NAV,NAVPublished,Cusip/&_=1546832481302
If you click the above link you will see the data displayed in the table in JSON format. This is what you need to convert as data frame.
url<-"https://www.cefconnect.com/api/v3/DailyPricing?props=Ticker,Name,DistributionRateNAV,LastUpdated,Discount,DistributionRatePrice,ReturnOnNAV,CategoryId,CategoryName,IsManagedDistribution,Price,PriceChange,NAV,NAVPublished,Cusip/&_=1546832481302"

library(rvest)
page<-html_session(url)
json<-readBin(page$response$content, what="json")

library(jsonlite)
df<-fromJSON(json)


text:
Q: How to Dynamically switch between protocols for a node(wireless) in NS2? i want to simulate a ns2 program in which a nodes moves from left to right, up to a certain x-y co-ordinates it should communicate with X-protocol after that point it should communicates with Y-protocol to other nodes.
for eg consider node 1 was using AODV routing protocol till (200,200) after that point node 1 start to use DSR protocol for communication.
if the movement of the node is reversed and node 1  again cross the x-y point to left then the protocol used by it should change to the initial protocol.
the Q also can explain  like this ,all the nodes left of the point x-y should communicate with x protocol and those are to the right should communicate with y protocol
is it possible to write a program like that in ns2  ??
if it possible please share your knowledge.


text:
Q: absolute value global/local Minima and Maxima (piecewise function)
given the function $
f(x)=
\begin{cases}
 |x-2|&\text {} \, 0<x<3\\
 |x-5|&\text{}\, 3≤x≤7\\
     \end{cases}$
which of the following statements is true?(there can be more than one true or all false)

*

*In the open interval $(0,7)$ there isn't a global maxima

*In the open interval $(4,5)$ there is a global minima

*The point $x=3$ is a local maxima or minima point in the interval $(0,7)$
What I tried:
First thing was to write it in a more comfortable way without the absolute value
$
f(x)=
\begin{cases}
 -x+2&\text {} \, 0<x<2\\
 x-2 &\text{}\, 2<x<3\\
-x+5 &\text{}\, 3<x<5\\
x-5 &\text{}\, 5<x<7\\
 \end{cases}$
then I checked if there is continuity at these points $(x=2,x=3,x=5)$ $\lim \limits_{x \to 2^+}=0$ $\lim \limits_{x \to 2^-}=0$ ,  $\lim \limits_{x \to 3^+}=2$ $\lim \limits_{x \to 3^-}=1$ (not continuous at x=3) and $\lim \limits_{x \to 5^+}=0$ $\lim \limits_{x \to 5^-}=0$.
then I calculated the derivative $
f'(x)=
\begin{cases}
 -1&\text {} \, 0<x<2\\
 1 &\text{}\, 2<x<3\\
-1 &\text{}\, 3<x<5\\
1 &\text{}\, 5<x<7\\
 \end{cases}$
checked the limits to see if it is differentiable at the points mentioned above and found that they are all critical points (sorry if it is not the right word but what I mean is "suspicious" points).
Did a small table to check if the points are minima or maxima. found out that $x=2$ is a minima , $x=3$ is a maxima and $x=5$ is also a minima but I cannot tell if local or global so I cannot tell if statements 1 or 2 are right since I cannot calculate $f(2)$ or $f(5)$ $f(3)$
Can anyone give me hints on how to continue from here? and if my way was correct?
Thank you!
Edit: I just checked the limits of the interval but what can I learn from that?
$\lim \limits_{x \to 0^+}=2$ $\lim \limits_{x \to 7^-}=2$
from what I personally know I can conclude from that if the limits are infinite

A: Actually, you can calculate $f(2)$ and $f(5)$. To check which of the two minima is the global one (both of them are local minima), you can see a bit more carefully the domains on which $f$ is defined. By doing this you should also discover that the function has an additional maximum, other than the one you found.


text:
Q: jQuery saving Time and expiraton date? I would like to know how I can save a date format in jQuery.
Today I had an idea to save a COOKIE by using jQuery.
After I had a look at the content of a COOKIE from another site I saw that it will be stored the date.
As I tried to do the same for my site I used this code:
$.cookie('name', new Date(), { expires: 365 });

The COOKIE will be set but with the difference that the content will be displayed in a strange format like this:
Thu%20Nov%2007%202013%2020%3A04%3A49%20GMT%2B0100%20(CET)

When I read out the COOKIE by using:
alert( $.cookie('name') );

It will display the date format correctly. So my first question is how can I save a date in the correct form like:

Thu Nov 7 2013 20:04:49 GMT+0100 (CET)

instead of that strange format from above.
And my second question is how to set an expiration date format that it will end on a specific time.
At this point It will expire on

Nov 7 2014 20:04:49 GMT+0100 (CET)

but how can I let it expire for example on

Nov 7 2014 00:00:00 GMT+0100 (CET)

?
Thanks alot.
UPDATE:
this is the Code I use:
...
var now = new Date();
var expireDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());

$.cookie('cookiePolicyConsent', new Date().toString(), { expires: expireDate });
...

it does not save the COOKIE. The rest of the Code still works. Only this lines dealing with the COOKIE.

A: First Question:
Use toString() if you just want to store the text. I agree with the comment above... does it really matter how it is stored as long as you get the correct value back? If you don't want to put the date object in the cookie then you can use .UTC() or .getTime()
There are several other toString functions on the date object that will help you get it in the format you want: http://www.w3schools.com/jsref/jsref_obj_date.asp
Second question:
You can pass in a date instead of number with the "expire" property. So you could do something like:
var now = new Date();

// Expire the cookie tonight at midnight
var expireDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);

$.cookie('name', new Date().toString(), { expires: expireDate });

A: It is probably easier if you save the date in millisecond like so
$.cookie('name', new Date().getTime(), { expires: 365 });

and then when you retrieve it
alert( new Date($.cookie('name')) );


text:
Q: can not config R Language "bzip2 library and headers are required" when try to run config file in R Source in Cent OS 7 ,I received the following error .
"Checking whether bzip2 support suffices ... configure: error: bzip2 library and headers are required".

A: You need to install the bzip2 development package to your OS. On an ubuntu system that would be:
sudo apt install libbz2-dev

and a similar incantation using CentOS' package manager should do it for you. Is it yum on CentOS?
Other fails during running ./config are also possibly due to development packages being missing from your OS - look for things like libjpeg-dev to get JPEG image support and so on.


text:
Q: Jquery when i click on img it behaves like link (triggering link) i have a problem, I got some li, inside them i have a link and an image. What i want is when someone clicks on the image it triggers the link. I cant put the image in a link, don't ask why :)... So basically it looks something like this

sometext

sometext

...

And i was thinking of doing something like this:
$(img).click(function(){
  var link = $(this).prev;
  $(link).trigger('click');
})

I know this is not correct, but i think you got the picture, thanks for your help.

A: Don't use jQuery, but simply move the closing  tag at the right side of the  tag:

sometext

sometext

If you don't want to change the HTML, use:
$('img').click(function(){
    location.href = $(this).prev().attr("href");
});

Code review

*

*$(img) - img is not defined. Did you mean: $('img')? (added quotes, using selector img)

*var link = $(this).prev; - prev is nto a property, but a method. It has to be invoked: var link = $(this).prev()

*$(link).trigger('click'). Since link is a jQuery object already, it's unnecessary to wrap the object in another jQuery object. Use: link.trigger('click');

*Flawed logic: .trigger('click') will not cause the page to be followed, because it doesn't trigger the default browser behaviour (following the link), but invokes the click event of the element. Which is not defined.

A: Actually, that looks like it oughta work. Just note that prev is a function.
Alternatively, you could do something like
window.location = link.attr('href');

A: You can probably get away with something like
$(img).click(function()
{
      var link = $(this).prev();
      window.location.href = link.attr('href');
});

A: you can set a css class for both the anchor link and the image and use a classname selector to hook the click event
$(".myclass").click(function(){
//Do Stuff
})

A: $('img').live('click', function () {
    $(this).closest('a').click();
});


text:
Q: What does leadership do? Damage and range are obvious, but I can not figure out how important leadership is. How much does it matter, how does it influence my soldiers?

A: Leadership increases the attack damage of soldiers. In fact it is more important than upgrading soldiers or unlocking some heroes. Troops with a high rate of fire will be scary when the leadership is high (the base attack doesn't make much difference with an upgraded weapon).

A: Leadership doesn't affect your soldiers but it can strength General's combat power.


text:
Q: Optimization of ODE with respect to the initial condition One has a (system) of ODEs with a one-parameter family of initial conditions. For example,
f[kk_] := N[aa = kk; s = NDSolve[{y''[t] == y[t]^2, y[1] == aa, y'[1] == 1},
                                  y, {t, 2}]; Evaluate[(y[2] /. s)][[1]]]

where k is the parameter, and one sees $f(k)$ as a function of $k$  works fine, as one can try to plot
Plot[f[x], {x, -3, 0}]

and obtain

However, when one tries to find the min, using FindMinimum or NMinimize, it does not work as it seems Mathematica would first perform symbolic calculation with
NDSolve[{(y''[t] == -2y[t], y[1] == x, y'[1] == 1}, y, {t, 2}]

which results an error as the initial condition is not a number, and returns y[2.] before continuing evaluating NMinimize[y[2.], x].
Does anyone know how to get around it, or some better ways to do the optimization?

A: Harnessing symbolic functionality one can get a glimpse of beauty of the mathematical world and a quantum of deeper understanding, therefore often it is of high importance and preferable to exploit symbolic rather than numeric tools, even though in certain cases the latter would yield more. Thus  it is a reasonable practice to put forward exact methods and use approximate ones only if symbolic functionality fails.
We'll demonstrate that the function to be minimized is quite involved
$$y(t,a)=6\;\wp\bigg(t-1+\wp^{-1}\Big(\frac{a}{6};\;0,\frac{a^3}{54}-\frac{1}{36}\Big);\;0,\frac{a^3}{54}-\frac{1}{36}\bigg)$$
where $\wp$ is the Weierstrass elliptic function and it can be done with NMinimize as well as with FindMinimum,  however getting the actual result involves some insight into the matter because of suboptimal handling of elliptic functions and integrals in Mathematica (a marvelous trademark figured out by J.M.). Encountering this issue wherever below one will be warned with  this sign $**$.
Let's start with a few quite natural observations. Having equations of the form y''[t] == y[t]^2 it is a good idea to multiply it by y'[t] and integrate it once using initial (boundary) conditions.
$0=y''(t)-y(t)^2\; $  thus $\;0=y'(t) y''(t)-y(t)^2 y'(t)\;$ i.e. $\;0=1/2 \;y'(t)^2 -1/3\; y(t)^3 +c$ and using initial conditions we find:  $\;c=-1/2 + a^3/3 $. Rewriting $\;y(t)=6 w(t)$ one obtains:
$$w'(t)^2-4w(t)^3+ \frac{a^3}{54} - \frac{1}{36}=0$$
This is a standard form of a differential equation for the Weierstrass elliptic function $w'(t)^2-4w(t)^3+ g_2 w(t)+g_3=0\;$ with $\;g_2=0$ and $g_3= \frac{a^3}{54} - \frac{1}{36}$.
Mathematica can $**$ solve  this more general form on the symbolic level without specifying initial conditions:
w[t]/. DSolve[ w'[t]^2 - 4 w[t]^3 + g2 w[t] + g3 == 0, w[t], t]

{ WeierstrassP[ t - C[1], {g2, g3}], WeierstrassP[ t + C[1], {g2, g3}]}

however one might be misled using it $**$ with $g_2=0$.
Now, using once more the initial conditions we find
C[1] == 1 - InverseWeierstrassP[ a/6, {0, a^3/54 - 1/36}] and finally:
y[t_, a_] := 6 WeierstrassP[ t - 1 + InverseWeierstrassP[ a/6, {0, a^3/54 - 1/36}],
                             {0, a^3/54 - 1/36}]

when plotting this function $**$ one uses Re[ y[2,a]] rather than y[2,a] alone, since the latter produces $**$ some nonvanishing imaginary perturbations.
Plot[ Re @ y[2, a], {a, -3, 0}, AxesOrigin -> {0, 0}, PlotStyle -> Thick]

$**$ Minimize[{y[2, a], -3 < a < 0}, a] doesn't work, however $**$ NMinimize[{ Re @ y[2, a], -3 < a < 0}, a] works fine and alternatively an excellent approximation $**$ with FindMinimum as you liked can be found:
FindMinimum[ Re @ y[2, a], {a, 0}] // Quiet

{0.0964433, {a -> -1.65429}}

If we'd like studying full complexity of the function y, a useful tool might be e.g.
Manipulate[ Plot[ Re @ y[t, a], {a, -10, 10}, AxesOrigin -> {0, 0}, PlotStyle -> Thick],
           {t, -30, 30}]

which wouldn't be readily available with a numerical approach.
Another nice application and  a bit more detailed explanation of a few issues related to elliptic functions one can find in e.g. Integrate yields complex value, while after variable transformation the result is real. Bug?. Elliptic functions are solutions to certain nonlinear ordinary differential equations and being implemented in Mathematica 1.0 they might be slightly revised, although some useful functionality like WeierstrassHalfPeriodW1 is implemented also in verion 11.2.

A: Use ParametricNDSolve or it's cousin ParametricNDSolveValue:
s = ParametricNDSolveValue[
    {y''[t] == y[t]^2, y[1] == aa, y'[1] == 1},
    y[2],
    {t, 2},
    aa
];

NMinimize[s[aa], aa]

{0.0964433, {aa -> -1.65429}}

A: A very simple fix for your problem is to prevent f from evaluating without numeric arguments. While I'm at it, I'll also rewrite f in a slightly nicer way:
Clear[f];
f[kk_?NumericQ] := Module[{sol, y},
  sol = First[
    N[NDSolve[{y''[t] == y[t]^2, y[1] == kk, y'[1] == 1}, y, {t, 2}]]
  ];
  y[2] /. sol
];

The _?NumericQ pattern on f prevents the function from evaluating symbolically. In this form, NMinimize and FindMinimum work immediately:
NMinimize[f[x], x]
FindMinimum[f[x], {x, 0}]

Finally, I'd like to point out that your use of Evaluate does nothing in your code. Evaluate is used to override a Hold attribute. For example:
Hold[Range[3], Evaluate[Range[3]]]


text:
Q: What is a clean, Pythonic way of setting multiple members in a constuctor from one method in Python? I have a triangle class with vertices, area, and contours. What is the Pythonic way of setting multiple members in a constructor using One method, if needing to set three members in a Constructor at once?
I'm using dictionary method below, however it seems clunky. Wondering if this is appropriate or any optimal method?
This question is a variation of this question, What is a clean, Pythonic way to have multiple constructors in Python?
class TriangleData():

    vertices_key: str = 'vertices'
    triangle_area_key: str = 'triangle_area'
    contours_key: str = 'contours'

    def __init__(self, contour_data: np.ndarray):
        self.contour_data = contour_data
        data = self.get_triangle_data()
        self.vertices: np.ndarray = data[self.vertices_key]
        self.triangle_area: float = data[self.triangle_area_key]
        self.poly_dp_contours: np.ndarray = data[self.contours_key]
        self.color = self.get_color()

    def get_triangle_data(self):

        # Run calculations from original contour dataetc etc
       .....

        return {
            self.vertices_key: vertices_final,
            self.triangle_area_key: triangle_area,
            self.contours_key: contours
        }

A: This boils down to stylistic preferences. I personally don't have qualms with having some of the attributes defined outside of __init__(...), and so would opt for something like:
class TriangleData():

    def __init__(self, contour_data: np.ndarray):
        self.get_triangle_data(contour_data)

    def get_triangle_data(self, contour_data):
        # calculations
        self.vertices = vertices_final
        self.triangle_area = triangle_area
        self.contours = contours

and disable any linter warnings that didn't like it. You could also opt for something like:
class TriangleData():

    def __init__(self, contour_data: np.ndarray):
        self.vertices, self.triangle_area, self.contours = self.get_triangle_data(contour_data)

    def get_triangle_data(self, contour_data):
        # calculations
        return vertices_final, triangle_area, contours

which I think should satify the linter as-is.

A: There is a wide spectrum of approaches and libraries to eliminate redundancy of a plain __init__().  Please take a look at the dataclasses, attrs, NamedTuple and Pydantic.

UPD: I'm agree with Randy: there's nothing wrong about setting attributes outside of __init__.
Beside of that, you could update instance dict directly. This would be better in case when the final set of fields should be computed dynamically.
class TriangleData():

    def __init__(self, contour_data: np.ndarray):
        self.contour_data = contour_data
        data = self.get_triangle_data()

        # That's strange, that you return that field from `get` method
        # with different name, than you need to bind. Could we avoid that?
        # data['poly_dp_contours'] = data.pop('contorous')

        self.set_triangle_data(**data)

    def set_triangle_data(self, vertices, triangle, contorous):
        self.vertices = vertices
        self.triangle = triangle
        self.contorous = contorous

    # or even like below

    def set_triangle_data(self, **data):
        valid_keys = ['vertices', 'triangle', 'contorous', <...>]
        vars(self).update({k: data[k] for k in valid_keys if k in data})

    def get_triangle_data(self):

        # Run calculations from original contour dataetc etc
        .....

        return {
            self.vertices_key: vertices_final,
            self.triangle_area_key: triangle_area,
            self.contours_key: contours,
        }

A: To follow the pattern of setting/initializing variables in the constructor, from Instance variables in methods outside the constructor (Python) -- why and how? (see answer from BrianOakley and others)
You can declare your object members as follows, and them set them in a method afterwards.
def __init__(self, contour_data: np.ndarray):
    self.contour_data = contour_data
    self.vertices: np.ndarray = np.asarray([])
    self.triangle_area: float = float()
    self.contour_final: np.ndarray = np.asarray([])

    self.set_triangle_data()

def set_triangle_data(self):
    # Run calculations from original contour data etc
    .....
    self.vertices = vertices_final,
    self.triangle_area = triangle_area
    self.contour_final = contours


text:
Q: Error binding to target method I am trying to call a static method from a helper class, of which the type is not known until runtime. I thought I had solved the problem however I am getting the following error -
"Error binding to target method."
Can anyone see what is wrong with this code? Any help would be appreciated..
    Delegate del = Delegate.CreateDelegate(typeof(Func<string>),
                    typeof(RepositoryStringExtensions).GetMethod("GetTableName", BindingFlags.Static | BindingFlags.Public)
                    .MakeGenericMethod(new Type[] { objectType })) as Func<string>;

    string tableName = (string)del.DynamicInvoke(context);

The type "objecttype" above can be any class, "RepositoryStringExtensions" is the helper class which contains the method, the method it is trying to call is displayed below -
    public static string GetTableName<T>(this DbContext context) where T : class
    {
        ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;

        return objectContext.GetTableNameByObject<T>();
    }

A: You should use Func<DbContext, string> instead of Func<string>.


text:
Q: PHP mssql select blob field error? insert into blob field I have a php script wich selects data from ms sql database.
the following error apears.
"PHP Warning:
  mssql_query():
  Query failed in /var/www/integration/sqlview.php on line 59,
  referer: http://*****/integration/
"

Upon investigating I found that the one field is a blob field, and when i take it out of my php select statement the query works, but when i add it it fails. But there is nothing wrong with the select statement as it works 100 persent in sql browser.

$host = '****\sagex3';
$port = '**';
$server = $host;
$database = '***';
$user = 'sa';
$password = '****';

$link = mssql_connect ($server, $user, $password);
if (!$link)
{
die('ERROR: Could not connect: ' . mssql_get_last_message());
}

mssql_select_db($database);

$query = "
SELECT
MSGID_0,
PARENTID_0,
MSGTYPE_0,
MSGSTATUS_0,
POLLMETHOD_0,
CLIENTNAME_0,
USERID_0,
CPY_0,
FCY_0,
PARAM1_0,
PARAM3_0,
POPULATEDDAT_0,
POPULATEDTIM_0,
STARTDAT_0,
STARTTIM_0,
ENDDAT_0,
ENDTIM_0,
RETRYONERROR_0,
RETRIES_0,
POLLERID_0,
ERRORMSG_0,
ERRORDETAIL_0 ---  when i remove this field the query works. this seems to be a blob field?
FROM PILOT.Y9CONTROL
 ";
//this is line 59
$result = mssql_query($query);
if (!$result)
{
    $message = 'ERROR: ' . mssql_get_last_message();
    return $message;
}
else
{
    $i = 0;
    echo '

';
    while ($i < mssql_num_fields($result))
    {
        $meta = mssql_fetch_field($result, $i);
        echo '' . $meta->name . '	';
        $i = $i + 1;
    }
    echo '
';

    while ( ($row = mssql_fetch_row($result)))
    {
        $count = count($row);
        $y = 0;
        echo '
';
        while ($y < $count)
        {
            $c_row = current($row);
            echo '' . $c_row . '	';
            next($row);
            $y = $y + 1;
        }
        echo '
';
    }
    mssql_free_result($result);

    echo '
';
}

 echo "done";

?>

It seems that the ERRORDETAIL_0 is a blob field causing problems. Ho do i get around this

A: Ok I found the answer. utf8 on php.ini.
Once I changed that it works 100%.
Thanks all


text:
Q: Finding standard deviation from a normal distribution This is for a homework assignment, I'm really only confused about one step within the problem though.
Question: Suppose $X \sim N(400, \sigma^2)$ where $\sigma$ is the standard deviation. If we have $P(380 \leq X \leq 420) = 0.99$, what is the standard deviation $\sigma$? (Hint: Use standardization)
So the class came up with this answer:
1) $z = \frac{x - 400}{\sigma} \sim N(0,1)$
2) $P(\frac{-20}{\sigma} \leq z \leq \frac{20}{\sigma}) = 0.99$
3) $1 - 0.99 = 0.01$
4) $\frac{0.01}{2} = 0.005$
5) $1 - 0.005 = 0.995$
6) $\frac{20}{\sigma} = z_{0.995} = 2.576$
7) Solving for $\sigma$ gives you $7.76$
I understand everything except for steps 3, 4, and 5. Mainly why do we decide to subtract $1 - 0.99$ and then why do we randomly decide to divide by $2$? Finally, why would we want to subtract it by $1$ again?

A: Q-function is defined as $Q(x) = \frac{1}{\sqrt{2\pi}} \int_x^\infty \exp\left(-\frac{u^2}{2}\right) \, du$
$P(−\frac{20}{σ}≤z≤\frac{20}{σ})=0.99$
It implies $\frac{1}{\sqrt{2\pi}} \int_{−\frac{20}{σ}}^{\frac{20}{σ}} \exp\left(-\frac{u^2}{2}\right) \, du = 0.99$
As normal distribution is symmetric,  $\frac{1}{\sqrt{2\pi}} \int_{0}^{\frac{20}{σ}} \exp\left(-\frac{u^2}{2}\right) \, du = 0.99 / 2 = 0.495$
Also  $\frac{1}{\sqrt{2\pi}} \int_{0}^{\infty} \exp\left(-\frac{u^2}{2}\right) \, du = 0.5$
So  $\frac{1}{\sqrt{2\pi}} \int_{\frac{20}{σ}}^{\infty} \exp\left(-\frac{u^2}{2}\right) \, du = 0.5-0.495 = 0.005$
Then from table of Q-function you can find $σ$.
Hope my answer clarifies your doubt.

A:
I  understand everything except for steps 3, 4, and 5. Mainly why do we decide to subtract 1−0.99 and then why do we randomly decide to divide by 2? Finally, why would we want to subtract it by 1 again?

Standard Normal Tables (or Z-Tables) look up the the cumulative probability ($\alpha$) and report the value $z_\alpha$, such that:
$$\mathsf P(Z\leq z_\alpha)=\alpha$$
So the manipulation in steps 3,4,5 is to obtain the $\alpha$ value you need to look up to find the required $z_\alpha$ value.
Basically you have: $$\begin{align}\mathsf P(-z_\alpha\leq Z\leq z_\alpha)=\beta \tag{given}
\\ \mathsf P(Z\leq -z_\alpha)+\mathsf P(-z_\alpha\leq Z\leq z_\alpha)+\mathsf P(Z\geq z_\alpha) &= 1 \tag{total probability}
\\\mathsf P(Z\leq -z_\alpha)&=\mathsf P(Z\geq z_\alpha)\tag{symmetry}
\\[1ex] \hline & \hline
\\[0ex] \therefore \mathsf P(Z\leq z_\alpha) & = 1-\frac{1-\beta}{2}
\\[2ex] \beta  =0.99 & \implies \alpha = 0.995
\\[2ex] \text{Find}\quad & z_{0.995}
\end{align}$$


text:
Q: I/flutter ( 8686): Another exception was thrown: NoSuchMethodError: The method 'save' was called on null The following NoSuchMethodError was thrown while handling a gesture:
The method 'save' was called on null.
Receiver: null
Tried calling: save()
I'm creating a page to update user registration data, and when I click on update this error appears and nothing happens. I'm learning flutter now, and there's a lot that I don't know, can someone help me?
import 'package:flutter/material.dart';

import '../../generated/l10n.dart';
import '../models/user.dart';
import '../helpers/helper.dart';
import '../elements/BlockButtonWidget.dart';
import '../helpers/app_config.dart' as config;

import 'package:mvc_pattern/mvc_pattern.dart';
import '../repository/user_repository.dart' as repository;

import '../repository/user_repository.dart';

class SettingsController extends ControllerMVC {

  GlobalKey<FormState> loginFormKey;
  GlobalKey<ScaffoldState> scaffoldKey;

  SettingsController() {
    loginFormKey = new GlobalKey<FormState>();
    this.scaffoldKey = new GlobalKey<ScaffoldState>();

  }

  void update(User user) async {
    user.deviceToken = null;
    repository.update(user).then((value) {
      scaffoldKey?.currentState?.showSnackBar(SnackBar(
        content: Text("Atualizado com Sucesso"),
      ));
    });
  }
}

class ProfileSettingsDialog extends StatefulWidget {
  final User user;
  final VoidCallback onChanged;

  ProfileSettingsDialog({Key key, this.user, this.onChanged}) : super(key: key);

  @override
  _ProfileSettingsDialogState createState() => _ProfileSettingsDialogState();

}

class _ProfileSettingsDialogState extends State<ProfileSettingsDialog> {
  GlobalKey<FormState> _profileSettingsFormKey = new GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: Helper.of(context).onWillPop,
      child: Scaffold(
        resizeToAvoidBottomPadding: false,
        body: Stack(
          alignment: AlignmentDirectional.topCenter,
          children: <Widget>[
            Positioned(
              top: 0,
              child: Container(
                width: config.App(context).appWidth(100),
                height: config.App(context).appHeight(29.5),
                decoration: BoxDecoration(color: Theme.of(context).accentColor),
              ),
            ),
            Positioned(
              top: config.App(context).appHeight(29.5) - 120,
              child: Container(
                width: config.App(context).appWidth(84),
                height: config.App(context).appHeight(29.5),
                child: Text(
                  S.of(context).lets_start_with_register,
                  style: Theme.of(context).textTheme.headline2.merge(TextStyle(color: Theme.of(context).primaryColor)),
                ),
              ),
            ),
            Positioned(
              top: config.App(context).appHeight(29.5) - 50,
              child: Container(
                decoration: BoxDecoration(color: Theme.of(context).primaryColor, borderRadius: BorderRadius.all(Radius.circular(10)), boxShadow: [
                  BoxShadow(
                    blurRadius: 50,
                    color: Theme.of(context).hintColor.withOpacity(0.2),
                  )
                ]),
                margin: EdgeInsets.symmetric(
                  horizontal: 20,
                ),
                padding: EdgeInsets.symmetric(vertical: 50, horizontal: 27),
                width: config.App(context).appWidth(88),
//              height: config.App(context).appHeight(55),
                child: Form(

                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      TextFormField(
                        keyboardType: TextInputType.text,
                        onSaved: (input) => widget.user.phone = input,
                        validator: (input) => input.trim().length < 3 ? S.of(context).not_a_valid_phone : null,
                        decoration: InputDecoration(
                          labelText: "Celular",
                          labelStyle: TextStyle(color: Theme.of(context).accentColor),
                          contentPadding: EdgeInsets.all(12),
                          hintText: S.of(context).john_doe,
                          hintStyle: TextStyle(color: Theme.of(context).focusColor.withOpacity(0.7)),
                          prefixIcon: Icon(Icons.person_outline, color: Theme.of(context).accentColor),
                          border: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.2))),
                          focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.5))),
                          enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.2))),
                        ),
                      ),
                      SizedBox(height: 30),
                      TextFormField(
                        keyboardType: TextInputType.text,
                          onSaved: (input) => widget.user.address = input,
                          validator: (input) => input.trim().length < 3 ? S.of(context).not_a_valid_address : null,
                          decoration: InputDecoration(
                          labelText: "Endereço",
                          labelStyle: TextStyle(color: Theme.of(context).accentColor),
                          contentPadding: EdgeInsets.all(12),
                          hintText: 'johndoe@gmail.com',
                          hintStyle: TextStyle(color: Theme.of(context).focusColor.withOpacity(0.7)),
                          prefixIcon: Icon(Icons.alternate_email, color: Theme.of(context).accentColor),
                          border: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.2))),
                          focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.5))),
                          enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.2))),
                        ),
                      ),
                      SizedBox(height: 30),
                      TextFormField(
                          keyboardType: TextInputType.text,
                          onSaved: (input) => widget.user.bio = input,
                          validator: (input) => input.trim().length < 3 ? S.of(context).not_a_valid_biography : null,
                          decoration: InputDecoration(
                          labelText: "Biografia",
                          labelStyle: TextStyle(color: Theme.of(context).accentColor),
                          contentPadding: EdgeInsets.all(12),
                          hintText: 'johndoe@gmail.com',
                          hintStyle: TextStyle(color: Theme.of(context).focusColor.withOpacity(0.7)),
                          prefixIcon: Icon(Icons.alternate_email, color: Theme.of(context).accentColor),
                          border: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.2))),
                          focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.5))),
                          enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).focusColor.withOpacity(0.2))),
                        ),
                      ),

                      SizedBox(height: 30),
                      BlockButtonWidget(
                        text: Text(
                          S.of(context).register,
                          style: TextStyle(color: Theme.of(context).primaryColor),
                        ),
                        color: Theme.of(context).accentColor,

                        onPressed: () {
                          _profileSettingsFormKey.currentState.save();
                          widget.onChanged();
                          Navigator.pop(context);
                          update(currentUser.value);
                              //setState(() {});
                          },
                        //  widget.update(currentUser.value);
                      ),
                      SizedBox(height: 25),
//                      FlatButton(
//                        onPressed: () {
//                          Navigator.of(context).pushNamed('/MobileVerification');
//                        },
//                        padding: EdgeInsets.symmetric(vertical: 14),
//                        color: Theme.of(context).accentColor.withOpacity(0.1),
//                        shape: StadiumBorder(),
//                        child: Text(
//                          'Register with Google',
//                          textAlign: TextAlign.start,
//                          style: TextStyle(
//                            color: Theme.of(context).accentColor,
//                          ),
//                        ),
//                      ),
                    ],
                  ),
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }

  InputDecoration getInputDecoration({String hintText, String labelText}) {
    return new InputDecoration(
      hintText: hintText,
      labelText: labelText,
      hintStyle: Theme.of(context).textTheme.bodyText2.merge(
            TextStyle(color: Theme.of(context).focusColor),
          ),
      enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Theme.of(context).hintColor.withOpacity(0.2))),
      focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: Theme.of(context).hintColor)),
      floatingLabelBehavior: FloatingLabelBehavior.auto,
      labelStyle: Theme.of(context).textTheme.bodyText2.merge(
            TextStyle(color: Theme.of(context).hintColor),
          ),
    );
  }

}

A: You should bind the key _profileSettingsFormKey to Form, else the key would not get any state and so the currentState would be null
thus calling save() on null throws the exception
Form(
  key: _profileSettingsFormKey,
  child: ...
)

A: _profileSettingsFormKey is null, you need to use a Form widget and bind the key to it:
    return Form(
        key: _profileSettingsFormKey,

A: You forgot to assign the key to your Form, so the currentState of the key is null.
Form(
  key: _profileSettingsFormKey,
  // ...
)

A: thank you, now this error is showing
The setter 'address=' was called on null.
Receiver: null
Tried calling: address="siahduiasudi, 189"


text:
Q: Wicket two links in same column I want to add to all my tree nodes edit and create new child links, but I am getting error that child with id cell is already existing.
columns.add(new AbstractColumn<Classification, String>(Model.of("")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Classification>> cellItem, String componentId,
                final IModel<Classification> rowModel) {

            cellItem.add(new TreeLinkPanel(componentId, rowModel, tree));
        }
    });
    columns.add(new AbstractColumn<Classification, String>(Model.of("")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Classification>> cellItem, String componentId,
                final IModel<Classification> rowModel) {

            cellItem.add(new ClassificationNewLink(componentId, rowModel, tree));
        }
    });

For now I am doing this, but this one is ugly. I can't write header for my column. Any ideas how to put two links in same column?

A: The cell item is just a component that has its wicket id, so you cannot really add it more than once.
The simplest way is to create an panel or fragment that contains any of components you want to add (e.g. two links).
your code example:
columns.add(new AbstractColumn<Classification, String>(Model.of("")) {
    private static final long serialVersionUID = 1L;

    @Override
    public void populateItem(Item<ICellPopulator<Classification>> cellItem, String componentId, final IModel<Classification> rowModel) {
        // your model
        cellItem.add(new MyCellPanel(componentId, rowModel, tree));
    }
});

MyCellPanel class example:
public class MyCellPanel extends Panel {

    MyCellPanel(String componentId, final IModel<Classification>rowModel, final Tree tree) {
        super(componentId, rowModel);
        add(new TreeLinkPanel("treeLink", rowModel, tree); {
        add(new ClassificationNewLink("classificationNewLink", rowModel, tree); {

    }

}

MyCellPanel.html example:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <wicket:panel xmlns:wicket="http://wicket.apache.org">

tree link

        classification link
    </wicket:panel>

A: This is just a wild guess, but what if you try to populate the column only once:
columns.add(new AbstractColumn<Classification, String>(Model.of("")) {
    private static final long serialVersionUID = 1L;

    @Override
    public void populateItem(Item<ICellPopulator<Classification>> cellItem, String componentId,final IModel<Classification> rowModel) {
        // your model
        cellItem.add(new TreeLinkPanel("treeLinkPanelId", rowModel, tree));
        // the add link
        cellItem.add(new ClassificationNewLink("classificationNewLinkId", rowModel, tree));
    }
});


text:
Q: For Selenium WebDriver - Maven and initial pom.xml configuration I am new for Selenium Webdriver. When I start with the tool I came to know there are two things necessary to start with: Maven and pom.xml. But I didn't find the details on these things. Could anyone let know what is the meaning of these files and how do I create them.
Also I would be thankful, if someone could share some knowledge on the Selenium WebDriver like how do I start with the tool, and how to write a scripts - I have Java knowledge, so I can prefer to that language.
Thanks in advance :) awaiting to learn about the tools :)

A: Maven and it's pom.xml are not a must (but a recommended solution).
Their role in the process is just to add the selenium jar to your project.
You can manually add the Selenium jar file to your project by downloading the jar from http://docs.seleniumhq.org/download/ and adding it to your classpath.
OR,
https://code.google.com/p/selenium/downloads/list?can=1&q=&colspec=Filename+Summary+Uploaded+ReleaseDate+Size+DownloadCount
Selenium site has also the relevant documentation to get you started - http://docs.seleniumhq.org/docs/03_webdriver.jsp
Maven: http://maven.apache.org/

A: I would recommend starting with a pom.xml that looks like this.  You will have to manually create the directories src/main/java, src/test/java, and src/test/resources, but after do so, if you run "mvn clean build", it will refresh and give you the proper perspective in Eclipse IDE.  Maven can be confusing on a new project because it doesn't auto generate those directories. :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SeleniumMavenExample</groupId>
  <artifactId>SeleniumMavenExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <selenium.version>2.39.0</selenium.version>
    <maven.surefire.plugin.version>2.16</maven.surefire.plugin.version>
    <testng.version>6.8.7</testng.version>
  </properties>
  <build>
    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <finalName>${project.artifactId}-${project.version}</finalName>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>src/test/resources</directory>
      </testResource>
    </testResources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.plugin.version}</version>
        <configuration>
          <showSuccess>true</showSuccess>
          <suiteXmlFiles>
            <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
          </suiteXmlFiles>
          <configuration>
            <systemPropertyVariables>
              <build-name>${surefire.testng.build}</build-name>
            </systemPropertyVariables>
            <groups>${surefire.testng.groups}</groups>
            <testFailureIgnore>true</testFailureIgnore>
          </configuration>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.apache.metamodel</groupId>
      <artifactId>MetaModel-full</artifactId>
      <version>4.0.0-incubating</version>
    </dependency>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>${testng.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>16.0.1</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>1.7.6</version>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>${selenium.version}</version>
    </dependency>
    <dependency>
      <groupId>net.lightbody.bmp</groupId>
      <artifactId>browsermob-proxy</artifactId>
      <version>2.0-beta-9</version>
    </dependency>
  </dependencies>
</project>


text:
Q: How do I output hyperlinks for Custom Object name fields in an apex:PageBlockTable Sounds easy enough, but I'm taking the values output in my table from a number of field sets, so admin users can customise the columns that appear in the table.
Here's my functioning page block...
        <apex:pageBlock title="{!$Label.Search_Results}">
        <apex:pageBlockTable value="{!SearchResults}" var="pictureGallerySearchResult" title="SearchResults">
            <apex:column headerValue="Image" styleClass="imageDataCell">

            </apex:column>
            <apex:column headerValue="Test" value="{!pictureGallerySearchResult.Project[pictureGallerySearchResultField]}"/>
            <apex:repeat value="{!$ObjectType.Project__c.FieldSets.Picture_Gallery_Search_Results}" var="pictureGallerySearchResultField">
                <apex:column headerValue="{!$ObjectType.Project__c.Fields[pictureGallerySearchResultField].label}" value="{!pictureGallerySearchResult.Project[pictureGallerySearchResultField]}"/>
            </apex:repeat>
            <apex:repeat value="{!$ObjectType.Store__c.FieldSets.Picture_Gallery_Search_Results}" var="pictureGallerySearchResultField">
                <apex:column headerValue="{!$ObjectType.Store__c.Fields[pictureGallerySearchResultField].label}" value="{!pictureGallerySearchResult.Store[pictureGallerySearchResultField]}"/>
            </apex:repeat>
            <apex:repeat value="{!$ObjectType.Visit__c.FieldSets.Picture_Gallery_Search_Results}" var="pictureGallerySearchResultField">
                <apex:column headerValue="{!$ObjectType.Visit__c.Fields[pictureGallerySearchResultField].label}" value="{!pictureGallerySearchResult.Visit[pictureGallerySearchResultField]}"/>
            </apex:repeat>
            <apex:repeat value="{!$ObjectType.Photo_Attachment__c.FieldSets.Picture_Gallery_Search_Results}" var="pictureGallerySearchResultField">
                <apex:column headerValue="{!$ObjectType.Photo_Attachment__c.Fields[pictureGallerySearchResultField].label}" value="{!pictureGallerySearchResult.PhotoAttachment[pictureGallerySearchResultField]}"/>
            </apex:repeat>
        </apex:pageBlockTable>
    </apex:pageBlock>

You can see I've created a 'hard-coded' hyperlink for an image in the first column, but I want to dynamically hyperlink a field, if it is the name field for a custom object.
For example, if the fieldset...
$ObjectType.Project__c.FieldSets.Picture_Gallery_Search_Results

...contains the a field called 'Name', I want to insert a hyperlink that would take you to the salesforce page to view that project.
So firstly I need to be able to determine if the field is a custom object name field and secondly, output a hyper link rather than a label.
If anyone has any ideas, I would be most appreciative.
Thanks for taking the time to read this.

A: Have you considered doing this logic in an APEX controller/extension? After you execute your query, you can iterate over the results, determine what you want the hyperlink to be for each, and populate a map you expose to your Visualforce page keyed by some unique value in the search result (presumably ID) and the value would be the hyperlink. Then in your Visualforce iterator you can do map[SearchResult.Id] or whatever the key ends up being.

A: <apex:column headerValue="{!$Label.Filename}">{!pictureGallerySearchResult.ActualAttachment.Name}</apex:column>
<apex:repeat value="{!$ObjectType.Project__c.FieldSets.Picture_Gallery_Search_Results}" var="pictureGallerySearchResultField">
    <apex:column headerValue="{!$ObjectType.Project__c.Fields[pictureGallerySearchResultField].label}">
        <apex:outputLabel value="{!pictureGallerySearchResult.Project[pictureGallerySearchResultField]}" rendered="{!NOT(ShowResultFieldHyperlinkMap[$ObjectType.Project__c.Fields[pictureGallerySearchResultField].label])}"/>
        <apex:outputLink value="{!URLFOR($Action.Project__c.View, pictureGallerySearchResult.Project['Id'])}" rendered="{!ShowResultFieldHyperlinkMap[$ObjectType.Project__c.Fields[pictureGallerySearchResultField].label]}" styleClass="resultFieldHyperlink">
            <apex:outputLabel value="{!pictureGallerySearchResult.Project[pictureGallerySearchResultField]}" styleClass="resultFieldHyperlinkLabel"/>
        </apex:outputLink>
    </apex:column>
</apex:repeat>


text:
Q: how to let eclipse java ingore codes after return I'll have some essays and will return in the middle of program,but when I've written return;
the code after return will be raised as unuseful code, and I can't execute it unless I mark them and after it I have to unmark them, is there any good way to let eclipse close the eye on my redundant code after return?

A: If you don't want to comment out the code, this does the trick:

code;
if(true) {
   return;
}
more code;


text:
Q: asp.net mvc 2 How to get the first part of the url parameters and pass it to controllers? I'm building a site that has a number of language versions. currently I use session variable to manage the country code for different language version
but today the client specifically requires to put the country code in the url right behind the domain name so the site url will be like these examples
uk version: www.mysite.com/uk/{controller}/{action}/{id}
usa version: www.mysite.com/usa/{controller}/{action}/{id}
I defined the default route to
  routes.MapRoute(
            "Default", // Route name
            "{country}/{controller}/{action}/{id}", // URL with parameters
            new { country ="uk", controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults.uk is the default value
        );

but I'm not sure how to get the first segment of the url in the controllers?

A: Found the solution,
Just use RouteData.Values["country"], nice and simple!


text:
Q: Jekyll Contentful, how to hide api key from config file? Jekyll contentful plugin is configured in the config.yml file. But if I publish the repo on a public github repository, the api key will be available for anyone to use it.
How can I avoid that?

A: You can use CloudCannon (CMS for Jekyll) as an alternative. CloudCannon does not require an API key, supports Github and allows you to use a private repo. The free account should fit your needs.

A: Currently there is no possible way to do that.
Please open an issue on GitHub and we'll add that feature as soon as we can.
Else, as a workaround, you can omit your config.yml file from being pushed if you're not using it for GitHub Pages, by adding it to your .gitignore.