问:
Rails polymorphic aliased associations
I would like to try set up this association:

```<code># app/models/course.rb
class Course < ActiveRecord::Base
  belongs_to :subjectable, polymorphic: true
end

# app/models/student.rb
class Student < ActiveRecord::Base
  has_many :courses, as: :subjectable
end

# app/models/campus.rb
class Campus < ActiveRecord::Base
  has_many :courses, as: :subjectable
end
</code>```

But this did not read very well in the code.

```<code>#this seems fine
campus = Campus.last
campus.courses

#this dosent make much sense gramatically
student = Student.last
student.courses
</code>```

Campuses offer Courses, but Students don't have courses they have subjects. Now they are the same thing under the covers they just don't read well.

How could I get it so that student.subejects would yield the same result as student.courses?

答:
You can name the association as you want, you don't have to mach the associated class.

In this case, you have to tell ActiveRecord what the pointed class is :

```<code># app/models/student.rb
class Student < ActiveRecord::Base
  has_many :subjects, as: :subjectable, class_name: 'Course'
end
</code>```

Title: Rails polymorphic aliased associations

Body:
I would like to try set up this association:

# app/models/course.rb
class Course < ActiveRecord::Base
  belongs_to :subjectable, polymorphic: true
end

# app/models/student.rb
class Student < ActiveRecord::Base
  has_many :courses, as: :subjectable
end

# app/models/campus.rb
class Campus < ActiveRecord::Base
  has_many :courses, as: :subjectable
end

But this did not read very well in the code.

#this seems fine
campus = Campus.last
campus.courses

#this dosent make much sense gramatically
student = Student.last
student.courses

Campuses offer Courses, but Students don't have courses they have subjects. Now they are the same thing under the covers they just don't read well.

How could I get it so that student.subejects would yield the same result as student.courses?

Body:
You can name the association as you want, you don't have to mach the associated class.

In this case, you have to tell ActiveRecord what the pointed class is :

# app/models/student.rb
class Student < ActiveRecord::Base
  has_many :subjects, as: :subjectable, class_name: 'Course'
end


来源: stackexchange

问:
Is Haskell a Lisp?
I've been reading The Haskell Road to Logic, Maths and Programming by Doets and Eijck 2004. It seems to be a well respected book, but I was struck when it claims that Haskell is a member of the Lisp family. Is this accurate? I would characterise Lisps with s-expressions, impure functions, and lists as the only composite data structure. Haskell has none of that. What justification is there for that claim?</p>

答:
Hoyte compares some languages and claims that Haskell is NOT a Lisp for it is too strict in types and only for academics, whereas Common Lisp is more like a prototyping language (no strictness, dynamic typing).

