问:
Java Simple date format - dd/MM/yy v/s dd/MM/yyyy
I need to parse a String into dd/MM/YY hh:mm:ss format.

Suppose if a String has value 09/06/17 05:59:59 then it should be parsed but if a String has value 09/06/2017 05:59:59 then this is also a valid format and getting parsed but in my requirement, a parse exception should be thrown for the later.

Code:

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {

    public static void main(String[] args) {

        String line=" 09/06/17 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";
        //String line=" 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";

        String dt=null;
        dt=line.substring(1, 19);

        SimpleDateFormat org_format = new SimpleDateFormat("dd/MM/YY hh:mm:ss");
        SimpleDateFormat tgt_format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
              dt=line.substring(1, 19);

              System.out.println(dt);
              Date date = org_format.parse(dt);
              System.out.println(date);

              String tgt_date=tgt_format.format(date);
              System.out.println(tgt_date);
         } catch (ParseException e) {
              System.out.println(line);
         }
    }
}
</code>```

Problem - In the code, uncommented line variable and commented line variable, both are giving result successfully. but the commented line should throw parsable exception as it's the pattern dd/MM/yyyy, not dd/MM/yy.

fmt.setLenient(false) is not working.

I'm using Java 7. Don't have option to use Java 8 or later so can't use java.time.

答:
Don't have option to use java 8 or later so cant use java.time

The Java 8 date and time classes have been backported to Java 6 and 7, so yes, you can use them in your Java 7. Get ThreeTen Backport. This is also the futureproof investment: if and when eventually you upgrade to Java 8 or 9, you will only have to modify your import declarations and your code will work with the java.time classes.

So I recommend you throw the outdated classes SimpleDateFormat and Date over the shoulder. It’s very typical for SimpleDateFormat to give you a result (very often an incorrect one) in a situation where you would want an exception. As you noted, sometimes org_format.setLenient(false); helps, but not in your case.

Using ThreeTen Backport:

```<code>    DateTimeFormatter originalFormat = DateTimeFormatter.ofPattern("dd/MM/uu HH:mm:ss");
    ParsePosition pos = new ParsePosition(1); // skip leading space
    LocalDateTime ldt = LocalDateTime.from(originalFormat.parse(line, pos));
</code>```

This parses your line with 2-digit year into

```<code>2017-01-02 05:59:59
</code>```

For the line with 4-digit year for which “in my requirement, parse exception should be thrown”, we get

Exception in thread "main" java.time.format.DateTimeParseException:
  Text ' 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD
  ...' could not be parsed at index 9

It says index 9, that’s at the 17 in 2017, that is, exactly where the third digit of the year is when there were only supposed to be two digits.

A couple of points to be aware of:

Use capital HH in the format pattern for hour of day (small hh is for hour with AM or PM, only useful with an AM/PM marler). Use lowercase for the year, either uu or yy (not uppercase YY, it’s for weekbased year, only useful with a week number). BTW, again SimpleDateFormat let you get away with these bugs and will sometimes give you incorrect results; the modern classes will object by throwing an exception.

My code will parse into a year from 2000 through 2099. Please check whether this is what you want. You may want to impose an additional restriction, for example, that the date-time should be in the past and not more than 5 years ago, for enhanced validation. You know better than I.

To convert into your target format:

```<code>    DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String targetDate = ldt.format(targetFormat);
</code>```

With the former of your lines the result is

```<code>2017-01-02 05:59:59
</code>```

Body:
I need to parse a String into dd/MM/YY hh:mm:ss format.

Suppose if a String has value 09/06/17 05:59:59 then it should be parsed but if a String has value 09/06/2017 05:59:59 then this is also a valid format and getting parsed but in my requirement, a parse exception should be thrown for the later.

Code:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {

    public static void main(String[] args) {

        String line=" 09/06/17 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";
        //String line=" 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";

        String dt=null;
        dt=line.substring(1, 19);

        SimpleDateFormat org_format = new SimpleDateFormat("dd/MM/YY hh:mm:ss");
        SimpleDateFormat tgt_format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
              dt=line.substring(1, 19);

              System.out.println(dt);
              Date date = org_format.parse(dt);
              System.out.println(date);

              String tgt_date=tgt_format.format(date);
              System.out.println(tgt_date);
         } catch (ParseException e) {
              System.out.println(line);
         }
    }
}

Problem - In the code, uncommented line variable and commented line variable, both are giving result successfully. but the commented line should throw parsable exception as it's the pattern dd/MM/yyyy, not dd/MM/yy.

fmt.setLenient(false) is not working.

I'm using Java 7. Don't have option to use Java 8 or later so can't use java.time.

Body:
Don't have option to use java 8 or later so cant use java.time

The Java 8 date and time classes have been backported to Java 6 and 7, so yes, you can use them in your Java 7. Get ThreeTen Backport. This is also the futureproof investment: if and when eventually you upgrade to Java 8 or 9, you will only have to modify your import declarations and your code will work with the java.time classes.

So I recommend you throw the outdated classes SimpleDateFormat and Date over the shoulder. It’s very typical for SimpleDateFormat to give you a result (very often an incorrect one) in a situation where you would want an exception. As you noted, sometimes org_format.setLenient(false); helps, but not in your case.

Using ThreeTen Backport:

    DateTimeFormatter originalFormat = DateTimeFormatter.ofPattern("dd/MM/uu HH:mm:ss");
    ParsePosition pos = new ParsePosition(1); // skip leading space
    LocalDateTime ldt = LocalDateTime.from(originalFormat.parse(line, pos));

This parses your line with 2-digit year into

2017-01-02 05:59:59

For the line with 4-digit year for which “in my requirement, parse exception should be thrown”, we get

Exception in thread "main" java.time.format.DateTimeParseException:
  Text ' 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD
  ...' could not be parsed at index 9

It says index 9, that’s at the 17 in 2017, that is, exactly where the third digit of the year is when there were only supposed to be two digits.

A couple of points to be aware of:

Use capital HH in the format pattern for hour of day (small hh is for hour with AM or PM, only useful with an AM/PM marler). Use lowercase for the year, either uu or yy (not uppercase YY, it’s for weekbased year, only useful with a week number). BTW, again SimpleDateFormat let you get away with these bugs and will sometimes give you incorrect results; the modern classes will object by throwing an exception.

My code will parse into a year from 2000 through 2099. Please check whether this is what you want. You may want to impose an additional restriction, for example, that the date-time should be in the past and not more than 5 years ago, for enhanced validation. You know better than I.

To convert into your target format:

    DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String targetDate = ldt.format(targetFormat);

With the former of your lines the result is

2017-01-02 05:59:59


来源: stackexchange

问:
Yii GridView: Highlight Row Based on Condition
We have a timetable application in our school. We are looking to expand its functionality.

Currently when a class code is searched we get a list of students in that class. We have created a new model for our database that has a list of students with medical requirements.

We'd like the Gridview in our timetable view to highlight the students with a record in our medical table. We are just unsure how to go about this we've never had to highlight in gridview based on a condition.

timetable model;

```<code>public function rules()
    {
        return [
            [['ttLastName', 'ttFirstName', 'ttYearLevel', 'stuId', 'ttClassId'], 'required'],
            [['ttYearLevel'], 'integer'],
            [['ttLastName', 'ttFirstName', 'stId', 'ttClassId'], 'string', 'max' => 255],
            [['stuId'], 'exist', 'skipOnError' => true, 'targetClass' => Student::className(), 'targetAttribute' => ['stuId' => 'stuId']],
        ];
    }
</code>```

medical model;

```<code> public function rules()
    {
        return [
            [['amCreatedAt', 'amBackGround', 'amStrategies', 'amCreatedBy'], 'required'],
            [['amCreatedBy', 'stuId'], 'integer'],
            [['amCreatedAt'], 'string', 'max' => 100],
            [['amBackGround', 'amStrategies'], 'string'],
            [['stuId'], 'exist', 'skipOnError' => true, 'targetClass' => Student::className(), 'targetAttribute' => ['stuId' => 'stuId']],
        ];
    }
