问:
Making a new list with tuples based on strings in the list
```<code>L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
</code>```

Each number represents a person. So, there are five people from 0 to 4 in the list. L[0] always shows how many people are in the list.

```<code>L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]
</code>```

The person "0" is paired with 1 and 2. So, it has a list of 1, 2 in a tuple. My approach to get the result above is to compare the first character in L[1] to the end of the list. If the first letter in L[1] matches with the first letter in L[2], it bundles the second letter in L[2] with the second letter in L[1]. Finally, the new list is paired with 0 in a tuple. By the way, I cannot come up with such thing that can check the first letter in strings. I am not sure if this approach is right or not.

I am struggling to make such list L1 above. Could anyone let me know if my approach to this question is right? If it is wrong, please briefly give me a hint to solve this.

答:
Instead of list, go with dict and use this pattern without importing any external module.

```<code>L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]

final_dict={}
new=[]
for item in L:
    if not len(item)<2:
        if int(item[0]) not in final_dict:
            final_dict[int(item[0])]=[int(item[2])]
        else:
            final_dict[int(item[0])].append(int(item[2]))

print(final_dict)
</code>```

output:

```<code>{0: [1, 2], 1: [3], 2: [3, 4], 3: [4]}
</code>```

or if you want the result in the list then add this line end of above code:

```<code>print([(key,value) for key,value in final_dict.items()])
</code>```

output:

```<code>[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
</code>```

Body:
L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]

Each number represents a person. So, there are five people from 0 to 4 in the list. L[0] always shows how many people are in the list.

L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]

The person "0" is paired with 1 and 2. So, it has a list of 1, 2 in a tuple. My approach to get the result above is to compare the first character in L[1] to the end of the list. If the first letter in L[1] matches with the first letter in L[2], it bundles the second letter in L[2] with the second letter in L[1]. Finally, the new list is paired with 0 in a tuple. By the way, I cannot come up with such thing that can check the first letter in strings. I am not sure if this approach is right or not.

I am struggling to make such list L1 above. Could anyone let me know if my approach to this question is right? If it is wrong, please briefly give me a hint to solve this.

Body:
Instead of list, go with dict and use this pattern without importing any external module.

L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]

final_dict={}
new=[]
for item in L:
    if not len(item)<2:
        if int(item[0]) not in final_dict:
            final_dict[int(item[0])]=[int(item[2])]
        else:
            final_dict[int(item[0])].append(int(item[2]))

print(final_dict)

output:

{0: [1, 2], 1: [3], 2: [3, 4], 3: [4]}

or if you want the result in the list then add this line end of above code:

print([(key,value) for key,value in final_dict.items()])

output:

[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]


来源: stackexchange

问:
Pass packages to pyspark running on dataproc from airflow?
We have an Airflow DAG that involves running a pyspark job on Dataproc. We need a jdbc driver during the job, which I'd normally pass to the dataproc submit command:

```<code>gcloud dataproc jobs submit pyspark \
--cluster my-cluster \
--properties spark.jars.packages=mysql:mysql-connector-java:6.0.6 \
--py-files ...
</code>```

But how can I do it with Airflow's DataProcPySparkOperator?

For now we're adding this library to the cluster itself:

```<code>gcloud dataproc clusters create my-cluster \
  --region global \
  --zone europe-west1-d \
  ...
  --properties spark:spark.jars.packages=mysql:mysql-connector-java:6.0.6 \
  ...
</code>```

This seems to be working fine, but it doesn't feel like the right way to do it. Is there another way?

答:
I believe you want to pass dataproc_pyspark_properties to the DataProcPySparkOperator.

See:
https://github.com/apache/incubator-airflow/blob/master/airflow/contrib/operators/dataproc_operator.py

ContentLicense: CC BY-SA 3.0

Body:
We have an Airflow DAG that involves running a pyspark job on Dataproc. We need a jdbc driver during the job, which I'd normally pass to the dataproc submit command:

gcloud dataproc jobs submit pyspark \
--cluster my-cluster \
--properties spark.jars.packages=mysql:mysql-connector-java:6.0.6 \
--py-files ...

But how can I do it with Airflow's DataProcPySparkOperator?

For now we're adding this library to the cluster itself:

gcloud dataproc clusters create my-cluster \
  --region global \
  --zone europe-west1-d \
  ...
  --properties spark:spark.jars.packages=mysql:mysql-connector-java:6.0.6 \
  ...

This seems to be working fine, but it doesn't feel like the right way to do it. Is there another way?


问:
How to override the metaclass constructor in Ruby
I want a piece of code to run before any other static methods run, is it possible to do something in the spirit of the following?

```<code>class MyClass
  def self.initialize
    @stuff = 1
  end
  def self.print_stuff
    puts @stuff
  end
end
</code>```

My Ruby version of interest is 2.3.

答:
There's no such thing as an explicit metaclass initializer. The class itself is "initialized" as it's defined, so it's perfectly valid to do this:

```<code>class MyClass
  # Code here will be executed as the class itself is defined.
  @stuff = 1

  def self.print_stuff
    puts @stuff
  end
end

MyClass.print_stuff
</code>```

Remember that def itself is a form of method call and defining a class in Ruby involves sending a bunch of messages (method calls) around to the proper context objects, such as the class itself as it's being defined.

Body:
I want a piece of code to run before any other static methods run, is it possible to do something in the spirit of the following?

class MyClass
  def self.initialize
    @stuff = 1
  end
  def self.print_stuff
    puts @stuff
  end
end

My Ruby version of interest is 2.3.

Body:
There's no such thing as an explicit metaclass initializer. The class itself is "initialized" as it's defined, so it's perfectly valid to do this:

class MyClass
  # Code here will be executed as the class itself is defined.
  @stuff = 1

  def self.print_stuff
    puts @stuff
  end
end

MyClass.print_stuff

Remember that def itself is a form of method call and defining a class in Ruby involves sending a bunch of messages (method calls) around to the proper context objects, such as the class itself as it's being defined.


答:
Every chunk of code in Ruby is an expression. Even a class definition is a series of expressions: method definitions are expressions that have the side-effect of adding the method to the class.

This is how meta-programming methods work. attr_reader is a private method call where the implicit self is the class. So, long story short, you aren't restricted inside a class body, you can put whatever code you want to run in the context of the class:

```<code>class MyClass
  @stuff = 1

  def self.print_stuff
    puts @stuff
  end
end
</code>```

Title: How to override the metaclass constructor in Ruby

Body:
Every chunk of code in Ruby is an expression. Even a class definition is a series of expressions: method definitions are expressions that have the side-effect of adding the method to the class.

This is how meta-programming methods work. attr_reader is a private method call where the implicit self is the class. So, long story short, you aren't restricted inside a class body, you can put whatever code you want to run in the context of the class:

class MyClass
  @stuff = 1

  def self.print_stuff
    puts @stuff
  end
end


问:
Haskell function that returns a sorted list of points depending on how close they are to a certain point
I have the following three functions. The function "distance" calculates the distance between two points. The function "calculatesDistances" takes a point (x1, y1) and a list of points [(x2, y2)] and uses the "distance" function to calculate the distance between (x1, y1) and every (x2, y2) in the list [(x2, y2)]. It returns a sorted list of points depending on their distance to (x1, y1). The function "closestDistances" returns the n closest points to (x1, y1) and it uses the sorted list from the function "calculatesDistances".

I think my algorithm is correct but as you can see my code for "calculatesDistances" is missing because I have no idea how to write this in Haskell. I am a beginner and I'm really struggling with Haskell syntax. Any help will be appreciated.

```<code>distance :: (Floating a, Ord a) => (a,a) -> (a,a)-> a
    distance (x1 , y1) (x2 , y2) = sqrt (x'*x' + y'*y')
        where
          x' = x1 - x2
          y' = y1 - y2

    Example outputs:
    *Main> distance (0,0) (1,0)
    1.0
    *Main> distance (0,0) (2,0)
    2.0
    *Main> distance (0,0) (3,0)
    3.0

    calculatesDistances :: (Floating a, Ord a) => (a,a) -> [(a,a)] -> [(a,a)]
    Psesudocode:
    Apply function distance to (x1 , y1) and every (x2 , y2) in [(x2 , y2)] and get a distance for every input
    Return the list [(x2 , y2)] but sorted in ascending order depending on the distance

    Expected output:
    *Main> calculatesDistances (0,0) [(3,0), (2,0),(-3,0), (1,0)]
     [(1,0),(2,0),(3,0),(-3,0)]

    closestDistances :: (Floating a, Ord a) => Int -> (a,a) -> [(a,a)] -> [(a,a)]
    closestDistances n (x1, y1) [(x2, y2)] = take n (calculatesDistances (x1, y1) [(x2, y2)])

    Expected output:

    *Main> closestDistances 3 (0,0) [(1,0),(2,0),(3,0),(-3,0)]
     [(1,0),(2,0),(3,0)]

    *Main> closestDistances 2 (0,0) [(1,0),(2,0),(3,0),(-3,0)]
     [(1,0),(2,0)]
</code>```