See: Let Over Lambda—50 Years of Lisp by Doug Hoyte (an advanced book about Common Lisp, http://letoverlambda.com/)

Haskell and Common Lisp (probably all Lisps) are optimized against the functional programming (FP) paradigm. Haskell is pure, whereas Common Lisp is unpure. Contrast the term FP also with "total functional programming".

Also have a look at this diagram comparing programming language paradigms: http://www.info.ucl.ac.be/~pvr/paradigms.html

ContentLicense: CC BY-SA 4.0

Title: Is Haskell a Lisp?

ContentLicense: CC BY-SA 2.5


问:
How can I join into insert statement?
Here is my table structure:

```<code>// pages
+----+-----------------------+--------+
| id |         path          | method |
+----+-----------------------+--------+
| 1  | list_role             | get    |
| 2  | make_role             | post   |
| 3  | edit_role/id          | get    |
| 4  | list_voucher/activate | get    |
| 5  | list_voucher/activate | post   |
| 6  | expire_voucher/id     | get    |
+----+-----------------------+--------+

// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
</code>```

Now I want to insert multiple rows into role_page table according to this array: (noted that I have $role_id)

```<code>$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example
</code>```

So the expected output is:

```<code>// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
| 4       | 1       |
| 4       | 4       |
+---------+---------+
</code>```

How can I do that by a join?

Currently I do that by a loop on $arr like this:

```<code>$role_id = 4;

foreach($arr as $row) {
    // match the page id
    $page_id = pages::where('path', row[0])->where('method', row[1])->first();

    // insert
    $role_page = new role_page;
    $role_page->role_id = $role_id;
    $role_page->page_id = $page_id;
}
</code>```

答:
Try this

Page Model (you may have to customize this relation)

```<code>public function roles(){
    return $this->belongsToMany(Role::class, 'role_page', 'page_id', 'role_id')
}
</code>```

Then

```<code>$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example

$query = Page::query();

foreach ($arr as $page){
    $query = $query->orWhere(function($query){
        $query->where('path', $page[0])->where('method', $page[1]);
    }
}
$pages =$query->get();

foreach($pages as $page){
    $page->roles()->attach($role_id);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can I join into insert statement?

Body:
Here is my table structure:

// pages
+----+-----------------------+--------+
| id |         path          | method |
+----+-----------------------+--------+
| 1  | list_role             | get    |
| 2  | make_role             | post   |
| 3  | edit_role/id          | get    |
| 4  | list_voucher/activate | get    |
| 5  | list_voucher/activate | post   |
| 6  | expire_voucher/id     | get    |
+----+-----------------------+--------+

// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+

Now I want to insert multiple rows into role_page table according to this array: (noted that I have $role_id)

$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example

So the expected output is:

// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
| 4       | 1       |
| 4       | 4       |
+---------+---------+

How can I do that by a join?

Currently I do that by a loop on $arr like this:

$role_id = 4;

foreach($arr as $row) {
    // match the page id
    $page_id = pages::where('path', row[0])->where('method', row[1])->first();

    // insert
    $role_page = new role_page;
    $role_page->role_id = $role_id;
    $role_page->page_id = $page_id;
}

Body:
Try this

Page Model (you may have to customize this relation)

public function roles(){
    return $this->belongsToMany(Role::class, 'role_page', 'page_id', 'role_id')
}

Then

$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example

$query = Page::query();

foreach ($arr as $page){
    $query = $query->orWhere(function($query){
        $query->where('path', $page[0])->where('method', $page[1]);
    }
}
$pages =$query->get();

foreach($pages as $page){
    $page->roles()->attach($role_id);
}


问:
What is the purpose of the 'reuse' flag in GAN implemented in tensorflow?
I'm going through a GAN tutorial and I've noticed the use of 'reuse' flags and I don't quite get what they are doing or preventing. If you take a look at the code below you will see that reuse is used within each variable scope initialization.

(I tried looking at the docs but still an not clear:
https://www.tensorflow.org/versions/r0.12/how_tos/variable_scope/)

```<code>def discriminator(images, reuse=False):
    """
    Create the discriminator network
    """
    alpha = 0.2

    with tf.variable_scope('discriminator', reuse=reuse):
        # using 4 layer network as in DCGAN Paper

        # Conv 1
        conv1 = tf.layers.conv2d(images, 64, 5, 2, 'SAME')
        lrelu1 = tf.maximum(alpha * conv1, conv1)

        # Conv 2
        conv2 = tf.layers.conv2d(lrelu1, 128, 5, 2, 'SAME')
        batch_norm2 = tf.layers.batch_normalization(conv2, training=True)
        lrelu2 = tf.maximum(alpha * batch_norm2, batch_norm2)

        # Conv 3
        conv3 = tf.layers.conv2d(lrelu2, 256, 5, 1, 'SAME')
        batch_norm3 = tf.layers.batch_normalization(conv3, training=True)
        lrelu3 = tf.maximum(alpha * batch_norm3, batch_norm3)

        # Flatten
        flat = tf.reshape(lrelu3, (-1, 4*4*256))

        # Logits
        logits = tf.layers.dense(flat, 1)

        # Output
        out = tf.sigmoid(logits)

        return out, logits
def generator(z, out_channel_dim, is_train=True):
    """
    Create the generator network
    """
    alpha = 0.2

    with tf.variable_scope('generator', reuse=False if is_train==True else True):
        # First fully connected layer
        x_1 = tf.layers.dense(z, 2*2*512)

        # Reshape it to start the convolutional stack
        deconv_2 = tf.reshape(x_1, (-1, 2, 2, 512))
        batch_norm2 = tf.layers.batch_normalization(deconv_2, training=is_train)
        lrelu2 = tf.maximum(alpha * batch_norm2, batch_norm2)

        # Deconv 1
        deconv3 = tf.layers.conv2d_transpose(lrelu2, 256, 5, 2, padding='VALID')
        batch_norm3 = tf.layers.batch_normalization(deconv3, training=is_train)
        lrelu3 = tf.maximum(alpha * batch_norm3, batch_norm3)

        # Deconv 2
        deconv4 = tf.layers.conv2d_transpose(lrelu3, 128, 5, 2, padding='SAME')
        batch_norm4 = tf.layers.batch_normalization(deconv4, training=is_train)
        lrelu4 = tf.maximum(alpha * batch_norm4, batch_norm4)

        #Deconv 3
        deconv5 = tf.layers.conv2d_transpose(lrelu4, 64, 5, 2, padding='SAME')
        batch_norm5 = tf.layers.batch_normalization(deconv5, training=is_train)
        lrelu5 = tf.maximum(alpha * batch_norm5, batch_norm5)

        # Output layer
        logits = tf.layers.conv2d_transpose(lrelu5, out_channel_dim, 5, 2, padding='SAME')
        out = tf.tanh(logits)

        return out
</code>```

Thank you.

答:
For the generator, we're going to train it, but also sample from it as we're training and after training. The discriminator will need to share variables between the fake and real input images. So, we can use the reuse keyword for tf.variable_scope to tell TensorFlow to reuse the variables instead of creating new ones if we build the graph again.

Then the discriminators. We'll build two of them, one for real data and one for fake data. Since we want the weights to be the same for both real and fake data, we need to reuse the variables. For the fake data, we're getting it from the generator as g_model. So the real data discriminator is discriminator(input_real) while the fake discriminator is discriminator(g_model, reuse=True).

Body:
I'm going through a GAN tutorial and I've noticed the use of 'reuse' flags and I don't quite get what they are doing or preventing. If you take a look at the code below you will see that reuse is used within each variable scope initialization.

(I tried looking at the docs but still an not clear:
https://www.tensorflow.org/versions/r0.12/how_tos/variable_scope/)

def discriminator(images, reuse=False):
    """
    Create the discriminator network
    """
    alpha = 0.2

    with tf.variable_scope('discriminator', reuse=reuse):
        # using 4 layer network as in DCGAN Paper

        # Conv 1
        conv1 = tf.layers.conv2d(images, 64, 5, 2, 'SAME')
        lrelu1 = tf.maximum(alpha * conv1, conv1)

        # Conv 2
        conv2 = tf.layers.conv2d(lrelu1, 128, 5, 2, 'SAME')
        batch_norm2 = tf.layers.batch_normalization(conv2, training=True)
        lrelu2 = tf.maximum(alpha * batch_norm2, batch_norm2)

        # Conv 3
        conv3 = tf.layers.conv2d(lrelu2, 256, 5, 1, 'SAME')
        batch_norm3 = tf.layers.batch_normalization(conv3, training=True)
        lrelu3 = tf.maximum(alpha * batch_norm3, batch_norm3)

        # Flatten
        flat = tf.reshape(lrelu3, (-1, 4*4*256))

        # Logits
        logits = tf.layers.dense(flat, 1)

        # Output
        out = tf.sigmoid(logits)

        return out, logits
def generator(z, out_channel_dim, is_train=True):
    """
    Create the generator network
    """
    alpha = 0.2

    with tf.variable_scope('generator', reuse=False if is_train==True else True):
        # First fully connected layer
        x_1 = tf.layers.dense(z, 2*2*512)

        # Reshape it to start the convolutional stack
        deconv_2 = tf.reshape(x_1, (-1, 2, 2, 512))
        batch_norm2 = tf.layers.batch_normalization(deconv_2, training=is_train)
        lrelu2 = tf.maximum(alpha * batch_norm2, batch_norm2)

        # Deconv 1
        deconv3 = tf.layers.conv2d_transpose(lrelu2, 256, 5, 2, padding='VALID')
        batch_norm3 = tf.layers.batch_normalization(deconv3, training=is_train)
        lrelu3 = tf.maximum(alpha * batch_norm3, batch_norm3)

        # Deconv 2
        deconv4 = tf.layers.conv2d_transpose(lrelu3, 128, 5, 2, padding='SAME')
        batch_norm4 = tf.layers.batch_normalization(deconv4, training=is_train)
        lrelu4 = tf.maximum(alpha * batch_norm4, batch_norm4)

        #Deconv 3
        deconv5 = tf.layers.conv2d_transpose(lrelu4, 64, 5, 2, padding='SAME')
        batch_norm5 = tf.layers.batch_normalization(deconv5, training=is_train)
        lrelu5 = tf.maximum(alpha * batch_norm5, batch_norm5)

        # Output layer
        logits = tf.layers.conv2d_transpose(lrelu5, out_channel_dim, 5, 2, padding='SAME')
        out = tf.tanh(logits)

        return out

Thank you.


问:
why a method has to be generic when passing a generic type
For example i have this C# method :

```<code>public static int Count<T>(IEnumerable<T> sequence)
{
     return 0;
}
</code>```

Why i have to write Count<T> rather than Count even when i'm not using the T type inside the method ?

答:
You don't have to. You could go entirely non-generic:

```<code>public static int Count(IEnumerable sequence)
{
     return 0;
}
</code>```

And since IEnumerable<out T> : IEnumerable, this will work for all sequences.

One reason not to do this, however, is that if you plan to do:

```<code>int count = 0;
foreach(var obj in sequence) count++;
return count;
</code>```

then the non-generic version when used with value types will box every value - increasing allocations. The generic version will not do any boxing.

Body:
For example i have this C# method :

public static int Count<T>(IEnumerable<T> sequence)
{
     return 0;
}

Why i have to write Count<T> rather than Count even when i'm not using the T type inside the method ?

Body:
You don't have to. You could go entirely non-generic:

public static int Count(IEnumerable sequence)
{
     return 0;
}

And since IEnumerable<out T> : IEnumerable, this will work for all sequences.

One reason not to do this, however, is that if you plan to do:

int count = 0;
foreach(var obj in sequence) count++;
return count;

then the non-generic version when used with value types will box every value - increasing allocations. The generic version will not do any boxing.


问:
Listing all resources in a namespace
I would like to see all resources in a namespace.

Doing kubectl get all will, despite of the name, not list things like services and ingresses.

If I know the the type I can explicitly ask for that particular type, but it seems there is also no command for listing all possible types. (Especially kubectl get does for example not list custom types).

How to show all resources before for example deleting that namespace?

答:
All kubernetes objects are stored in etcd.

All objects are stored in ETCD v3 the following way:

```<code>/registry/<object_type>/<namespace>/<name>
</code>```

I suggest just to take the list of all resources of some namespace from etcd v3 directly:

```<code>ETCDCTL_API=3 etcdctl --endpoints=<etcd_ip>:2379 get / --prefix --keys-only | grep -E "^/\w+/\w+/<namespace>/+"
</code>```

Title: Listing all resources in a namespace

Body:
All kubernetes objects are stored in etcd.

All objects are stored in ETCD v3 the following way:

/registry/<object_type>/<namespace>/<name>

I suggest just to take the list of all resources of some namespace from etcd v3 directly:

ETCDCTL_API=3 etcdctl --endpoints=<etcd_ip>:2379 get / --prefix --keys-only | grep -E "^/\w+/\w+/<namespace>/+"


问:
Give the classes a specific id
I have a question about the class, and give the class a specific id.

For example I've got a html code like this:

```<code><div class="test">text1</div>
<div class="test">text2</div>
<div class="test">text3</div>
<div class="test">text4</div>
<div class="test">text5</div>
</code>```

My question is how can I add an id by each .test class.

I thought something like this in Jquery:

```<code>var i = 1;
$('.test').each(function(){
   $('.test').attr('id','id_'+i+'');
   i++
});
</code>```

This doesn't work I think it's something with .closest() or .next()
to solve this problem.

Regards,

Frank

EDIT:

I solved the problem by myself the answer is:

```<code>    $('.test').each(function(){
        $(this).attr('class','test').attr('id','id_'+i+'');
        i++;
    });
</code>```

答:
You were on the right path:</p>

```<code>var i = 1;
$('.test').each(function(){
   $(this).attr('id','id_'+i+'');
   i++
});
</code>```

Title: Give the classes a specific id

Body:
I have a question about the class, and give the class a specific id.

For example I've got a html code like this:

text1

text2

text3

text4

text5

My question is how can I add an id by each .test class.

I thought something like this in Jquery:

var i = 1;
$('.test').each(function(){
   $('.test').attr('id','id_'+i+'');
   i++
});

This doesn't work I think it's something with .closest() or .next()
to solve this problem.

Regards,

Frank

EDIT:

I solved the problem by myself the answer is:

    $('.test').each(function(){
        $(this).attr('class','test').attr('id','id_'+i+'');
        i++;
    });

Body:
You were on the right path:

var i = 1;
$('.test').each(function(){
   $(this).attr('id','id_'+i+'');
   i++
});


问:
Removing white spacing between stacked elements in CSS
I am trying to remove spacing between elements stacked on each other.

This is what i have:

input[type="text"] {
  width: 40%;
  height: 30px;
  border-radius: 29px;
  border-style: none;
  padding-right: 100px;
  padding-left: 30px;
  border-width: 0;
}

input[type="submit"] {
  margin-left: -100px;
  height: 30px;
  width: 100px;
  border-width: 0;
  border-radius: 29px;
  background: blue;
  color: white;
  -webkit-appearance: none;
}

body {
  background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br/>
<form>
  <label for="fname">First Name</label>
  <input type="text" id="fname" name="fname" placeholder="Enter your email"><input type="submit">
</form></code>```

I have tried top:0; and bottom:0; but it does not seem to solve my problem in this example.

答:
Remove padding-top and padding-bottom on input[type="text"]

```<code>padding-top: 0px;
padding-bottom: 0px;
</code>```

input[type="text"] {
padding-top: 0px;
padding-bottom: 0px;
    width: 40%;
    height:30px;
      border-radius: 29px;
     border-style:none;
      padding-right:100px;
      padding-left:30px;
      border-width: 0;
}
input[type="submit"] {

    margin-left: -100px;
   height:30px;

    width: 100px;

    border-width: 0;
     border-radius: 29px;
    background: blue;
    color: white;
    -webkit-appearance: none;
}
body {
background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br/>
<form>
  <label for="fname">First Name</label>
  <input type="text" id="fname" name="fname"  placeholder="Enter your email"><input type="submit">
</form></code>```

Body:
I am trying to remove spacing between elements stacked on each other.

This is what i have:

input[type="text"] {
  width: 40%;
  height: 30px;
  border-radius: 29px;
  border-style: none;
  padding-right: 100px;
  padding-left: 30px;
  border-width: 0;
}

input[type="submit"] {
  margin-left: -100px;
  height: 30px;
  width: 100px;
  border-width: 0;
  border-radius: 29px;
  background: blue;
  color: white;
  -webkit-appearance: none;
}

body {
  background-color: black;
}

<form>
  First Name
  <input type="text" id="fname" name="fname" placeholder="Enter your email"><input type="submit">
</form>

I have tried top:0; and bottom:0; but it does not seem to solve my problem in this example.

Body:
Remove padding-top and padding-bottom on input[type="text"]

padding-top: 0px;
padding-bottom: 0px;

input[type="text"] {
padding-top: 0px;
padding-bottom: 0px;
    width: 40%;
    height:30px;
      border-radius: 29px;
     border-style:none;
      padding-right:100px;
      padding-left:30px;
      border-width: 0;
}
input[type="submit"] {

    margin-left: -100px;
   height:30px;

    width: 100px;

    border-width: 0;
     border-radius: 29px;
    background: blue;
    color: white;
    -webkit-appearance: none;
}
body {
background-color: black;
}

<br/>
<form>
  <label for="fname">First Name</label>
  <input type="text" id="fname" name="fname"  placeholder="Enter your email"><input type="submit">
</form>


问:
Preserve Encapsulation while Displaying Information
Suppose I've got the following class to represent a Car and Tire:

```<code>public final class Tire{

    private final String brand
    private final TireType type;

    public Tire(String brand, type)
    {
      this.brand = brand
      this.type = type;
    }

    //getters and toString() for tire attributes
}

public final class Car{

    private final String name;
    private final Tire tire;

    public Car(String name, Tire tire){
        this.name = name;
        this.tire = tire;
    }

    public String getName(){
        return this.name;
    }
}
</code>```

I'm fully aware that my Car and Tire example are lacking notable attributes, but that's not the focus of my question, it's the simplest MCVE I could come up with.

From Effective Java(p. 53):

Whether or not you specify the format, provide programmatic access to
  all of the information contained in the value returned by toString.

In my Car class, the toString() method will obviously return the name, and according to Effective Java, as quoted above I should provide a getter as well. My problem is when returning the details of the Tire.

Question:

Given the advice quoted from Effective Java, how would I properly return the details of my car including the Tire for display purposes?

Would I do this:

```<code>public Tire getTire(){
    return this.tire
}

public String toString(){
     return  "Name:  " + this.name + " Tire: " + this.tire;
}
</code>```

Or to put it another way, when you have a class, in my case(Tire), that is also an attribute of another class, in my case(Car), when returning the details to be printed in a GUI, how would I do so and perverse encapsulation?

答:
This conflict (and it is a conflict, you can't have both!) can be solved by deciding what you value more. Do you value OO, Encapsulation, Law of Demeter more than that quoted advice from Effective Java.

If you value the former, then the advice from Effective Java can't be really followed. I would even argue that having any getters is wrong inside an application (a library with a public API is somewhat different).

If you value the advice more, then obviously you can define whatever getters you want.

I know this isn't a satisfying answer, but don't be fooled that you can have both! You can't.

Body:
Suppose I've got the following class to represent a Car and Tire:

public final class Tire{

    private final String brand
    private final TireType type;

    public Tire(String brand, type)
    {
      this.brand = brand
      this.type = type;
    }

    //getters and toString() for tire attributes
}

public final class Car{

    private final String name;
    private final Tire tire;

    public Car(String name, Tire tire){
        this.name = name;
        this.tire = tire;
    }

    public String getName(){
        return this.name;
    }
}

I'm fully aware that my Car and Tire example are lacking notable attributes, but that's not the focus of my question, it's the simplest MCVE I could come up with.

From Effective Java(p. 53):

Whether or not you specify the format, provide programmatic access to
  all of the information contained in the value returned by toString.

In my Car class, the toString() method will obviously return the name, and according to Effective Java, as quoted above I should provide a getter as well. My problem is when returning the details of the Tire.

Question:

Given the advice quoted from Effective Java, how would I properly return the details of my car including the Tire for display purposes?

Would I do this:

public Tire getTire(){
    return this.tire
}

public String toString(){
     return  "Name:  " + this.name + " Tire: " + this.tire;
}

Or to put it another way, when you have a class, in my case(Tire), that is also an attribute of another class, in my case(Car), when returning the details to be printed in a GUI, how would I do so and perverse encapsulation?


问:
How to change the height of the view inside the adapter?
I want to change the height of the view and decrease height all the bottom view. This works well in the fragment, but does not work in the adapter.
I do not want to squeeze the main view, I need to increase only the size of containerAvatar.

```<code>public class OrderAdapter extends ArrayAdapter {

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    convertView = layoutInflater.inflate(R.layout.open_order_item, parent, false);

    containerAvatar = convertView.findViewById(R.id.container_avatar_size);
    imgAvatar = convertView.findViewById(R.id.img_open_order_avatar);

    Glide.with(context)
            .load("http://neuronovosti.ru/wp-content/uploads/2017/12/Drosophila-Brain-1024x1024.jpg")
            .into(imgAvatar);

    containerAvatar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final ViewGroup.LayoutParams lp = containerAvatar.getLayoutParams();
            final ResizeAnimation a = new ResizeAnimation(containerAvatar);
            a.setDuration(500);
            a.setParams(lp.height, lp.height * 2);
            containerAvatar.startAnimation(a);
        }
    });

    return convertView;
}