</code>```

timetable gridview;

```<code><?= GridView::widget([
        'dataProvider' => $dataProvider,

        //'filterModel' => $searchModel,
        'columns' => [
            //['class' => 'yii\grid\SerialColumn'],

            'ttLastName',
            'ttFirstName',
            'ttYearLevel',
            'bceId',
            'ttClassId',

            // 'ttClassId',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</code>```

Any help would be appreciated, we don't need the full code just an explanation on how to approach it.

Thank you

答:
You can ccustomize rowOptions property of GridView to add a class for grid row. Then add css to that class to have a background color

```<code><?= GridView::widget([
    'dataProvider' => $dataProvider,

    //'filterModel' => $searchModel,
    'rowOptions' => function ($model, $key, $index, $grid) {
        // $model is the current data model being rendered
        // check your condition in the if like `if($model->hasMedicalRecord())` which could be a method of model class which checks for medical records.
        if() {
             return ['class' => 'highlighted_grid_row'];
        }
        return [];
    }
    'columns' => [
        //['class' => 'yii\grid\SerialColumn'],

        'ttLastName',
        'ttFirstName',
        'ttYearLevel',
        'bceId',
        'ttClassId',

        // 'ttClassId',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We have a timetable application in our school. We are looking to expand its functionality.

Currently when a class code is searched we get a list of students in that class. We have created a new model for our database that has a list of students with medical requirements.

We'd like the Gridview in our timetable view to highlight the students with a record in our medical table. We are just unsure how to go about this we've never had to highlight in gridview based on a condition.

timetable model;

public function rules()
    {
        return [
            [['ttLastName', 'ttFirstName', 'ttYearLevel', 'stuId', 'ttClassId'], 'required'],
            [['ttYearLevel'], 'integer'],
            [['ttLastName', 'ttFirstName', 'stId', 'ttClassId'], 'string', 'max' => 255],
            [['stuId'], 'exist', 'skipOnError' => true, 'targetClass' => Student::className(), 'targetAttribute' => ['stuId' => 'stuId']],
        ];
    }

medical model;

 public function rules()
    {
        return [
            [['amCreatedAt', 'amBackGround', 'amStrategies', 'amCreatedBy'], 'required'],
            [['amCreatedBy', 'stuId'], 'integer'],
            [['amCreatedAt'], 'string', 'max' => 100],
            [['amBackGround', 'amStrategies'], 'string'],
            [['stuId'], 'exist', 'skipOnError' => true, 'targetClass' => Student::className(), 'targetAttribute' => ['stuId' => 'stuId']],
        ];
    }

timetable gridview;

<?= GridView::widget([
        'dataProvider' => $dataProvider,

        //'filterModel' => $searchModel,
        'columns' => [
            //['class' => 'yii\grid\SerialColumn'],

            'ttLastName',
            'ttFirstName',
            'ttYearLevel',
            'bceId',
            'ttClassId',

            // 'ttClassId',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

Any help would be appreciated, we don't need the full code just an explanation on how to approach it.

Thank you

Body:
You can ccustomize rowOptions property of GridView to add a class for grid row. Then add css to that class to have a background color

<?= GridView::widget([
    'dataProvider' => $dataProvider,

    //'filterModel' => $searchModel,
    'rowOptions' => function ($model, $key, $index, $grid) {
        // $model is the current data model being rendered
        // check your condition in the if like `if($model->hasMedicalRecord())` which could be a method of model class which checks for medical records.
        if() {
             return ['class' => 'highlighted_grid_row'];
        }
        return [];
    }
    'columns' => [
        //['class' => 'yii\grid\SerialColumn'],

        'ttLastName',
        'ttFirstName',
        'ttYearLevel',
        'bceId',
        'ttClassId',

        // 'ttClassId',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>


问:
How to play the audio again after completing the audio?
I am facing the issue in playing the same audio after completing the audio. In my case i am using the play and pause function in a single button. When mediaplayer is playing the pause icon is visible ,when the audio is paused the play icon is visible.My problem is after audio is finished palying the audio, the mediaplayer seekbar should be in starting point of the audio and play button should be visible. How can i do this.

I tried mediaPlayer.setLooping(true);   but the after completing the audio it starts again but pause icon is visible and audio is playing continiously.

also i tried `

```<code>   mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
      //     mediaPlayer.seekTo((int) startTime);
            stop.setVisibility(View.GONE);
            play.setVisibility(View.VISIBLE);
            seekBar.setProgress((int) startTime);
        }
    });
</code>```

In this method it shows only the mediaplayer completing state.

My Requirement is after completing the audio the mediaplayer  should  be in initial state and in pause condition. If audio is pause means the play icon should be visible.

In above image while playing the audio the pause image is visible, while in pause condition the play icon will be visible. When the audio is completed the seekbar position should be in starting point and audio should be pause condition.How to do this please help me.

答:
```<code>mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    //     mediaPlayer.seekTo((int) startTime);
    //                stop.setVisibility(View.GONE);
    //                play.setVisibility(View.VISIBLE);
    //                seekBar.setProgress((int) startTime);

                    seekBar.setProgress(0);

                    if (mediaPlayer.isPlaying()){
                        stop.setVisibility(View.VISIBLE);
                        play.setVisibility(View.GONE);
                    }else {
                        stop.setVisibility(View.GONE);
                        play.setVisibility(View.VISIBLE);
                    }
                }
            });
</code>```

I hope it's helpful to you ..!

Body:
I am facing the issue in playing the same audio after completing the audio. In my case i am using the play and pause function in a single button. When mediaplayer is playing the pause icon is visible ,when the audio is paused the play icon is visible.My problem is after audio is finished palying the audio, the mediaplayer seekbar should be in starting point of the audio and play button should be visible. How can i do this.

I tried mediaPlayer.setLooping(true);   but the after completing the audio it starts again but pause icon is visible and audio is playing continiously.

also i tried `

   mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
      //     mediaPlayer.seekTo((int) startTime);
            stop.setVisibility(View.GONE);
            play.setVisibility(View.VISIBLE);
            seekBar.setProgress((int) startTime);
        }
    });

In this method it shows only the mediaplayer completing state.

My Requirement is after completing the audio the mediaplayer  should  be in initial state and in pause condition. If audio is pause means the play icon should be visible.

In above image while playing the audio the pause image is visible, while in pause condition the play icon will be visible. When the audio is completed the seekbar position should be in starting point and audio should be pause condition.How to do this please help me.

Body:
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    //     mediaPlayer.seekTo((int) startTime);
    //                stop.setVisibility(View.GONE);
    //                play.setVisibility(View.VISIBLE);
    //                seekBar.setProgress((int) startTime);

                    seekBar.setProgress(0);

                    if (mediaPlayer.isPlaying()){
                        stop.setVisibility(View.VISIBLE);
                        play.setVisibility(View.GONE);
                    }else {
                        stop.setVisibility(View.GONE);
                        play.setVisibility(View.VISIBLE);
                    }
                }
            });

I hope it's helpful to you ..!


问:
Name clash from implementing interface
I have spent a few hours reading Java documentation/Stackoverflow answers on generics and type erasure but I still don't understand the topic fully.
The problem is implementing the following simple interface:

```<code>public interface Stack {
void push(Object element); }
</code>```

I have implemented this in a simple generic class:

```<code>public class NodeStack<T> implements Stack {
private Node<T> top;
private int size;

public void push(T value) {
    if(this.size == 0) {
        this.top = new Node<>(value, null);
    } else {
        this.top = new Node<>(value, this.top);
    }
    this.size++;}
}
</code>```

When I attempt to compile this I get the compiler error messages:

```<code>NodeStack.java:10: error: NodeStack is not abstract and does not override abstract method push(Object) in Stack
public class NodeStack<T> implements Stack {
   ^
NodeStack.java:63: error: name clash: push(T) in NodeStack and push(Object) in Stack have the same erasure, yet neither overrides the other

    public void push(T value) {
                ^
where T is a type-variable:
    T extends Object declared in class NodeStack
2 errors
</code>```

I think this problem occurs because of type erasure - the push method in the class and the push method in the interface have the same signature after type erasure. What I don't understand is why this would be a problem. The push method implementation should have the same signature as the interface method, right? What am I missing here? Any help is greatly appreciated.

答:
The push method in the class and the push method in the interface have
  the same signature after type erasure.

This as I understand it, is the crux of the problem.

Your class is clashing it's method signature with that of the interface, but the method signature of the class at a source level is much more strict/defined then the object type on the interface. So they both don't match before, as well as matching afterwards due to erasure, so you get a compile error.

It could get objects, other then subtypes of T passed to it, and it wouldn't be able to deal with it, yet the interface says it's fine at a source level.

Even if this would work, it would be a bad idea, as the interface says it can accept any object, when the implementation can only take types of T.

If we allowed this to work, you could potentially store and get a string into a Stack<Integer> by using the interface method, then elsewhere a reference to Stack<Integer>  would end up getting a String, breaking type safety.

Title: Name clash from implementing interface

Body:
I have spent a few hours reading Java documentation/Stackoverflow answers on generics and type erasure but I still don't understand the topic fully.
The problem is implementing the following simple interface:

public interface Stack {
void push(Object element); }

I have implemented this in a simple generic class:

public class NodeStack<T> implements Stack {
private Node<T> top;
private int size;

public void push(T value) {
    if(this.size == 0) {
        this.top = new Node<>(value, null);
    } else {
        this.top = new Node<>(value, this.top);
    }
    this.size++;}
}

When I attempt to compile this I get the compiler error messages:

NodeStack.java:10: error: NodeStack is not abstract and does not override abstract method push(Object) in Stack
public class NodeStack<T> implements Stack {
   ^
NodeStack.java:63: error: name clash: push(T) in NodeStack and push(Object) in Stack have the same erasure, yet neither overrides the other

    public void push(T value) {
                ^
where T is a type-variable:
    T extends Object declared in class NodeStack
2 errors

I think this problem occurs because of type erasure - the push method in the class and the push method in the interface have the same signature after type erasure. What I don't understand is why this would be a problem. The push method implementation should have the same signature as the interface method, right? What am I missing here? Any help is greatly appreciated.

ContentLicense: CC BY-SA 4.0


问:
How to retrieve the value stored in localstorage?
```<code>var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
        $checkboxes = $("#list :checkbox");

    $checkboxes.on("change", function(){
        $checkboxes.each(function(){
            checkboxValues[this.id] = this.checked;
        });
        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });
</code>```

I am using the code above to store the data into local storage.

```<code>{"2":false,"3":false,"4":true}
</code>```

The data stored in the local storage. How can i get only the value 2 or false?
I want to collect the data in the local storage and stored into an array during submit the form.

```<code>var items=[];
$.each(checkboxValues, function(key, value) {
            if(value===true){
                $("#" + key).prop('checked', value);
                items.push(key);
            }
        });
</code>```

The code seem like got problem during submit which caused integrity constraint duplicate entry when store the data to database. I am using ajax to post the data to server and store the data. Is there anything wrong with my code?

答:
Use the below code to access the checkboxValues object. You need to parse it.

```<code>var obj = JSON.parse(localStorage.getItem("checkboxValues"));
</code>```

To access "2", use obj["2"].

```<code>var obj = {"2":false,"3":false,"4":true};
localStorage.setItem('checkboxValues',JSON.stringify(obj));
var storedObject = JSON.parse(localStorage.getItem('checkboxValues'));
console.log(storedObject["2"]);
</code>```

Body:
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
        $checkboxes = $("#list :checkbox");

    $checkboxes.on("change", function(){
        $checkboxes.each(function(){
            checkboxValues[this.id] = this.checked;
        });
        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });

I am using the code above to store the data into local storage.

{"2":false,"3":false,"4":true}

The data stored in the local storage. How can i get only the value 2 or false?
I want to collect the data in the local storage and stored into an array during submit the form.

var items=[];
$.each(checkboxValues, function(key, value) {
            if(value===true){
                $("#" + key).prop('checked', value);
                items.push(key);
            }
        });

The code seem like got problem during submit which caused integrity constraint duplicate entry when store the data to database. I am using ajax to post the data to server and store the data. Is there anything wrong with my code?

Body:
Use the below code to access the checkboxValues object. You need to parse it.

var obj = JSON.parse(localStorage.getItem("checkboxValues"));

To access "2", use obj["2"].

var obj = {"2":false,"3":false,"4":true};
localStorage.setItem('checkboxValues',JSON.stringify(obj));
var storedObject = JSON.parse(localStorage.getItem('checkboxValues'));
console.log(storedObject["2"]);


问:
type mismatch in kotlin
I'm newbie to Kotlin language and Object Oriented Programming, so I wonder why  there's a wrong type of instance of the class inherited from class Fragment() in android. These are my codes

Fragment.kt

```<code> class MyFragment: Fragment() {
 //do something
 }
</code>```

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {
val fm : Fragment? = MyFragment()
...
}
</code>```

Why fm return MyFragment type, not Fragment? ??
Thank you

答:
Use

```<code> changeFragment(MyFragment())
</code>```

method should be like this

```<code>    fun changeFragment(f: Fragment, cleanStack: Boolean = false) {
    val ft = supportFragmentManager.beginTransaction();
    if (cleanStack) {
        clearBackStack();
    }
    ft.replace(R.id.activity_base_content, f);
    ft.addToBackStack(null);
    ft.commit();
   }

    fun clearBackStack() {
    val manager = supportFragmentManager;
    if (manager.backStackEntryCount > 0) {
        val first = manager.getBackStackEntryAt(0);
        manager.popBackStack(first.id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
     }
     }
</code>```

Title: type mismatch in kotlin

Body:
I'm newbie to Kotlin language and Object Oriented Programming, so I wonder why  there's a wrong type of instance of the class inherited from class Fragment() in android. These are my codes

Fragment.kt

 class MyFragment: Fragment() {
 //do something
 }

MainActivity.kt

class MainActivity : AppCompatActivity() {
val fm : Fragment? = MyFragment()
...
}

Why fm return MyFragment type, not Fragment? ??
Thank you

Body:
Use

 changeFragment(MyFragment())

method should be like this

    fun changeFragment(f: Fragment, cleanStack: Boolean = false) {
    val ft = supportFragmentManager.beginTransaction();
    if (cleanStack) {
        clearBackStack();
    }
    ft.replace(R.id.activity_base_content, f);
    ft.addToBackStack(null);
    ft.commit();
   }

    fun clearBackStack() {
    val manager = supportFragmentManager;
    if (manager.backStackEntryCount > 0) {
        val first = manager.getBackStackEntryAt(0);
        manager.popBackStack(first.id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
     }
     }


问:
DataContractJsonSerializer Date Serialization
Is there a way to change how the DataContractJsonSerializer serializes dates?

Currently, it'll convert a date to something like:

{
  "date": "/Date(1260597600000-0600)/"
}

I want to convert it into human readable date format.

I am building a RestApi using openrasta framework. Can i write OperationInterceptors which will at some stage before serialization/deserialization convert JSON datetime format to something which is human readable?Or is there any other way to do it?

答:
Use DataContractJsonSerializer constructor to pass your serialization settings:</p>

```<code>    var s = new DataContractJsonSerializer(
            typeof(YourTypeToSerialize),
            new DataContractJsonSerializerSettings
            {
                DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
            }
        );
</code>```

Body:
Use DataContractJsonSerializer constructor to pass your serialization settings:

    var s = new DataContractJsonSerializer(
            typeof(YourTypeToSerialize),
            new DataContractJsonSerializerSettings
            {
                DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
            }
        );


问:
API architecture
I am in the process of designing an API. I would like to know if what I have come up with is a good solution:

I have a respository type of data layer that talks to a database by converting business classes into entities(generated from LLBL GEN, I didn't want to use the entities directly as my business objects because I wanted to keep them simple and allow me to swap out to Entity Framework or some other mapper is I needed to)

I have a WCF service layer that I'm using as a type of facade. It calls the respository layer and converts the business objects to DTOs and passes them through the API service call via a message to the client. The client can be an ASPX website, Silverlight app, WPF app, or even a WP7 app. The problem I keep runnnig into is when I want to run business logic I have to send the DTO back to the WCF service and then back to the client. This doesn't seem "right" to me. I can't put business logic in the DTO because that defeats the purpose. But if I want business type code to run on the client I have a lot of duplication of code throughout my different clients.

My business layer does not know of the data layer, my data layer knows of the business layer and my facade layer knows of the data layer and the business layer and the DTOs. Is this a bad design for an API? And can anyone offer me any suggestions? I have only learned of enterprise level apps through reading different articles online.

Thanks!

答:
Relations between layers

If I understand your design well, the business layer does not know of (=does not use) the data layer, and the facade actually interconnects them by translating DAOs into DTOs and vice-versa.

You should consider a rather different approach: Define interfaces for all data-related objects (regardless if DAOs or DTOs) and use an Inversion-of-Control container to weave the business layer and data access layer together. The reason is that in your design you might quickly run into the inability to retrieve additional data in right in the business layer. You'd end up with the facade substituting this lack and hence doing too much actual business logic.

In case you make a clear connection between the business layer and the underlying data layer, while separating them with well-designed interfaces and an IoC container, you prevent this problem while maintaining good and concise internal design.

Usage of DTOs

I think it's alright that you have to pass the DTOs back to the back-end of your app. In your case the purpose of DTOs is (1) to supply information for the presentation layer, and (2) to provide a way of passing modified or new data to the back-end for further processing. DTOs for cases (1) and (2) need not be the same. Hence if it makes sense, you can pass to the back-end just a DTO representing a subset of the whole information.

However, the back-end shall return a new DTO after processing, which, again, needs not to be the same DTO as the input DTO. This way the presentation layer can easily adapt to changes made by the back-end into related parts of the whole object.

Imagine a simple Get / Update API such as this one:

```<code>CustomerDTO GetCustomer(int customerID);

CustomerDTO UpdateCustomerAddress(int customerID, AddressDTO address);

CustomerDTO UpdateCustomerPrimaryContact(int customerID, PersonDTO primaryContact);
</code>```

You are using an ID to identify a customer and passing in a DTO that represents a subset of the customer record to be updated (regardless of the underlying data architecture). The out DTO represents the customer as a whole, simplifying the presentation-layer's task of updating the information shown to the user. The advantage is the back-end does not need to know which subset of customer data the presentation layer actually needs, and the presentation layer can pass the back-end only those parts that were really modified.

Update — technical note: Consider using a tool like AutoMapper (C#) to automate translations between DTOs and DAOs. While this matter is a subject of technology used, generally this approach saves a lot of manual work and is able to eliminate hard-to-discover bugs. Having such an object translation automation in place helps promote better design practices and allows you to produce more-specialized and hence semantically more accurate DTOs.

Disclaimer: While this is a rather general question, my recommendations may not seem right in respect to further details of your application which are not covered in your question.

ContentLicense: CC BY-SA 2.5

Title: API architecture

Body:
Relations between layers

If I understand your design well, the business layer does not know of (=does not use) the data layer, and the facade actually interconnects them by translating DAOs into DTOs and vice-versa.

You should consider a rather different approach: Define interfaces for all data-related objects (regardless if DAOs or DTOs) and use an Inversion-of-Control container to weave the business layer and data access layer together. The reason is that in your design you might quickly run into the inability to retrieve additional data in right in the business layer. You'd end up with the facade substituting this lack and hence doing too much actual business logic.

In case you make a clear connection between the business layer and the underlying data layer, while separating them with well-designed interfaces and an IoC container, you prevent this problem while maintaining good and concise internal design.

Usage of DTOs

I think it's alright that you have to pass the DTOs back to the back-end of your app. In your case the purpose of DTOs is (1) to supply information for the presentation layer, and (2) to provide a way of passing modified or new data to the back-end for further processing. DTOs for cases (1) and (2) need not be the same. Hence if it makes sense, you can pass to the back-end just a DTO representing a subset of the whole information.

However, the back-end shall return a new DTO after processing, which, again, needs not to be the same DTO as the input DTO. This way the presentation layer can easily adapt to changes made by the back-end into related parts of the whole object.

Imagine a simple Get / Update API such as this one:

CustomerDTO GetCustomer(int customerID);

CustomerDTO UpdateCustomerAddress(int customerID, AddressDTO address);

CustomerDTO UpdateCustomerPrimaryContact(int customerID, PersonDTO primaryContact);

You are using an ID to identify a customer and passing in a DTO that represents a subset of the customer record to be updated (regardless of the underlying data architecture). The out DTO represents the customer as a whole, simplifying the presentation-layer's task of updating the information shown to the user. The advantage is the back-end does not need to know which subset of customer data the presentation layer actually needs, and the presentation layer can pass the back-end only those parts that were really modified.

Update — technical note: Consider using a tool like AutoMapper (C#) to automate translations between DTOs and DAOs. While this matter is a subject of technology used, generally this approach saves a lot of manual work and is able to eliminate hard-to-discover bugs. Having such an object translation automation in place helps promote better design practices and allows you to produce more-specialized and hence semantically more accurate DTOs.

Disclaimer: While this is a rather general question, my recommendations may not seem right in respect to further details of your application which are not covered in your question.


问:
What is {{$guid}} used for in Postman?
Postman's official website states that Postman has a few dynamic variables. My question is about:

{{$guid}}: Adds a v4 style guid

What kind of variable is {{$guid}}? How can it be used in test scripts for API requests?

答:
In Postman there are Two types of variable available.

1). If you have static variable like Ip, Port or Something who doesn't change through the project you can store into the Environments Variable using

1.1). Setting > Manage Environment > Add > Name of Environment > Add Parameters Like >In Key : Port and In Value : 80

1.2). You can also add in request > Pre-request Script

add "Set an environment variable " from snippet...

postman.setEnvironmentVariable("Port", "80");

2). for Dynamic Variable like  SessionIdentifier.You have to capture from response and add in Test set a global variable from snippet it looks like

"var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("SessionIdentifier", jsonData.Data.);"

in the same response.
For use, you should {{Port}},{{SessionIdentifier}}.

After it added into the Environments.

Title: What is {{$guid}} used for in Postman?


问:
Selenium problems
I'm clicking the date box, clearing the values and requesting for new data. I'm trying to click the date field, but I don't see the calendar pop up as it should. How can i go about this? </p>

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox(executable_path='/home/usch/Desktop/PyCharm/Project/geckodriver')

#load up website
driver.get('https://www.fxstreet.com/economic-calendar')

time.sleep(10)

#close popup
popup = driver.find_element_by_xpath('//button[@aria-label="Close Modal"]')
popup.click()

#click filter options
filter = driver.find_element_by_id('fxit-advlink')
filter.click()

#set start and end time
startDate = driver.find_element_by_xpath("//input[contains(@id,'fxit-start-advanced')]")
startDate.send_keys(Keys.ENTER)
startDate.clear()
startDate.send_keys("01/02/2017")
startDate.send_keys(Keys.ENTER)

endDate = driver.find_element_by_xpath("//input[contains(@id,'fxit-end-advanced')]")
endDate.send_keys(Keys.ENTER)
endDate.clear()
endDate.send_keys("06/01/2017")
endDate.send_keys(Keys.ENTER)

#driver.switch_to.default_content()
#select countries

#select data type
category = driver.find_element_by_xpath('//a[@class="fxst-selectall" and @data-name="fxst-category"]').click()

#refresh your results
refresh = driver.find_element_by_xpath('//a[@id="fxit-filterbutton"]').click()
</code>```

答:
The problem is with the locator as when you try to run the above code it throws error "element not clickable other element would receive click"

Just add  execute_script() in your code it will work

Also never use a reserved keyword in your coding as filter is a keyword in python

```<code>filter1 = driver.find_element_by_css_selector('#fxit-advlink')
driver.execute_script("arguments[0].click();", filter1)

category = driver.find_element_by_xpath('//a[@class="fxst-selectall" and @data-name="fxst-category"]')
driver.execute_script("arguments[0].click();", category)

#refresh your results
refresh = driver.find_element_by_xpath('//a[@id="fxit-filterbutton"]')
driver.execute_script("arguments[0].click();", refresh)
</code>```

Title: Selenium problems

Body:
I'm clicking the date box, clearing the values and requesting for new data. I'm trying to click the date field, but I don't see the calendar pop up as it should. How can i go about this?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox(executable_path='/home/usch/Desktop/PyCharm/Project/geckodriver')

#load up website
driver.get('https://www.fxstreet.com/economic-calendar')

time.sleep(10)

#close popup
popup = driver.find_element_by_xpath('//button[@aria-label="Close Modal"]')
popup.click()

#click filter options
filter = driver.find_element_by_id('fxit-advlink')
filter.click()

#set start and end time
startDate = driver.find_element_by_xpath("//input[contains(@id,'fxit-start-advanced')]")
startDate.send_keys(Keys.ENTER)
startDate.clear()
startDate.send_keys("01/02/2017")
startDate.send_keys(Keys.ENTER)

endDate = driver.find_element_by_xpath("//input[contains(@id,'fxit-end-advanced')]")
endDate.send_keys(Keys.ENTER)
endDate.clear()
endDate.send_keys("06/01/2017")
endDate.send_keys(Keys.ENTER)

#driver.switch_to.default_content()
#select countries

#select data type
category = driver.find_element_by_xpath('//a[@class="fxst-selectall" and @data-name="fxst-category"]').click()

#refresh your results
refresh = driver.find_element_by_xpath('//a[@id="fxit-filterbutton"]').click()

Body:
The problem is with the locator as when you try to run the above code it throws error "element not clickable other element would receive click"

Just add  execute_script() in your code it will work

Also never use a reserved keyword in your coding as filter is a keyword in python

filter1 = driver.find_element_by_css_selector('#fxit-advlink')
driver.execute_script("arguments[0].click();", filter1)

category = driver.find_element_by_xpath('//a[@class="fxst-selectall" and @data-name="fxst-category"]')
driver.execute_script("arguments[0].click();", category)

#refresh your results
refresh = driver.find_element_by_xpath('//a[@id="fxit-filterbutton"]')
driver.execute_script("arguments[0].click();", refresh)


问:
how to centering the image and text inside layout android
```<code> <TextView
    android:id="@+id/tv_connStatus"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_gravity="center"
    android:background="#C5CAE9"
    android:drawableLeft="@drawable/circle_gr"
    android:gravity="center|left"
    android:padding="5dp"
    android:text="TextView"
    android:textStyle="bold" />
</code>```

I tried both center but image goes left for me . I want image and text in center inside text view

答:
I centering the image and text by gravity center and wrap the height and width in text view</p>

```<code><LinearLayout
        android:id="@+id/ll_chatconnectionStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_chatconnectionStatus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@color/sandal_color"
            android:drawablePadding="5dp"
            android:drawableStart="@drawable/circle_bl"
            android:hint="@string/connection_status"
            android:padding="5dp"
            android:textColor="@color/blacktext"
            android:textStyle="bold" />
    </LinearLayout>
</code>```

Body:
 <TextView
    android:id="@+id/tv_connStatus"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_gravity="center"
    android:background="#C5CAE9"
    android:drawableLeft="@drawable/circle_gr"
    android:gravity="center|left"
    android:padding="5dp"
    android:text="TextView"
    android:textStyle="bold" />

I tried both center but image goes left for me . I want image and text in center inside text view

Body:
I centering the image and text by gravity center and wrap the height and width in text view

<LinearLayout
        android:id="@+id/ll_chatconnectionStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_chatconnectionStatus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@color/sandal_color"
            android:drawablePadding="5dp"
            android:drawableStart="@drawable/circle_bl"
            android:hint="@string/connection_status"
            android:padding="5dp"
            android:textColor="@color/blacktext"
            android:textStyle="bold" />
    </LinearLayout>


问:
How to implement a small popup with some images on a button click

I want a popup like this when user click on the three blue dot button. how to achieve this type of popup view in android . any library is available .?

答:
You should try PopupMenu

A PopupMenu displays a Menu in a modal popup window anchored to a View. The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.

Here is a good tutorial.


问:
Error: could not find implicit value for parameter timeout: akka.util.Timeout
I have this code, where I am making an ask request in Scala:

```<code> implicit val result =system.actorOf(Props(new TestActor("TestingName")),name = "Scala")

   val future3:Future[String]= ask(result ,Message).mapTo[String]
  val results = Await.result(future3, 5 second)
</code>```

here my import statements

```<code>import scala.concurrent.{Await, Future}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import akka.pattern.ask
import scala.concurrent.Await
import scala.concurrent.duration._
</code>```

and I get the error messages like

Error:(42, 35) could not find implicit value for parameter timeout: akka.util.Timeout
   val future3:Future[String]= ask(result ,Message).mapTo[String]

Error:(42, 35) not enough arguments for method ask: (implicit timeout: akka.util.Timeout)scala.concurrent.Future[Any].
Unspecified value parameter timeout.
   val future3:Future[String]= ask(result ,Message).mapTo[String]

答:
If you look at the signature for ask, or ?, you see:

```<code>def ask(message: Any)(implicit timeout: Timeout,
                      sender: ActorRef = Actor.noSender): Future[Any]
</code>```

It takes an implicit timeout: Timeout parameter which tells the future when to time out. You have to have it in scope when you call ask:

```<code>import scala.concurrent.duration._
import akka.util.Timeout

implicit val timeout: Timeout = Timeout(5 seconds)
val future3: Future[String]= ask(result, Message).mapTo[String]
</code>```

Body:
I have this code, where I am making an ask request in Scala:

 implicit val result =system.actorOf(Props(new TestActor("TestingName")),name = "Scala")

   val future3:Future[String]= ask(result ,Message).mapTo[String]
  val results = Await.result(future3, 5 second)

here my import statements

import scala.concurrent.{Await, Future}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import akka.pattern.ask
import scala.concurrent.Await
import scala.concurrent.duration._

and I get the error messages like

Error:(42, 35) could not find implicit value for parameter timeout: akka.util.Timeout
   val future3:Future[String]= ask(result ,Message).mapTo[String]

Error:(42, 35) not enough arguments for method ask: (implicit timeout: akka.util.Timeout)scala.concurrent.Future[Any].
Unspecified value parameter timeout.
   val future3:Future[String]= ask(result ,Message).mapTo[String]

Body:
If you look at the signature for ask, or ?, you see:

def ask(message: Any)(implicit timeout: Timeout,
                      sender: ActorRef = Actor.noSender): Future[Any]

It takes an implicit timeout: Timeout parameter which tells the future when to time out. You have to have it in scope when you call ask:

import scala.concurrent.duration._
import akka.util.Timeout

implicit val timeout: Timeout = Timeout(5 seconds)
val future3: Future[String]= ask(result, Message).mapTo[String]


问:
NSAttributedString extension in swift 3
I'm migrating my code to swift 3 and I'm having a hard time with this extension that was working on the previous swift version.

```<code>extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}
</code>```

Now when I try to call this piece of code I get an exception error like this

```<code>error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated
</code>```

That's how I call the method from my view controller

```<code>let htmlCode = "<html><head><style type=\"text/css\">@font-face {font-family: Avenir-Roman}body {font-family: Avenir-Roman;font-size:15;margin: 0;padding: 0}</style></head><body bgcolor=\"#FBFBFB\">" + htmlBodyCode + "</body>"
newsDescription.attributedText = htmlCode.utf8Data?.attributedString
</code>```

答:
In case anyone needs assistance in Swift 5.2+ :

```<code>extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options: [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}
</code>```

Title: NSAttributedString extension in swift 3

Body:
I'm migrating my code to swift 3 and I'm having a hard time with this extension that was working on the previous swift version.

extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}

Now when I try to call this piece of code I get an exception error like this

error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated

That's how I call the method from my view controller

let htmlCode = "" + htmlBodyCode + ""
newsDescription.attributedText = htmlCode.utf8Data?.attributedString

Body:
In case anyone needs assistance in Swift 5.2+ :

extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options: [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}


问:
What is the time complexity of adding an element at the beginning of an ArrayList?
Say I have a ArrayList with n element in this array, and I add an element at the beginning:

```<code>myArrayList.add(0,'some value');
</code>```

What will be the time complexity of this operation?

The Java Doc doesn't specify this.

Also

I just start learning Java, and I saw the sentence

```<code>An ArrayList in Java is a List that is backed by an array.
</code>```

What does 'backed' here mean? Thank you!

答:
Building the list from scratch and adding lots of elements to the beginning runs in quadratic time: O(n2).

Adding all elements to the end of the list and then calling
Collections.reverse(list) runs in linear time: O(n).

Body:
Say I have a ArrayList with n element in this array, and I add an element at the beginning:

myArrayList.add(0,'some value');

What will be the time complexity of this operation?

The Java Doc doesn't specify this.

Also

I just start learning Java, and I saw the sentence

An ArrayList in Java is a List that is backed by an array.

What does 'backed' here mean? Thank you!


问:
Asp.net DropDownList to show items?
```<code>int CountryID = Convert.ToInt32(ddlcountry.SelectedValue);
</code>```

Here is a ddlcountry selected value of what type,
I mean what is the data type of (ddlcountry.SelectedValue); ?

答:
you have to convert it into .ToString();

```<code>string value = ddlcountry.SelectedValue.ToString();
</code>```

Title: Asp.net DropDownList to show items?

Body:
int CountryID = Convert.ToInt32(ddlcountry.SelectedValue);

Here is a ddlcountry selected value of what type,
I mean what is the data type of (ddlcountry.SelectedValue); ?

Body:
you have to convert it into .ToString();

string value = ddlcountry.SelectedValue.ToString();


答:
you can use this library to achieve your goal look at this

Android Tooltip library 1

Android Tooltip library 2

Android Tooltip library 3

Android Tooltip library 4

and if you want create your custom than use following class
create one custom class like this

```<code>public class TooltipWindow {

private static final int MSG_DISMISS_TOOLTIP = 100;
private Context ctx;
private PopupWindow tipWindow;
private View contentView;
private LayoutInflater inflater;

public TooltipWindow(Context ctx) {
    this.ctx = ctx;
    tipWindow = new PopupWindow(ctx);

    inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    contentView = inflater.inflate(R.layout.tooltip_layout, null);
}

void showToolTip(View anchor) {

    tipWindow.setHeight(LayoutParams.WRAP_CONTENT);
    tipWindow.setWidth(LayoutParams.WRAP_CONTENT);

    tipWindow.setOutsideTouchable(true);
    tipWindow.setTouchable(true);
    tipWindow.setFocusable(true);
    tipWindow.setBackgroundDrawable(new BitmapDrawable());

    tipWindow.setContentView(contentView);

    int screen_pos[] = new int[2];
    // Get location of anchor view on screen
    anchor.getLocationOnScreen(screen_pos);

    // Get rect for anchor view
    Rect anchor_rect = new Rect(screen_pos[0], screen_pos[1], screen_pos[0]
            + anchor.getWidth(), screen_pos[1] + anchor.getHeight());

    // Call view measure to calculate how big your view should be.
    contentView.measure(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);

    int contentViewHeight = contentView.getMeasuredHeight();
    int contentViewWidth = contentView.getMeasuredWidth();
    // In this case , i dont need much calculation for x and y position of
    // tooltip
    // For cases if anchor is near screen border, you need to take care of
    // direction as well
    // to show left, right, above or below of anchor view
    int position_x = anchor_rect.centerX() - (contentViewWidth / 2);
    int position_y = anchor_rect.bottom - (anchor_rect.height() / 2);

    tipWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, position_x, position_y);

    // send message to handler to dismiss tipWindow after X milliseconds
    handler.sendEmptyMessageDelayed(MSG_DISMISS_TOOLTIP, 4000);
}

boolean isTooltipShown() {
    if (tipWindow != null && tipWindow.isShowing())
        return true;
    return false;
}

void dismissTooltip() {
    if (tipWindow != null && tipWindow.isShowing())
        tipWindow.dismiss();
}

Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case MSG_DISMISS_TOOLTIP:
                if (tipWindow != null && tipWindow.isShowing())
                    tipWindow.dismiss();
                break;
        }
    }

    ;
};

}
</code>```

now Crete your custom layout for this like tooltip_layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
    android:id="@+id/tooltip_nav_up"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:layout_gravity="center"
    android:background="@drawable/nav_up" />

<TextView
    android:id="@+id/tooltip_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/tooltip_bg"
    android:gravity="center"
    android:padding="10dp"
    android:text="Tooltip using PopupWindow:)"
    android:textColor="@android:color/white"
    android:textSize="20dp"
    android:textStyle="bold" />
    </LinearLayout>
</code>```

