text:
Q: Tomcat won't allow me to send @POST requests using Jersey (Jax-RS) I have been trying (for about a day now) to figure out how to send a @POST request from my client to my web service but I am getting a 403 error and I have no idea why.  I have tried editing my web.xml files to allow the correct authorization but it still isn't working.  Below are my WEB-INF web.xml and Tomcat web.xml files.  Any help would be greatly appreciated, this has been beyond frustrating. Also, I am very new to both Tomcat and Jersey so it very well could be a very stupid/simple error.
Specs

*

*OS X El Capitan 10.11.2

*Tomcat Version 7.0 Server

*Eclipse JEE Kepler R Cocoa x86_64

*Jersey 2.23.1

*JRE 1.7

*Postman as my client (Google chrome ext)

Server web.xml
<servlet>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>xpoweredBy</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>readonly</param-name>
            <param-value>false</param-value>
        </init-param>

        <load-on-startup>3</load-on-startup>
</servlet>

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Accept,Accept-Encoding,Accept-Language,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Connection,Content-Type,Host,Origin,Referer,Token-Id,User-Agent, X-Requested-With</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
    </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

WEB-INF web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.example.messenger</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

A: That should not happen. Your error is handled somewhere. Look these annotations:
@ControllerAdvice
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(YourException.class)

A: This example (https://wolfpaulus.com/journal/java-journal/jersey/) has a somewhat altered web.xml:
<display-name>Jersey Web Application</display-name>
<servlet>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

That example page seems to highlight your exact environment (except the author uses IntelliJ rather than Eclipse... but you can download the community edition for free, and Java 8 rather than 7) - so you may want to follow along with it to get up and running.


text:
Q: How to add a fragment to an Activity without a container Is that possible I can add a fragment view on the activity view without specifying "fragment" view component in activity's layout xml file? Which function should I look for?

A: Simply, while creating a fragment we have to replace or add fragment's view with a view present in our application. To replace or add a fragment's, we normally add a Framelayout or any other layout view(as a fragmentview container) in activity or in a fragment.
Now, If you want to replace or add a fragment's view without adding a extra view container in your activity. You can simply do it by accessing the view's provided by AppCompatActivity or Activity.
Now, you can create a fragment, without adding a view container in your activity you can create as,
YourFragment fragment = new YourFragment();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, fragment);  //here, android.R.id.content is a view on which your fragment's view is replaced
transaction.commit();

A: You need to have a layout in your activity to contain the fragment (preferably a FrameLayout).
<FrameLayout 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:id="@+id/container"
android:name="com.gdevelopers.movies.movies.FragmentMoreMovies"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />

Then in activity put this code.
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  getSupportFragmentManager().beginTransaction()
    .replace(R.id.container, new YourFragment())
    .commit();
  }
}

A: If you don't want to go with @CommonsWare answer, then you'll have to provide a container by code. then function you need is....
setContentView(View)

Yep. If you check the activity class code, you'll see that setContentView can be called with an INT (layouts are identified with ints), or with Views. Therefore, you can create a viewgroup instance on the fly, keep a reference to it (you would need to do the same with an XML generated view), and add your fragments there. This is possible because XML files are just arguments which the view factory class, Inflater, uses to find which view subclasses has to instantiate, using a set of parameters provided in the XML. And obviously, you can do that by hand. Just pick whatever layout class you want to use, for example, FrameLayout, and:
public class Activity extends AppCompatActivity{

private FrameLayout root;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    root = new FrameLayout(this);
 root.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
    setContentView(root);
//go on
}

}

A: use android container instead of custom container like
fragmentTransaction.replace(android.R.id.content,yourFragment);

A: 1.use getWindow().getDecorView() to get a DecorView(FramLayout)
2.add a container view to DecorView
3.add Fragment to the container view

A: LinearLayout llRoot = findViewById(R.id.parent);

FragmentManager fragMan = getSupportFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();
YourFragment yourFragment = (YourFragment)fragMan.findFragmentByTag("yourFragment");
if (yourFragment == null) {
  yourFragment = new YourFragment();
}
fragTransaction.replace(llRoot.getId(), yourFragment, "yourFragment");
fragTransaction.commit();

llRoot is a LinearLayout which contains different view object of your  activity

A: Well, the UI of the fragment has to go somewhere. If you want the entire "content view" to be the fragment, add the fragment to android.R.id.content:
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null) {
      getSupportFragmentManager().beginTransaction()
        .add(android.R.id.content, new ToDoRosterListFragment())
        .commit();
    }
  }

Otherwise, somewhere in the activity's view hierarchy, you need a container (usually a FrameLayout) in which to place the fragment's UI. Typically, we do that by putting the container in the layout resource.

A: @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

        getSupportFragmentManager().beginTransaction()
            .add(android.R.id.content, MyFragment.newInstance())
            .commit();

   //Some of your code here
}

android.R.id.content is the container of entire app screen.
It can be used with Fragment:
The android.R.id.content ID value indicates the ViewGroup of the entire content area of an Activity.
The code above will insert the View created by Fragment into the ViewGroup identified by android.R.id.content.

A: If you don't want to allocate a specific place in the view to the fragment container you can always use the RelativeLayour. I guess without a container we cant place a fragment in a view.

A: If you have any View or say root view from the activity window, get its Id using view.getId() (relevant to android:id) and pass that id to the fragmentTransaction.add() as the container id. Here's just a sample:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    View view = new View(this);
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(view.getId(), new Fragment());
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I send email through HTML and JavaScript? I have a contact form on my website and I wanted to make a send button. I would not want an e-mail program on the computer to start, I just want the text to be sent to my e-mail right away by just pressing the button. I have searched for weeks now on the internet and I am giving up.
<form method="post" name="contact" action="#">
    Name:
    <input type="text" id="author" name="author" class="required input_field" />

    Email:
    <input type="text" class="validate-email required input_field" name="email" id="email" />

    Subject:
    <input type="text" class="validate-subject required input_field" name="subject" id="subject"/>

    Message:
    <textarea id="text" name="text" rows="0" cols="0" class="required"></textarea>

    <input type="submit" value="Send" id="submit" name="submit" class="submit_btn float_l" />
    <input type="reset" value="Reset" id="reset" name="reset" class="submit_btn float_r" />
</form>

A: Maybe if you don't want to use php, you may try just use an external API to provide you the email to be sent.
Mandrill can do that.
It's free up to 12k emails per month.
In you page the code would be like this:
$.ajax({
  type: "POST",
  url: "https://mandrillapp.com/api/1.0/messages/send.json",
  data: {
    'key': 'YOUR API KEY HERE',
    'message': {
      'from_email': 'YOUR@EMAIL.HERE',
      'to': [
          {
            'email': 'RECIPIENT_NO_1@EMAIL.HERE',
            'name': 'RECIPIENT NAME (OPTIONAL)',
            'type': 'to'
          },
          {
            'email': 'RECIPIENT_NO_2@EMAIL.HERE',
            'name': 'ANOTHER RECIPIENT NAME (OPTIONAL)',
            'type': 'to'
          }
        ],
      'autotext': 'true',
      'subject': 'YOUR SUBJECT HERE!',
      'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
    }
  }
 }).done(function(response) {
   console.log(response); // if you're into that sorta thing
 });

Here how:
https://medium.com/design-startups/b53319616782
http://www.codecademy.com/tracks/mandrill
(CodeCademy can teach how to use the API)