public class ResizeAnimation extends Animation {
    private int startHeight;
    private int deltaHeight; // distance between start and end height
    private View view;

public ResizeAnimation(View v) {
    this.view = v;
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {

    view.getLayoutParams().height = (int) (startHeight + deltaHeight * interpolatedTime);
    view.requestLayout();
}

public void setParams(int start, int end) {

    this.startHeight = start;
    deltaHeight = end - startHeight;
}

@Override
public void setDuration(long durationMillis) {
    super.setDuration(durationMillis);
}

@Override
public boolean willChangeBounds() {
    return true;
}
</code>```

That's what you need

答:
Try with setLayoutParams() Method of View -

```<code>private void setDimensions(View view, int width, int height){
    android.view.ViewGroup.LayoutParams params = view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);
}
</code>```

Added it on your Adapter -

```<code>public class OrderAdapter extends ArrayAdapter {

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    convertView = layoutInflater.inflate(R.layout.open_order_item, parent, false);

    containerAvatar = convertView.findViewById(R.id.container_avatar_size);
    imgAvatar = convertView.findViewById(R.id.img_open_order_avatar);

    Glide.with(context)
            .load("http://neuronovosti.ru/wp-content/uploads/2017/12/Drosophila-Brain-1024x1024.jpg")
            .into(imgAvatar);

    containerAvatar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setDimensions(containerAvatar, 100, 100);
        }
    });

    return convertView;
}

private void setDimensions(View view, int width, int height){
    android.view.ViewGroup.LayoutParams params = view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);
}

}
</code>```

Body:
I want to change the height of the view and decrease height all the bottom view. This works well in the fragment, but does not work in the adapter.
I do not want to squeeze the main view, I need to increase only the size of containerAvatar.

public class OrderAdapter extends ArrayAdapter {

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    convertView = layoutInflater.inflate(R.layout.open_order_item, parent, false);

    containerAvatar = convertView.findViewById(R.id.container_avatar_size);
    imgAvatar = convertView.findViewById(R.id.img_open_order_avatar);

    Glide.with(context)
            .load("http://neuronovosti.ru/wp-content/uploads/2017/12/Drosophila-Brain-1024x1024.jpg")
            .into(imgAvatar);

    containerAvatar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final ViewGroup.LayoutParams lp = containerAvatar.getLayoutParams();
            final ResizeAnimation a = new ResizeAnimation(containerAvatar);
            a.setDuration(500);
            a.setParams(lp.height, lp.height * 2);
            containerAvatar.startAnimation(a);
        }
    });

    return convertView;
}

public class ResizeAnimation extends Animation {
    private int startHeight;
    private int deltaHeight; // distance between start and end height
    private View view;

public ResizeAnimation(View v) {
    this.view = v;
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {

    view.getLayoutParams().height = (int) (startHeight + deltaHeight * interpolatedTime);
    view.requestLayout();
}

public void setParams(int start, int end) {

    this.startHeight = start;
    deltaHeight = end - startHeight;
}

@Override
public void setDuration(long durationMillis) {
    super.setDuration(durationMillis);
}

@Override
public boolean willChangeBounds() {
    return true;
}

That's what you need

Body:
Try with setLayoutParams() Method of View -

private void setDimensions(View view, int width, int height){
    android.view.ViewGroup.LayoutParams params = view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);
}

Added it on your Adapter -

public class OrderAdapter extends ArrayAdapter {

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    convertView = layoutInflater.inflate(R.layout.open_order_item, parent, false);

    containerAvatar = convertView.findViewById(R.id.container_avatar_size);
    imgAvatar = convertView.findViewById(R.id.img_open_order_avatar);

    Glide.with(context)
            .load("http://neuronovosti.ru/wp-content/uploads/2017/12/Drosophila-Brain-1024x1024.jpg")
            .into(imgAvatar);

    containerAvatar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setDimensions(containerAvatar, 100, 100);
        }
    });

    return convertView;
}

private void setDimensions(View view, int width, int height){
    android.view.ViewGroup.LayoutParams params = view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);
}

}


问:
Need help for java to randomly decide between male or female
I am new to coding, and I am currently modding a code. Here is pat of the original.

```<code> if ((world[row][col] == ORGANISM) && (check == 2))
            worldCopy[row][col] = ORGANISM;