create one drawable file nav_up like this

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <rotate
        android:fromDegrees="45"
        android:pivotX="-50%"
        android:pivotY="80%"
        android:toDegrees="45" >
        <shape android:shape="rectangle" >
            <solid android:color="#000000" >
            </solid>

            <stroke
                android:width="2dp"
                android:color="#000000" />
        </shape>
    </rotate>
</item>
</code>```

now use this tooltip like this

```<code>TooltipWindow tipWindow = new TooltipWindow(MainActivity.this);
 @Override
public void onClick(View v) {
    if (!tipWindow.isTooltipShown())
        tipWindow.showToolTip(v);
}
</code>```

ask me in case of any query

Title: How to implement a small popup with some images on a button click

Body: I want a popup like this when user click on the three blue dot button. how to achieve this type of popup view in android . any library is available .?

Body:
you can use this library to achieve your goal look at this

Android Tooltip library 1

Android Tooltip library 2

Android Tooltip library 3

Android Tooltip library 4

and if you want create your custom than use following class
create one custom class like this

public class TooltipWindow {

private static final int MSG_DISMISS_TOOLTIP = 100;
private Context ctx;
private PopupWindow tipWindow;
private View contentView;
private LayoutInflater inflater;

public TooltipWindow(Context ctx) {
    this.ctx = ctx;
    tipWindow = new PopupWindow(ctx);

    inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    contentView = inflater.inflate(R.layout.tooltip_layout, null);
}

void showToolTip(View anchor) {

    tipWindow.setHeight(LayoutParams.WRAP_CONTENT);
    tipWindow.setWidth(LayoutParams.WRAP_CONTENT);

    tipWindow.setOutsideTouchable(true);
    tipWindow.setTouchable(true);
    tipWindow.setFocusable(true);
    tipWindow.setBackgroundDrawable(new BitmapDrawable());

    tipWindow.setContentView(contentView);

    int screen_pos[] = new int[2];
    // Get location of anchor view on screen
    anchor.getLocationOnScreen(screen_pos);

    // Get rect for anchor view
    Rect anchor_rect = new Rect(screen_pos[0], screen_pos[1], screen_pos[0]
            + anchor.getWidth(), screen_pos[1] + anchor.getHeight());

    // Call view measure to calculate how big your view should be.
    contentView.measure(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);

    int contentViewHeight = contentView.getMeasuredHeight();
    int contentViewWidth = contentView.getMeasuredWidth();
    // In this case , i dont need much calculation for x and y position of
    // tooltip
    // For cases if anchor is near screen border, you need to take care of
    // direction as well
    // to show left, right, above or below of anchor view
    int position_x = anchor_rect.centerX() - (contentViewWidth / 2);
    int position_y = anchor_rect.bottom - (anchor_rect.height() / 2);

    tipWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, position_x, position_y);

    // send message to handler to dismiss tipWindow after X milliseconds
    handler.sendEmptyMessageDelayed(MSG_DISMISS_TOOLTIP, 4000);
}

boolean isTooltipShown() {
    if (tipWindow != null && tipWindow.isShowing())
        return true;
    return false;
}

void dismissTooltip() {
    if (tipWindow != null && tipWindow.isShowing())
        tipWindow.dismiss();
}

Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case MSG_DISMISS_TOOLTIP:
                if (tipWindow != null && tipWindow.isShowing())
                    tipWindow.dismiss();
                break;
        }
    }

    ;
};

}

now Crete your custom layout for this like tooltip_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
    android:id="@+id/tooltip_nav_up"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:layout_gravity="center"
    android:background="@drawable/nav_up" />

<TextView
    android:id="@+id/tooltip_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/tooltip_bg"
    android:gravity="center"
    android:padding="10dp"
    android:text="Tooltip using PopupWindow:)"
    android:textColor="@android:color/white"
    android:textSize="20dp"
    android:textStyle="bold" />
    </LinearLayout>

create one drawable file nav_up like this

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <rotate
        android:fromDegrees="45"
        android:pivotX="-50%"
        android:pivotY="80%"
        android:toDegrees="45" >
        <shape android:shape="rectangle" >
            <solid android:color="#000000" >
            </solid>

            <stroke
                android:width="2dp"
                android:color="#000000" />
        </shape>
    </rotate>
</item>

now use this tooltip like this

TooltipWindow tipWindow = new TooltipWindow(MainActivity.this);
 @Override
public void onClick(View v) {
    if (!tipWindow.isTooltipShown())
        tipWindow.showToolTip(v);
}

ask me in case of any query


问:
UIDatePicker not showing up in UITextField. Swift 3
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

```<code>import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}
</code>```

答:
UIDatePicker did not need to add delegate in swift 3 Just check the code

```<code>class ViewController: UIViewController {
//Text Field Connection
@IBOutlet weak var txtDatePicker: UITextField!
//Uidate picker
let datePicker = UIDatePicker()

override func viewDidLoad() {
    super.viewDidLoad()
    //show date picker
    showDatePicker()
}

func showDatePicker(){
    //Formate Date
    datePicker.datePickerMode = .date

    //ToolBar
    let toolbar = UIToolbar();
    toolbar.sizeToFit()

    //done button & cancel button
    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: "donedatePicker")
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.bordered, target: self, action: "cancelDatePicker")
    toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)

    // add toolbar to textField
    txtDatePicker.inputAccessoryView = toolbar
    // add datepicker to textField
    txtDatePicker.inputView = datePicker

}