A: This maybe what are you searching for: http://www.sanwebe.com/2011/12/making-simple-jquery-ajax-contact-form . You can only do what do you want by using PHP and HTML + AJAX. Create the form in HTML and than send the request + data using Jquery POST request like this:
        $.post('sendmail.php', post_data, function(response){  ... }

A: The process of sending a mail happens server-side, HTML/JavaScript is client-side. As far as I can see you're not using a web-server nor are you hosting the website somewhere.
There is a FakeSendMail option with the new install from XAMPP which you could use to emulate the mail() function from PHP. XAMPP is one of the most known localhost web servers , which you could use to finish your project, in case you don't really need that mail to be actually sent. If you do, I recommend using a webhosting.
But first you need to understand the difference between Client-Side and Server-Side. As far as Client Side is concerned, all it does is render your static data. (HTML/CSS/JS). But, as for Server Side, there is a lot more use to it, as you can work with a database, fetch and insert data from or to it, and eventually render data which will be processed by the Browser (client side)

A: I don't think you 'searched' the net for weeks either :)
After one google search I got the following:
https://medium.com/design-startups/b53319616782
Thechnically it is not possible to send emails with javascript alone. You always need a backend service. But as described in the link above, there are mostly free (depends on volume) services available (as mentioned in the article above: https://mandrill.com/).
here is the code example of the link above:
$.ajax({
  type: 'POST',
  url: 'https://mandrillapp.com/api/1.0/messages/send.json',
  data: {
    'key': 'YOUR API KEY HERE',
    'message': {
      'from_email': 'YOUR@EMAIL.HERE',
      'to': [
          {
            'email': 'RECIPIENT_NO_1@EMAIL.HERE',
            'name': 'RECIPIENT NAME (OPTIONAL)',
            'type': 'to'
          },
          {
            'email': 'RECIPIENT_NO_2@EMAIL.HERE',
            'name': 'ANOTHER RECIPIENT NAME (OPTIONAL)',
            'type': 'to'
          }
        ],
      'autotext': 'true',
      'subject': 'YOUR SUBJECT HERE!',
      'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
    }
  }
}).done(function(response) {
    console.log(response); // if you're into that sorta thing
});

Hope this helps.
Best regards,
Chris

A: I am being lazy and copied shamelessly from W3Schools (Please don't go and say how crappy W3schools is, I know but this serves the purpose!)>

Feedback Form

<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"])) {
  ?>
  <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from">

  Subject: <input type="text" name="subject">

  Message: <textarea rows="10" cols="40" name="message"></textarea>

  <input type="submit" name="submit" value="Submit Feedback">
  </form>
  <?php
} else {    // the user has submitted the form
  // Check if the "from" input field is filled out
  if (isset($_POST["from"])) {
    $from = $_POST["from"]; // sender
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    // message lines should not exceed 70 characters (PHP rule), so wrap it
    $message = wordwrap($message, 70);
    // send mail
    mail("webmaster@example.com",$subject,$message,"From: $from\n");
    echo "Thank you for sending us feedback";
  }
}
?>


text:
Q: 'initial' is an invalid keyword argument for this function i'm Getting this error "'initial' is an invalid keyword argument for this function", I'm trying to create an object by a createview, what is this error and why am I getting it ?
urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^add/$', views.CriarTrabalhador.as_view(), name='add')]

models.py
from django.db import models

    # Create your models here.

    class Trabalhadores(models.Model):
        Nome = models.CharField('Name',max_length=100)
        Cpf = models.CharField(primary_key=True,max_length=11)
        Data = models.DateField('Data de Nascimento')

        def __str__(self):
            return self.Nome

forms.py
   from django import forms
   from .models import Trabalhadores

    class TrabalhadoresForm(forms.ModelForm):
        class Meta:
           model = Trabalhadores
                fields = ["Nome","Cpf","Data"]

views.py
from django.shortcuts import render
from django.views.generic.list import ListView
from django.core.urlresolvers import reverse
from .models import Trabalhadores
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView,CreateView
from . import forms

class CriarTrabalhador(CreateView):
    model = Trabalhadores
    form_class = forms.Trabalhadores
    template_name = 'mytemp/adicionartrabalhador.html'

    def get_success_url(self):
        return reverse('trabalhadores')

edit
After submiting the form, I'm getting this url
localhost/add/?csrfmiddlewaretoken=PVjqYnZNwJZpHuObu1OXNSnIekeqMVVeNIIxTkr2UFH7ii83QScfGdBrX5HjmZCe&Nome=test&Cpf=00000000000&Data=1998-12-14
Why is that ?

A: You've set the form_class in that view to be Trabalhadores, which is the model, instead of TrabalhadoresForm, which is the form.

A: You have to put your form_class is equals to your form
Like form_class =TrabalhadoresForm , because you are creating view using your from class and data will be pass through your model class
Same for all type of Django generic class view


text:
Q: PHP not retaining Javascript changes I have this simple javascript function which changes the body zoom of the web page. The function runs properly when I am having it on a HTML page as a normal javascript. When I embed it in PHP, it is not retaining the body zoom change. The javascript embedded in PHP can be shown as follows:
<?php
?>

<form name="test">

<button onclick="zoomout()">1024</button>
</form>

What am I doing wrong here. Thanks

A: Maybe try taking the form tags out.  You really don't need them if you aren't submitting something somewhere


text:
Q: Determining if a field $f$ is conservative So there is a question that I did where it made me find the integral of $f \cdot dr$ under the path $C$ (which is a semicircle when $x=0$ so $y^2 + z^2 = $) for the arc that connects $(0,0,-1)$ to $(0,0,1)$. For clarity, the function $f$ is $(x^2 + y^2 + z^2 , -z, y+1)$. I evaluated this to be $\pi + 2$. Now, it asks whether $f$ is conservative, and the answer says : "No, the line integral is dependent on the path". Now I know this is exactly the definition of a conservative field (that it is independent of its path), but how can we come to this conclusion?
I evaluated it for the path that forms the full circle which is non-zero, so it mustn't be conservative, but is there another way? How do we show it is path dependent?

A: hint
It is conservative if
$$f_xdx+f_ydy+f_zdz=dU $$
or
$$(x^2+y^2+z^2)dx-zdy+(y+1)dz=dU $$
then
$$U=-yz+C_1(x,z) $$
and
$$U=yz+z+C_2(x,y) $$
which impossible.


text:
Q: Does a set $G$ need to be closed under a binary operation $\star$ for $(G, \star)$ to be a group?
Does a set $G$ need to be closed under a binary operation $\star$ for $(G, \star)$ to be a group?

Definition (Binary Operation): A binary operation, on a set $G$ is a function $$\star  : G \times G \to G$$
Definition (Group): A group, is an ordered pair $(G, \star)$ where $G$ is set, and $\star$ is a binary operation on $G$ satisfying the following axioms

*

*$(a \star b) \star c = a \star (b \star c) \forall a, b, c \in G $

*$\exists e \in G$ (called an identity of $G$) such that $a \star e = e \star a = a \forall a \in G$

*For each $a \in G$, there is an $a^{-1}$ in $G$ (called an inverse of $a$) such that $a \star a^{-1} = a^{-1} \star a = e$

If for some $a, b \in G$, $\not\exists \  c \in G$ such that $a \star b = c$. Is $(G, \star)$ still a group?
I know that to verify that $(G, \star)$ is a group all we need to do is check the axioms for a group and verify that the necessary properties (of which closure is not one), hold, which leads me to believe that $(G, \star)$ is indeed a group, even though it's not closed under $\star$.
But perhaps more importantly, I can't see why one would define a group in this way (apart from it being obviously more general). I can't see the motivation for closure to not be an axiom for a group (again apart from generality).
As must of us know from the Vector Space axioms, that $V$ is a vector space only if it is closed under both addition and multiplication, which is where this question sprung about.
Even more generally is there any reason apart from generality, as to why some mathematical structures have an axiom for closure under a binary operation (e.g. addition/multiplication etc.) and others don't?

A: A binary operation $\ast$ on $G$ is a mapping $\ast:G\times G\to G$ and so by definition $G$ is closed under $\ast$. Perhaps you are thinking of verifying the axioms for subgroups, in which case you do have to verify closure. That is, to verify that $H$ is a subgroup, you have to check that the restriction of $\ast$ to $H\times H$ is a mapping $H\times H\to H$.

A: part of the definition of what a binary operation is ensures closure.
Recall that the first requirement is that the group has a binary opertation, in other words a function $G\times G \rightarrow G$,

A: Closure is most definitely part of the definition of a group.
It might be that in some texts, closure is part of the definition of the binary operation, e.g., implicit when writing $\star : G \times G \to G$. (Rather than reiterating it as a separate axiom.)


text:
Q: looking for a postcode radius search for Joomla looking for a postcode radius search for joomla.
enter postcode, select radius
displays all entrys from the database of postcodes that fall within that radius.
Cheers

A: I have used SobiPro Radius search before and it worked well for what I needed.
http://extensions.joomla.org/extensions/extension-specific/sobipro-extensions/19800
Good luck!


text:
Q: Linq: transform memberExpression type to not nullable the following member expression type can sometimes be NUllable, I m checking that , however I need to convert it to a non nullable type ,
MemberExpression member = Expression.Property(param, something);
var membertype = member.Type;
if (membertype.IsGenericType && membertype.GetGenericTypeDefinition() == typeof(Nullable<>))
        { // convert to not nullable type?...

Does anyone know how?

A: You can use Nullable.GetUnderlyingType to check (more simply) for Nullable<T>, and just use GetValueOrDefault - like below (I've only included the Func<Foo,int> etc as demo):
using System;
using System.Linq.Expressions;
class Foo {
    public int? Bar { get; set; }

    static void Main() {
        var param = Expression.Parameter(typeof(Foo), "foo");
        Expression member = Expression.PropertyOrField(param, "Bar");
        Type typeIfNullable = Nullable.GetUnderlyingType(member.Type);
        if (typeIfNullable != null) {
            member = Expression.Call(member,"GetValueOrDefault",Type.EmptyTypes);
        }
        var body = Expression.Lambda<Func<Foo, int>>(member, param);

        var func = body.Compile();
        int result1 = func(new Foo { Bar = 123 }),
            result2 = func(new Foo { Bar = null });
    }
}

A: This is just a guess, but could you use Nullable.GetValueOrDefault? I am not sure if the return type would be correct.


text:
Q: Corebluetooth: pass connected peripheral from view to another I'm am working on using BLE on a project previously using MFi devices.
The goal is to achieve a sort of serial connection.
With EAaccessory I had a popover asking for the device to connect to and was working fine.
Using CB, I added a view that I call to scan and select the device to connect to.
I can connect the device fine, but when I go back to main view, I loose the connection to the peripheral.
CoreBluetooth[WARNING] <CBConcretePeripheral: ... IsConnected = YES> is being dealloc'ed while connected

So, as I am not a genius nor a good iOs programmer...
Could someone point me in the right direction to retain the connected peripheral from one view to the main ?
I tried to understand a sample from ConnectBlue, the manufacturer of the BT devices on my project, but they use Storyboard, and I don't.
Using their demo, I can connect to the peripheral, on the main view and chat with it on another view.
I tried to google, but found nothing relevant.
Edit:
The connection code part
#import "ScanTableViewController.h"
#import <CoreBluetooth/CBCentralManager.h>
#import <CoreBluetooth/CBPeripheral.h>
#import "DiscoveredPeripheral.h"
#import "ScanCell.h"

typedef enum
{
    SCAN_S_NOT_LOADED,
    SCAN_S_DISAPPEARED,
    SCAN_S_WILL_DISAPPEAR,
    SCAN_S_APPEARED_IDLE,
    SCAN_S_APPEARED_SCANNING

} SCAN_State;
@interface ScanTableViewController ()

@end

@implementation ScanTableViewController
{
    SCAN_State          state;

    CBCentralManager    *cbCentralManager;
    NSMutableArray      *discoveredPeripherals;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"Scan viewDidLoad");

    cbCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    // Do any additional setup after loading the view from its nib.
    CGRect tableViewFrame = self.view.bounds;

    UITableView *tableview = [[UITableView alloc] initWithFrame:tableViewFrame style:UITableViewStylePlain];

    self.myTableView = tableview;
    self.myTableView.rowHeight = 60;
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    //Make sure our table view resizes correctly
    self.myTableView.autoresizingMask =
    UIViewAutoresizingFlexibleWidth |
    UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:tableview];

    discoveredPeripherals = [[NSMutableArray alloc] init];

    //[cbCentralManager retrieveConnectedPeripherals];

    state = SCAN_S_DISAPPEARED;

}

- (void)viewDidUnload
{
    //[self setScanButton:nil];
    [super viewDidUnload];
    NSLog(@"Scan viewDidUnload");
    cbCentralManager = nil;

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

    state = SCAN_S_NOT_LOADED;

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"Scan viewWillAppear");
    [self.myTableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"Scan viewDidAppear");

    [self clearPeriph];

    state = SCAN_S_APPEARED_IDLE;

    [self.myTableView reloadData];
}

 - (void)viewWillDisappear:(BOOL)animated
 {
 NSLog(@"Scan viewWillDisappear");
 //[self scan: FALSE];

 state = SCAN_S_WILL_DISAPPEAR;

 [super viewWillDisappear:animated];
 }

 - (void)viewDidDisappear:(BOOL)animated
 {
 [super viewDidDisappear:animated];
 NSLog(@"Scan viewDidDisappear");

 state = SCAN_S_DISAPPEARED;
 }

-(void) enterForeground
{
    NSLog(@"Scan enterForeground");
    [self clearPeriph];

    state = SCAN_S_APPEARED_IDLE;
}

-(void) enterBackground
{
    NSLog(@"Scan enterBackground");
    [self scan: FALSE];

    state = SCAN_S_DISAPPEARED;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) initWithPeripherals: (NSMutableArray*) dp
{
    NSLog(@"Scan initWithPeripherals");
    discoveredPeripherals = dp;

    state = SCAN_S_NOT_LOADED;
}

#pragma mark - Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //NSLog(@"Nombre de sections");
    return 2;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSInteger nRows;

    switch(section)
    {
        case 0:
            nRows = 1;
            break;

        case 1:
            NSLog(@"Scan Nbre ligne section 1 : %i",discoveredPeripherals.count);
            nRows = discoveredPeripherals.count;
            break;

        default:
            nRows = 0;
            break;
    }

    return nRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //NSLog(@"Remplissage");
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:CellIdentifier] ;
        cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
    }

    NSLog(@"Scan Section table:%u",indexPath.section);

    switch(indexPath.section)
    {
        case 0:
        {
            cell.textLabel.text = @"";
            if(state == SCAN_S_APPEARED_SCANNING)
            {
                cell.textLabel.text = @"Stop Scan";
                //cell.labelInfo.text = @"Active";

                //[cell.activityView startAnimating];
            }
            else
            {
                cell.textLabel.text = @"Start Scan";
                //cell.labelInfo.text = @"Inactive";
                //
                //[cell.activityView stopAnimating];
            }
            break;
        }
        case 1:
        {
            if ( [discoveredPeripherals count] > 0)
            {
                DiscoveredPeripheral* discoveredPeripheral;
                discoveredPeripheral = [discoveredPeripherals objectAtIndex:indexPath.row];
                cell.textLabel.text =discoveredPeripheral.peripheral.name;
            }

            cell.detailTextLabel.textColor = [UIColor blackColor];
        }
    }
    return cell;
}