答:
You can use sortOn, which has type

```<code>sortOn :: Ord b => (a -> b) -> [a] -> [a]
</code>```

and which sorts the as by comparing the output of the a -> b function. For example,

```<code>Data.List> sortOn (distance (0,0)) [(3,0), (1,1), (0,1)]
[(0.0,1.0),(1.0,1.0),(3.0,0.0)]
</code>```

You might also consider writing a squaredDistance function which omits the sqrt for efficiency, since sqrt is monotonic and hence does not affect sort order.

Body:
I have the following three functions. The function "distance" calculates the distance between two points. The function "calculatesDistances" takes a point (x1, y1) and a list of points [(x2, y2)] and uses the "distance" function to calculate the distance between (x1, y1) and every (x2, y2) in the list [(x2, y2)]. It returns a sorted list of points depending on their distance to (x1, y1). The function "closestDistances" returns the n closest points to (x1, y1) and it uses the sorted list from the function "calculatesDistances".

I think my algorithm is correct but as you can see my code for "calculatesDistances" is missing because I have no idea how to write this in Haskell. I am a beginner and I'm really struggling with Haskell syntax. Any help will be appreciated.

distance :: (Floating a, Ord a) => (a,a) -> (a,a)-> a
    distance (x1 , y1) (x2 , y2) = sqrt (x'*x' + y'*y')
        where
          x' = x1 - x2
          y' = y1 - y2

    Example outputs:
    *Main> distance (0,0) (1,0)
    1.0
    *Main> distance (0,0) (2,0)
    2.0
    *Main> distance (0,0) (3,0)
    3.0

    calculatesDistances :: (Floating a, Ord a) => (a,a) -> [(a,a)] -> [(a,a)]
    Psesudocode:
    Apply function distance to (x1 , y1) and every (x2 , y2) in [(x2 , y2)] and get a distance for every input
    Return the list [(x2 , y2)] but sorted in ascending order depending on the distance

    Expected output:
    *Main> calculatesDistances (0,0) [(3,0), (2,0),(-3,0), (1,0)]
     [(1,0),(2,0),(3,0),(-3,0)]

    closestDistances :: (Floating a, Ord a) => Int -> (a,a) -> [(a,a)] -> [(a,a)]
    closestDistances n (x1, y1) [(x2, y2)] = take n (calculatesDistances (x1, y1) [(x2, y2)])

    Expected output:

    *Main> closestDistances 3 (0,0) [(1,0),(2,0),(3,0),(-3,0)]
     [(1,0),(2,0),(3,0)]

    *Main> closestDistances 2 (0,0) [(1,0),(2,0),(3,0),(-3,0)]
     [(1,0),(2,0)]

Body:
You can use sortOn, which has type

sortOn :: Ord b => (a -> b) -> [a] -> [a]

and which sorts the as by comparing the output of the a -> b function. For example,

Data.List> sortOn (distance (0,0)) [(3,0), (1,1), (0,1)]
[(0.0,1.0),(1.0,1.0),(3.0,0.0)]

You might also consider writing a squaredDistance function which omits the sqrt for efficiency, since sqrt is monotonic and hence does not affect sort order.


问:
Pointing multiple projects' log sinks to one bucket
I have a few GCP projects with log sinks to different storage buckets.  I'd like to combine them into a single bucket.  But the stackdriver export doesn't add any distinguishing information to the object names it creates; they all look like cloudaudit.googleapis.com/activity/2017/11/14/00:00:00_00:59:59_S0.json

What will happen if I start pushing them all to a single bucket?  Will the different project sinks overwrite each other's objects?  Is there any way to distinguish which project created the logs just from the object?

If not, I guess I should switch to pubsub sinks, and then write some code that produces objects with more desirable names.  Are there any established patterns or examples for doing this?

Update: I filed https://issuetracker.google.com/issues/69371200 for this issue.

答:
If you have an organization or folder which includes all the projects that you want to collect logs from, then you can create a sink that collects from all projects in that org/folder.

Unfortunatlely, you cannot do this from the Cloud Console. Instead you must use gcloud with the --organization or --folder option or the API.


问:
how to log scroll events to console with javascript
I want to output to the console the x and y changes of any scroll event on the window - just to test something.

How do you do this with plain JS?

答:
I usually use something like this:</p>

```<code>window.addEventListener('scroll', console.log);
</code>```

Body:
I usually use something like this:

window.addEventListener('scroll', console.log);


问:
Prevent hyperlinks in HTML emails (namely Outlook)
We've got some HTML emails that get sent out that show email addresses our service has blocked. When viewing the email in Outlook (and presumably in other clients as well) these plain-text email addresses get turned into clickable links that would compose a new message to this address when clicked.

Is there a way to prevent this from happening?  Perhaps a meta tag with a flag that would prevent Outlook from converting these into clickable links?

答: Most email clients strip out META tags, Javascript, and other types of code not necessary for email. Outlook is going to do what it wants with your email, so what you may want to do is wrap the addresses with your own anchor tag and use a blank HREF. Then, style the link to look like the rest of your text. </p>

ContentLicense: CC BY-SA 2.5


问:
Django with multiple ManyToManyField form
This is my first Django app to prove to myself (and my company) that we should adopt Django, but so far it has proven tricky.

I'm trying to create an app that shows all the employees of a company and for each, all the employee's many skills organized in categories.
Here's my model:

```<code>from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=64)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Skill(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Employee(models.Model):
    login = models.CharField(max_length=16)
    fullname = models.CharField(max_length=64)
    skills = models.ManyToManyField(Skill, through='EmployeeSkill')

    def __str__(self):              # __unicode__ on Python 2
        return self.fullname

class EmployeeSkill(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    skill    = models.ForeignKey(Skill,    on_delete=models.CASCADE)
    LEVELS = (
        ('0', 'None'),
        ('1', 'Very Basic Knowledge (hours)'),
        ('2', 'Basic Knowledge (days)'),
        ('3', 'Good Understanding Knowledge (weeks)'),
        ('4', 'Excellent Knowledge (months)'),
        ('5', 'Expert Knowledge (years)'),
    )
    level = models.CharField(max_length=1, choices=LEVELS)
    desired_level = models.CharField(max_length=1, choices=LEVELS)

    def __str__(self):
        return "{} level of knowledge for {} is {} / desired is {}".format(self.employee.fullname, self.skill.name, self.level, self.desired_level)
</code>```

I'm able to create an Employee, a Skill and an EmployeeSkill, and even show all the employee skills for a given employee but where I'm struggling is how I should go about creating a form that shows all possible EmployeeSkills for an employee and allow that employee to change the level (and desired_level) associated with each EmployeeSkill.

Please help!

答:
You can generate a select for the options on the ManyToManyFIeld and render each option on the select and add the values using AJAX.

```<code><select name="material" id="id_material" required>
    <option value="0" disabled selected>Selecciona el material</option>
     {% for material in materiales %}
       <option value="{{material.id}}">{{material.descripcion}} ({{material.id_tipo_material.unidad}}) -  Total = {{material.cantidad}}</option>
     {% endfor %}
</select>
</code>```

And the AJAX request:

```<code>function agrega_material(){

        var url = '{% url "paquetes:agrega_material_paquete" %}';

        var paquete = $('#id_cantidad').data('paquete');

        var material = $('#id_material').val();

        var cantidad = $('#id_cantidad').val();

        $.post(url,
        {
            paquete:paquete,
            material:material,
            cantidad:cantidad
        })
        .done(function( data ) {
            if(data['status'] == 'ko'){
                Materialize.toast('Cantidad es más grande que el material restante.', 4000)
            }else{
                $('#forma_material_paquete').html(data);
                $('select').material_select();
                Materialize.toast('El material ha sido agregado.', 4000)
            }
        });

        return false;
};
</code>```

You are gonna submit the form using AJAX, passing the data to a view of django and adding the element or making a modification on your views, then you can pop a notification if the request status was ok. Example of view:

```<code>def agrega_material_paquete(request):
if request.method == 'POST':
    #Procesar datos
    id_paquete = int(request.POST.get('paquete')) //Here you receive the data of the AJAX request.
    paquete = get_object_or_404(Paquete, id=id_paquete )
    id_material = int(request.POST.get('material'))
    material = get_object_or_404(Material, id=id_material)
    cantidad_material = int(material.cantidad)
    cantidad = int(request.POST.get('cantidad'))

    if cantidad_material >= cantidad:
        Material_por_paquete.objects.create(paquete=paquete,material=material,cantidad=cantidad)
        #Mostrar vista de nuevo
        form = FormaMateriales()
        materiales = Material.objects.filter(activo=True)
        id_paquete = request.POST.get('paquete')
        materiales_paquete = Material_por_paquete.materiales_paquete(id_paquete)
        html = render_to_string('paquetes/select_materiales.html', {'form': form,'materiales':materiales,'materiales_paquete':materiales_paquete,'paquete':paquete})
        return HttpResponse(html)
    else:
        return JsonResponse({'status':'ko'})
else:
    return JsonResponse({'status':'ko'})
</code>```

Body:
This is my first Django app to prove to myself (and my company) that we should adopt Django, but so far it has proven tricky.

I'm trying to create an app that shows all the employees of a company and for each, all the employee's many skills organized in categories.
Here's my model:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=64)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Skill(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Employee(models.Model):
    login = models.CharField(max_length=16)
    fullname = models.CharField(max_length=64)
    skills = models.ManyToManyField(Skill, through='EmployeeSkill')

    def __str__(self):              # __unicode__ on Python 2
        return self.fullname

class EmployeeSkill(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    skill    = models.ForeignKey(Skill,    on_delete=models.CASCADE)
    LEVELS = (
        ('0', 'None'),
        ('1', 'Very Basic Knowledge (hours)'),
        ('2', 'Basic Knowledge (days)'),
        ('3', 'Good Understanding Knowledge (weeks)'),
        ('4', 'Excellent Knowledge (months)'),
        ('5', 'Expert Knowledge (years)'),
    )
    level = models.CharField(max_length=1, choices=LEVELS)
    desired_level = models.CharField(max_length=1, choices=LEVELS)

    def __str__(self):
        return "{} level of knowledge for {} is {} / desired is {}".format(self.employee.fullname, self.skill.name, self.level, self.desired_level)

I'm able to create an Employee, a Skill and an EmployeeSkill, and even show all the employee skills for a given employee but where I'm struggling is how I should go about creating a form that shows all possible EmployeeSkills for an employee and allow that employee to change the level (and desired_level) associated with each EmployeeSkill.

Please help!

Body:
You can generate a select for the options on the ManyToManyFIeld and render each option on the select and add the values using AJAX.

<select name="material" id="id_material" required>
    <option value="0" disabled selected>Selecciona el material</option>
     {% for material in materiales %}
       <option value="{{material.id}}">{{material.descripcion}} ({{material.id_tipo_material.unidad}}) -  Total = {{material.cantidad}}</option>
     {% endfor %}
</select>

And the AJAX request:

function agrega_material(){

        var url = '{% url "paquetes:agrega_material_paquete" %}';

        var paquete = $('#id_cantidad').data('paquete');

        var material = $('#id_material').val();

        var cantidad = $('#id_cantidad').val();

        $.post(url,
        {
            paquete:paquete,
            material:material,
            cantidad:cantidad
        })
        .done(function( data ) {
            if(data['status'] == 'ko'){
                Materialize.toast('Cantidad es más grande que el material restante.', 4000)
            }else{
                $('#forma_material_paquete').html(data);
                $('select').material_select();
                Materialize.toast('El material ha sido agregado.', 4000)
            }
        });

        return false;
};

You are gonna submit the form using AJAX, passing the data to a view of django and adding the element or making a modification on your views, then you can pop a notification if the request status was ok. Example of view:

def agrega_material_paquete(request):
if request.method == 'POST':
    #Procesar datos
    id_paquete = int(request.POST.get('paquete')) //Here you receive the data of the AJAX request.
    paquete = get_object_or_404(Paquete, id=id_paquete )
    id_material = int(request.POST.get('material'))
    material = get_object_or_404(Material, id=id_material)
    cantidad_material = int(material.cantidad)
    cantidad = int(request.POST.get('cantidad'))

    if cantidad_material >= cantidad:
        Material_por_paquete.objects.create(paquete=paquete,material=material,cantidad=cantidad)
        #Mostrar vista de nuevo
        form = FormaMateriales()
        materiales = Material.objects.filter(activo=True)
        id_paquete = request.POST.get('paquete')
        materiales_paquete = Material_por_paquete.materiales_paquete(id_paquete)
        html = render_to_string('paquetes/select_materiales.html', {'form': form,'materiales':materiales,'materiales_paquete':materiales_paquete,'paquete':paquete})
        return HttpResponse(html)
    else:
        return JsonResponse({'status':'ko'})
else:
    return JsonResponse({'status':'ko'})


问:
Remove already asscoiated values from choice list in sonata admin
I have an one to one relation in my sonata admin bundle.

```<code>Person <-> Player.
</code>```

If i go to my Person admin i can choose the player from the choice list.

If i go to another Person object the player (which is now already assigned) is shown again ... if i choose it, there occurs an error ...

The error is

Failed to update object: AppBundle\Entity\Person

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '18' for key 'UNIQ_9A5FDF45F6B75B26'

Can i change the behaviour that already assigned values do not appear in other objects?

I cant find a option for doing this in sonata admin

答:
You can generate a custom choice list for every Person.

Add method to PlayerRepository:

```<code>class PlayerRepository extends EntityRepository
{
    public function getNotAssociatedPlayers($person)
    {
        $qb = $this->createQueryBuilder('p')
                   ->leftJoin('p.person', 'prsn')
                   ->where('prsn.id is null');
        if($person !== null)
        {
            $qb->orWhere('prsn.id = :person')
               ->setParameter('person', $person);
        }

        return $qb->getQuery()
                  ->getResult();
    }
}
</code>```

And use it in PersonAdmin:

```<code>protected function configureFormFields(FormMapper $formMapper)
{
    $person = ($this->getSubject()->getPlayer() !== null)
              ? $this->getSubject()->getId()
              : null;
    $em = $this->getConfigurationPool()->getContainer()->get('doctrine.orm.entity_manager');
    $choices = $em->getRepository('YourBundle:Player')->getNotAssociatedPlayers($person);

    $formMapper
        ->add('player', null, array(
            'choices' => $choices,
        ));
</code>```

Please, let me know if something went wrong with that.

EDIT:

Documented solution is a query_builder option for the field:

```<code>$formMapper
    ->add('player', null, array(
        'query_builder' => function(EntityRepository $er)
        {
            $qb = $er->createQueryBuilder('p')
                     ->leftJoin('p.person', 'prsn')
                     ->where('prsn.id is null');
            if($this->getSubject()->getPlayer() !== null)
            {
                $qb->orWhere('prsn.id = :person')
                   ->setParameter('person', $this->getSubject()->getId());
            }
            return $qb;
        }
    ));
</code>```

Body:
I have an one to one relation in my sonata admin bundle.

Person <-> Player.

If i go to my Person admin i can choose the player from the choice list.

If i go to another Person object the player (which is now already assigned) is shown again ... if i choose it, there occurs an error ...

The error is

Failed to update object: AppBundle\Entity\Person

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '18' for key 'UNIQ_9A5FDF45F6B75B26'

Can i change the behaviour that already assigned values do not appear in other objects?

I cant find a option for doing this in sonata admin

Body:
You can generate a custom choice list for every Person.

Add method to PlayerRepository:

class PlayerRepository extends EntityRepository
{
    public function getNotAssociatedPlayers($person)
    {
        $qb = $this->createQueryBuilder('p')
                   ->leftJoin('p.person', 'prsn')
                   ->where('prsn.id is null');
        if($person !== null)
        {
            $qb->orWhere('prsn.id = :person')
               ->setParameter('person', $person);
        }

        return $qb->getQuery()
                  ->getResult();
    }
}

And use it in PersonAdmin:

protected function configureFormFields(FormMapper $formMapper)
{
    $person = ($this->getSubject()->getPlayer() !== null)
              ? $this->getSubject()->getId()
              : null;
    $em = $this->getConfigurationPool()->getContainer()->get('doctrine.orm.entity_manager');
    $choices = $em->getRepository('YourBundle:Player')->getNotAssociatedPlayers($person);

    $formMapper
        ->add('player', null, array(
            'choices' => $choices,
        ));

Please, let me know if something went wrong with that.

EDIT:

Documented solution is a query_builder option for the field:

$formMapper
    ->add('player', null, array(
        'query_builder' => function(EntityRepository $er)
        {
            $qb = $er->createQueryBuilder('p')
                     ->leftJoin('p.person', 'prsn')
                     ->where('prsn.id is null');
            if($this->getSubject()->getPlayer() !== null)
            {
                $qb->orWhere('prsn.id = :person')
                   ->setParameter('person', $this->getSubject()->getId());
            }
            return $qb;
        }
    ));


问:
Exception- Writing exception to parcel
This is a small assignment to insert simple text data to sqlite database. I have used SQLiteOpenHelper class for this and used given code.
I've found some similiar questions here but not the exact same. Please help me out. Here is the exception-

```<code>11-14 21:59:17.786 5746-5763/? E/DatabaseUtils: Writing exception to parcel
                                            java.lang.SecurityException: Neither user 10169 nor current process has android.permission.READ_PROFILE.
                                                at android.app.ContextImpl.enforce(ContextImpl.java:1921)
                                                at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1950)
                                                at android.content.ContextWrapper.enforceCallingOrSelfPermission(ContextWrapper.java:600)
                                                at com.android.providers.contacts.ProfileProvider.enforceReadPermission(ProfileProvider.java:54)
                                                at com.android.providers.contacts.ProfileProvider.query(ProfileProvider.java:84)
                                                at com.android.providers.contacts.ContactsProvider2.query(ContactsProvider2.java:5066)
                                                at android.content.ContentProvider$Transport.query(ContentProvider.java:214)
                                                at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
                                                at android.os.Binder.execTransact(Binder.java:446)
</code>```

I've used following permissions in my AndroidManifest.XML file:

```<code><uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

this is my DBHelper class-

```<code>public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "CANDIDATES";
public static final String TABLE_NAME = "CANDIDATES_TABLE";
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String QUAL = "QUALIFICATION";
public static final String SALARY = "SALARY";
public static final String ADD = "ADDRESS";
public static final String DES = "DESCRIPTION";
Context context;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table "+ TABLE_NAME +" ("+NAME+" TEXT,"+AGE+" INTEGER,"+QUAL+" TEXT,"+SALARY+" INTEGER,"+ADD+" TEXT,"+DES+" TEXT )");

}

public boolean insertData(String name,int age,String qual,int salary, String add, String des){
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put(NAME,name);
    contentValues.put(AGE,age);
    contentValues.put(QUAL,qual);
    contentValues.put(SALARY,salary);
    contentValues.put(ADD,add);
    contentValues.put(DES,des);
    long result=db.insert(TABLE_NAME,null,contentValues);
    Log.v("check",name+age+""+qual+salary+""+add+des);
    if(result==-1){
        return false;
    }
    else return true;
}

public Cursor getData(){
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor cursor=db.rawQuery("Select * from"+TABLE_NAME,null);
    return cursor;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}
</code>```

}

答:
You need to ask runtime permissions. Adding manifest is not enough for newer versions.</p>

```<code>if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.READ_CONTACTS)
    != PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.READ_CONTACTS)) {

    // Show an explanation to the user *asynchronously* -- don't block
    // this thread waiting for the user's response! After the user
    // sees the explanation, try again to request the permission.

} else {

    // No explanation needed, we can request the permission.

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_CONTACTS},
            MY_PERMISSIONS_REQUEST_READ_CONTACTS);

    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
    // app-defined int constant. The callback method gets the
    // result of the request.
}
}
</code>```

Title: Exception- Writing exception to parcel

Body:
This is a small assignment to insert simple text data to sqlite database. I have used SQLiteOpenHelper class for this and used given code.
I've found some similiar questions here but not the exact same. Please help me out. Here is the exception-

11-14 21:59:17.786 5746-5763/? E/DatabaseUtils: Writing exception to parcel
                                            java.lang.SecurityException: Neither user 10169 nor current process has android.permission.READ_PROFILE.
                                                at android.app.ContextImpl.enforce(ContextImpl.java:1921)
                                                at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1950)
                                                at android.content.ContextWrapper.enforceCallingOrSelfPermission(ContextWrapper.java:600)
                                                at com.android.providers.contacts.ProfileProvider.enforceReadPermission(ProfileProvider.java:54)
                                                at com.android.providers.contacts.ProfileProvider.query(ProfileProvider.java:84)
                                                at com.android.providers.contacts.ContactsProvider2.query(ContactsProvider2.java:5066)
                                                at android.content.ContentProvider$Transport.query(ContentProvider.java:214)
                                                at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
                                                at android.os.Binder.execTransact(Binder.java:446)

I've used following permissions in my AndroidManifest.XML file:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

this is my DBHelper class-

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "CANDIDATES";
public static final String TABLE_NAME = "CANDIDATES_TABLE";
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String QUAL = "QUALIFICATION";
public static final String SALARY = "SALARY";
public static final String ADD = "ADDRESS";
public static final String DES = "DESCRIPTION";
Context context;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table "+ TABLE_NAME +" ("+NAME+" TEXT,"+AGE+" INTEGER,"+QUAL+" TEXT,"+SALARY+" INTEGER,"+ADD+" TEXT,"+DES+" TEXT )");

}

public boolean insertData(String name,int age,String qual,int salary, String add, String des){
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put(NAME,name);
    contentValues.put(AGE,age);
    contentValues.put(QUAL,qual);
    contentValues.put(SALARY,salary);
    contentValues.put(ADD,add);
    contentValues.put(DES,des);
    long result=db.insert(TABLE_NAME,null,contentValues);
    Log.v("check",name+age+""+qual+salary+""+add+des);
    if(result==-1){
        return false;
    }
    else return true;
}

public Cursor getData(){
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor cursor=db.rawQuery("Select * from"+TABLE_NAME,null);
    return cursor;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}

}

Body:
You need to ask runtime permissions. Adding manifest is not enough for newer versions.

if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.READ_CONTACTS)
    != PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.READ_CONTACTS)) {

    // Show an explanation to the user *asynchronously* -- don't block
    // this thread waiting for the user's response! After the user
    // sees the explanation, try again to request the permission.

} else {

    // No explanation needed, we can request the permission.

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_CONTACTS},
            MY_PERMISSIONS_REQUEST_READ_CONTACTS);

    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
    // app-defined int constant. The callback method gets the
    // result of the request.
}
}


问:
Format excel column to decimal doing export from c#
Hi I am exporting database to excel with below method as

```<code>        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
        Response.ContentType = "application/vnd.ms-excel";
        EnableViewState = false;
        Response.Write("<style> TABLE { border:dotted 1px #999; } TH { border:dotted 1px #D5D5D5; text-align:center } TD { border:dotted 1px #D5D5D5; } </style>");
        Response.Write("<table>");
        Response.Write("<tr>");
        Response.Write("<th>Actual Estimated Price</th>");
        Response.Write("<th>Aprroved Estimated Price </th>");
        Response.Write("<th>Actual Price</th>");
        Response.Write("<th>Aprroved Actual Price </th>");
        Response.Write("<th>TransactionID </th>");
        Response.Write("<th>Created On</th>");
        Response.Write("</tr>");
        foreach (DataRow dr in dt.Rows)
        {
            Response.Write("<tr>");
            Response.Write("<td>");
            Response.Write(String.Format("{0:0.0#}", dr["EstimatedPriceTotal"].ToString()));
            Response.Write("</td>");
            Response.Write("<td>");
            Response.Write(String.Format("{0:0.0#}", dr["ApprovedEstimatedPriceTotal"].ToString()));
            Response.Write("</td>");
            Response.Write("<td>");
            Response.Write(String.Format("{0:0.0#}", dr["ActualPriceTotal"].ToString()));
            Response.Write("</td>");
            Response.Write("<td>");
            Response.Write(String.Format("{0:0.0#}", dr["ApprovedActualPriceTotal"].ToString()));
            Response.Write("</td>");
            Response.Write("<td>");
            Response.Write(dr["TransactionID"].ToString());
            Response.Write("</td>");
            Response.Write("<td>");
            Response.Write(Convert.ToDateTime(dr["CreatedOn"].ToString()));
            Response.Write("</td>");
            Response.Write("</tr>");
        }
        Response.Write("</table>");
        Response.End();