func donedatePicker(){
    //For date formate
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yyyy"
    txtDatePicker.text = formatter.string(from: datePicker.date)
    //dismiss date picker dialog
    self.view.endEditing(true)
}

  func cancelDatePicker(){
    //cancel button dismiss datepicker dialog
    self.view.endEditing(true)
  }
}
</code>```

Check full source to github Link:https://github.com/enamul95/DatePicker1

Body:
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}

Body:
UIDatePicker did not need to add delegate in swift 3 Just check the code

class ViewController: UIViewController {
//Text Field Connection
@IBOutlet weak var txtDatePicker: UITextField!
//Uidate picker
let datePicker = UIDatePicker()

override func viewDidLoad() {
    super.viewDidLoad()
    //show date picker
    showDatePicker()
}

func showDatePicker(){
    //Formate Date
    datePicker.datePickerMode = .date

    //ToolBar
    let toolbar = UIToolbar();
    toolbar.sizeToFit()

    //done button & cancel button
    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: "donedatePicker")
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.bordered, target: self, action: "cancelDatePicker")
    toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)

    // add toolbar to textField
    txtDatePicker.inputAccessoryView = toolbar
    // add datepicker to textField
    txtDatePicker.inputView = datePicker

}

func donedatePicker(){
    //For date formate
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yyyy"
    txtDatePicker.text = formatter.string(from: datePicker.date)
    //dismiss date picker dialog
    self.view.endEditing(true)
}

  func cancelDatePicker(){
    //cancel button dismiss datepicker dialog
    self.view.endEditing(true)
  }
}

Check full source to github Link:https://github.com/enamul95/DatePicker1


问:
Different UI for different iPAD sizes
Our project runs for all iPAD's and we came across a problem as an example we have 8 buttons vertically sitting on a screen with constraints being added as vertical spacing they look fine on a iPAD 9.7 inch, but they look really big on iPAD 12.9, so the question is, is there any good way to actually use the screen space for something better, as in add an extra UIView if it is iPAD 12.9. I have looked into working with size classes, but I believe there is one size class for all iPADs, what I want is if there is a way to have different UI for different iPAD sizes using the Interface builder</p>

答:
You can use this

All buttons embeded into view and set to its constraints to superview.

make sure add a aspect ratio constraints to it.

Select all buttons and add constraints

Equal width ,Equal Height, Aspect ratio

Title: Different UI for different iPAD sizes


问:
join CompletableFuture vs synchronous method
Having:

```<code>String getData(String key){
    // Slow operation
}