- (NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *str;

    switch(section)
    {
        case 0:
            str = @"Bluetooth Low Energy Scanning";
            break;

        case 1:
            str = @"Found Devices";
            break;

        default:
            break;
    }

    return str;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if(cbCentralManager.state == CBCentralManagerStatePoweredOn)
    {
        //ScanCell* cell = (ScanCell*)[tableView cellForRowAtIndexPath:indexPath];
        //static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if(indexPath.section == 0)
        {
            if(state == SCAN_S_APPEARED_SCANNING)
            {
                [self scan: FALSE];

                cell.textLabel.text = @"Start Scan";
                //cell.labelInfo.text = @"Inactive";
                //[cell.activityView stopAnimating];

                state = SCAN_S_APPEARED_IDLE;
            }
            else if((state == SCAN_S_APPEARED_IDLE) &&
                    (cbCentralManager.state == CBCentralManagerStatePoweredOn))
            {

                [self scan: TRUE];

                cell.textLabel.text = @"Stop Scan";
                //cell.labelInfo.text = @"Active";
                //[cell.activityView startAnimating];

                state = SCAN_S_APPEARED_SCANNING;
            }
        }
        else
        {
            DiscoveredPeripheral* dp = [discoveredPeripherals objectAtIndex:indexPath.row];

            NSDictionary *dictionary;

            switch (dp.state)
            {
                case DP_STATE_IDLE:

                    cell.textLabel.text = @"Connecting";

                    //[cell.activityView startAnimating];

                    dictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey];

                    [cbCentralManager connectPeripheral:dp.peripheral options:dictionary];

                    dp.state = DP_STATE_CONNECTING;
                    break;

                case DP_STATE_CONNECTED:
                case DP_STATE_CONNECTING:
                    [cbCentralManager cancelPeripheralConnection:dp.peripheral];

                    cell.textLabel.text = @"";

                    //[cell.activityView stopAnimating];
                    cell.accessoryType = UITableViewCellAccessoryNone;

                    dp.state = DP_STATE_IDLE;
                    break;

                default:
                    break;
            }
        }

        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

- (void) scan: (bool) enable
{
    if(enable == TRUE)
    {
        NSLog(@"Scan Scan ON");
        NSDictionary *dictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];

        [cbCentralManager scanForPeripheralsWithServices:nil options:dictionary];
    }
    else
    {
        NSLog(@"Scan Scan Off");
        [cbCentralManager stopScan];
    }
}

- (IBAction)startScan:(id)sender {

    if(state == SCAN_S_APPEARED_IDLE)
    {
        [self scan: TRUE];

        state = SCAN_S_APPEARED_SCANNING;
    }
    else if(state == SCAN_S_APPEARED_SCANNING)
    {
        [self scan: FALSE];

        state = SCAN_S_APPEARED_IDLE;
    }
}

- (void) clearPeriphForRow: (NSInteger)row
{
    DiscoveredPeripheral* dp = [discoveredPeripherals objectAtIndex:row];

    //if( (dp.peripheral.isConnected == FALSE) &&
    //   ( (dp.state == DP_STATE_CONNECTED) || (dp.state == DP_STATE_DISCONNECTING)))
    if(dp.peripheral.isConnected == FALSE)
    {
        dp.state = DP_STATE_IDLE;
    }
    else if( (dp.peripheral.isConnected == TRUE) &&
            (dp.state != DP_STATE_CONNECTED))
    {
        dp.state = DP_STATE_CONNECTED;
    }

    if(dp.state == DP_STATE_IDLE)
    {
        [discoveredPeripherals removeObjectAtIndex:row];

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:1];
        //ScanCell* cell = (ScanCell*)[self.tableView cellForRowAtIndexPath:indexPath];
        UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
        //[cell.activityView stopAnimating];

        cell.accessoryType = UITableViewCellAccessoryNone;

        [self.myTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void) clearPeriph
{
    if(self->discoveredPeripherals.count > 0)
    {
        for(int i = discoveredPeripherals.count - 1; i >= 0 ; i--)
        {
            [self clearPeriphForRow:i];
        }
    }

    [self.myTableView reloadData];
}

- (IBAction)clearPeripherals:(id)sender {

    [self clearPeriph];

    [self scan: FALSE];

    state = SCAN_S_APPEARED_IDLE;
}

- (NSInteger)getRowForPeripheral: (CBPeripheral*)peripheral
{
    NSInteger row = -1;
    DiscoveredPeripheral* p;

    for(int i = 0; (i < discoveredPeripherals.count) && (row == -1); i++)
    {
        p = [discoveredPeripherals objectAtIndex:i];

        if([peripheral isEqual:p.peripheral] == TRUE)
        {
            row = i;
        }
    }

    return row;
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSInteger row = [self getRowForPeripheral:peripheral];

    if(row != -1)
    {
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:1];
        UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
        //ScanCell* cell = (ScanCell*)[self.tableView cellForRowAtIndexPath:indexPath];

        cell.textLabel.text = [[NSString alloc] initWithFormat:@"Connected"];

        //[cell.activityView stopAnimating];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

        DiscoveredPeripheral* dp = [discoveredPeripherals objectAtIndex:row];

        dp.state = DP_STATE_CONNECTED;

        //[peripheral discoverServices:nil];

        //[self scan:FALSE];

        //[[self navigationController] popViewControllerAnimated:NO];
        //[self.delegate didConnectedPeriph:dp];
    }
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSInteger row = [self getRowForPeripheral:peripheral];

    if(row != -1)
    {
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:1];

        UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
        //ScanCell* cell = (ScanCell*)[self.tableView cellForRowAtIndexPath:indexPath];

        cell.textLabel.text = [[NSString alloc] initWithFormat:@""];

        cell.accessoryType = UITableViewCellAccessoryNone;
        //[cell.activityView stopAnimating];

        DiscoveredPeripheral* dp = [discoveredPeripherals objectAtIndex:row];

        dp.state = DP_STATE_IDLE;
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    bool new = TRUE;
    DiscoveredPeripheral* discPeripheral;
    int row = -1;

    if((state == SCAN_S_APPEARED_SCANNING) &&
       (peripheral != nil))
    {

        for(int i = 0; (i < discoveredPeripherals.count) && (new == TRUE); i++)
        {
            NSLog(@"Scan Ajout periph");
            discPeripheral = [discoveredPeripherals objectAtIndex:i];

            if(discPeripheral.peripheral == peripheral)
            {
                new = false;
                row = i;

                discPeripheral.peripheral = peripheral;
            }
        }

        if(new == TRUE)
        {
            discPeripheral = [[DiscoveredPeripheral alloc] initWithPeripheral:peripheral andAdvertisment:advertisementData andRssi:RSSI];

            discPeripheral.rssi = RSSI;

            if(peripheral.isConnected == TRUE)
            {
                discPeripheral.state = DP_STATE_CONNECTED;
            }

            [discoveredPeripherals addObject:discPeripheral];
            NSLog(@"Scan Ajout periph, total:%i",[discoveredPeripherals count]);
            NSLog(@"Scan %i: Add %@",[discoveredPeripherals count]-1, discPeripheral.peripheral.name);

            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[discoveredPeripherals count]-1 inSection:1];
            NSLog(@"Scan Nouveau periph, index:%i, section:%i",indexPath.row,indexPath.section);
            UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
            cell.textLabel.text = discPeripheral.peripheral.name;
            //[self.tableView insertRowsAtIndexPaths: [NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.myTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        else
        {
            discPeripheral.peripheral = peripheral;
            discPeripheral.advertisment = advertisementData;
            discPeripheral.rssi = RSSI;

            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:1];
            UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];

            //ScanCell* cell = (ScanCell*)[self.tableView cellForRowAtIndexPath:indexPath];

            //NSLog(@"%i: Update %@", row, discPeripheral.peripheral.name);

            cell.textLabel.text = discPeripheral.peripheral.name;
            //cell.labelInfo.text = [[NSString alloc] initWithFormat:@"RSSI: %@", discPeripheral.rssi];
        }
    }
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSInteger row = [self getRowForPeripheral:peripheral];

    if(row != -1)
    {
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:1];
        UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];

        //ScanCell* cell = (ScanCell*)[self.tableView cellForRowAtIndexPath:indexPath];

        cell.textLabel.text = [[NSString alloc] initWithFormat:@""];

        cell.accessoryType = UITableViewCellAccessoryNone;
        //[cell.activityView stopAnimating];

        DiscoveredPeripheral* dp = [discoveredPeripherals objectAtIndex:row];

        dp.state = DP_STATE_IDLE;
    }
}