</code>```

but I am not able to export  Actual Estimated Price,  Aprroved  Estimated Price in excel as decimal format

The value is coming as 5 instead of showing 5.00

How can I format some column of excel to decimal format from c# side

Update

How can I merge column header merge in EPPPlus

I want both header name as

```<code>CustomerName
Mitesh Jain
</code>```

答:
Here you go, one complete method. Just send a DataTable and a file name and this does the rest. This snippet will also make the header row gray with bold text and will auto fit the columns.</p>

```<code>using OfficeOpenXml;
using OfficeOpenXml.Style;

public void ExportToExcel(DataTable dt, string FileName)
{
    //create a new byte array
    byte[] bin;

    //create a new excel document
    using (ExcelPackage excelPackage = new ExcelPackage())
    {
        //create a new worksheet
        ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add(FileName);

        //add the contents of the datatable to the excel file
        ws.Cells["A1"].LoadFromDataTable(dt, true);

        //auto fix the columns
        ws.Cells[ws.Dimension.Address].AutoFitColumns();

        //loop all the columns
        for (int col = 1; col <= ws.Dimension.End.Column; col++)
        {
            //make all columns just a bit wider, it would sometimes not fit
            ws.Column(col).Width = ws.Column(col).Width + 1;

            var cell = ws.Cells[1, col];

            //make the text bold
            cell.Style.Font.Bold = true;

            //make the background of the cell gray
            var fill = cell.Style.Fill;
            fill.PatternType = ExcelFillStyle.Solid;
            fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));

            //make the header text upper case
            cell.Value = ((string)cell.Value).ToUpper();
        }

        //convert the excel package to a byte array
        bin = excelPackage.GetAsByteArray();
    }

    //clear the buffer stream
    Response.ClearHeaders();
    Response.Clear();
    Response.Buffer = true;

    //set the correct contenttype
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    //set the correct length of the data being send
    Response.AddHeader("content-length", bin.Length.ToString());

    //set the filename for the excel package
    Response.AddHeader("content-disposition", "attachment; filename=\"" + FileName + ".xlsx\"");

    //send the byte array to the browser
    Response.OutputStream.Write(bin, 0, bin.Length);

    //cleanup
    Response.Flush();
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}
</code>```

Body:
Hi I am exporting database to excel with below method as

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
        Response.ContentType = "application/vnd.ms-excel";
        EnableViewState = false;
        Response.Write("");
        Response.Write("
");
        Response.Write("
");
        Response.Write("Actual Estimated Price	");
        Response.Write("Aprroved Estimated Price 	");
        Response.Write("Actual Price	");
        Response.Write("Aprroved Actual Price 	");
        Response.Write("TransactionID 	");
        Response.Write("Created On	");
        Response.Write("
");
        foreach (DataRow dr in dt.Rows)
        {
            Response.Write("
");
            Response.Write("");
            Response.Write(String.Format("{0:0.0#}", dr["EstimatedPriceTotal"].ToString()));
            Response.Write("	");
            Response.Write("");
            Response.Write(String.Format("{0:0.0#}", dr["ApprovedEstimatedPriceTotal"].ToString()));
            Response.Write("	");
            Response.Write("");
            Response.Write(String.Format("{0:0.0#}", dr["ActualPriceTotal"].ToString()));
            Response.Write("	");
            Response.Write("");
            Response.Write(String.Format("{0:0.0#}", dr["ApprovedActualPriceTotal"].ToString()));
            Response.Write("	");
            Response.Write("");
            Response.Write(dr["TransactionID"].ToString());
            Response.Write("	");
            Response.Write("");
            Response.Write(Convert.ToDateTime(dr["CreatedOn"].ToString()));
            Response.Write("	");
            Response.Write("
");
        }
        Response.Write("
");
        Response.End();

but I am not able to export  Actual Estimated Price,  Aprroved  Estimated Price in excel as decimal format

The value is coming as 5 instead of showing 5.00

How can I format some column of excel to decimal format from c# side

Update

How can I merge column header merge in EPPPlus

I want both header name as

CustomerName
Mitesh Jain

Body:
Here you go, one complete method. Just send a DataTable and a file name and this does the rest. This snippet will also make the header row gray with bold text and will auto fit the columns.

using OfficeOpenXml;
using OfficeOpenXml.Style;

public void ExportToExcel(DataTable dt, string FileName)
{
    //create a new byte array
    byte[] bin;

    //create a new excel document
    using (ExcelPackage excelPackage = new ExcelPackage())
    {
        //create a new worksheet
        ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add(FileName);

        //add the contents of the datatable to the excel file
        ws.Cells["A1"].LoadFromDataTable(dt, true);

        //auto fix the columns
        ws.Cells[ws.Dimension.Address].AutoFitColumns();

        //loop all the columns
        for (int col = 1; col <= ws.Dimension.End.Column; col++)
        {
            //make all columns just a bit wider, it would sometimes not fit
            ws.Column(col).Width = ws.Column(col).Width + 1;

            var cell = ws.Cells[1, col];

            //make the text bold
            cell.Style.Font.Bold = true;

            //make the background of the cell gray
            var fill = cell.Style.Fill;
            fill.PatternType = ExcelFillStyle.Solid;
            fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));

            //make the header text upper case
            cell.Value = ((string)cell.Value).ToUpper();
        }

        //convert the excel package to a byte array
        bin = excelPackage.GetAsByteArray();
    }

    //clear the buffer stream
    Response.ClearHeaders();
    Response.Clear();
    Response.Buffer = true;

    //set the correct contenttype
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    //set the correct length of the data being send
    Response.AddHeader("content-length", bin.Length.ToString());

    //set the filename for the excel package
    Response.AddHeader("content-disposition", "attachment; filename=\"" + FileName + ".xlsx\"");

    //send the byte array to the browser
    Response.OutputStream.Write(bin, 0, bin.Length);

    //cleanup
    Response.Flush();
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

ContentLicense: CC BY-SA 4.0


问:
jquery click on div in Chrome Console
Maybe one of you can help me.
How do I click on a div, by using the Chrome Console?

I want to be able to click the div on this site any ideas.

example: https://gleam.io/ZyYPU/100-subscriber-giveaway-100-usd

Tried this without any luck.

```<code>$('.entry-method #em2690957').click();
</code>```

答:
Also you can do it via angular:</p>

```<code>angular.element('#em2690957 a').triggerHandler('click');
</code>```

Title: jquery click on div in Chrome Console

Body:
Maybe one of you can help me.
How do I click on a div, by using the Chrome Console?

I want to be able to click the div on this site any ideas.

example: https://gleam.io/ZyYPU/100-subscriber-giveaway-100-usd

Tried this without any luck.

$('.entry-method #em2690957').click();

Body:
Also you can do it via angular:

angular.element('#em2690957 a').triggerHandler('click');


问:
Why does my Spring Boot App always shutdown immediately after starting?
This is my first Spring Boot code. Unfortunately, it always shuts down. I was expecting it to run continuously so that my web client can get some data from the browser.

```<code>package hello;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