</code>```

The original code would basically spawn a offspring (a.k.a a *) in a certain location on a grid. However, now I am modding for the offspring to be randomly male or female. How should I write a new piece of subcode so that it would randomly pick for ORGANISM to be male or female? I don't need specifics, just want some help because I am stuck.

答:
Math.random() method can be used which returns a decimal number between 0.0 to 1.0. A check can be done to see if the value is > or < 0.5 and decide based on that.</p>

```<code>String gender;
if(Math.random() > 0.5) gender  = "MALE";
else gender = "FEMALE";
</code>```

Body:
I am new to coding, and I am currently modding a code. Here is pat of the original.

 if ((world[row][col] == ORGANISM) && (check == 2))
            worldCopy[row][col] = ORGANISM;

The original code would basically spawn a offspring (a.k.a a *) in a certain location on a grid. However, now I am modding for the offspring to be randomly male or female. How should I write a new piece of subcode so that it would randomly pick for ORGANISM to be male or female? I don't need specifics, just want some help because I am stuck.

Body:
Math.random() method can be used which returns a decimal number between 0.0 to 1.0. A check can be done to see if the value is > or < 0.5 and decide based on that.

String gender;
if(Math.random() > 0.5) gender  = "MALE";
else gender = "FEMALE";


问:
Request to VSTS REST API only works on Postman
I'm trying to run this request

```<code>curl -X POST \
  'https://*****.visualstudio.com/DefaultCollection/_apis/wit/wiql?=&api-version=1.0' \
  -H 'authorization: Basic *****' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'postman-token: *****' \
  -d '{
  "query": "SELECT [System.Id] FROM WorkItems"
}'
</code>```

but I keep getting this error

```<code>{"count":1,"value":{"Message":"A value is required but was not present in the request.\r\n"}}
</code>```

It works as expected on Postman, so I think the request and the server are OK.

I'm trying to follow the first example shown here: https://www.visualstudio.com/en-us/docs/integrate/api/wit/wiql

Am I missing something?

答:
The URL is wrong, remove =& from the REST API url and the url will be like this:

https://*****.visualstudio.com/DefaultCollection/_apis/wit/wiql?api-version=1.

Body:
I'm trying to run this request

curl -X POST \
  'https://*****.visualstudio.com/DefaultCollection/_apis/wit/wiql?=&api-version=1.0' \
  -H 'authorization: Basic *****' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'postman-token: *****' \
  -d '{
  "query": "SELECT [System.Id] FROM WorkItems"
}'

but I keep getting this error

{"count":1,"value":{"Message":"A value is required but was not present in the request.\r\n"}}

It works as expected on Postman, so I think the request and the server are OK.

I'm trying to follow the first example shown here: https://www.visualstudio.com/en-us/docs/integrate/api/wit/wiql

Am I missing something?


问:
icon set/library for angular 2 and above
I used Ionic and it provides default ionicons icon set. I'm new to angular. I'm searching for angular icon set.

What is the default icon set for the angular app?

I know, it is a basic question but yet not finding any official link, what is default icon set or any preferred one?

Please guide me!

答: There is no such thing as a preferred Angular icon set. Some standard ones that you'll see being used often are Bootstrap's Glyphicons and Material Design's icons. However, Angular itself is entirely agnostic and makes no special preference for any type of icon at all.</p>


问:
PHP redirect without header() or meta
I'm trying to design a page which does some database actions, then redirects to user back to the page they came from. The problem is that I use a require() function to get the connection to the database, so the headers are already sent. A meta tag is out of the question since I want it to look like all the processes are done from the page they came from. Any tips? Is there a way I can use the require() and the header() or do I have to drop one? Is there an alternative to header()?

答:
You cannot send headers after any data has been sent to the client.

However, using require does not meen that you output something. If i understand your right, you can include your database files, run your queries and then redirect the user. This is perfectly valid.

If you need to send some output (why if you need to do a redirect?) another option is to use output buffering. By using output buffering, you're not sending the data to the browser when you echo it, but you store it in a buffer. The data will be sent when you call ob_end_flush or you reach the end of the script. After ob_end_flush, you won't be able to send any new headers. You start output buffering with ob_start.

Title: PHP redirect without header() or meta


问:
Improve performance of dynamically adding views in a layout

Working on app in which there are forms.
Forms have categories A, B, C and D.

I receive JSON of form from server and i have to convert it in Form(layout).

A form may contain one field or 100 depending on category.

What i want: If there is a form with 100 fields how can improve performance of loading form.

What I'm doing: I have loop of fields size() and checking each field type if it is MCQ(Multiple Choice Question) I have model of RadioGroup which add in ViewGroup in loop.

答:
RecyclerView my friend.

It works well with list of models

It supports having view types

It will recycler views for you, no need to worry about memory


问:
Error while decrypting file in java which is encrypted in.Net using Rijndael
I am given a Rijndael .Net encrypted file and .Net RSA XML Key and asked to decrypt it in Java.

The key provided to me is 256 bit.

I have parsed the RSA XML file and generated the public Key in Java. I tried to decrypt using the generated key, however I am getting the exception Illegal Key Size, I think I am doing something wrong in my Java code.

Can any one please help to check if anything is wrong with my code?

.Net encryption code:

```<code>public static void EncryptFile(string fileIn, string fileOut,
                                   string publicKeyName, string publicKeyFile)
    {
        try
        {
            // Read the public key from key file
            StreamReader sr = new StreamReader(publicKeyFile);
            string strKeyText = sr.ReadToEnd();
            sr.Close();

            //Initialize Key container and Crypto service provider
            RSACryptoServiceProvider rsa;
            CspParameters cspp = new CspParameters();
            cspp.KeyContainerName = publicKeyName;
            rsa = new RSACryptoServiceProvider(cspp);
            rsa.FromXmlString(strKeyText);
            rsa.PersistKeyInCsp = true;

            // Create instance of Rijndael for
            // symetric encryption of the data.
            RijndaelManaged alg = new RijndaelManaged();
            // Key size is set to 256 for strong encryption
            alg.KeySize = 256;
            alg.BlockSize = 256;
            // Cipher Mode is set to CBC to process the file in chunks
            alg.Mode = CipherMode.CBC;
            // Set padding mode to process the last block of the file
            alg.Padding = PaddingMode.ISO10126;

            ICryptoTransform transform = alg.CreateEncryptor();

            // Use RSACryptoServiceProvider to
            // enrypt the Rijndael key.
            byte[] KeyEncrypted = rsa.Encrypt(alg.Key, false);

            // Create byte arrays to contain
            // the length values of the key and IV.
            int intKeyLength = KeyEncrypted.Length;
            byte[] LenK = BitConverter.GetBytes(intKeyLength);
            int intIVLength = alg.IV.Length;
            byte[] LenIV = BitConverter.GetBytes(intIVLength);

            using (FileStream fsOut = new FileStream(fileOut, FileMode.Create))
            {
                // Write the following to the FileStream
                // for the encrypted file (fsOut):
                // - length of the key
                // - length of the IV
                // - ecrypted key
                // - the IV
                // - the encrypted cipher content
                fsOut.Write(LenK, 0, 4);
                fsOut.Write(LenIV, 0, 4);
                fsOut.Write(KeyEncrypted, 0, intKeyLength);
                fsOut.Write(alg.IV, 0, intIVLength);

                // Now write the cipher text using
                // a CryptoStream for encrypting.
                using (CryptoStream cs = new CryptoStream(fsOut, transform, CryptoStreamMode.Write))
                {
                    // intBlockSizeBytes can be any arbitrary size.
                    int intBlockSizeBytes = alg.BlockSize / 8;
                    byte[] DataBytes = new byte[intBlockSizeBytes];
                    int intBytesRead = 0;

                    using (FileStream fsIn = new FileStream(fileIn, FileMode.Open))
                    {
                        // By encrypting a chunk at
                        // a time, you can save memory
                        // and accommodate large files.
                        int intCount;
                        int intOffset = 0;

                        do
                        {
                            // if last block size is less than encryption chunk size
                            // use the last block size and padding character is used
                            // for remaining bytes
                            if (intBlockSizeBytes > (fsIn.Length - fsIn.Position))
                            {
                                intBlockSizeBytes = ((int)(fsIn.Length - fsIn.Position));
                                DataBytes = new byte[intBlockSizeBytes];
                            }
                            // read data bytes
                            intCount = fsIn.Read(DataBytes, 0, intBlockSizeBytes);
                            intOffset += intCount;
                            // write it into crypto stream
                            cs.Write(DataBytes, 0, intCount);
                            intBytesRead += intBlockSizeBytes;
                        } while (intCount > 0);
                        // close input file
                        fsIn.Close();
                    }
                    // close crypto stream
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                // close output file
                fsOut.Close();
            }
        }
        catch
        {
            throw;
        }
    }
</code>```

Java Code that I wrote to decrypt it:

```<code>    byte[] expBytes = Base64.decodeBase64(pkey.getExponentEle().trim());
    byte[] modBytes = Base64.decodeBase64(pkey.getModulusEle().trim());
    byte[] dBytes = Base64.decodeBase64(pkey.getdEle().trim());

    BigInteger modules = new BigInteger(1, modBytes);
    BigInteger exponent = new BigInteger(1, expBytes);
    BigInteger d = new BigInteger(1, dBytes);

    KeyFactory factory = KeyFactory.getInstance("RSA");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modules, exponent);
    PublicKey pubKey = factory.generatePublic(pubSpec);

    final byte[] keyData = Arrays.copyOf(pubKey.getEncoded(), 256
            / Byte.SIZE);
        final byte[] ivBytes = Arrays.copyOf(keyData, cipher.getBlockSize());
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivBytes);

        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyData, "AES"), paramSpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    System.out.println("decrypted: " + new String(decrypted));