- (void)centralManager:(CBCentralManager *)central didRetrieveConnectedPeripherals:(NSArray *)peripherals
{
    //DiscoveredPeripheral*   discPeripheral;
    CBPeripheral*           peripheral;

    for(int i = 0; i < peripherals.count; i++)
    {
        peripheral = [peripherals objectAtIndex:i];

        /*
         discPeripheral = [[DiscoveredPeripheral alloc] initWithPeripheral:peripheral andAdvertisment:nil andRssi:nil];

         if(peripheral.isConnected == TRUE)
         {
         discPeripheral.state = DP_STATE_CONNECTED;
         }

         [discoveredPeripherals addObject:discPeripheral];

         NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[discoveredPeripherals count] - 1 inSection:1];

         [self.tableView insertRowsAtIndexPaths: [NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
         */

        //[cbCentralManager cancelPeripheralConnection:peripheral];

        NSDictionary *dictionary;

        dictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey];

        [cbCentralManager connectPeripheral:peripheral options:dictionary];

    }
}

- (void)centralManager:(CBCentralManager *)central didRetrievePeripherals:(NSArray *)peripherals
{

}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    //NSLog(@"Central Manager State: %d", [central state]);

    if(central.state == CBCentralManagerStatePoweredOn)
    {
        [cbCentralManager retrieveConnectedPeripherals];
    }
}

@end

Edit:
This view is called from a view controller.
The view controller is receiving data from bluetooth, record and displays the data.
What I would like to achieve is to have a separate view to connect to the BLE peripheral, go back to the main view, attach the serial port and run.
In a second time, if the peripheral is lost, try to reconnect to it, else pop the connection view and alert the user.
Cheers.
Cedric

A: You need to retain the peripheral. As soon as the peripheral object you are passed is released, iOS drops the connection. Save the CBPeripheral object in a variable, and be sure to pass that back to your main view when the scan view closes.

A: A very nice way to manage your entire bluetooth processes is the singleton model.  You can move all your bluetooth code to a separate NSObject class and declare that file as a singleton. Create a function within your singleton class to initiate the connectPeripheral after you discover your device. Whenever you connect, you can save the peripheral you are connecting to as a variable or in an array if you have multiple devices. It's quite simple once you get the hang of it. Using this method of implementation you can refer to your connected Peripheral from anywhere within your app. Hope this helped!


text:
Q: JQuery Animation with ScrollTop Hello Stackoverflow people!
I am having some trouble in JavaScript since I've been experiementing a little with different things something I've had a lot of trouble with is the following:
$(document).scroll(function () {
    $('.header').toggleClass('scrolled', $(this).scrollTop() > 1);
});

This works fine, but I want to add an "animation" to it where it fades in when I scroll down on my page, and fades out when I scroll to the top of my page.
The class "Scrolled" is what I want to fade in and out.
Somebody that might be able to help me with this?


text:
Q: how to eliminate tags in Output XML if the respective tags in Input XML are not present using XSLT Input XML:
<PostedOrder>
    <ID>12345</ID>
    <Email>abc@gmail.com</Email>
    <Sender>John</Sender>
    <Recepient>Mary</Recepient>
    <ShipTo>Delhi</ShipTo>
    <ShipFrom>Mumbai</ShipFrom>
    <ShipUnit>MAIL</ShipUnit>
</PostedOrder>

Output XML:
<PostedOrder>
    <OrderID>12345</OrderID>
    <Contact>abc@gmail.com</Contact>
    <SentTo>Mary</SentTo>
    <Sentfrom>John</Sentfrom>
    <To>Delhi</To>
    <From>Mumbai</From>
    <ShipUnitID>
        <LocationID>
            <Bid>
                <Domain>Buisness</Domain><!-- Hardcoded value-->
                <Xid>MAIL</Xid>
            </Bid>
        </LocationID>
    </ShipUnitID>
</PostedOrder>

XSL:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:strip-space elements="" />
    <xsl:output method="xml" indent="yes" />
    <xsl:template match="/">
        <PostedOrder>
            <xsl:for-each select="/PostedOrder">
                <OrderID><xsl:value-of select="ID" /></OrderID>
                <Contact><xsl:value-of select="Email" /></Contact>
                <SentTo><xsl:value-of select="Recepient" /></SentTo>
                <Sentfrom><xsl:value-of select="Sender" /></Sentfrom>
                <To><xsl:value-of select="ShipTo" /></To>
                <From><xsl:value-of select="ShipFrom" /></From>
                <ShipUnitID>
                    <LocationID>
                        <Bid>
                            <Domain>Buisness</Domain><!-- Hardcoded value-->
                            <Xid>
                                <xsl:value-of select="ShipUnit" />
                            </Xid>
                        </Bid>
                    </LocationID>
                </ShipUnitID>
            </xsl:for-each>
        </PostedOrder>
    </xsl:template>
</xsl:stylesheet>

In the above example, I have a requirement not to create the <ShipUnitID> and the subsequent child elements in the Output XML if the <ShipUnit> is missing in the Input XML using XSLT. Can someone please help me with this, I'm new to the XML transformations. Thanks in Advance.

A: Since you do not need the <ShipUnitID> element and it's children in the output, you can add <xsl:if> condition to check for <ShipUnit> before preparing the <ShipUnitID> element. Below is code for reference.
<xsl:if test="ShipUnit != ''" >
    <ShipUnitID>
        <LocationID>
            <Bid>
                <Domain>Buisness</Domain>
                <Xid><xsl:value-of select="ShipUnit" /></Xid>
            </Bid>
        </LocationID>
    </ShipUnitID>
</xsl:if>

To test this, we can modify the input XML to have 2 elements for <PostedOrder>, one with <ShipUnit> as a child and one without as below.
<PostedOrders>
    <PostedOrder>
        <ID>12345</ID>
        <Email>abc@gmail.com</Email>
        <Sender>John</Sender>
        <Recepient>Mary</Recepient>
        <ShipTo>Delhi</ShipTo>
        <ShipFrom>Mumbai</ShipFrom>
        <ShipUnit>MAIL</ShipUnit>
    </PostedOrder>
    <PostedOrder>
        <ID>23456</ID>
        <Email>xyz@gmail.com</Email>
        <Sender>Paul</Sender>
        <Recepient>Tom</Recepient>
        <ShipTo>Chennai</ShipTo>
        <ShipFrom>Bengaluru</ShipFrom>
    </PostedOrder>
</PostedOrders>

Updated XSLT: XSLT has been modified to match template <PostedOrder> instead of matching the root element "/" and thereby eliminating the need of the <xsl:for-each>.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:strip-space elements="*" />
    <xsl:output method="xml" indent="yes" />
    <xsl:template match="PostedOrder">
        <PostedOrder>
            <OrderID><xsl:value-of select="ID" /></OrderID>
            <Contact><xsl:value-of select="Email" /></Contact>
            <SentTo><xsl:value-of select="Recepient" /></SentTo>
            <Sentfrom><xsl:value-of select="Sender" /></Sentfrom>
            <To><xsl:value-of select="ShipTo" /></To>
            <From><xsl:value-of select="ShipFrom" /></From>
            <xsl:if test="ShipUnit != ''" >
                <ShipUnitID>
                    <LocationID>
                        <Bid>
                            <Domain>Buisness</Domain>
                            <Xid><xsl:value-of select="ShipUnit" /></Xid>
                        </Bid>
                    </LocationID>
                </ShipUnitID>
            </xsl:if>
        </PostedOrder>
    </xsl:template>
</xsl:stylesheet>

Output
<PostedOrder>
   <OrderID>12345</OrderID>
   <Contact>abc@gmail.com</Contact>
   <SentTo>Mary</SentTo>
   <Sentfrom>John</Sentfrom>
   <To>Delhi</To>
   <From>Mumbai</From>
   <ShipUnitID>
      <LocationID>
         <Bid>
            <Domain>Buisness</Domain>
            <Xid>MAIL</Xid>
         </Bid>
      </LocationID>
   </ShipUnitID>
</PostedOrder>
<PostedOrder>
   <OrderID>23456</OrderID>
   <Contact>xyz@gmail.com</Contact>
   <SentTo>Tom</SentTo>
   <Sentfrom>Paul</Sentfrom>
   <To>Chennai</To>
   <From>Bengaluru</From>
</PostedOrder>


text:
Q: What's the maximum key length for PHP APC? You would think this would be super-easy to find, but I can't seem to.

A: There appears to be no limitation on key size/content.
Internally, keys are initialized via the C function apc_cache_make_user_key, which takes the given key string ("identifier") and stores it along with a hashed version.

A: I really don't know PHP, but it looks like values are added using apc_add() or apc_store(), which take keys which are strings. I would infer that the maximum key length is therefore the maximum length of a string in PHP.
According to PHP: Strings,

Note: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.


text:
Q: How to have two ControllerAdvice in the same SpringMvc application I would like to manage Exception thrown by simple Controller or RestController in two ways:
1) html redirection
2) Json error
I tested the code below :
@ControllerAdvice(annotations = Controller.class)
public class ExceptionHandlerController
{
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(HttpServletRequest _req, Exception _ex)
    {
        K_LOGGER.info("test");
        return new ModelAndView();
    }
}