[@localhost initial]$ java -jar build/libs/gs-spring-boot-0.1.0.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 09:20:24.805  INFO 14650 --- [           main] hello.SampleController                   : Starting SampleController on localhost.localdomain with PID 14650 (/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boot-0.1.0.jar started by xxx)
2014-03-13 09:20:25.002  INFO 14650 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:28.833  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Registering beans for JMX exposure on startup
2014-03-13 09:20:30.148  INFO 14650 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2014-03-13 09:20:30.154  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint]
2014-03-13 09:20:30.316  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint]
2014-03-13 09:20:30.335  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint]
2014-03-13 09:20:30.351  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint]
2014-03-13 09:20:30.376  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint]
2014-03-13 09:20:30.400  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint]
2014-03-13 09:20:30.413  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint]
2014-03-13 09:20:30.428  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint]
2014-03-13 09:20:30.450  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'autoConfigurationAuditEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationAuditEndpoint]
2014-03-13 09:20:30.465  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'shutdownEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=shutdownEndpoint]
2014-03-13 09:20:30.548  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint]
2014-03-13 09:20:30.589  INFO 14650 --- [           main] hello.SampleController                   : Started SampleController in 7.396 seconds (JVM running for 9.569)
2014-03-13 09:20:30.608  INFO 14650 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:30.610  INFO 14650 --- [       Thread-2] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2014-03-13 09:20:30.624  INFO 14650 --- [       Thread-2] o.s.b.a.e.jmx.EndpointMBeanExporter      : Unregistering JMX-exposed beans on shutdown
</code>```

Please advise.

Thanks

P.S. build.gradle is the fault.

```<code>dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        **exclude module: "spring-boot-starter-tomcat"**
    }
</code>```

Once I took off the above line in bold, everything works. My application context now is correct. Thanks Dave

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 13:58:08.965  INFO 7307 --- [           main] hello.Application                        : Starting
 Application on  with PID 7307 (/ladev/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boo
t-0.1.0.jar started by xxx)
2014-03-13 13:58:09.021  INFO 7307 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshi
ng org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45490eb5: startup
 date [Thu Mar 13 13:58:09 MDT 2014]; root of context hierarchy
2014-03-13 13:58:09.653  INFO 7307 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overridi
ng bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=fal
se; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanNam
e=org.springframework.boot.actuate.autoconfigure.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration;
 factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class
 path resource [org/springframework/boot/actuate/autoconfigure/ErrorMvcAutoConfiguration$WhitelabelErrorView
Configuration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3;
 dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconf
igure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; in
itMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/au
toconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
</code>```

答:
Maybe it does not fit to your code but i found out if you have a code snippet like this:

```<code>@SpringBootApplication
public class SpringBootApacheKafkaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApacheKafkaApplication.class,args).close();
    }
}
</code>```

then just remove the close() method. That's fixed my problem! Maybe I can help someone with that

Body:
This is my first Spring Boot code. Unfortunately, it always shuts down. I was expecting it to run continuously so that my web client can get some data from the browser.