</code>```

If I change cipher initialization to cipher.init(Cipher.DECRYPT_MODE, pubKey);, then I am getting the error Invalid AES key length: 162 bytes

答:
You are using the public key wrong way. Do you really understad how the C# program works? what parameters is it using?

You are just using the public key bits as the AES key (even I don't realy understand how do you get 162 bytes from it).

This is example of "hybrid encryption" - the data themselves are encrypted by a random AES key (in this you claim it's 256 bit) and the AES key (in this case the IV too) is encrypted by the RSA public key. In Java there are many examples how to do that.

Even to decrypt the AES key you should know parameters used to encrypt it (RSA/ECB/PKCS5Padding, RSA-AOEP, ...), though it should be inside the XML.

Comming to the parameters - you are using PKCS5Padding, but check the .NET code, it's different

Body:
I am given a Rijndael .Net encrypted file and .Net RSA XML Key and asked to decrypt it in Java.

The key provided to me is 256 bit.

I have parsed the RSA XML file and generated the public Key in Java. I tried to decrypt using the generated key, however I am getting the exception Illegal Key Size, I think I am doing something wrong in my Java code.

Can any one please help to check if anything is wrong with my code?

.Net encryption code:

public static void EncryptFile(string fileIn, string fileOut,
                                   string publicKeyName, string publicKeyFile)
    {
        try
        {
            // Read the public key from key file
            StreamReader sr = new StreamReader(publicKeyFile);
            string strKeyText = sr.ReadToEnd();
            sr.Close();

            //Initialize Key container and Crypto service provider
            RSACryptoServiceProvider rsa;
            CspParameters cspp = new CspParameters();
            cspp.KeyContainerName = publicKeyName;
            rsa = new RSACryptoServiceProvider(cspp);
            rsa.FromXmlString(strKeyText);
            rsa.PersistKeyInCsp = true;

            // Create instance of Rijndael for
            // symetric encryption of the data.
            RijndaelManaged alg = new RijndaelManaged();
            // Key size is set to 256 for strong encryption
            alg.KeySize = 256;
            alg.BlockSize = 256;
            // Cipher Mode is set to CBC to process the file in chunks
            alg.Mode = CipherMode.CBC;
            // Set padding mode to process the last block of the file
            alg.Padding = PaddingMode.ISO10126;

            ICryptoTransform transform = alg.CreateEncryptor();

            // Use RSACryptoServiceProvider to
            // enrypt the Rijndael key.
            byte[] KeyEncrypted = rsa.Encrypt(alg.Key, false);

            // Create byte arrays to contain
            // the length values of the key and IV.
            int intKeyLength = KeyEncrypted.Length;
            byte[] LenK = BitConverter.GetBytes(intKeyLength);
            int intIVLength = alg.IV.Length;
            byte[] LenIV = BitConverter.GetBytes(intIVLength);

            using (FileStream fsOut = new FileStream(fileOut, FileMode.Create))
            {
                // Write the following to the FileStream
                // for the encrypted file (fsOut):
                // - length of the key
                // - length of the IV
                // - ecrypted key
                // - the IV
                // - the encrypted cipher content
                fsOut.Write(LenK, 0, 4);
                fsOut.Write(LenIV, 0, 4);
                fsOut.Write(KeyEncrypted, 0, intKeyLength);
                fsOut.Write(alg.IV, 0, intIVLength);

                // Now write the cipher text using
                // a CryptoStream for encrypting.
                using (CryptoStream cs = new CryptoStream(fsOut, transform, CryptoStreamMode.Write))
                {
                    // intBlockSizeBytes can be any arbitrary size.
                    int intBlockSizeBytes = alg.BlockSize / 8;
                    byte[] DataBytes = new byte[intBlockSizeBytes];
                    int intBytesRead = 0;

                    using (FileStream fsIn = new FileStream(fileIn, FileMode.Open))
                    {
                        // By encrypting a chunk at
                        // a time, you can save memory
                        // and accommodate large files.
                        int intCount;
                        int intOffset = 0;

                        do
                        {
                            // if last block size is less than encryption chunk size
                            // use the last block size and padding character is used
                            // for remaining bytes
                            if (intBlockSizeBytes > (fsIn.Length - fsIn.Position))
                            {
                                intBlockSizeBytes = ((int)(fsIn.Length - fsIn.Position));
                                DataBytes = new byte[intBlockSizeBytes];
                            }
                            // read data bytes
                            intCount = fsIn.Read(DataBytes, 0, intBlockSizeBytes);
                            intOffset += intCount;
                            // write it into crypto stream
                            cs.Write(DataBytes, 0, intCount);
                            intBytesRead += intBlockSizeBytes;
                        } while (intCount > 0);
                        // close input file
                        fsIn.Close();
                    }
                    // close crypto stream
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                // close output file
                fsOut.Close();
            }
        }
        catch
        {
            throw;
        }
    }

Java Code that I wrote to decrypt it:

    byte[] expBytes = Base64.decodeBase64(pkey.getExponentEle().trim());
    byte[] modBytes = Base64.decodeBase64(pkey.getModulusEle().trim());
    byte[] dBytes = Base64.decodeBase64(pkey.getdEle().trim());

    BigInteger modules = new BigInteger(1, modBytes);
    BigInteger exponent = new BigInteger(1, expBytes);
    BigInteger d = new BigInteger(1, dBytes);

    KeyFactory factory = KeyFactory.getInstance("RSA");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modules, exponent);
    PublicKey pubKey = factory.generatePublic(pubSpec);

    final byte[] keyData = Arrays.copyOf(pubKey.getEncoded(), 256
            / Byte.SIZE);
        final byte[] ivBytes = Arrays.copyOf(keyData, cipher.getBlockSize());
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivBytes);

        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyData, "AES"), paramSpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    System.out.println("decrypted: " + new String(decrypted));

If I change cipher initialization to cipher.init(Cipher.DECRYPT_MODE, pubKey);, then I am getting the error Invalid AES key length: 162 bytes


问:
Passing UI objects as Constructor Parameters
public ContactsPanel(Activity activity,GoogleMap mGoogleMap)

I have a Class with this Constructor. This class basically inflates a UI on "activity" with Marker details when a marker is clicked on mGoogleMaps. My questions for the community are:

If I am creating 1st instance of ContactsPanel then am I forcing OS to duplicate memory allocation for the objects activity and mGoogleMap?

And what if I have 10 instances of ContactsPanel? Will that mean 10 Google Maps in memory and 10 Activities in memory? Or will all the objects will be referring to same object, that was originally created?

Thanks!

答:
I think you can you use WeakReference<> to get instance of Activity or Object and to work with

```<code> class ExampleWeakReference {
    private WeakReference<DashboardActivity> mActivityWeakReference;

    ExampleWeakReference(DashboardActivity activity) {
        mActivityWeakReference = new WeakReference<DashboardActivity>(activity);
    }

    private void doSomethingWithId() {
        DashboardActivity dashboardActivity = mActivityWeakReference.get();
        dashboardActivity.mToolbar.setBackgroundColor(Color.RED);
    }
}
</code>```

Body:
I think you can you use WeakReference<> to get instance of Activity or Object and to work with

 class ExampleWeakReference {
    private WeakReference<DashboardActivity> mActivityWeakReference;

    ExampleWeakReference(DashboardActivity activity) {
        mActivityWeakReference = new WeakReference<DashboardActivity>(activity);
    }

    private void doSomethingWithId() {
        DashboardActivity dashboardActivity = mActivityWeakReference.get();
        dashboardActivity.mToolbar.setBackgroundColor(Color.RED);
    }
}


问:
Custom cell for UICollection view cell unable clear old data
I created a custom UICollection cell but the data sometimes appear in the wrong cell and no matter how much I refresh the UICollection view it refuses to change. I have done a print out to see if the data gotten from the array is wrong but it's not. Is there a way to clear the old data from the cell before inputting the next one. Any suggestion will be appreciated.

custom cell

```<code>class customAppointmentViewCell: UICollectionViewCell {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

let thumbnailImageView: UIImageView = {
    let tniv = UIImageView()
    tniv.translatesAutoresizingMaskIntoConstraints = false
    tniv.backgroundColor = UIColor.clear
    tniv.contentMode = .scaleAspectFit
    return tniv
}()

let seperatorView: UIView = {
    let sv = UIView()
    sv.translatesAutoresizingMaskIntoConstraints = false
    sv.backgroundColor = UIColor(r: 11, g: 49, b: 68)
    return sv
}()

let clientNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let openingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let closingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let bookedBarberNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let servicePricePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 10)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .right
    return fnhp
}()

func setupViews(){
    addSubview(thumbnailImageView)
    addSubview(clientNamePlaceHolder)
    addSubview(openingTimePlaceHolder)
    addSubview(closingTimePlaceHolder)
    addSubview(bookedBarberNamePlaceHolder)
    addSubview(servicePricePlaceHolder)
    addSubview(seperatorView)
    backgroundColor = UIColor(r: 23, g: 69, b: 90)
    addContraintsWithFormat(format: "H:|-16-[v0(90)]|", views: thumbnailImageView)
    addContraintsWithFormat(format: "H:|-116-[v0][v1(50)]-10-|", views: clientNamePlaceHolder, servicePricePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: openingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: closingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)][v1(20)][v2(20)][v3(20)]-10-|", views: clientNamePlaceHolder, openingTimePlaceHolder,closingTimePlaceHolder, bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)]|", views: servicePricePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0]-10-[v1(5)]|", views: thumbnailImageView,seperatorView)
    addContraintsWithFormat(format: "H:|[v0]|", views: seperatorView)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