CompletableFuture<String> getDataAsync(String key){
    return CompletableFuture.supplyAsync(() -> getData(key));
}
</code>```

What is the difference between the following?

a)

```<code>keyStream.map(key -> getData(key));
</code>```

b)

```<code>keyStream.map(key -> getDataAsync(key).join());
</code>```

Is there any advantage to use async in this case?

答: Usage Async here in your example will not make difference as you are calling join with that so join is blocking call and Async will no more be ASync</p>

Body:
Having:

String getData(String key){
    // Slow operation
}

CompletableFuture<String> getDataAsync(String key){
    return CompletableFuture.supplyAsync(() -> getData(key));
}

What is the difference between the following?

a)

keyStream.map(key -> getData(key));

b)

keyStream.map(key -> getDataAsync(key).join());

Is there any advantage to use async in this case?


问:
C# String Array Contains
Can someone explain to me why the top part of the code works but when test is an array it doesn't?

```<code>string test = "Customer - ";
if (test.Contains("Customer"))
{
    test = "a";
}
</code>```

The code below doesn't work

```<code>string[] test = { "Customer - " };
if (test.Contains("Customer"))
{
    test[0] = "a";
}
</code>```

答:
```<code>string test = "Customer - ";
if (test.Contains("Customer"))
{
  test = "a";
}
</code>```

In this Contains is a String Class Method it's base of IEnumerable checks

"Customer -" having Customer.

But

```<code>string[]test = { "Customer - " };
if (test.Contains("Customer"))
{
   test[1]= "a";
 }