package hello;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

[@localhost initial]$ java -jar build/libs/gs-spring-boot-0.1.0.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 09:20:24.805  INFO 14650 --- [           main] hello.SampleController                   : Starting SampleController on localhost.localdomain with PID 14650 (/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boot-0.1.0.jar started by xxx)
2014-03-13 09:20:25.002  INFO 14650 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:28.833  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Registering beans for JMX exposure on startup
2014-03-13 09:20:30.148  INFO 14650 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2014-03-13 09:20:30.154  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint]
2014-03-13 09:20:30.316  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint]
2014-03-13 09:20:30.335  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint]
2014-03-13 09:20:30.351  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint]
2014-03-13 09:20:30.376  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint]
2014-03-13 09:20:30.400  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint]
2014-03-13 09:20:30.413  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint]
2014-03-13 09:20:30.428  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint]
2014-03-13 09:20:30.450  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'autoConfigurationAuditEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationAuditEndpoint]
2014-03-13 09:20:30.465  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'shutdownEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=shutdownEndpoint]
2014-03-13 09:20:30.548  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint]
2014-03-13 09:20:30.589  INFO 14650 --- [           main] hello.SampleController                   : Started SampleController in 7.396 seconds (JVM running for 9.569)
2014-03-13 09:20:30.608  INFO 14650 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:30.610  INFO 14650 --- [       Thread-2] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2014-03-13 09:20:30.624  INFO 14650 --- [       Thread-2] o.s.b.a.e.jmx.EndpointMBeanExporter      : Unregistering JMX-exposed beans on shutdown

Please advise.

Thanks

P.S. build.gradle is the fault.

dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        **exclude module: "spring-boot-starter-tomcat"**
    }

Once I took off the above line in bold, everything works. My application context now is correct. Thanks Dave

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 13:58:08.965  INFO 7307 --- [           main] hello.Application                        : Starting
 Application on  with PID 7307 (/ladev/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boo
t-0.1.0.jar started by xxx)
2014-03-13 13:58:09.021  INFO 7307 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshi
ng org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45490eb5: startup
 date [Thu Mar 13 13:58:09 MDT 2014]; root of context hierarchy
2014-03-13 13:58:09.653  INFO 7307 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overridi
ng bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=fal
se; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanNam
e=org.springframework.boot.actuate.autoconfigure.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration;
 factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class
 path resource [org/springframework/boot/actuate/autoconfigure/ErrorMvcAutoConfiguration$WhitelabelErrorView
Configuration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3;
 dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconf
igure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; in
itMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/au
toconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]

Body:
Maybe it does not fit to your code but i found out if you have a code snippet like this:

@SpringBootApplication
public class SpringBootApacheKafkaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApacheKafkaApplication.class,args).close();
    }
}

then just remove the close() method. That's fixed my problem! Maybe I can help someone with that


问:
How to handle exceptions you want propagated up to the caller?
I'm a Pythonista moving into Java/Scala, and I am wondering how to handle the case where you want an exception to be thrown if it occurs.  Take the following toy example:

```<code>public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

In Python I would want this to throw an error if the file isn't found, and let the calling code handle the exception.  Is it convention just to re-throw the same exception?

答:
You can just do the following...</p>

```<code>public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) throws FileNotFoundException {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I'm a Pythonista moving into Java/Scala, and I am wondering how to handle the case where you want an exception to be thrown if it occurs.  Take the following toy example:

public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In Python I would want this to throw an error if the file isn't found, and let the calling code handle the exception.  Is it convention just to re-throw the same exception?

Body:
You can just do the following...

public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) throws FileNotFoundException {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


答:
You can make your method throw those exceptions :

```<code>public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) throws FileNotFoundException {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (IOException e) {
            //handle the exception you want to handle
            e.printStackTrace();
        }
    }
}
</code>```

Just make sure you declare your method with the throws statement, or your compiler might not like it ;)

You can also go this way (let's call this a semi-exception-handling) :

```<code>public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) throws FileNotFoundException, IOException {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (IOException e) {
            /*Some code to clear some data or to handle the
              exception but still throw an exception higher*/
            throw e;
        }
    }
}
</code>```

Title: How to handle exceptions you want propagated up to the caller?

Body:
You can make your method throw those exceptions :

public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) throws FileNotFoundException {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (IOException e) {
            //handle the exception you want to handle
            e.printStackTrace();
        }
    }
}

Just make sure you declare your method with the throws statement, or your compiler might not like it ;)

You can also go this way (let's call this a semi-exception-handling) :

public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) throws FileNotFoundException, IOException {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (IOException e) {
            /*Some code to clear some data or to handle the
              exception but still throw an exception higher*/
            throw e;
        }
    }
}


问:
Is the "link" element necessary when I want to modify the style of a webpage with CSS?
I was studying this example:

```<code><!DOCTYPE html>
<html>
<head>
<title>Introducing to CSS</title>
<link href="css/example.css" type="text/css"
rel="stylesheet" />
</head>
<body>
<h1>From Garden to Plate</h1>
<p> A <i>potager</i> or kitchen garden...</p>
<h2>What to plant</h2>
<p>Plant are chosen as...</p>
</body>
</html>

body {
font-family: Arial, Verdana, sans-serif;}
h1, h2 {
color: #ee3e80;}
p {
color: #665544;}
</code>```

The result was I couldn't make any change on my webpage.  The CSS rules don't work. I don't know why. My second question is: Is the "link" element necessary when I want to modify the style of a webpage with CSS?

答:
No it's not needed. You can replace the "link" tag by the following:

```<code><style>
body {
    font-family: Arial, Verdana, sans-serif;
}
h1, h2 {
    color: #ee3e80;
}
p {
    color: #665544;
}
</style>
</code>```

But if you want to work with separated html and css files (which can be considered a good practice), then you need the "link" tag

Body:
I was studying this example:

<!DOCTYPE html>

<title>Introducing to CSS</title>
<link href="css/example.css" type="text/css"
rel="stylesheet" />

From Garden to Plate

 A potager or kitchen garden...

What to plant

Plant are chosen as...