</code>```

collection view

```<code>extension AppointmentsViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.appointments.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! customAppointmentViewCell
    //empty cell data
    //real data

    cell.openingTimePlaceHolder.text = ""
    if let opentime = self.appointments[safe: indexPath.row]?.bookingStartTimeString {
        cell.openingTimePlaceHolder.text = opentime
    } else {
        cell.openingTimePlaceHolder.text = ""
    }

    cell.closingTimePlaceHolder.text = ""
    if let closetime = self.appointments[safe: indexPath.row]?.bookingEndTimeString {
        cell.closingTimePlaceHolder.text = closetime
    } else {
        cell.closingTimePlaceHolder.text = ""
    }

    cell.bookedBarberNamePlaceHolder.text = ""
    if let barberName = self.appointments[safe: indexPath.row]?.bookedBarberName {
        cell.bookedBarberNamePlaceHolder.text = barberName
    } else {
        cell.bookedBarberNamePlaceHolder.text = ""
    }

    cell.servicePricePlaceHolder.text = ""
    if let servicepricee = self.appointments[safe: indexPath.row]?.bookedServicePrice {
        cell.servicePricePlaceHolder.text = servicepricee
    } else {
        cell.servicePricePlaceHolder.text = ""
    }

    cell.thumbnailImageView.image = UIImage()
    if let profileimagess = self.appointments[safe: indexPath.row]?.profileImage {
        cell.thumbnailImageView.image = profileimagess
    } else {
        cell.thumbnailImageView.image = UIImage()
    }

    cell.clientNamePlaceHolder.text = ""
    if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
        cell.clientNamePlaceHolder.text = clientnamess
    } else {
        cell.clientNamePlaceHolder.text = ""
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectView.frame.width, height: 100)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let uuidAvail = UserDefaults.standard.object(forKey: "theOriginalBarberShopUUID") as? String{
        if let bookIDDD = self.appointments[safe: indexPath.row]?.bookingUniqueID {
            let orderDetail = OrderDetailViewController()
            orderDetail.specificAppintment = self.appointments[indexPath.row]
            orderDetail.barberShopID = uuidAvail
            orderDetail.bookingUniqueIDDD = bookIDDD
            orderDetail.bookedBarberUUIDAX = self.appointments[indexPath.row].bookedBarberUUID
            orderDetail.appointmentsviewhold = self
            orderDetail.indexPathSelected = indexPath.row
            navigationController?.pushViewController(orderDetail, animated: true)
        }
    }
}
}
</code>```

thanks

答:
Try this -

Implement the method prepareForReuse in your customAppointmentViewCell and in this method remove all the data and reset everything. If you are adding some subView to cell in cellForRow, remove that too.

By doing this you will be able to reduce this-

```<code>cell.clientNamePlaceHolder.text = ""
if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
    cell.clientNamePlaceHolder.text = clientnamess
} else {
    cell.clientNamePlaceHolder.text = ""
}
</code>```

to this-

```<code>if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
    cell.clientNamePlaceHolder.text = clientnamess
}
</code>```

After doing this, check if the issue is still there.

Hope this helps :)

Body:
I created a custom UICollection cell but the data sometimes appear in the wrong cell and no matter how much I refresh the UICollection view it refuses to change. I have done a print out to see if the data gotten from the array is wrong but it's not. Is there a way to clear the old data from the cell before inputting the next one. Any suggestion will be appreciated.

custom cell

class customAppointmentViewCell: UICollectionViewCell {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

let thumbnailImageView: UIImageView = {
    let tniv = UIImageView()
    tniv.translatesAutoresizingMaskIntoConstraints = false
    tniv.backgroundColor = UIColor.clear
    tniv.contentMode = .scaleAspectFit
    return tniv
}()

let seperatorView: UIView = {
    let sv = UIView()
    sv.translatesAutoresizingMaskIntoConstraints = false
    sv.backgroundColor = UIColor(r: 11, g: 49, b: 68)
    return sv
}()

let clientNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let openingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let closingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let bookedBarberNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let servicePricePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 10)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .right
    return fnhp
}()

func setupViews(){
    addSubview(thumbnailImageView)
    addSubview(clientNamePlaceHolder)
    addSubview(openingTimePlaceHolder)
    addSubview(closingTimePlaceHolder)
    addSubview(bookedBarberNamePlaceHolder)
    addSubview(servicePricePlaceHolder)
    addSubview(seperatorView)
    backgroundColor = UIColor(r: 23, g: 69, b: 90)
    addContraintsWithFormat(format: "H:|-16-[v0(90)]|", views: thumbnailImageView)
    addContraintsWithFormat(format: "H:|-116-[v0][v1(50)]-10-|", views: clientNamePlaceHolder, servicePricePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: openingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: closingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)][v1(20)][v2(20)][v3(20)]-10-|", views: clientNamePlaceHolder, openingTimePlaceHolder,closingTimePlaceHolder, bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)]|", views: servicePricePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0]-10-[v1(5)]|", views: thumbnailImageView,seperatorView)
    addContraintsWithFormat(format: "H:|[v0]|", views: seperatorView)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

collection view

extension AppointmentsViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.appointments.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! customAppointmentViewCell
    //empty cell data
    //real data

    cell.openingTimePlaceHolder.text = ""
    if let opentime = self.appointments[safe: indexPath.row]?.bookingStartTimeString {
        cell.openingTimePlaceHolder.text = opentime
    } else {
        cell.openingTimePlaceHolder.text = ""
    }

    cell.closingTimePlaceHolder.text = ""
    if let closetime = self.appointments[safe: indexPath.row]?.bookingEndTimeString {
        cell.closingTimePlaceHolder.text = closetime
    } else {
        cell.closingTimePlaceHolder.text = ""
    }

    cell.bookedBarberNamePlaceHolder.text = ""
    if let barberName = self.appointments[safe: indexPath.row]?.bookedBarberName {
        cell.bookedBarberNamePlaceHolder.text = barberName
    } else {
        cell.bookedBarberNamePlaceHolder.text = ""
    }

    cell.servicePricePlaceHolder.text = ""
    if let servicepricee = self.appointments[safe: indexPath.row]?.bookedServicePrice {
        cell.servicePricePlaceHolder.text = servicepricee
    } else {
        cell.servicePricePlaceHolder.text = ""
    }

    cell.thumbnailImageView.image = UIImage()
    if let profileimagess = self.appointments[safe: indexPath.row]?.profileImage {
        cell.thumbnailImageView.image = profileimagess
    } else {
        cell.thumbnailImageView.image = UIImage()
    }

    cell.clientNamePlaceHolder.text = ""
    if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
        cell.clientNamePlaceHolder.text = clientnamess
    } else {
        cell.clientNamePlaceHolder.text = ""
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectView.frame.width, height: 100)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let uuidAvail = UserDefaults.standard.object(forKey: "theOriginalBarberShopUUID") as? String{
        if let bookIDDD = self.appointments[safe: indexPath.row]?.bookingUniqueID {
            let orderDetail = OrderDetailViewController()
            orderDetail.specificAppintment = self.appointments[indexPath.row]
            orderDetail.barberShopID = uuidAvail
            orderDetail.bookingUniqueIDDD = bookIDDD
            orderDetail.bookedBarberUUIDAX = self.appointments[indexPath.row].bookedBarberUUID
            orderDetail.appointmentsviewhold = self
            orderDetail.indexPathSelected = indexPath.row
            navigationController?.pushViewController(orderDetail, animated: true)
        }
    }
}
}

thanks

Body:
Try this -

Implement the method prepareForReuse in your customAppointmentViewCell and in this method remove all the data and reset everything. If you are adding some subView to cell in cellForRow, remove that too.

By doing this you will be able to reduce this-

cell.clientNamePlaceHolder.text = ""
if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
    cell.clientNamePlaceHolder.text = clientnamess
} else {
    cell.clientNamePlaceHolder.text = ""
}

to this-

if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
    cell.clientNamePlaceHolder.text = clientnamess
}

After doing this, check if the issue is still there.

Hope this helps :)


问:
parsing dictionary of objects in c# Dictionary<string,object> data
I am passing following json in request body

```<code>{
  "areaId": "1",
  "cat": "2",
  "subcat": "41",
  "location": "1100",
  "sublocation": "11001",
  "briefDescription": "thissss is brief description",
  "detailedDescription": "this is detailed obj",
  "images": {
    "image1": "base64 string",
    "image2": "base64 string"
  }
}
</code>```

and my handler looks like this

```<code>[HttpPost]
public HttpResponseMessage Post(Dictionary<string,object> data)
{
    int areaId = Int32.Parse(data["areaId"].ToString()); //this is how i am getting area from it

    return Request.CreateResponse(HttpStatusCode.OK, new { some objects to return });
}
</code>```

how can I extract the images from this json in a dictionary? and what will be the efficient way of doing this

答:
As this is a JSON object, you could use a C# JSON Library, such as JSON.Net

You can use the 'Paste JSON as classes' functionality of Visual Studio to get the class structure:

```<code>public class Rootobject
{
    public string areaId { get; set; }
    public string cat { get; set; }
    public string subcat { get; set; }
    public string location { get; set; }
    public string sublocation { get; set; }
    public string briefDescription { get; set; }
    public string detailedDescription { get; set; }
    public Images images { get; set; }
}

public class Images
{
    public string image1 { get; set; }
    public string image2 { get; set; }
}
</code>```

And then use the JsonConvert.DeserializeObject method to deserialize the json to a 'RootObject' instance

If you want to treat the images as a dictionary, the following structure should  also work with json.net:

```<code>public class Rootobject
{
    public string areaId { get; set; }
    public string cat { get; set; }
    public string subcat { get; set; }
    public string location { get; set; }
    public string sublocation { get; set; }
    public string briefDescription { get; set; }
    public string detailedDescription { get; set; }
    public Dictionary<string, string> images { get; set; }
}
</code>```

Check https://www.newtonsoft.com/json/help/html/DeserializeDictionary.htm

Body:
I am passing following json in request body

{
  "areaId": "1",
  "cat": "2",
  "subcat": "41",
  "location": "1100",
  "sublocation": "11001",
  "briefDescription": "thissss is brief description",
  "detailedDescription": "this is detailed obj",
  "images": {
    "image1": "base64 string",
    "image2": "base64 string"
  }
}

and my handler looks like this

[HttpPost]
public HttpResponseMessage Post(Dictionary<string,object> data)
{
    int areaId = Int32.Parse(data["areaId"].ToString()); //this is how i am getting area from it

    return Request.CreateResponse(HttpStatusCode.OK, new { some objects to return });
}

how can I extract the images from this json in a dictionary? and what will be the efficient way of doing this

Body:
As this is a JSON object, you could use a C# JSON Library, such as JSON.Net

You can use the 'Paste JSON as classes' functionality of Visual Studio to get the class structure:

public class Rootobject
{
    public string areaId { get; set; }
    public string cat { get; set; }
    public string subcat { get; set; }
    public string location { get; set; }
    public string sublocation { get; set; }
    public string briefDescription { get; set; }
    public string detailedDescription { get; set; }
    public Images images { get; set; }
}

public class Images
{
    public string image1 { get; set; }
    public string image2 { get; set; }
}

And then use the JsonConvert.DeserializeObject method to deserialize the json to a 'RootObject' instance

If you want to treat the images as a dictionary, the following structure should  also work with json.net:

public class Rootobject
{
    public string areaId { get; set; }
    public string cat { get; set; }
    public string subcat { get; set; }
    public string location { get; set; }
    public string sublocation { get; set; }
    public string briefDescription { get; set; }
    public string detailedDescription { get; set; }
    public Dictionary<string, string> images { get; set; }
}

Check https://www.newtonsoft.com/json/help/html/DeserializeDictionary.htm


问:
How to add a class that does controls on an entire table?
in our project we have an SQL Database with a table representing all users

```<code>CREATE TABLE `user_table` (
`firstname` varchar(20) NOT NULL,
  `lastName` varchar(20) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(24) NOT NULL,
  `accessToken` varchar(64) NOT NULL,
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
)
</code>```

and we have a class UserDAO. We need to add methods such as

```<code>public boolean areUserCredentialsValid(String email, String password) {...}
public boolean isAccessTokenValid(String accessToken) {...}
public boolean isEmailInUse(String email) {...}
</code>```

I think the names are pretty self-explicative: we want to perform operations on the entire table in order to return boolean values, so we thought it may not be correct to add these methods in UserDAO, as they do not perform CRUD operations on a single User, instead they perform R-only operations on the entire User Table, so we were thinking about a new class AllUsersDAO but it does not seem convincing. What is the best solution here and why?

I don't know if we are overthinking this, but this is a project for an University course and we are evaluated especially for our software engineering abilities, so we want to be sure to adopt the best solution.

Thank you all in advance!

答:
Try to think a service class that use the UserDao for the CRUD operation.
The UserDao need to be a simple class that offer the basic operation for data access. The function you are thinking are more a Service function on the data. So try someting this:

```<code>public class UserService {

private UserDao userDao;

public boolean areUserCredentialsValid(String email, String password) {...}
public boolean isAccessTokenValid(String accessToken) {...}
public boolean isEmailInUse(String email)
}
</code>```

In addition, method like "isEmailInUse" sound to me like a DB costraint, try to look for a data check maybe is a better way instead to load 1k + Users in ram to check it.

Body:
in our project we have an SQL Database with a table representing all users

CREATE TABLE `user_table` (
`firstname` varchar(20) NOT NULL,
  `lastName` varchar(20) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(24) NOT NULL,
  `accessToken` varchar(64) NOT NULL,
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
)

and we have a class UserDAO. We need to add methods such as

public boolean areUserCredentialsValid(String email, String password) {...}
public boolean isAccessTokenValid(String accessToken) {...}
public boolean isEmailInUse(String email) {...}

I think the names are pretty self-explicative: we want to perform operations on the entire table in order to return boolean values, so we thought it may not be correct to add these methods in UserDAO, as they do not perform CRUD operations on a single User, instead they perform R-only operations on the entire User Table, so we were thinking about a new class AllUsersDAO but it does not seem convincing. What is the best solution here and why?

I don't know if we are overthinking this, but this is a project for an University course and we are evaluated especially for our software engineering abilities, so we want to be sure to adopt the best solution.

Thank you all in advance!

Body:
Try to think a service class that use the UserDao for the CRUD operation.
The UserDao need to be a simple class that offer the basic operation for data access. The function you are thinking are more a Service function on the data. So try someting this:

public class UserService {

private UserDao userDao;

public boolean areUserCredentialsValid(String email, String password) {...}
public boolean isAccessTokenValid(String accessToken) {...}
public boolean isEmailInUse(String email)
}

In addition, method like "isEmailInUse" sound to me like a DB costraint, try to look for a data check maybe is a better way instead to load 1k + Users in ram to check it.


问:
Custom loss in Keras
I'd like to implement a custom loss in Keras that takes the last affine layer as an input. This is the SGM loss described in Hariharan et al. 2017

This means that the loss function doesn't get only y_true and y_predict as parameters, but also the last affine layer. How can this be implemented in keras?

答:
You can create your own custom layer and call self.add_loss in the call method. The value should be a scalar tensor averaged across the samples in the batch. This will then be added to the usual loss function (the one that is a function of y_true and y_pred) when you compile the model. If this is not required, you also have the option of specifying loss=None.

See for example https://github.com/fchollet/keras/blob/master/examples/variational_autoencoder.py where the KL divergence is added to the Bernoulli negative log-likelihood to form the negative evidence lower bound loss for the variational autoencoder.

Title: Custom loss in Keras


问:
Declarative cache container setup — is it possible?
I'm using Wildfly 10.1.0 + Infinispan 8.2.4.Final + cache API 1.0.0 trying to enable Infinispan Jcache Interceptors in my application with minimum efforts, with no programmatic setup if possible.
I wanted to make such an annotation work to store some dictionaries:

```<code>@CacheResult(cacheName = "dictionary", cacheKeyGenerator = MyCacheKeyGeneratorImpl.class)
public List getDictionary() {
   ...
}
</code>```

I initially started this activity because I missed Spring @Cacheable annotations (we currently don't use Spring config/CDI, just a few libraries like Spring Data JPA Repositories).
So I downloaded Infinispan Wilfly/EAP module, unpacked it to Wilfly modules folder and added this to jboss-deployment-structure.xml:

```<code><jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
  <deployment>
  <dependencies>
  <module name="org.infinispan" slot="ispn-8.2" services="export"/>
  <module name="org.infinispan.cdi" slot="ispn-8.2" services="export"/>
  <module name="org.infinispan.jcache" slot="ispn-8.2" services="export"/>
  </dependencies>
  </deployment>