@ControllerAdvice(annotations = RestController.class)
public class ExceptionHandlerRestController
{

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(HttpServletRequest _req, Exception _ex)
    {
        return new ResponseEntity<>("test", HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

@RestController
public class GreetingController
{
    @RequestMapping("/greetingexception")
    public Greeting greetingException(@RequestParam(value = "name", defaultValue = "World") String name)
        throws Exception
    {
        throw new Exception();
    }
}

It doesn't work properly, I always pass by ExceptionHandlerController but not by ExceptionHandlerRestController.
I think it's because @RestController inherit of @Controller.
Do you have a other solution?

A: Try to add @Order(Ordered.HIGHEST_PRECEDENCE) annotation to rest exception handler. It may helps you.

A: eg04lt3r answer is correct, just though that more details might be useful for someone.
In case when you have global @ControllerAdvice and want to handle some exception in a different way in one of your Controllers you need to set @Order(Ordered.HIGHEST_PRECEDENCE) on the @ControllerAdvice which should have higher priority.
For example:
@ControllerAdvice
public class GeneralExceptionHandler {

    @ExceptionHandler(Exception.class)
    protected ResponseEntity<Error> handleException(Exception ex) {
        ...
    }
}

@ControllerAdvice(assignableTypes = MyController.class)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    protected ResponseEntity<Error> handleException(Exception ex) {
        ...
    }
}

@Order is needed because on startup one of the handlers will register with higher order automatically, anyway and your exception handling will become unpredictable. For example I recently saw a case when if you start an app using bootRun gradle task MyExceptionHandler was primary, but when started as jar GeneralExceptionHandler was primary.


text:
Q: Why sequences are recommended as conventional interfaces? From the reference of berkeley's version of  sicp text, It is mentioned that:

Expressing programs as sequence operations helps us design programs that are modular. That is, our designs are constructed by combining relatively independent pieces, each of which transforms a sequence. In general, we can encourage modular design by providing a library of standard components together with a conventional interface for connecting the components in flexible ways.

For instance, In python, <class 'list'> and <class 'tuple'> are some of the types of mostly used sequential data models for storage.
For instance, In python <class 'dict'> is one popular type of non-sequential data model.
Text reference gives below solutions written in python to two different problems  and mentions as similar solution, which is not convincing, because these two problems could not be the representative sample to take this decision.
>>> def sum_even_fibs(n):
        """Sum the even members of the first n Fibonacci numbers."""
        return sum(filter(iseven, map(fib, range(1, n+1))))
>>> sum_even_fibs(20)
3382

>>> def acronym(name):
        """Return a tuple of the letters that form the acronym for name."""
        return tuple(map(first, filter(iscap, name.split())))
>>> acronym('University of California Berkeley Undergraduate Graphics Group')
('U', 'C', 'B', 'U', 'G', 'G')

I am still not clear on the decision to make "sequences as conventional interfaces" despite these given examples.
So,
Amidst designing a library or component, Why sequential type data models are recommended to be chosen as conventional interfaces?Is this something to do with closure property of these sequential data models(provided by python/scheme/lisp)?
Note: Same recommendation is given in SICP text from MIT press

A: The purpose of a dictionary is to return a value given a specified key, not to serve as a sequential container.  Just because other data structures are sequential but dictionaries are not does not mean that the benefits of sequences are invalidated.
Sequences are one of the three fundamental logic structures in computing.  Every (solvable) computing problem can be solved with three tools: sequences, loops, and decisions.
Sequences preserve the relationship between elements; that is, the first element must occur before the second element, which must occur before the third element, and so forth.  That means we can retrieve the next element in a sequence, and be assured that we retrieved the element in the correct order, relative to the other elements.  This has obviously useful benefits: words always consist of the same sequence of letters each time they are read, and methods consist of the same sequence of instructions each time they are called.
You can make sequences lazy.  You can create a class that implements a state machine, and returns an element from the state machine each time a method is called.  You can cache sequences.
Sequences can be created from linked lists, trees, and other data structures.  Each data structure has its own specific qualities; a singly-linked list can be efficiently traversed in one direction, but not the other.  Some data structures, such as binary trees, will give you sequential access and also efficient random access.  Some data structures, such as doubly-linked lists, allow you to efficiently traverse the sequence backwards.
If you write your data structure to conform to a sequential interface, you can switch out your implementation of the sequence to whichever data structure is most appropriate for your given requirements.  You can then write your code against that interface, and be assured that the underlying implementations are modular.
I don't know much about sequences in python, but the fundamental data structure in Scheme (used in the original SICP) is a list, and the ways in which you can compose such lists (which are essentially sequences), and the flexibility and power that affords, should be obvious.  Every language containing sequences allows such compositions.


text:
Q: No such module 'MaterialComponents' only when archiving? I am trying to archive my app, but I get 'No such module 'MaterialComponents' error.
The app runs on simulator and real device.
This is the pod file:

These are pod frameworks:

A: First of all your running the main target so you never get the error because the error is in a different target. , try to run the notification service extension target then you get the error. the basic error is your other target check all the classes that you added in the notification extension you can find that in target membership . it's possible the one of the class is using the 'MaterialComponents' classes. the basic idea is to remove that classes if unwanted if you need that then add the pod into the notification service extension as well, or you can put extension condition in that classes. I had fac issues with my application because it has 3 major target and 5 extension targets.


text:
Q: Can't knit the R file that I am trying to make So I have a document where I'm trying to knit, but I get an error where it says that
Error: object 'r' not found
Execution halted

Here is my full code:
---
title: "Test"
author: "Test Test"
date: "05.15.2022"
output:
  html_document:
    toc: yes
    toc_float: yes
editor_options:
  markdown:
    wrap: sentence
---

# Header

##chunks

```{r}
summary(cars)
```

```{r}
knitr::opts_chunk$set(message = FALSE,warning = FALSE, error = FALSE)
```

```{r}
sapply(cars,class)
```

Any help? I am really new to R.


text:
Q: Launch MyApp from a link on Android, but not in the Activity declared as MAIN I'm launching MyApp from a URL.
I declared the intent and it works:
<intent-filter>
   <action android:name="android.intent.action.VIEW" />
   <category android:name="android.intent.category.DEFAULT" />
   <category android:name="android.intent.category.BROWSABLE" />

   <data   android:scheme =    "https"
           android:host =      "formiik.com"
           android:pathPrefix ="/citas"/>
   <data   android:scheme  =   "http"
           android:host =      "www.formiik.com"
           android:pathPrefix ="/citas"/>
</intent-filter>

But intent only works when it is declared with the intent.action.MAIN on the Activity.
If I put the intent to launch or in another Activity, the intent doesn't catch the URL.
Can't I launch it into another Activity that is not MAIN?
Or I need another instruction?
Thanks for your help.

A: Your intent looks fine,  make sure the other activity you want it on has android:exported="true" because it's not a launcher activity and then you should be good to go!


text:
Q: Meteor test driven development I don't see how to do test driven development  in meteor.
I don't see it mentioned anywhere in documentation or FAQ. I don't see any examples or anything like that.
I see that some packages are using Tinytest.
I would need response from developers, what is roadmap regarding this. Something along the lines of:

*

*possible, no documentation, figure it out yourself

*meteor is not built in a way that you can make testable apps

*this is planned feature

*etc

A: Update 3: As of Meteor 1.3, meteor includes a testing guide with step-by-step instructions for unit, integration, acceptance, and load testing.
Update 2: As of November 9th, 2015, Velocity is no longer maintained. Xolv.io is focusing their efforts on Chimp, and the Meteor Development Group must choose an official testing framework.
Update: Velocity is Meteor's official testing solution as of 0.8.1.

Not much has been written about automated testing with Meteor at this time. I expect the Meteor community to evolve testing best-practices before establishing anything in the official documentation. After all, Meteor reached 0.5 this week, and things are still changing rapidly.
The good news: you can use Node.js testing tools with Meteor.
For my Meteor project, I run my unit tests with Mocha using Chai for assertions. If you don't need Chai's full feature set, I recommend using should.js instead. I only have unit tests at the moment, though you can write integration tests with Mocha as well.
Be sure to place your tests in the "tests" folder so that Meteor does not attempt to execute your tests.
Mocha supports CoffeeScript, my choice of scripting language for Meteor projects. Here's a sample Cakefile with tasks for running your Mocha tests. If you are using JS with Meteor, feel free to adapt the commands for a Makefile.
Your Meteor models will need a slight bit of modification to expose themselves to Mocha, and this requires some knowledge of how Node.js works. Think of each Node.js file as being executed within its own scope. Meteor automatically exposes objects in different files to one another, but ordinary Node applications—like Mocha—do not do this. To make our models testable by Mocha, export each Meteor model with the following CoffeeScript pattern:
# Export our class to Node.js when running
# other modules, e.g. our Mocha tests
#
# Place this at the bottom of our Model.coffee
# file after our Model class has been defined.
exports.Model = Model unless Meteor?

...and at the top of your Mocha test, import the model you wish to test:
# Need to use Coffeescript's destructuring to reference
# the object bound in the returned scope
# http://coffeescript.org/#destructuring
{Model} = require '../path/to/model'

With that, you can start writing and running unit tests with your Meteor project!

A: I used this page a lot and tried all of the answers, but from my beginner's starting point, I found them quite confusing. Once I had any trouble, I was flummoxed as to how to fix them.
This solution is really simple to get started with, if not fully documented yet, so I recommend it for people like myself who want to do TDD but aren't sure how testing in JavaScript works and which libraries plug into what:
https://github.com/mad-eye/meteor-mocha-web
FYI, I found that I also need to use the router Atmosphere package to make a '/tests' route to run and display the results from the tests, as I didn't want it to clutter my app every time it loads.

A: About the usage of tinytest, you may want to take a look at those useful ressources:

*

*The basics are explained in this screencast:
https://www.eventedmind.com/feed/meteor-testing-packages-with-tinytest

*Once you understood the idea, you'll want the public API documentation for tinytest. For now, the only documentation for that is at the end of the source of the tinytest package: https://github.com/meteor/meteor/tree/devel/packages/tinytest

*Also, the screencast talks about test-helpers, you may want to have a look at all the available helpers in here:
https://github.com/meteor/meteor/tree/devel/packages/test-helpers
There often is some documentation inside each file

*Digging in the existing tests of meteor's packages will provide a lot of examples. One way of doing this is to make a search for Tinytest. or test. in the package directory of meteor's source code

A: Testing becomes a core part of Meteor in the upcoming 1.3 release.  The initial solution is based on Mocha and Chai.
The original discussions of the minimum viable design can be found here and the details of the first implementation can be found here.
MDG have produced the initial bones of the guide documentation for the testing which can be found here, and there are some example tests here.
This is an example of a publication test from the link above:

  it('sends all todos for a public list when logged in', (done) => {
    const collector = new PublicationCollector({userId});
    collector.collect('Todos.inList', publicList._id, (collections) => {
      chai.assert.equal(collections.Todos.length, 3);
      done();
    });
  });

A: Hi all checkout laika - the whole new testing framework for meteor
http://arunoda.github.io/laika/
You can test both the server and client at once.

*

*See some laika example here

*See here for features

*See concept behind laika

*See Github Repository
Disclaimer: I'm the author of Laika.

A: I'm doing functional/integration tests with Meteor + Mocha in the browser. I have something along the lines of the following (in coffeescript for better readability):
On the client...
Meteor.startup ->
    Meteor.call 'shouldTest', (err, shouldTest) ->
        if err? then throw err
        if shouldTest then runTests()

# Dynamically load and run mocha. I factored this out in a separate method so
# that I can (re-)run the tests from the console whenever I like.
# NB: This assumes that you have your mocha/chai scripts in .../public/mocha.
# You can point to a CDN, too.
runTests = ->
    $('head').append('<link href="/mocha/mocha.css" rel="stylesheet" />')
    $.getScript '/mocha/mocha.js', ->
      $.getScript '/mocha/chai.js', ->
        $('body').append('<div id="mocha"> </div>')
        chai.should() # ... or assert or explain ...
        mocha.setup 'bdd'
        loadSpecs() # This function contains your actual describe(), etc. calls.
        mocha.run()

...and on the server:
Meteor.methods 'shouldTest': -> true unless Meteor.settings.noTests  # ... or whatever.

Of course you can do your client-side unit testing in the same way. For integration testing it's nice to have all Meteor infrastructure around, though.

A: As Blackcout said, Velocity is the official TDD framework for Meteor. But at this moment velocity's webpage doesn't offer good documentation. So I recommend you to watch:

*

*Concept behind velocity

*Step by step tutorial

*And specially the Official examples

A: Another option, made easily available since 0.6.0, is to run your entire app out of local smart packages, with a bare minimum amount of code outside of packages to boot your app (possibly invoking a particular smart package that is the foundation of your app).
You can then leverage Meteor's Tinytest, which is great for testing Meteor apps.

A: I realize that this question is already answered, but I think this could use some more context, in the form of an additional answer providing said context.
I've been doing some app development with meteor, as well as package development, both by implementing a package for meteor core, as well as for atmosphere.
It sounds like your question might be actually a question in three parts:

*

*How does one run the entire meteor test suite?

*How does one write and run tests for individual smart packages?

*How does one write and run tests for his own application?

And, it also sounds like there may be a bonus question in there somewhere:
 4. How can one implement continuous integration for 1, 2, and 3?
I have been talking and begun collaborating with Naomi Seyfer (@sixolet) on the meteor core team to help get definitive answers to all of these questions into the documentation.
I had submitted an initial pull request addressing 1 and 2 to meteor core: https://github.com/meteor/meteor/pull/573.
I had also recently answered this question:
How do you run the meteor tests?
I think that @Blackcoat has definitively answered 3, above.
As for the bonus, 4, I would suggest using circleci.com at least to do continuous integration for your own apps. They currently support the use case that @Blackcoat had described. I have a project in which I've successfully gotten tests written in coffeescript to run unit tests with mocha, pretty much as @Blackcoat had described.
For continuous integration on meteor core, and smart packages, Naomi Seyfer and I are chatting with the founder of circleci to see if we can get something awesome implemented in the near term.

A: RTD has now been deprecated and replaced by Velocity, which is the official testing framework for Meteor 1.0. Documentation is still relatively new as Velocity is under heavy development. You can find some more information on the Velocity Github repo, the Velocity Homepage and The Meteor Testing Manual (paid content)
Disclaimer: I'm one of the core team members of Velocity and the author of the book.

Check out RTD, a full testing framework for Meteor here rtd.xolv.io.
It supports Jasmine/Mocha/custom and works with both plain JS and coffee. It includes test coverage too that combines unit/server/client coverage.
And an example project here
A blog to explain unit testing with Meteor here
An e2e acceptance testing approach using Selenium WebdriverJS and Meteor here
Hope that helps. Disclaimer: I am the author of RTD.

A: Ive successfully been using xolvio:cucumber and velocity to do my testing.  Works really well and runs continuously so you can always see that your tests are passing.

A: Meteor + TheIntern
Somehow I managed to test Meteor application with TheIntern.js.
Though it is as per my need. But still I think it may lead someone to the right direction and I am sharing what I have done to resolve this issue.
There is a execute function which allows us to run JS code thorugh which we can access browsers window object and hence Meteor also.
Want to know more about execute
This is how my test suite looks for Functional Testing
define(function (require) {
    var registerSuite = require('intern!object');
    var assert = require('intern/chai!assert');
    registerSuite({
        name: 'index',

        'greeting form': function () {
            var rem = this.remote;
            return this.remote
                .get(require.toUrl('localhost:3000'))
                .setFindTimeout(5000)
                .execute(function() {
                        console.log("browser window object", window)
                        return Products.find({}).fetch().length
                    })
                .then(function (text) {
                    console.log(text)
                    assert.strictEqual(text, 2,
                        'Yes I can access Meteor and its Collections');
                });
        }
    });
});

To know more, this is my gist
Note: I am still in very early phase with this solution. I don't know whether I can do complex testing with this or not. But i am pretty much confident about it.

A: Velocity is not mature yet. I am facing setTimeout issues to use velocity. For server side unit testing you can use this package.
It is faster than velocity. Velocity requires a huge time when I test any spec with a login. With Jasmine code we can test any server side method and publication.


text:
Q: fabricjs programmatically pan canvas on mobile browser I have a website with fabric and it renders fine a pdf(as images). with mobile browser it displays fine and I enabled allowtouchscrolling and can pan the image (almost equal to scroll but not as effective as scrolling) . I have annotations on the image rendered which user has to respond. as of now its tedious to find each annotation object. Is there a way I can programmatically pan the fabric canvas centered to a specific x,y?
thanks
prem

A: *

*Pan canvas so that [0,0] appears in center of viewport.
To achieve this do canvas.absolutePan(new fabric.Point(-canvas.getWidth() / 2, -canvas.getHeight() / 2)

*And then additionally offset canvas to your object coordinates (in my example I use [left,top] + [halfWidth, halfHeight] to calc offset of object center.
Thus conclude making canvas.absolutePan to [-canvas.getWidth() / 2 + obj.left + obj.width / 2, -canvas.getHeight() / 2 + obj.top + obj.height / 2
Working example you may find here: http://jsfiddle.net/mmalex/2rsevdLa/
function panTo(canvas, obj) {
    let w = canvas.getWidth();
    let h = canvas.getHeight();

    let targetX = obj.left + obj.width / 2;
    let targetY = obj.top + obj.height / 2;

    canvas.absolutePan(new fabric.Point(-w/2+targetX, -h/2+targetY))
}

function recenterCanvas() {
    panTo(canvas, refRect);
    canvas.bringToFront(refRect);
    canvas.renderAll();
}


text:
Q: Is it possible to make this shape in CSS3? Is it possible to make this shape in CSS3?

I saw this link http://css-tricks.com/examples/ShapesOfCSS/ , I don't know if any shape in this page can be edited to look like the shape i need.
Thank you..

A: put this to your css your shape div
 -webkit-transform: rotatey(16deg);
 -moz-transform: rotatey(16deg);
 transform: rotatey(16deg);
 position: absolute;

put this code your parent div of your shape div
-webkit-perspective: 175;
-moz-perspective: 175;
perspective: 175;
position: relative;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;

this code may be make shape that will you want and set height width and other css as your requirement. this code dont work on old browser like ie.
and you could make many type of shape with and css you want with the help of google web design software
here is link: https://www.google.com/webdesigner/

A: FIDDLE
Here is my approach:
div {
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;

    -webkit-transform: rotate(2deg);
    -moz-transform: rotate(2deg);
    -ms-transform: rotate(2deg);
    -o-transform: rotate(2deg);
    transform: rotate(2deg);
    -webkit-backface-visibility: hidden;

    -webkit-transform-origin: top left;
    -moz-transform-origin: top left;
    -ms-transform-origin: top left;
    -o-transform-origin: top left;
    transform-origin: top left;
}
div:after {
    content: "";
    display: block;
    position: absolute;
    border-style: solid;
    border-color: #FFF transparent transparent;
    border-width: 127px 0 25px 19px;
    right: 0;
}
div:before {
    background: rgba(255, 0, 0, 0.45);
    width: 668px;
    height: 240px;
    content: "";
    display: block;

    -webkit-transform-origin: top left;
    -moz-transform-origin: top left;
    -ms-transform-origin: top left;
    -o-transform-origin: top left;
    transform-origin: top left;

    -webkit-transform: rotate(-9.5deg) skewX(1deg);
    -moz-transform: rotate(-9.5deg) skewX(1deg);
    -ms-transform: rotate(-9.5deg) skewX(1deg);
    -o-transform: rotate(-9.5deg) skewX(1deg);
    transform: rotate(-9.5deg) skewX(1deg);
}

I guess, jingesh kheni's solution might be more clean but I tried it and somehow the perspective property doesn't work for me.
EDIT:
According to OP's comment about rough edges of the div, I updated the fiddle and the code above. I simply added this line of CSS:
-webkit-backface-visibility: hidden;

These rough edges are a bug in Chrome, here's the explanation.


text:
Q: Head First C# - Chapter 1 example I`m tring to learn from Head First C#, but i'm getting this error in the first chapter:
Additional information: Specified Visual is already a child of another Visual or the root of a CompositionTarget.
I'm pretty sure the code is exactly like in the book, but i am using VS2015 and the example is flr VS2013:
Here is my code:

<Window x:Class="Save_the_humans.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Save_the_humans"
        mc:Ignorable="d"
        Title="Save the Humans" Height="700" Width="1000">
    <Window.Resources>
        <ControlTemplate x:Key="EnemyTemplate" TargetType="{x:Type ContentControl}">
            <Grid>
                <Ellipse Fill="#FFD61001" Height="100" Stroke="Black" Width="100"/>
            </Grid>
        </ControlTemplate>
    </Window.Resources>
    <Grid Background="Black">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="140"/>
            <ColumnDefinition/>
            <ColumnDefinition Width="160"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="150"/>
        </Grid.RowDefinitions>
        <Button x:Name="startButton" Content="Start!" HorizontalAlignment="Center"
                Grid.Row="1" VerticalAlignment="Center" Click="startButton_Click"/>
        <ProgressBar x:Name="progressBar" Grid.Column="1" Grid.Row="1" Height="20"/>
        <StackPanel Grid.Column="2" Orientation="Vertical" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBox x:Name="AvoidThese"
                TextWrapping="Wrap" Text="Avoid These" FontSize="18" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="White" Background="Black"/>
            <ContentControl Content="ContentControl" HorizontalAlignment="Center" VerticalAlignment="Center" Template="{DynamicResource EnemyTemplate}"/>
        </StackPanel>
        <Canvas x:Name="playArea" Grid.ColumnSpan="3">
            <Canvas.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF0F259A" Offset="0.096"/>
                    <GradientStop Color="#FF25C714" Offset="1"/>
                </LinearGradientBrush>
            </Canvas.Background>
            <StackPanel x:Name="Human" Orientation="Vertical">
                <Ellipse Fill="White" Width="10" Height="10" Stroke="Black"/>
                <Rectangle Fill="White" Height="25" Width="10" Stroke="Black"/>
            </StackPanel>
            <TextBlock x:Name="gameOverText" Canvas.Left="210" TextWrapping="Wrap" Text="Game Over" Canvas.Top="195" Height="120" Width="535" FontFamily="Arial" FontSize="100" FontStyle="Italic" FontWeight="Bold"/>
            <Rectangle x:Name="target" Height="50" Canvas.Left="505" Stroke="Black" Canvas.Top="85" Width="50" RenderTransformOrigin="0.5,0.5">
                <Rectangle.RenderTransform>
                    <TransformGroup>
                        <ScaleTransform/>
                        <SkewTransform/>
                        <RotateTransform Angle="45"/>
                        <TranslateTransform/>
                    </TransformGroup>
                </Rectangle.RenderTransform>
                <Rectangle.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FFAE0E64" Offset="0.245"/>
                        <GradientStop Color="#FF170202" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Canvas>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Windows.Threading;
namespace Save_the_humans
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Random random = new Random();
        DispatcherTimer enemyTimer = new DispatcherTimer();
        DispatcherTimer targetTimer = new DispatcherTimer();
        bool humanCaptured = false;
        public MainWindow()
        {
            InitializeComponent();

            enemyTimer.Tick += enemyTimer_Tick;
            enemyTimer.Interval = TimeSpan.FromSeconds(2);

            targetTimer.Tick += TargetTimer_Tick;
            targetTimer.Interval = TimeSpan.FromSeconds(.1);

        }

        private void TargetTimer_Tick(object sender, EventArgs e)
        {
            progressBar.Value += 1;
            if (progressBar.Value >= progressBar.Maximum)
                EndTheGame();

        }

        private void EndTheGame()
        {
            if(!playArea.Children.Contains(gameOverText))
            {
                enemyTimer.Stop();
                targetTimer.Stop();
                humanCaptured = false;
                startButton.Visibility = Visibility.Visible;
                playArea.Children.Add(gameOverText);
            }
        }

        private void enemyTimer_Tick(object sender, EventArgs e)
        {
            AddEnemy();
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            StartGame();
        }

        private void StartGame()
        {
            Human.IsHitTestVisible = true;
            humanCaptured = false;
            progressBar.Value = 0;
            startButton.Visibility = Visibility.Collapsed;
            playArea.Children.Add(target);
            playArea.Children.Add(Human);
            enemyTimer.Start();
            targetTimer.Start();
        }

        private void AddEnemy()
        {
            ContentControl enemy = new ContentControl();
            enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
            AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
            AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
                         random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
            playArea.Children.Add(enemy);

        }

        private void AnimateEnemy(ContentControl enemy, double from , double to , string propertyToAnimate)
        {
            Storyboard storyBoard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
            DoubleAnimation animantion = new DoubleAnimation()
            {
                From = from,
                To = to,
                Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6))),
            };
            Storyboard.SetTarget(animantion, enemy);
            Storyboard.SetTargetProperty(animantion, new PropertyPath(propertyToAnimate));
            storyBoard.Children.Add(animantion);
            storyBoard.Begin();
        }
    }
}