</code>```

In this Place Contains is a IEnumerable Method it's base of IEnumerable checks.So, It's Not Working You Change the Code

```<code>string[] test = { "Customer - " };
if (test.Any(x => x.Contains("Customer")))
{

}
</code>```

test[1]="a"  It's throw Exception because, the array position start with  0 not 1

Title: C# String Array Contains

Body:
Can someone explain to me why the top part of the code works but when test is an array it doesn't?

string test = "Customer - ";
if (test.Contains("Customer"))
{
    test = "a";
}

The code below doesn't work

string[] test = { "Customer - " };
if (test.Contains("Customer"))
{
    test[0] = "a";
}

Body:
string test = "Customer - ";
if (test.Contains("Customer"))
{
  test = "a";
}

In this Contains is a String Class Method it's base of IEnumerable checks

"Customer -" having Customer.

But

string[]test = { "Customer - " };
if (test.Contains("Customer"))
{
   test[1]= "a";
 }

In this Place Contains is a IEnumerable Method it's base of IEnumerable checks.So, It's Not Working You Change the Code

string[] test = { "Customer - " };
if (test.Any(x => x.Contains("Customer")))
{

}

test[1]="a"  It's throw Exception because, the array position start with  0 not 1


问:
Initialize Jenkins with Pipeline Job
I am building Jenkins with a Dockerfile, and during the Docker build I would like to have Jenkins pre-configured with a set of jobs.  I find this works well with Jobs DSL, where jobs are seeded, but I have yet to preconfigure the "Pipeline" DSL.  Given the direction of Jenkins and use of Jenkisfile, Pipeline, etc, I think there must be some way to allow Jenkins to automatically run with a set of jobs that were built using the Pipeline approach

Example Pipeline:

```<code>    pipeline {
        agent {
            label 'cft'
        }
parameters {
        string(name: 'StackName', defaultValue: 'cft-stack', description: 'The name to give the CFT stack.')
        string(name: 'KeyName', defaultValue: 'ACCOUNT', description: 'The account key to use for encryption.')
        string(name: 'VpcId', defaultValue: 'vpc-1234', description: 'The VPC to assign to the cluster resources.')
        string(name: 'SubnetID', defaultValue: 'subnet-1234, subnet-6789', description: 'The subnet(s) to assign to the cluster resources.')
    stages {

        stage('Build') {

            steps {

               s3Download(file:'cft.yaml'
                    , bucket:'cft-resources'
                    , path:'cft.yaml'
                    , force:true)

                cfnUpdate(stack:"${params.StackName}"
                    , file:"cft.yaml"
                    , params:[
                    "SnapshotId=${params.SnapshotId}",
                    "KeyName=${params.KeyName}",
                    "VpcId=${params.VpcId}"
                    ]
                    , timeoutInMinutes: 20
                )
            }
        }
    }
    post {
        failure {
            echo 'FAILURE'
            cfnDelete(stack:"${params.StackName}")
        }
    }
}
</code>```

Dockerfile:

COPY ./groovy/*.groovy /usr/share/jenkins/ref/init.groovy.d/

答:
Pipeline's Groovy files differ from the Groovy code that can be executed to configure Jenkins. You can't add pipelines the way you're trying to do.

Your options include

copy the XML file for the job definition (pointing to your repo, as the pipeline should be in the Jenkinsfile in the repo)

create a job using Groovy and configure it (not really practicable IMHO)

use JobDSL (again, with XML as starting point) to specify your Jenkins jobs. An example for automatically adding this can be found in tknerr/jenkins-pipes-infra.

Title: Initialize Jenkins with Pipeline Job

Body:
I am building Jenkins with a Dockerfile, and during the Docker build I would like to have Jenkins pre-configured with a set of jobs.  I find this works well with Jobs DSL, where jobs are seeded, but I have yet to preconfigure the "Pipeline" DSL.  Given the direction of Jenkins and use of Jenkisfile, Pipeline, etc, I think there must be some way to allow Jenkins to automatically run with a set of jobs that were built using the Pipeline approach

Example Pipeline:

    pipeline {
        agent {
            label 'cft'
        }
parameters {
        string(name: 'StackName', defaultValue: 'cft-stack', description: 'The name to give the CFT stack.')
        string(name: 'KeyName', defaultValue: 'ACCOUNT', description: 'The account key to use for encryption.')
        string(name: 'VpcId', defaultValue: 'vpc-1234', description: 'The VPC to assign to the cluster resources.')
        string(name: 'SubnetID', defaultValue: 'subnet-1234, subnet-6789', description: 'The subnet(s) to assign to the cluster resources.')
    stages {

        stage('Build') {

            steps {

               s3Download(file:'cft.yaml'
                    , bucket:'cft-resources'
                    , path:'cft.yaml'
                    , force:true)

                cfnUpdate(stack:"${params.StackName}"
                    , file:"cft.yaml"
                    , params:[
                    "SnapshotId=${params.SnapshotId}",
                    "KeyName=${params.KeyName}",
                    "VpcId=${params.VpcId}"
                    ]
                    , timeoutInMinutes: 20
                )
            }
        }
    }
    post {
        failure {
            echo 'FAILURE'
            cfnDelete(stack:"${params.StackName}")
        }
    }
}

Dockerfile:

COPY ./groovy/*.groovy /usr/share/jenkins/ref/init.groovy.d/


问:
pgsql Materialized view refresh
I use materialized view in pgsql and i wonder if there is a way to refresh a materialized view for example A after that another materialized view B has been completely refreshed.
Thank you in advance.</p>

答:
HOW TO REFRESH MATVIEW

1. Bash Script

2. Create Function

```<code>CREATE OR REPLACE FUNCTION refresh_mv() RETURNS VARCHAR AS $LABEL$
DECLARE
v_result integer;
BEGIN

refresh materialized view mv_b with data;

refresh materialized view mv_a with data;

RETURN ('Success');

END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;
</code>```

Execute select * from refresh_mv();

Title: pgsql Materialized view refresh

Body:
HOW TO REFRESH MATVIEW

1. Bash Script

2. Create Function

CREATE OR REPLACE FUNCTION refresh_mv() RETURNS VARCHAR AS $LABEL$
DECLARE
v_result integer;
BEGIN

refresh materialized view mv_b with data;

refresh materialized view mv_a with data;

RETURN ('Success');

END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;

Execute select * from refresh_mv();


问:
Why is the `LIKE` operator not working with integer columns?
I'm trying to receive some ids from my database for an autocomplete search on my CAKEPHP 3.3 site. But my problem is that its only returning the id if I type in the exact id and not part of it.

Here is my function to search the data. The name variable is what is being passed from input.

```<code>public function search()
{
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices->find('all', [
            'conditions' => ['Invoices.id LIKE' => ($name . '%')]
        ]);
        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = ($result['id']);
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);
    }
}
</code>```

For example there is a id in the table '5254' and I type in part of the id '52' nothing is returned but when I type in the whole id '5254' the id is returned.

I'm unsure why this is the case because in my sql query i'm using the percent sign to say any characters after what has been typed into the input.

Here is part of my table

SQL debug when 52 is entered.

```<code>object(Cake\ORM\Query) {

    '(help)' => 'This is a Query object, to get the results execute or iterate it.',
    'sql' => 'SELECT Invoices.id AS `Invoices__id`, Invoices.start_date AS `Invoices__start_date`, Invoices.close_date AS `Invoices__close_date`, Invoices.customer_id AS `Invoices__customer_id`, Invoices.invoice_to_address AS `Invoices__invoice_to_address`, Invoices.ship_to_address AS `Invoices__ship_to_address`, Invoices.customer_contact_id AS `Invoices__customer_contact_id`, Invoices.aircraft_registration_id AS `Invoices__aircraft_registration_id`, Invoices.shipping_company_id AS `Invoices__shipping_company_id`, Invoices.notes AS `Invoices__notes`, Invoices.worksheet_notes AS `Invoices__worksheet_notes`, Invoices.closed AS `Invoices__closed`, Invoices.times_printed AS `Invoices__times_printed`, Invoices.payment_due AS `Invoices__payment_due`, Invoices.GST_rate AS `Invoices__GST_rate`, Invoices.opening_notes AS `Invoices__opening_notes`, Invoices.courier_ticket AS `Invoices__courier_ticket`, Invoices.job_description AS `Invoices__job_description`, Invoices.worksheets_printed AS `Invoices__worksheets_printed`, Invoices.supervising_engineer_id AS `Invoices__supervising_engineer_id`, Invoices.job_type_id AS `Invoices__job_type_id`, Invoices.opened_by_id AS `Invoices__opened_by_id`, Invoices.assigned_to_id AS `Invoices__assigned_to_id`, Invoices.certification_required AS `Invoices__certification_required`, Invoices.currency_id AS `Invoices__currency_id`, Invoices.xero_batch_number AS `Invoices__xero_batch_number`, Invoices.xero_amount AS `Invoices__xero_amount`, Invoices.exchange_rate AS `Invoices__exchange_rate`, Invoices.payment_instructions AS `Invoices__payment_instructions`, Invoices.email AS `Invoices__email`, Invoices.inv_email AS `Invoices__inv_email` FROM invoices Invoices WHERE Invoices.id like :c0',
    'params' => [
        ':c0' => [
            'value' => '52%',
            'type' => 'integer',
            'placeholder' => 'c0'
        ]
</code>```

答:
Try it like this:</p>

```<code>'conditions' => ['Invoices.id LIKE' => '"' . $name . '%"']
</code>```

Body:
I'm trying to receive some ids from my database for an autocomplete search on my CAKEPHP 3.3 site. But my problem is that its only returning the id if I type in the exact id and not part of it.

Here is my function to search the data. The name variable is what is being passed from input.

public function search()
{
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices->find('all', [
            'conditions' => ['Invoices.id LIKE' => ($name . '%')]
        ]);
        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = ($result['id']);
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);
    }
}

For example there is a id in the table '5254' and I type in part of the id '52' nothing is returned but when I type in the whole id '5254' the id is returned.

I'm unsure why this is the case because in my sql query i'm using the percent sign to say any characters after what has been typed into the input.

Here is part of my table

SQL debug when 52 is entered.

object(Cake\ORM\Query) {

    '(help)' => 'This is a Query object, to get the results execute or iterate it.',
    'sql' => 'SELECT Invoices.id AS `Invoices__id`, Invoices.start_date AS `Invoices__start_date`, Invoices.close_date AS `Invoices__close_date`, Invoices.customer_id AS `Invoices__customer_id`, Invoices.invoice_to_address AS `Invoices__invoice_to_address`, Invoices.ship_to_address AS `Invoices__ship_to_address`, Invoices.customer_contact_id AS `Invoices__customer_contact_id`, Invoices.aircraft_registration_id AS `Invoices__aircraft_registration_id`, Invoices.shipping_company_id AS `Invoices__shipping_company_id`, Invoices.notes AS `Invoices__notes`, Invoices.worksheet_notes AS `Invoices__worksheet_notes`, Invoices.closed AS `Invoices__closed`, Invoices.times_printed AS `Invoices__times_printed`, Invoices.payment_due AS `Invoices__payment_due`, Invoices.GST_rate AS `Invoices__GST_rate`, Invoices.opening_notes AS `Invoices__opening_notes`, Invoices.courier_ticket AS `Invoices__courier_ticket`, Invoices.job_description AS `Invoices__job_description`, Invoices.worksheets_printed AS `Invoices__worksheets_printed`, Invoices.supervising_engineer_id AS `Invoices__supervising_engineer_id`, Invoices.job_type_id AS `Invoices__job_type_id`, Invoices.opened_by_id AS `Invoices__opened_by_id`, Invoices.assigned_to_id AS `Invoices__assigned_to_id`, Invoices.certification_required AS `Invoices__certification_required`, Invoices.currency_id AS `Invoices__currency_id`, Invoices.xero_batch_number AS `Invoices__xero_batch_number`, Invoices.xero_amount AS `Invoices__xero_amount`, Invoices.exchange_rate AS `Invoices__exchange_rate`, Invoices.payment_instructions AS `Invoices__payment_instructions`, Invoices.email AS `Invoices__email`, Invoices.inv_email AS `Invoices__inv_email` FROM invoices Invoices WHERE Invoices.id like :c0',
    'params' => [
        ':c0' => [
            'value' => '52%',
            'type' => 'integer',
            'placeholder' => 'c0'
        ]

Body:
Try it like this:

'conditions' => ['Invoices.id LIKE' => '"' . $name . '%"']


问:
Trying to figure out reason for 400 error in post testing Django-Rest-Framework API
Here is the model that I am testing:

```<code>class Entity(TimestampModerated):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True)
    description = models.TextField(verbose_name='description of entity', blank=True)
    media = models.URLField(verbose_name='media representing entity (image, mp3, mpg, etc)',
                            blank=True, null=True)
    uuid = models.UUIDField(db_index=True,
                            default=uuid_lib.uuid4(),
                            editable=False,
                            )
    owner = models.ForeignKey('auth.User', related_name='entities', on_delete=models.CASCADE)
    tags = TaggableManager(blank=True)

    def get_absolute_url(self):
        return reverse('entities:detail', kwargs={'slug': self.slug})

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "entities"
</code>```

Here is the ViewSet:

```<code>class EntityViewSet(viewsets.ModelViewSet):
    """
    This viewsetomatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.
    """
    queryset = Entity.objects.all()
    serializer_class = EntitySerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)
    lookup_field = 'slug'

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
</code>```

Here are my urls:

```<code>router = DefaultRouter()
router.register(r'entities', views.EntityViewSet)
router.register(r'users', views.UserViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
]
</code>```

Here is my test:

```<code>class EntitiesAPITests(test.APITestCase):
    def setUp(self):
        test_user = models.User.objects.create(username='testuser', password='password')

    def test_login_post(self):
        client = APIClient()
        client.login(username='testuser', password='password')
        response = client.post('/api/entities/', data={
            'name': 'Sean Penn',
            'slug': 'sean-penn'
        })
        self.assertContains(response, 200)
        client.logout()