body {
font-family: Arial, Verdana, sans-serif;}
h1, h2 {
color: #ee3e80;}
p {
color: #665544;}

The result was I couldn't make any change on my webpage.  The CSS rules don't work. I don't know why. My second question is: Is the "link" element necessary when I want to modify the style of a webpage with CSS?

Body:
No it's not needed. You can replace the "link" tag by the following:

<style>
body {
    font-family: Arial, Verdana, sans-serif;
}
h1, h2 {
    color: #ee3e80;
}
p {
    color: #665544;
}
</style>

But if you want to work with separated html and css files (which can be considered a good practice), then you need the "link" tag


问:
group numbers in an array by step value changes
i have an array like [101, 107, 106, 199, 204, 205, 207, 306, 310, 312, 312, 314, 317, 318, 380, 377, 379, 382, 466, 469, 471, 472, 557, 559, 562, 566, 569...]

In this array, after a few integers, there will be a step change in value.(like between [101,107,106] and [199,204,...])
Or put it in another way, the array is made up of groups of integers, each group with values centered around an unknown mean.
But i won't know how many groups are there in total ,and the number of integers in each is uncertain.

How could i group those integers in each step change into different arrays.

Thanks

答:
I took a stab at doing what I suggested in my comment. I think this will give a good solution to a more generalized problem, but I caution that I haven't thought about all edge cases or considered algorithmic complexity here.

```<code>import numpy as np

# function to initialize clusters
def init_clusters(x, num_elements_per_cluster=3):
    # initialize clusters by splitting into n groups
    x.sort()  # sort the list
    nclusters = len(x) / num_elements_per_cluster
    clusters = {i: {'values': []} for i in range(nclusters)}

    # assign to clusters (helps that list is sorted)
    for i in range(len(x)):
        index = min(i/num_elements_per_cluster, nclusters-1)
        clusters[index]['values'].append(x[i])

    # compute variance
    for index in clusters:
        clusters[index]['var'] = np.var(clusters[index]['values'])

    return clusters

def get_avg_var(clusters):
    total_var = 0.0
    denom = 0.0
    for index in clusters:
        total_var += clusters[index]['var'] * len(clusters[index]['values'])
        denom += len(clusters[index]['values'])
    return total_var / denom  # possible div by 0, but shouldn't happen

def assign_value_to_cluster(clusters, value):
    """
    add value to a cluster such that results in the lowest variance
    """
    new_cluster_vars = []
    indices = []
    for index in clusters:
        new_cluster_vars.append(np.var(clusters[index]['values'] + [value]))
        indices.append(index)

    index_min_new_cluster_var = indices[np.argmin(new_cluster_vars)]
    clusters[index_min_new_cluster_var]['values'].append(value)
    # update the variances
    clusters[index_min_new_cluster_var]['var'] = new_cluster_vars[index_min_new_cluster_var]

def purify(clusters):
    curr_var = get_avg_var(clusters)
    prev_var = curr_var*10
    max_iter = 1000
    iter_count = 0
    while(curr_var < prev_var):
        if iter_count > max_iter:
            break

        prev_var = curr_var

        # start with the cluster with the highest variance
        sorted_vars = sorted(
            [{'index': i, 'var': clusters[i]['var']} for i in clusters],
            key=lambda x: x['var'],
            reverse=True
        )
        highest_var_index = sorted_vars[0]['index']

        vals = clusters[highest_var_index]['values']
        if len(vals) > 2:
            # find the element that when removed will minimize the variance of this cluster
            dropout_variance = [np.var([vals[j] for j in range(len(vals)) if j != i]) for i in range(len(vals))]
            index_to_drop = np.argmin(dropout_variance)
            value_to_reassign = clusters[highest_var_index]['values'].pop(index_to_drop)
            # update the variances
            clusters[highest_var_index]['var'] = dropout_variance[index_to_drop]
            assign_value_to_cluster(clusters, value_to_reassign)
        else:
            # break this cluster and assign values to others
            clusters.pop(highest_var_index)
            for val in vals:
                assign_value_to_cluster(clusters, val)

        curr_var = get_avg_var(clusters)
        print "after iter %04d: %04.2f" % (iter_count, curr_var)
        iter_count += 1

    return clusters
</code>```

Run the algorithm on the sample data OP provided:

```<code># vector x of values that we want to cluster
x = [
    101, 107, 106, 199, 204, 205, 207, 306, 310, 312,
    312, 314, 317, 318, 380, 377, 379, 382, 466, 469,
    471, 472, 557, 559, 562, 566, 569
]

clusters = init_clusters(x)
final_clusters = purify(clusters)

# print values of the final clusters
[final_clusters[y]['values'] for y in final_clusters]
</code>```

Output:

```<code>[[101, 106, 107],
 [204, 205, 207, 199],
 [306, 310],
 [312, 312, 314],
 [317, 318],
 [379, 380, 382, 377],
 [466, 469, 471, 472],
 [557, 559],
 [562, 566, 569]]
</code>```

Edit: Fixed a bug in get_avg_var() and realized I was not updating the cluster variances. This is sensitive to the initialization, but it will generally provide reasonable clusters. That being said, you can define your own optimization parameter (rather than using average cluster variance as I did).

Body:
I took a stab at doing what I suggested in my comment. I think this will give a good solution to a more generalized problem, but I caution that I haven't thought about all edge cases or considered algorithmic complexity here.

import numpy as np

# function to initialize clusters
def init_clusters(x, num_elements_per_cluster=3):
    # initialize clusters by splitting into n groups
    x.sort()  # sort the list
    nclusters = len(x) / num_elements_per_cluster
    clusters = {i: {'values': []} for i in range(nclusters)}

    # assign to clusters (helps that list is sorted)
    for i in range(len(x)):
        index = min(i/num_elements_per_cluster, nclusters-1)
        clusters[index]['values'].append(x[i])

    # compute variance
    for index in clusters:
        clusters[index]['var'] = np.var(clusters[index]['values'])

    return clusters

def get_avg_var(clusters):
    total_var = 0.0
    denom = 0.0
    for index in clusters:
        total_var += clusters[index]['var'] * len(clusters[index]['values'])
        denom += len(clusters[index]['values'])
    return total_var / denom  # possible div by 0, but shouldn't happen

def assign_value_to_cluster(clusters, value):
    """
    add value to a cluster such that results in the lowest variance
    """
    new_cluster_vars = []
    indices = []
    for index in clusters:
        new_cluster_vars.append(np.var(clusters[index]['values'] + [value]))
        indices.append(index)

    index_min_new_cluster_var = indices[np.argmin(new_cluster_vars)]
    clusters[index_min_new_cluster_var]['values'].append(value)
    # update the variances
    clusters[index_min_new_cluster_var]['var'] = new_cluster_vars[index_min_new_cluster_var]

def purify(clusters):
    curr_var = get_avg_var(clusters)
    prev_var = curr_var*10
    max_iter = 1000
    iter_count = 0
    while(curr_var < prev_var):
        if iter_count > max_iter:
            break

        prev_var = curr_var

        # start with the cluster with the highest variance
        sorted_vars = sorted(
            [{'index': i, 'var': clusters[i]['var']} for i in clusters],
            key=lambda x: x['var'],
            reverse=True
        )
        highest_var_index = sorted_vars[0]['index']

        vals = clusters[highest_var_index]['values']
        if len(vals) > 2:
            # find the element that when removed will minimize the variance of this cluster
            dropout_variance = [np.var([vals[j] for j in range(len(vals)) if j != i]) for i in range(len(vals))]
            index_to_drop = np.argmin(dropout_variance)
            value_to_reassign = clusters[highest_var_index]['values'].pop(index_to_drop)
            # update the variances
            clusters[highest_var_index]['var'] = dropout_variance[index_to_drop]
            assign_value_to_cluster(clusters, value_to_reassign)
        else:
            # break this cluster and assign values to others
            clusters.pop(highest_var_index)
            for val in vals:
                assign_value_to_cluster(clusters, val)

        curr_var = get_avg_var(clusters)
        print "after iter %04d: %04.2f" % (iter_count, curr_var)
        iter_count += 1

    return clusters

Run the algorithm on the sample data OP provided:

# vector x of values that we want to cluster
x = [
    101, 107, 106, 199, 204, 205, 207, 306, 310, 312,
    312, 314, 317, 318, 380, 377, 379, 382, 466, 469,
    471, 472, 557, 559, 562, 566, 569
]

clusters = init_clusters(x)
final_clusters = purify(clusters)

# print values of the final clusters
[final_clusters[y]['values'] for y in final_clusters]

Output:

[[101, 106, 107],
 [204, 205, 207, 199],
 [306, 310],
 [312, 312, 314],
 [317, 318],
 [379, 380, 382, 377],
 [466, 469, 471, 472],
 [557, 559],
 [562, 566, 569]]

Edit: Fixed a bug in get_avg_var() and realized I was not updating the cluster variances. This is sensitive to the initialization, but it will generally provide reasonable clusters. That being said, you can define your own optimization parameter (rather than using average cluster variance as I did).


问:
SQL INTERSECT by one field and get another field
I'm trying to do this SQL query:

```<code> SELECT field FROM table
 INTERSECT
 SELECT field FROM table
</code>```

Which return the intersection by the given field, but I want to get another field from the table as a result (intersected by the given field), how do I do that?

答:
You can use IN.

```<code>SELECT c1
FROM a
WHERE c2 IN (
        SELECT x1
        FROM b
        );
</code>```

Example:

Table: a

```<code>c1  c2
------
1   10
2   20
3   30
</code>```

Table: b

```<code>x1
---
20
30
</code>```

Result:

```<code>c1
--
2
3
</code>```

DEMO

Body:
I'm trying to do this SQL query:

 SELECT field FROM table
 INTERSECT
 SELECT field FROM table

Which return the intersection by the given field, but I want to get another field from the table as a result (intersected by the given field), how do I do that?

Body:
You can use IN.

SELECT c1
FROM a
WHERE c2 IN (
        SELECT x1
        FROM b
        );

Example:

Table: a

c1  c2
------
1   10
2   20
3   30

Table: b

x1
---
20
30

Result:

c1
--
2
3

DEMO


问:
Symfony Bundle Load YML Configuration
Since I am new to Symfony and I couldn't manage to find some useful information in google I decided to write to you.
I've read about the way of loading custom DI alias information from a dependency injector in your bundle and how to create a Configuration class that will expose the alias structure. However I am to some extend confused how I can create a file, for example routing.yml, in my AcmeBundle/Resources/config/ folder and read the data from it. E.g:

```<code>some_alias:
    resource: "@AcmeBundle/Controller/"
    type:     annotation
    prefix:   /
</code>```

I want to make a bundle with routing, independent from the main configuration files in the app folder.

答:
You can create your bundle routing.yml in your WhateverBundle/Resources/config/routing.yml and the in the app/routing.yml just include your bundle's routes.

```<code>mybundleorwhatever:
    resource: "@WhateverBundle/Resources/config/routing.xml"
</code>```

Title: Symfony Bundle Load YML Configuration

Body:
Since I am new to Symfony and I couldn't manage to find some useful information in google I decided to write to you.
I've read about the way of loading custom DI alias information from a dependency injector in your bundle and how to create a Configuration class that will expose the alias structure. However I am to some extend confused how I can create a file, for example routing.yml, in my AcmeBundle/Resources/config/ folder and read the data from it. E.g:

some_alias:
    resource: "@AcmeBundle/Controller/"
    type:     annotation
    prefix:   /

I want to make a bundle with routing, independent from the main configuration files in the app folder.

Body:
You can create your bundle routing.yml in your WhateverBundle/Resources/config/routing.yml and the in the app/routing.yml just include your bundle's routes.

mybundleorwhatever:
    resource: "@WhateverBundle/Resources/config/routing.xml"


问:
Making a new list with tuples based on strings in the list
```<code>L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
</code>```

Each number represents a person. So, there are five people from 0 to 4 in the list. L[0] always shows how many people are in the list.

```<code>L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]
</code>```

The person "0" is paired with 1 and 2. So, it has a list of 1, 2 in a tuple. My approach to get the result above is to compare the first character in L[1] to the end of the list. If the first letter in L[1] matches with the first letter in L[2], it bundles the second letter in L[2] with the second letter in L[1]. Finally, the new list is paired with 0 in a tuple. By the way, I cannot come up with such thing that can check the first letter in strings. I am not sure if this approach is right or not.

I am struggling to make such list L1 above. Could anyone let me know if my approach to this question is right? If it is wrong, please briefly give me a hint to solve this.

答:
I would suggest you use a form of dictionary for easier processing of the data later on. So here, defualtdict would be best utilized.

```<code>>>> from collections import defaultdict
>>> L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
>>> n  = int(L.pop(0))                                    #number of people

>>> d = defaultdict(list)
>>> for ele in L:
        x, y  = map(int, ele.split())
        d[x].append(y)

>>> d
=> defaultdict(<class 'list'>, {0: [1, 2], 1: [3], 2: [3, 4], 3: [4]})
</code>```

If neccessary to have that list format, use dict.items() and type cast it to list

```<code>>>> l1 = list(d.items())
>>> l1
=> [(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
</code>```

Body:
L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]

Each number represents a person. So, there are five people from 0 to 4 in the list. L[0] always shows how many people are in the list.

L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]