A: If i comment this two lines, i get no error
        playArea.Children.Add(target);
        playArea.Children.Add(Human);

somehow this two are already inside the canvas from xaml .. or i dont know


text:
Q: Can the effect of Object.freeze be reversed in ES5? Once I do this:
var x = { };
Object.freeze( x );

Is there any way to modify x?
Thanks.

A:
Nothing can be added to or removed from the properties set of a frozen
  object. Any attempt to do so will fail, either silently or by throwing
  a TypeError exception (most commonly, but not exclusively, when in
  strict mode).

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/freeze
You can think about it like this:
if( typeof ChuckNorris === 'undefined' ) {
    ChuckNorris = Object.create( [Infinity], {
        canCountTo: {
            value: Infinity * 2,
            writable: true,
            configurable: true
        }
    });

    Object.freeze( ChuckNorris ); // nothing can harm Chuck anymore !
}

console.log( ChuckNorris.canCountTo );  // Infinity
delete ChuckNorris.canCountTo;
console.log( ChuckNorris.canCountTo );  // Infinity

So basically, freeze will set the objects writable and configurable flags to false after creation.

A: No, the idea of Object.freeze is that you cannot change it anymore. According to the documentation:

In essence the object is made effectively immutable.

and:

Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, ...


text:
Q: How to Post and Get Data Unique to Each Logged In User with Express and Mongoose? I am currently working on a small single page app that lets users login with PassportJs and Mongoose.
One of the things I am trying to do is allow users to login and each user has a unique todo/task list which are items associated to that user.
I have been able to do the first part...users can login and express/passport session is accessed using jade #{user.username}, so when logged in the user see "Welcome, [user.username]".
Now I add a form (accessible when user logged in) and the form says undefined. I'm not sure if its my Mongoose schema design or Routes that are causing the problem. Thanks for reading this and here is my code:
Mongoose Schema
mongoose.connect('mongodb://localhost/poplivecore')
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var user = new Schema({
username: String,
password: String,
email: String,
todos: [Todo]
});