</code>```

When I run the tests I get the following error, which I haven't been able to figure out:

```<code>======================================================================
FAIL: test_login_post (entities.tests.test_api.EntitiesAPITests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/xxx/xxx/entities/tests/test_api.py", line 63, in test_login_post
    self.assertContains(response, 200)
  File "/Users/xxx/xxx/.virtualenv/lib/python3.6/site-packages/django/test/testcases.py", line 385, in assertContains
    response, text, status_code, msg_prefix, html)
  File "/Users/xxx/xxx/.virtualenv/lib/python3.6/site-packages/django/test/testcases.py", line 357, in _assert_contains
    " (expected %d)" % (response.status_code, status_code)
AssertionError: 400 != 200 : Couldn't retrieve content: Response code was 400 (expected 200)

----------------------------------------------------------------------
Ran 10 tests in 0.280s

FAILED (failures=1)
Destroying test database for alias 'default'...
</code>```

Here is the Serializer:

```<code>from django.contrib.auth.models import User
from rest_framework import serializers
from taggit_serializer.serializers import TagListSerializerField

from entities.models import Entity

class EntitySerializer(serializers.ModelSerializer):
    owner = serializers.CharField(source='owner.username', read_only=True)
    tags = TagListSerializerField()

    class Meta:
        model = Entity
        fields = ('id', 'created', 'name', 'description', 'media', 'moderation_code', 'owner', 'updated', 'tags',
                  'slug', 'uuid')