The person "0" is paired with 1 and 2. So, it has a list of 1, 2 in a tuple. My approach to get the result above is to compare the first character in L[1] to the end of the list. If the first letter in L[1] matches with the first letter in L[2], it bundles the second letter in L[2] with the second letter in L[1]. Finally, the new list is paired with 0 in a tuple. By the way, I cannot come up with such thing that can check the first letter in strings. I am not sure if this approach is right or not.

I am struggling to make such list L1 above. Could anyone let me know if my approach to this question is right? If it is wrong, please briefly give me a hint to solve this.

Body:
I would suggest you use a form of dictionary for easier processing of the data later on. So here, defualtdict would be best utilized.

>>> from collections import defaultdict
>>> L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
>>> n  = int(L.pop(0))                                    #number of people

>>> d = defaultdict(list)
>>> for ele in L:
        x, y  = map(int, ele.split())
        d[x].append(y)

>>> d
=> defaultdict(<class 'list'>, {0: [1, 2], 1: [3], 2: [3, 4], 3: [4]})

If neccessary to have that list format, use dict.items() and type cast it to list

>>> l1 = list(d.items())
>>> l1
=> [(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]


问:
list assignment index out of range for 2d array error
I looked into answers regarding similar questions but couldn't figure out my problem. I am newbie to python please help.

```<code>length = 13
breadth = 24
sheet = [ [ 0 for y in range( length ) ] for x in range( breadth ) ]
sheet[length-2][breadth-3] = 1
</code>```

The above code gives me list assignment index out of range error.

答:
You have either the list-comprehension the wrong way around, it should be:

```<code>length = 13
breadth = 24
sheet = [ [ 0 for x in range( breadth ) ] for y in range( length ) ]
sheet[length-2][breadth-3] = 1
</code>```

Or you have the indexing of the sheet list the wrong way around, it should be:

```<code>length = 13
breadth = 24
sheet = [ [ 0 for x in range( length ) ] for y in range( breadth ) ]
sheet[breadth-2][length-3] = 1
</code>```

Both corrections will work fine, but it depends on what you are defining breadth and width to be.

In the first example, the list looks like:

```<code>  #breadth --->
[[0,0 ....  0,0],  #width |
 ...               #      |
 [0,0 ....  0,0],  #      \/
]
</code>```

there are width rows of size breadth

In the second:

```<code>  #width --->
[[0,0 ....  0,0],  #breadth |
 ...               #        |
 [0,0 ....  0,0],  #        \/
]
</code>```

there are breadth rows of size width

Body:
I looked into answers regarding similar questions but couldn't figure out my problem. I am newbie to python please help.

length = 13
breadth = 24
sheet = [ [ 0 for y in range( length ) ] for x in range( breadth ) ]
sheet[length-2][breadth-3] = 1

The above code gives me list assignment index out of range error.

Body:
You have either the list-comprehension the wrong way around, it should be:

length = 13
breadth = 24
sheet = [ [ 0 for x in range( breadth ) ] for y in range( length ) ]
sheet[length-2][breadth-3] = 1

Or you have the indexing of the sheet list the wrong way around, it should be:

length = 13
breadth = 24
sheet = [ [ 0 for x in range( length ) ] for y in range( breadth ) ]
sheet[breadth-2][length-3] = 1

Both corrections will work fine, but it depends on what you are defining breadth and width to be.

In the first example, the list looks like:

  #breadth --->
[[0,0 ....  0,0],  #width |
 ...               #      |
 [0,0 ....  0,0],  #      \/
]

there are width rows of size breadth

In the second:

  #width --->
[[0,0 ....  0,0],  #breadth |
 ...               #        |
 [0,0 ....  0,0],  #        \/
]

there are breadth rows of size width


问:
Maven project.build.directory
In Maven, what does the project.build.directory refer to? I am a bit confused, does it reference the source code directory or the target directory in the Maven project?

答:
You can find the most up to date answer for the value in your project just execute the

```<code>mvn3 help:effective-pom
</code>```

command and find the <build> ... <directory> tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.

Title: Maven project.build.directory

Body:
You can find the most up to date answer for the value in your project just execute the

mvn3 help:effective-pom

command and find the <build> ... <directory> tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.


答:
You have the axes mixed up, try using

```<code>sheet[breadth-3][length-2] = 1
</code>```

Alternatively, you could use numpy to do this more elegantly:

```<code>import numpy as np

breadth = 5
length = 3

sheet = np.zeros(shape=(breadth, length))
sheet[breadth-3, length-2] = 1

sheet.shape
>>> (5, 3)

sheet
>>> array([[ 0.,  0.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  1.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  0.,  0.]])
</code>```

Title: list assignment index out of range for 2d array error

Body:
You have the axes mixed up, try using

sheet[breadth-3][length-2] = 1

Alternatively, you could use numpy to do this more elegantly:

import numpy as np

breadth = 5
length = 3

sheet = np.zeros(shape=(breadth, length))
sheet[breadth-3, length-2] = 1

sheet.shape
>>> (5, 3)

sheet
>>> array([[ 0.,  0.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  1.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  0.,  0.]])


问:
Highcharts tooltip date format when using pointFormat
hi i am working on highcharts with net transactions on y-axis and type datetime on x-axis. i have shown month and date on x-axis point label as (jan 2016) and want to show the same date format on tooltip. but its showing full date with day as well like "Monday, jan 1, 2016.

here is my js code.

```<code>tooltip: {
        headerFormat: '<span style="font-size:10px">{point.x:%Y-%m}</span><table>',
        pointFormat: '<tr><td style="color:{series.color};padding:0;font-size:11px;">{series.name}: </td>' +
        '<td style="padding:0"><b>{point.y:,.0f}</b></td></tr>',
        footerFormat: '</table>',
        shared: true,
        useHTML: true
    },
</code>```

Thanks for any help

答:
You should modify the tooltip header format

```<code>tooltip: {
    xDateFormat: '%b %Y'
}
</code>```

Or if you want to modify the whole html

```<code>tooltip: {
    headerFormat: '<b>{point.key:%b \'%y}</b><br>'
}
</code>```

Body:
hi i am working on highcharts with net transactions on y-axis and type datetime on x-axis. i have shown month and date on x-axis point label as (jan 2016) and want to show the same date format on tooltip. but its showing full date with day as well like "Monday, jan 1, 2016.

here is my js code.

tooltip: {
        headerFormat: '{point.x:%Y-%m}
',
        pointFormat: '
{series.name}: 	' +
        '{point.y:,.0f}
',
        footerFormat: '
',
        shared: true,
        useHTML: true
    },

Thanks for any help

Body:
You should modify the tooltip header format

tooltip: {
    xDateFormat: '%b %Y'
}

Or if you want to modify the whole html

tooltip: {
    headerFormat: '<b>{point.key:%b \'%y}</b><br>'
}