var Todo = new Schema({
name: {type: String, default : ''},
user: {type: Schema.ObjectId, ref: 'user'},
createdAt  : {type : Date, default : Date.now}

})

var Todo = mongoose.model('Todo', Todo);
var user = mongoose.model('user', user);

Here are my Express routes:
    //WORKING....This route is the one that a logged in user sees, form posts with
app.get('/home', ensureAuthenticated ,function(req, res){
res.render('home', { user: req.user});
});

//WORKING...This route allows user to post/submit the login
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
function(req, res) {
res.redirect('/home');
});

//WORKING....This route allows user to create a user/account

app.post('/create', function(req, res, next){
var user = new user({
"username": req.body.username,
"password" : req.body.password,
"email" : req.body.email});

user.save(function (err) {
if (!err) {
  res.redirect('/home');
}
else {
  res.redirect('/');
  }
 });
});

**//NOT WORKING..Post used in the form inside the logged in Area, that adds a 'todo'**

app.post('/todo', function(req, res){
var todo = new todo(req.body.name);

todo.save(function (err) {
if (!err) {
  res.redirect('/home');
}
else {
  res.redirect('/fail');
  }
 });
});

Jade Form, for Adding a todo
enter code here
form(method='post', action='/todo')
 //input(type='hidden', value= user._id)#userId
 fieldset
  label Todo
   div.input
    input(name='todo.name', type='todo.name', class='xlarge')
   div.actions
    input(type='submit', value='Save', class='btn primary')
    button(type='reset', class='btn') Cancel

I can post on github if you need to see more code...thanks.
Update as per 'numbers1311407' suggesion
*New post route for todo, also changed todo to 'Todo' in both schema and routes*
app.post('/todo', function(req, res){
var todo = new Todo({name : req.body["Todo.name"]});

 todo.save(function (err) {
 if (!err) {
  res.redirect('/home');
 }
 else {
  res.redirect('/fail');
 }
 });
});

A: There are at least two problems here that would cause this to not work:

*

*The name of the input passed by your form is todo.name, and you're referencing it as req.body.name in the route.

*mongoose models are instantiated with an attributes object, but you're just giving it a string (which, actually, is null currently because of the first issue).
So for your route to work it would look more like this:
app.post("/todo", function (req, res) {
  var todo = new Todo({name: req.body["todo.name"]});
  todo.user = req.user._id;
  // ...
});

If you wanted to pass todo attributes as a parameter object, you'd want to name them with brackets todo[name], rather than dots.  This would result in the todo attributes being on object on the req.body, e.g.:
app.post("/todo", function (req, res) {
  console.log(req.body.todo); //=> { name: "whatever" }
  // ... which means you could do
  var todo = new Todo(req.body.todo);
  todo.user = req.user._id;
  // ...
});

Some other things you might want to change:

*

*As @NilsH points out, you don't want to pass the user id in the form, as that would allow anyone to make a todo for anyone else just by knowing their ID.  Rather since you're using passport, make use of the user in the session.  You should have access to the user ID through the passport determined user, like req.user._id.  I added this to both examples above.

*The type of your form input is todo.name.  It should be text (that's what the browser is treating it as anyway).

*Not necessarily an error, but model names are conventionally capitalized.  This also solves an issue your code has above in that you're redefining todo when you say var todo = new todo(...).


text:
Q: EF Core database-first identity column issue I am using EF Core 3.1 with a database-first approach using Linq-to-Entities to add a new entity, but I get the following error:

Cannot insert explicit value for identity column in table XXX when IDENTITY_INSERT is set to OFF.

I generated the tables automatically so the ID column type is int and set by default to 0.and I cannot set it to NULL because it is not Nullable.
I don't want to explicitly set value, I just want it to auto increase as it should.
Here is my code:
Person person =new Person()
{
     FirstName="Dan",
     Age=22
};
db.Persons.Add(person);
db.SaveChanges();

Class Person (generated from db):
public partial class Person
{
  public int ID { get; set; }
  public string FirstName { get; set; }
  public int Age { get; set; }
}

Thank in advance for any help

A: You should add the next attributes to your class definition:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
....
public partial class Person
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int ID { get; set; }

  public string FirstName { get; set; }
  public int Age { get; set; }
}