</code>```

答:
Try changing like this,</p>

```<code>class EntitiesAPITests(test.APITestCase):
    def setUp(self):
        self.user = models.User.objects.create(username='testuser', password='password')

    def test_login_post(self):
        client = APIClient()
        client.force_authenticate(self.user)
        response = client.post('/api/entities/', data={
            'name': 'Sean Penn',
            'slug': 'sean-penn'
        })
        self.assertContains(response, 200)
        client.logout()
</code>```

Body:
Here is the model that I am testing:

class Entity(TimestampModerated):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True)
    description = models.TextField(verbose_name='description of entity', blank=True)
    media = models.URLField(verbose_name='media representing entity (image, mp3, mpg, etc)',
                            blank=True, null=True)
    uuid = models.UUIDField(db_index=True,
                            default=uuid_lib.uuid4(),
                            editable=False,
                            )
    owner = models.ForeignKey('auth.User', related_name='entities', on_delete=models.CASCADE)
    tags = TaggableManager(blank=True)

    def get_absolute_url(self):
        return reverse('entities:detail', kwargs={'slug': self.slug})

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "entities"

Here is the ViewSet:

class EntityViewSet(viewsets.ModelViewSet):
    """
    This viewsetomatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.
    """
    queryset = Entity.objects.all()
    serializer_class = EntitySerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)
    lookup_field = 'slug'

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

Here are my urls:

router = DefaultRouter()
router.register(r'entities', views.EntityViewSet)
router.register(r'users', views.UserViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
]

Here is my test:

class EntitiesAPITests(test.APITestCase):
    def setUp(self):
        test_user = models.User.objects.create(username='testuser', password='password')

    def test_login_post(self):
        client = APIClient()
        client.login(username='testuser', password='password')
        response = client.post('/api/entities/', data={
            'name': 'Sean Penn',
            'slug': 'sean-penn'
        })
        self.assertContains(response, 200)
        client.logout()

When I run the tests I get the following error, which I haven't been able to figure out:

======================================================================
FAIL: test_login_post (entities.tests.test_api.EntitiesAPITests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/xxx/xxx/entities/tests/test_api.py", line 63, in test_login_post
    self.assertContains(response, 200)
  File "/Users/xxx/xxx/.virtualenv/lib/python3.6/site-packages/django/test/testcases.py", line 385, in assertContains
    response, text, status_code, msg_prefix, html)
  File "/Users/xxx/xxx/.virtualenv/lib/python3.6/site-packages/django/test/testcases.py", line 357, in _assert_contains
    " (expected %d)" % (response.status_code, status_code)
AssertionError: 400 != 200 : Couldn't retrieve content: Response code was 400 (expected 200)

----------------------------------------------------------------------
Ran 10 tests in 0.280s

FAILED (failures=1)
Destroying test database for alias 'default'...

Here is the Serializer:

from django.contrib.auth.models import User
from rest_framework import serializers
from taggit_serializer.serializers import TagListSerializerField

from entities.models import Entity

class EntitySerializer(serializers.ModelSerializer):
    owner = serializers.CharField(source='owner.username', read_only=True)
    tags = TagListSerializerField()

    class Meta:
        model = Entity
        fields = ('id', 'created', 'name', 'description', 'media', 'moderation_code', 'owner', 'updated', 'tags',
                  'slug', 'uuid')

Body:
Try changing like this,

class EntitiesAPITests(test.APITestCase):
    def setUp(self):
        self.user = models.User.objects.create(username='testuser', password='password')

    def test_login_post(self):
        client = APIClient()
        client.force_authenticate(self.user)
        response = client.post('/api/entities/', data={
            'name': 'Sean Penn',
            'slug': 'sean-penn'
        })
        self.assertContains(response, 200)
        client.logout()