</jboss-deployment-structure>
</code>```

Now the annotations are processed and some default cache container is used to create "dictionary" cache. Now I want to fine-tune this cache container.
What's the common way to inject infinispan configuration? Is it possible to plug the module settings into the main Wilfly configuration file (standalone.xml) to define this cache container like this, or specify them in a separate file?

```<code><cache-container name="JCacheContainer" default-cache="default" module="org.infinispan.jcache">
  <local-cache name="default">
   <transaction mode="NONE"/>
   <eviction strategy="LRU" max-entries="1000"/>
   <expiration max-idle="3600000"/>
  </local-cache>
  <local-cache name="dictionary">
   <locking acquire-timeout="15000" isolation="REPEATABLE_READ"/>
   <transaction locking="PESSIMISTIC" mode="NONE"/>
   <eviction strategy="LRU" max-entries="100000"/>
   <expiration lifespan="15000" max-idle="15000"/>
  </local-cache>
</cache-container>
</code>```

Any help is very much appreciated.

答:
A working example of such configuration might be found in Infinispan Integration Tests. The only difference is that Infinispan is deployed inside a WAR file and not put in the modules.

All you need to do is to put infinispan.xml inside WEB-INF directory and use proper beans.xml.

Another example using Modules and CDI might be found in JBoss Data Grid Quickstarts. The only missing bit from the example is JCache.

Finally, you might find be interested in JCache documentation paragraph from Infinispan User Guide.

Body:
I'm using Wildfly 10.1.0 + Infinispan 8.2.4.Final + cache API 1.0.0 trying to enable Infinispan Jcache Interceptors in my application with minimum efforts, with no programmatic setup if possible.
I wanted to make such an annotation work to store some dictionaries:

@CacheResult(cacheName = "dictionary", cacheKeyGenerator = MyCacheKeyGeneratorImpl.class)
public List getDictionary() {
   ...
}

I initially started this activity because I missed Spring @Cacheable annotations (we currently don't use Spring config/CDI, just a few libraries like Spring Data JPA Repositories).
So I downloaded Infinispan Wilfly/EAP module, unpacked it to Wilfly modules folder and added this to jboss-deployment-structure.xml:

<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
  <deployment>
  <dependencies>
  <module name="org.infinispan" slot="ispn-8.2" services="export"/>
  <module name="org.infinispan.cdi" slot="ispn-8.2" services="export"/>
  <module name="org.infinispan.jcache" slot="ispn-8.2" services="export"/>
  </dependencies>
  </deployment>
</jboss-deployment-structure>

Now the annotations are processed and some default cache container is used to create "dictionary" cache. Now I want to fine-tune this cache container.
What's the common way to inject infinispan configuration? Is it possible to plug the module settings into the main Wilfly configuration file (standalone.xml) to define this cache container like this, or specify them in a separate file?

<cache-container name="JCacheContainer" default-cache="default" module="org.infinispan.jcache">
  <local-cache name="default">
   <transaction mode="NONE"/>
   <eviction strategy="LRU" max-entries="1000"/>
   <expiration max-idle="3600000"/>
  </local-cache>
  <local-cache name="dictionary">
   <locking acquire-timeout="15000" isolation="REPEATABLE_READ"/>
   <transaction locking="PESSIMISTIC" mode="NONE"/>
   <eviction strategy="LRU" max-entries="100000"/>
   <expiration lifespan="15000" max-idle="15000"/>
  </local-cache>
</cache-container>

Any help is very much appreciated.


问:
Ansys MPI_Init_thread: multiple pkey found / partition key table / MPI_IB_PKEY
there are problems with ansys. When I start it, it complains about some partitions. We are using slurm. Does it complain about slurm partitions, in which the jobs run? But RDMA sounds more a hard drive partition. I am a bit confused what the cause of the problem is. Access to the file system or different queues (partitions) in slurm? And how to fix it. Does any one encountered this bug before and maybe know a solution?

It is running on a slurm cluster with an NFS /home an NFS /opt (ansys install) and a BeeGFS /work dir (for models etc).

```<code>cfx5remote: Rank 0:35: MPI_Init_thread: multiple pkey found in partition key table, please choose one via MPI_IB_PKEY

cfx5remote: Rank 0:35: MPI_Init_thread: pkey table:

cfx5remote: Rank 0:35: MPI_Init_thread: 0x8001

cfx5remote: Rank 0:35: MPI_Init_thread: 0x7fff

cfx5remote: Rank 0:25: MPI_Init_thread: multiple pkey found in partition key table, please choose one via MPI_IB_PKEY

cfx5remote: Rank 0:25: MPI_Init_thread: pkey table:

cfx5remote: Rank 0:35: MPI_Init_thread: 0xffff

cfx5remote: Rank 0:25: MPI_Init_thread: 0x8001

cfx5remote: Rank 0:25: MPI_Init_thread: 0x7fff

cfx5remote: Rank 0:25: MPI_Init_thread: 0xffff

cfx5remote: Rank 0:25: MPI_Init_thread: ibv_get_pkey() failed

cfx5remote: Rank 0:21: MPI_Init_thread: multiple pkey found in partition key table, please choose one via MPI_IB_PKEY

cfx5remote: Rank 0:25: MPI_Init_thread: Can't initialize RDMA device
</code>```

答:
cfx5remote: Rank 0:25: MPI_Init_thread: multiple pkey found in partition key table, please choose one via MPI_IB_PKEY

cfx5remote: Rank 0:25: MPI_Init_thread: ibv_get_pkey() failed

-> This is infiniband/rmda, very likely totally unrelated to your file systems.

Body:
there are problems with ansys. When I start it, it complains about some partitions. We are using slurm. Does it complain about slurm partitions, in which the jobs run? But RDMA sounds more a hard drive partition. I am a bit confused what the cause of the problem is. Access to the file system or different queues (partitions) in slurm? And how to fix it. Does any one encountered this bug before and maybe know a solution?

It is running on a slurm cluster with an NFS /home an NFS /opt (ansys install) and a BeeGFS /work dir (for models etc).

cfx5remote: Rank 0:35: MPI_Init_thread: multiple pkey found in partition key table, please choose one via MPI_IB_PKEY

cfx5remote: Rank 0:35: MPI_Init_thread: pkey table:

cfx5remote: Rank 0:35: MPI_Init_thread: 0x8001

cfx5remote: Rank 0:35: MPI_Init_thread: 0x7fff

cfx5remote: Rank 0:25: MPI_Init_thread: multiple pkey found in partition key table, please choose one via MPI_IB_PKEY

cfx5remote: Rank 0:25: MPI_Init_thread: pkey table:

cfx5remote: Rank 0:35: MPI_Init_thread: 0xffff

cfx5remote: Rank 0:25: MPI_Init_thread: 0x8001

cfx5remote: Rank 0:25: MPI_Init_thread: 0x7fff

cfx5remote: Rank 0:25: MPI_Init_thread: 0xffff

cfx5remote: Rank 0:25: MPI_Init_thread: ibv_get_pkey() failed

cfx5remote: Rank 0:21: MPI_Init_thread: multiple pkey found in partition key table, please choose one via MPI_IB_PKEY

cfx5remote: Rank 0:25: MPI_Init_thread: Can't initialize RDMA device


答: All is fine, you may put that methods to dao because all this methods related to user, it's better to have dao, and separate class that get all users from dao and search through users to find already used tokens, emails and etc. </p>

Title: How to add a class that does controls on an entire table?


问:
boxplot in ggplot gives unexpected output
I would like to plot a grouped boxplot using ggplot.  Something like the picture below:

Below please see a sample (10 rows) from my data:

```<code>    alpha   colsample_bytree    best_F1
35  0.00    0.5                 0.5825656
78  0.10    0.3                 0.4716612
68  0.00    0.3                 0.4714286
27  0.40    1.0                 0.4786216
49  0.15    0.5                 0.4943968
62  0.00    0.3                 0.4938805
70  0.00    0.3                 0.4849785
73  0.10    0.3                 0.4997061
59  0.30    0.5                 0.4856369
88  0.20    0.3                 0.4552402

   sort(unique(data$alpha))
   0 0.1 0.15 0.2 0.3 0.4

   sort(unique(data$colsample_bytree))
  0.3 0.5 1