The Key attribute denotes the field should be a primary key,
and the DatabaseGenerated attribute tells about key generation way.

A: You should tell EF Core that ID is generated by the database. One way to do this is with the DatabaseGenerated attribute, eg :
public partial class Person
{
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int ID { get; set; }
  public string FirstName { get; set; }
  public int Age { get; set; }
}

The DatabaseGeneratedOption.Identity option tells EF Core that the database generates new values when a record is inserted. Without this, EF Core would include the value of the ID property in the INSERT command


text:
Q: English for "prolongement" or "Fortsetzung"? I'm sorry if that's not the right place to ask for, wikipedia failed to give me the correct word...
What's the English for a function that is defined on a larger domain than the original function and coincides with it on the original domain? Is it "extension" or "continuation" or something else?

A: Both "extension" and "continuation" are OK. I would be inclined to reserve "continuation" for the analytic continuation of analytic functions (or similar cases where the extension is somehow determined by its restriction to the original domain).

A: Yes, if $X\subset Y$ and $f:X\to Z$ and $g: Y\to Z$ such that $f(x)=g(x)$ for all $x\in X$, it is possible to call $g$ an extension of $f$, or to just say that "$g$ extends $f$."
"Continuation" connotes that the extension is somehow generated by the function and the subset, but in most cases a general function could be defined quite arbitrarily outside of $X$, so it does not seem to be a good substitute for "extension."
If you'd like to know the counterpart to the phrase "$g$ extends $f$," then we would speak of "restriction." That is, "$f$ is equal to the restriction of $g$ to the set $X$."


text:
Q: Mapbox GL JS ImageSource wrong coordinates I'm struggling to position an image correctly onto my map. I'm using one of the following URLs for my (live) image:

*

*https://maps.dwd.de/geoserver/dwd/wms?service=WMS&version=1.3.0&request=GetMap&layers=dwd:RX-Produkt&styles=&width=1024&height=1024&srs=EPSG:3857&bbox=230596.40272276622,5934337.07299266,1750026.7710981474,7343518.710858418&format=image/png&transparent=true

*https://maps.dwd.de/geoserver/dwd/wms?service=WMS&version=1.3.0&request=GetMap&layers=dwd:RX-Produkt&styles=&width=1024&height=1024&srs=CRS:84&bbox=2.0714827302884133,47.14423415016973,15.72075796095801,55.07980923136505&format=image/png&transparent=true

*https://maps.dwd.de/geoserver/dwd/wms?service=WMS&version=1.3.0&request=GetMap&layers=dwd:RX-Produkt&styles=&srs=EPSG:1000001&bbox=-523.462,-4658.645,376.538,-3758.645&width=1024&height=1024&format=image/png&transparent=true
These are the associated WMS capabilities: https://maps.dwd.de/geoserver/ows?service=wms&version=1.3.0&request=GetCapabilities
I tried adding an image source according to this example. Using these coordinates:
[2.0714827302884133, 55.07980923136505],
[15.72075796095801, 55.07980923136505],
[15.72075796095801, 47.14423415016973],
[2.0714827302884133, 47.14423415016973]

The problem is that the image is not aligned 100 % correctly, but slightly shifted/stretched. I read something about Mapbox using the Mercator projection and not being able to handle others? That's why there are three different URLs above, but all of them fail. Next I tried to convert my coordinates like this:
var westLongitude = 2.0714827302884133;
var eastLongitude = 15.72075796095801;
var southLatitude = 47.14423415016973;
var northLatitude = 55.07980923136505;

var topLeft = { lng: westLongitude, lat: northLatitude};
var mTopLeft = mapboxgl.MercatorCoordinate.fromLngLat(topLeft, 0).toLngLat();

var topRight = { lng: eastLongitude, lat: northLatitude};
var mTopRight = mapboxgl.MercatorCoordinate.fromLngLat(topRight, 0).toLngLat();

var bottomRight = { lng: eastLongitude, lat: southLatitude};
var mBottomRight = mapboxgl.MercatorCoordinate.fromLngLat(bottomRight, 0).toLngLat();

var bottomLeft = { lng: westLongitude, lat: southLatitude};
var mBottomLeft = mapboxgl.MercatorCoordinate.fromLngLat(bottomLeft, 0).toLngLat();

var mercatorCoordinates = [[mTopLeft.lng, mTopLeft.lat], [mTopRight.lng, mTopRight.lat], [mBottomRight.lng, mBottomRight.lat], [mBottomLeft.lng, mBottomLeft.lat]];

However this also didn't align the image correctly. I think, I'm using wrong coordinates. Any idea how to do it right?
Thank you so much.
Here's code to play around with (please compare the location of the radar blind spot (grey) with the image below to see the offset): js fiddle
Here's where the radar blind spot (pink) has to be:

A: Using the following coordinates/projection seems to work:
CRS=EPSG:3857&BBOX=614360.8293587392,5933210.01991552,1713821.866597408,7423590.537061271

Here's another js fiddle.


text:
Q: When to use sp_updatestats and when to use sp_updatestats with the resample option? I am confused about the usage of RESAMPLE option and when to use it.
We had problems with a customer DB. One/some queries took longer as expected and the CPU usage on the machine was higher than in the past.
The fix was executing an sp_updatestats;. Fine!
Now I started to collect some information to write a small article for our KB that used internally by our support and our customers.
So I want to check if I am correct with my understanding of the function of sp_updatestats;
sp_updatestats; just executes on all tables
UPDATE STATISTIC tbl;

sp_updatestats @resample='resample'; just executes on all tables
UPDATE STATISTIC tbl WITH RESAMPLE;

Instead of executing UPDATE STATISTICS on all tables the sp_updatestats always checks if the UPDATE STATISTICS is required and does nothing if no update seams to be necessary.
Without the RESAMPLE option the sample rate is recalculated to match the requirements of the table size. With the RESAMPLE option the last calculated sample rate is used and the statistics are regenerated. Always a recalculation is only applied if required.
So if the last UPDATE STATISTICS used a FULLSCAN, executing sp_updatestats with RESAMPLE will do a FULLSCAN again.
So in my eyes RESAMPLE is only valuable, when I am depending on existing UPDATE STATISTICS tbl WITH FULLSCAN. The normal approach would be just to use sp_updatestats;. In fact this recalculates a normal appropriate sample rate and updates the statistics (always only if required).
So my questions:
Is it correct that the RESAMPLE option doesn't make sense when I never used a specific sample rate for a table?
In other words not using RESAMPLE will reset the sample rate to the default?
Is it correct that sp_updatestats; does nothing if some internal checks detect, that the statistic data for the index or table doesn't require an update? So to force an update to all statistics of a DB I have to execute
EXEC sp_MSforeachtable 'PRINT ''?''; UPDATE STATISTICS ?;'

And this command resets the sample rate to the default.


text:
Q: Can someone further explain checking out of remote branches with git? I've looked at a few questions here, notably this one but I'm still confused.
I have a server set up with a slow up-link that I access through an SSH tunnel.  On it, I cloned a bare repository of the Linux kernel (origin points to kernel.org).  I then cloned the bare repository on my home machine, checked out tag, created a branch ('test' say), made changes on that branch and finally pushed the changes to the bare repo on my server.
Now I'm at a client site and want to checkout the branch.  To avoid my slow uplink at the client site, I cloned the linux repo from the kernel.org and changed 'origin' to point to my server via the SSH tunnel.  I can see the branch, but can't check it out:
~/linux-3.0.y$ git version
git version 1.7.0.4
~/linux-3.0.y$
~/linux-3.0.y$ git status
# On branch master
nothing to commit (working directory clean)
~/linux-3.0.y$
~/linux-3-0.y$ git remote show origin
git-user@localhost's password:
* remote origin
  Fetch URL: git+ssh://git-user@localhost:48884/home/git-user/linux-3.0.y
  Push  URL: git+ssh://git-user@localhost:48884/home/git-user/linux-3.0.y
  HEAD branch: master
  Remote branches:
    test    new (next fetch will store in remotes/origin)
    master  new (next fetch will store in remotes/origin)
  Local ref configured for 'git push':
    master pushes to master (up to date)
~/linux-3.0.y$
~/linux-3.0.y$ git checkout -b test origin/test
fatal: git checkout: updating paths is incompatible with switching branches.
Did you intend to checkout 'origin/test' which can not be resolved as commit?

What I actually intended was to be able to work on the branch created at home at my client's site.  What should I do (have done) to checkout this branch?

A: Well first, it seems that you didn't fetch the branches.
Use git branch -a instead of git remote show origin.
If the test branch is missing, then do git fetch --all.
Now if you want to checkout a remote branch as a local branch with the same name, just do git checkout BRANCH_NAME, it will be automatically set up to track the origin.


text:
Q: How can show the count of a element of a csv file I've placed the contents of a .csv file in the data list
with the following code in Jupyter notebook
data = []
with open("president_county_candidate.csv", "r") as f:
    contents = csv.reader(f)
    for c in contents:
        data.append(c)

I can only get an element through the index number, but that gives me the whole row of the list. How can I choose specific elements and the count? In the image, you can see the content of the List(data).
data

A: You can use pandas library to read csv in form of Dataframes and also you can perform various operations on the same. Refer the below code:
import pandas as pd
df = pd.read_csv('president_county_candidate.csv')
print(df.shape)

This will give you the number of rows and columns present in CSV file.
Also in order to extract any specific column you can use:
newdf = df[['candidates', 'votes']]

This will give you the new dataframe with the above mentioned columns.
Also please find the solution for your approach mentioned in question
You can extract the column index and then while parsing the contents, mention the index number of the columns you need.
For example:
data = []
with open("president_county_candidate.csv", "r") as f:
    contents = csv.reader(f)
    for c in contents:
        data.append([c[2], c[4]])

This will only get the data of Candidate and Votes.
Note: It's better to get the index number of specific column using list.index('columnName') and pass the same variable instead of hard-coded index.