</code>```

My code is the following:

```<code>library(ggplot2)
library(ggthemes)

ggplot(data, aes(x= colsample_bytree, y = best_F1, fill = as.factor(alpha))) +

geom_boxplot(alpha = 0.5, position=position_dodge(1)) + theme_economist() +
ggtitle("F1 for alpha and colsample_bytree")
</code>```

This produces the following plot:

and the following Warning:

```<code>Warning message:
"position_dodge requires non-overlapping x intervals"
</code>```

Since the variable colsample_bytree takes 3 discrete values and the variable alpha takes 6 I would expect to see 3 groups of boxplots --each group comprised from 6 boxplots corresponding to the different alpa values and each group positioned at a different value of colsample_bytree,i.e. 0.3, 0.5 and 1.

I would expect the boxplots to not overlap just like in the example I cited.

答: You just have to include data$colsample_bytree <- as.factor(data$colsample_bytree) before you plot your data with the ggplot command.

Body:
I would like to plot a grouped boxplot using ggplot.  Something like the picture below:

Below please see a sample (10 rows) from my data:

    alpha   colsample_bytree    best_F1
35  0.00    0.5                 0.5825656
78  0.10    0.3                 0.4716612
68  0.00    0.3                 0.4714286
27  0.40    1.0                 0.4786216
49  0.15    0.5                 0.4943968
62  0.00    0.3                 0.4938805
70  0.00    0.3                 0.4849785
73  0.10    0.3                 0.4997061
59  0.30    0.5                 0.4856369
88  0.20    0.3                 0.4552402

   sort(unique(data$alpha))
   0 0.1 0.15 0.2 0.3 0.4

   sort(unique(data$colsample_bytree))
  0.3 0.5 1

My code is the following:

library(ggplot2)
library(ggthemes)

ggplot(data, aes(x= colsample_bytree, y = best_F1, fill = as.factor(alpha))) +

geom_boxplot(alpha = 0.5, position=position_dodge(1)) + theme_economist() +
ggtitle("F1 for alpha and colsample_bytree")

This produces the following plot:

and the following Warning:

Warning message:
"position_dodge requires non-overlapping x intervals"

Since the variable colsample_bytree takes 3 discrete values and the variable alpha takes 6 I would expect to see 3 groups of boxplots --each group comprised from 6 boxplots corresponding to the different alpa values and each group positioned at a different value of colsample_bytree,i.e. 0.3, 0.5 and 1.

I would expect the boxplots to not overlap just like in the example I cited.


问:
How to set default selected values in multiselect with ngModel in Angular 2
How to set default selected values in multiselect. I get current_options and all_options from database and I want to update current_options and send new values do database again.

Updating database works but when I refresh page none of options are selected.

```<code>current_options = [{id:1, name:'name1'}];                    #from database
all_options = [{id:1, name:'name1'},{id:2, name:'name2'}];   #from database
</code>```

My template:

```<code><select multiple name="type" [(ngModel)]="current_options">
    <option  *ngFor="let option of all_options" [ngValue] = "option">
        {{option.name}}
    </option>
</select>`
</code>```

答:
You should be using an array of selected items

```<code><select [(ngModel)]="selectedElement" multiple>
     <option *ngFor="let type of types" [ngValue]="type"> {{type.Name}}</option>
</select>
</code>```

My selected item will be as below

```<code>selectedElement:any= [
                {id:1,Name:'abc'},
                {id:2,Name:'abdfsdgsc'}];
</code>```

LIVE DEMO

Body:
How to set default selected values in multiselect. I get current_options and all_options from database and I want to update current_options and send new values do database again.

Updating database works but when I refresh page none of options are selected.

current_options = [{id:1, name:'name1'}];                    #from database
all_options = [{id:1, name:'name1'},{id:2, name:'name2'}];   #from database

My template:

<select multiple name="type" [(ngModel)]="current_options">
    <option  *ngFor="let option of all_options" [ngValue] = "option">
        {{option.name}}
    </option>
</select>`

Body:
You should be using an array of selected items

<select [(ngModel)]="selectedElement" multiple>
     <option *ngFor="let type of types" [ngValue]="type"> {{type.Name}}</option>
</select>

My selected item will be as below

selectedElement:any= [
                {id:1,Name:'abc'},
                {id:2,Name:'abdfsdgsc'}];

LIVE DEMO


问:
Jmeter-Beanshell -how to round up the price value
How can i round up price value in bean shell?
For example:902.7 TO 903 OR 902.0 to 902

I have written below code,But it just takes off .00 from the code,i.e. if there is 92.00,It ll remove .00.But if there is 92.37,It wont change at all

```<code>String priceAdder(String Price,double per)
{
      prcv= Float.parseFloat(Price);
      prec=per*1/100;
      prec=prcv*prec;
      if(prec>95.00)
      {
          prec=95.00;
      }
      price=prcv+prec;
      price=price.toString();
      String[] ppr=price.split("\\.");
      if(ppr[1].length()==1)
      {
          ppr[1]=ppr[1]+"0";
          price=ppr[0]+"."+ppr[1];
      }
      else
      {    //System.out.println("The value ppr[1]:"+ppr[1]);
         if(Character.getNumericValue(ppr[1].charAt(2))>=5)
         {
            Integer tadd=Integer.parseInt(ppr[1].substring(0,2))+1;
            if(tadd.toString().length()==1)
            {
                tad="0"+tadd.toString();
             }else{
                tad=tadd.toString();
             }
              price=ppr[0]+"."+tad.toString();
         }
         else
         {
            price=ppr[0]+"."+ppr[1].substring(0,2);
         }
      // price=ppr[0]+"."+ppr[1].substring(0,2);
}
 return price.toString();
}
</code>```

答:
Something like:

```<code>originalPrice = Double.parseDouble(price);
roundedPrice = Math.round(originalPrice);
return String.valueOf(roundedPrice);
</code>```

Should round your price to the nearest whole number. See Math.round() JavaDoc for more information.

Demo:

Be aware that starting from JMeter 3.1 it is recommended to use JSR223 Elements and Groovy language for any form of scripting so consider migrating to JSR223 Test Elements on next available opportunity.

Body:
How can i round up price value in bean shell?
For example:902.7 TO 903 OR 902.0 to 902

I have written below code,But it just takes off .00 from the code,i.e. if there is 92.00,It ll remove .00.But if there is 92.37,It wont change at all

String priceAdder(String Price,double per)
{
      prcv= Float.parseFloat(Price);
      prec=per*1/100;
      prec=prcv*prec;
      if(prec>95.00)
      {
          prec=95.00;
      }
      price=prcv+prec;
      price=price.toString();
      String[] ppr=price.split("\\.");
      if(ppr[1].length()==1)
      {
          ppr[1]=ppr[1]+"0";
          price=ppr[0]+"."+ppr[1];
      }
      else
      {    //System.out.println("The value ppr[1]:"+ppr[1]);
         if(Character.getNumericValue(ppr[1].charAt(2))>=5)
         {
            Integer tadd=Integer.parseInt(ppr[1].substring(0,2))+1;
            if(tadd.toString().length()==1)
            {
                tad="0"+tadd.toString();
             }else{
                tad=tadd.toString();
             }
              price=ppr[0]+"."+tad.toString();
         }
         else
         {
            price=ppr[0]+"."+ppr[1].substring(0,2);
         }
      // price=ppr[0]+"."+ppr[1].substring(0,2);
}
 return price.toString();
}

Body:
Something like:

originalPrice = Double.parseDouble(price);
roundedPrice = Math.round(originalPrice);
return String.valueOf(roundedPrice);

Should round your price to the nearest whole number. See Math.round() JavaDoc for more information.

Demo:

Be aware that starting from JMeter 3.1 it is recommended to use JSR223 Elements and Groovy language for any form of scripting so consider migrating to JSR223 Test Elements on next available opportunity.


问:
How to create a read-only entity using Jhipster?
I have an existing view in a relational database and I'd like to add it as an existing entity in the model with jhipster using jdl-import.
How can I mark the entity as readOnly using jdl-import generator?</p>

答: You can't do it in JDL nor in entity sub generator, you must do it manually in code after generation.</p>


问:
Drawing path with google direction api

I am trying to draw path between multiple places with google direction api but the problem is when I zoom the map the path is not drawn correctly.

I am hitting this api and drawing the path with 'overview_polyline' points from the response of the JSON.

https://maps.googleapis.com/maps/api/directions/json?origin=(startLocationLat),(startLocationLong)&destination=(endLocationLat),(endLocationLong)&waypoints=(self.wayPointBetweenLocations)&key=AIzaSyCK0dxRGRlFqM84SUM3zbVQAdbXEXtN-x0&mode=driving

```<code>let polygon = GMSPolygon()
polygon.path = GMSPath(fromEncodedPath: "\(self.overview_points)")
</code>```

Please help me with this.
Thank you

答: Try to use Google Maps Roads API part Snap to Roads for points from the response of the JSON.</p>

Title: Drawing path with google direction api

Body:
I am trying to draw path between multiple places with google direction api but the problem is when I zoom the map the path is not drawn correctly.

I am hitting this api and drawing the path with 'overview_polyline' points from the response of the JSON.

https://maps.googleapis.com/maps/api/directions/json?origin=(startLocationLat),(startLocationLong)&destination=(endLocationLat),(endLocationLong)&waypoints=(self.wayPointBetweenLocations)&key=AIzaSyCK0dxRGRlFqM84SUM3zbVQAdbXEXtN-x0&mode=driving

let polygon = GMSPolygon()
polygon.path = GMSPath(fromEncodedPath: "\(self.overview_points)")

Please help me with this.
Thank you