问:
Calculate Points from Letters in a Switch Case
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

```<code>/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }
</code>```

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

答:
I'm not sure that the code you've shown us will compile. There are a few things you need to change;

1) You're setting a String to an int. You'll want to change that to

int point = 0

2) You aren't setting anything in the switch statement

Change case 'a': = "1": to case 'a': point = 1;

3) You will never set a unique value in the switch statement because you aren't using 'break'
Checkout this page for a good tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Basically without any break statements, your code will go through the of the statements and point will just be assigned to your last case
You want to have something along the lines of

```<code>switch(char)  {
    case 'a': point = 1;
        break;
    case 'e': point = 1;
        break;
    // etc.
    default: point = 1;  // maybe throw an error or add some logging for the default case
         break;
}
return point;
</code>```

I am presuming that you actually have this switch statement in it's own method and not in main as you've shown us above, otherwise the return statement won't help you.
You can also shorten this so that each case simply returns a value (again, if this is in it's own method), i.e.

```<code>switch(char) {
    case 'a': return 1;
    case 'b': return 1;
    // etc.
}
</code>```

edit:

The best way to get the point value of the whole word via a switch statement is:

```<code>char[] chars = word.toCharArray();
int point=0;
for (char c: chars) {
    switch(c) {
        case 'a':
            point += 1;
            break;
        // etc.
    }
}
System.out.println("Total point value of word '" + word + "' was " + point);
</code>```

Body:
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

Body:
I'm not sure that the code you've shown us will compile. There are a few things you need to change;

1) You're setting a String to an int. You'll want to change that to

int point = 0

2) You aren't setting anything in the switch statement

Change case 'a': = "1": to case 'a': point = 1;

3) You will never set a unique value in the switch statement because you aren't using 'break'
Checkout this page for a good tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Basically without any break statements, your code will go through the of the statements and point will just be assigned to your last case
You want to have something along the lines of

switch(char)  {
    case 'a': point = 1;
        break;
    case 'e': point = 1;
        break;
    // etc.
    default: point = 1;  // maybe throw an error or add some logging for the default case
         break;
}
return point;

I am presuming that you actually have this switch statement in it's own method and not in main as you've shown us above, otherwise the return statement won't help you.
You can also shorten this so that each case simply returns a value (again, if this is in it's own method), i.e.

switch(char) {
    case 'a': return 1;
    case 'b': return 1;
    // etc.
}

edit:

The best way to get the point value of the whole word via a switch statement is:

char[] chars = word.toCharArray();
int point=0;
for (char c: chars) {
    switch(c) {
        case 'a':
            point += 1;
            break;
        // etc.
    }
}
System.out.println("Total point value of word '" + word + "' was " + point);


来源: stackexchange

问:
Check Route Prefix in Blade If Loop
I have a route defined like such: </p>

```<code>Route::get('aanmelden/{companySlug}/{packageSlug}', ['as' => 'register', 'uses' => 'UsersController@create'])
</code>```

<p>I want to display some extra plug-in on this specific page, so in the header I want an if loop that checks for the prefix 'register' to display the code.. No luck yet. I tried this: </p>

```<code>@if(Request::is('register'))

@if(Request::path() == 'aanmelden')
</code>```

答:
You might also go like:

@if (Route::is('register*'))
```

which is shorter.

https://laravel.com/docs/5.8/helpers#method-str-is

ContentLicense: CC BY-SA 3.0

Title: Check Route Prefix in Blade If Loop

Body:
I have a route defined like such:

Route::get('aanmelden/{companySlug}/{packageSlug}', ['as' => 'register', 'uses' => 'UsersController@create'])

I want to display some extra plug-in on this specific page, so in the header I want an if loop that checks for the prefix 'register' to display the code.. No luck yet. I tried this:

@if(Request::is('register'))

@if(Request::path() == 'aanmelden')

Body:
You might also go like:

@if (Route::is('register*'))

which is shorter.

https://laravel.com/docs/5.8/helpers#method-str-is

ContentLicense: CC BY-SA 4.0


问:
Null Pointer Debugging
quick summary of what I'm trying to do.

Using shared preferences so that when a user watches a video a green tick will appear beside it to mark it as complete. Currently getting a null pointer error.

Basically there are two pages - main page and video page. When user lands on the main page the if statement should check the sharepreferences to see if they have already visited the video page. If they have it should display the completedTick imageView.

Please see the code and context below.

MAIN PAGE CODE SNIPPET:

```<code> /**
 * Shared preferences variable which is used to store the userId which is captured at the login screen.
 */
private SharedPreferences loginPref, activityPref;
private ImageView completedTick;
private Boolean activityCompleted;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    View view = inflater.inflate(R.layout.fragment_activities, container, false);

    initialiseRecyclerView(view);
    retrieveActivities();

    if(activityCompleted == false || activityCompleted == null ) {
        completedTick.setVisibility(view.INVISIBLE);
    }else{
        completedTick.setVisibility(View.VISIBLE);
    }

    return view;

}

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

/**
 * Method which is used to initialise the recycler view
 *
 * @param view
 */
private void initialiseRecyclerView(View view) {
    mRecyclerView = view.findViewById(R.id.recyclerViewActivities);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    EmptyAdapter emptyAdapter = new EmptyAdapter();
    mRecyclerView.setAdapter(emptyAdapter);
    completedTick = view.findViewById(R.id.completedTick);
}
</code>```

VIDEO PAGE CODE SNIPPET:

```<code>private SharedPreferences activityPref;
private Boolean activityCompleted;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.youtube_layout);

    Log.d(TAG, "onCreateView: Starting");
    activityPref = getSharedPreferences("activityPref", MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

        getExtrasMethod();
        initialiseViews();
        setTextInViews();
        checkCompleteD();

 private void checkCompleteD() {

    if (activityCompleted) {
        SharedPreferences.Editor editor = activityPref.edit();
        activityCompleted = false;
        editor.putBoolean("activityCompleted", activityCompleted);
        editor.apply();

    }
}
</code>```

The error is :

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.fit.ActivitiesFragment.onCreateView(ActivitiesFragment.java:78)
</code>```

UPDATE:

Made the suggedted changes

```<code>@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    completedTick = view.findViewById(R.id.completedTickImage);
    initialiseRecyclerView(view);
    retrieveActivities();

    if (activityCompleted == false || activityCompleted == null) {
        completedTick.setVisibility(View.INVISIBLE);
    } else {
        completedTick.setVisibility(View.VISIBLE);
    }
}
</code>```

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.feelingfit.ActivitiesFragment.onViewCreated(ActivitiesFragment.java:85)

Which is this line :  completedTick.setVisibility(View.INVISIBLE);

答: Do the operation of CompleteTick.setVisibility inside onActivityCreated() method and also replace the view.INVISIBLE to View.INVISIBLE

Title: Null Pointer Debugging

Body:
quick summary of what I'm trying to do.

Using shared preferences so that when a user watches a video a green tick will appear beside it to mark it as complete. Currently getting a null pointer error.

Basically there are two pages - main page and video page. When user lands on the main page the if statement should check the sharepreferences to see if they have already visited the video page. If they have it should display the completedTick imageView.

Please see the code and context below.

MAIN PAGE CODE SNIPPET:

 /**
 * Shared preferences variable which is used to store the userId which is captured at the login screen.
 */
private SharedPreferences loginPref, activityPref;
private ImageView completedTick;
private Boolean activityCompleted;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    View view = inflater.inflate(R.layout.fragment_activities, container, false);

    initialiseRecyclerView(view);
    retrieveActivities();

    if(activityCompleted == false || activityCompleted == null ) {
        completedTick.setVisibility(view.INVISIBLE);
    }else{
        completedTick.setVisibility(View.VISIBLE);
    }

    return view;

}

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

/**
 * Method which is used to initialise the recycler view
 *
 * @param view
 */
private void initialiseRecyclerView(View view) {
    mRecyclerView = view.findViewById(R.id.recyclerViewActivities);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    EmptyAdapter emptyAdapter = new EmptyAdapter();
    mRecyclerView.setAdapter(emptyAdapter);
    completedTick = view.findViewById(R.id.completedTick);
}

VIDEO PAGE CODE SNIPPET:

private SharedPreferences activityPref;
private Boolean activityCompleted;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.youtube_layout);

    Log.d(TAG, "onCreateView: Starting");
    activityPref = getSharedPreferences("activityPref", MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

        getExtrasMethod();
        initialiseViews();
        setTextInViews();
        checkCompleteD();

 private void checkCompleteD() {

    if (activityCompleted) {
        SharedPreferences.Editor editor = activityPref.edit();
        activityCompleted = false;
        editor.putBoolean("activityCompleted", activityCompleted);
        editor.apply();

    }
}

The error is :

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.fit.ActivitiesFragment.onCreateView(ActivitiesFragment.java:78)

UPDATE:

Made the suggedted changes

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    completedTick = view.findViewById(R.id.completedTickImage);
    initialiseRecyclerView(view);
    retrieveActivities();

    if (activityCompleted == false || activityCompleted == null) {
        completedTick.setVisibility(View.INVISIBLE);
    } else {
        completedTick.setVisibility(View.VISIBLE);
    }
}

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.feelingfit.ActivitiesFragment.onViewCreated(ActivitiesFragment.java:85)

Which is this line :  completedTick.setVisibility(View.INVISIBLE);


问:
Disable CTRL+C on JTable (after duoble click on a cell)
I've been asked to edit a java desktop application developed by others. I've never worked on Java desktop application before.

There's a JTable and I have to prevent the user from doing CTRL+C and copy the value of a cell. I did it.

The problem is that when the user double clicks a cell and the cursor appears (as you can see from the pic)

I'm not able to prevent the user to do CTRL+C. How can I do it?

答:
Take away their keyboard!

Okay, that may be problematic. If you don't need the users to edit the table, you could try making the table non-editable. Rather than regurgitate one of many examples on this, I'll leave you this guide on doing it and a StackOverflow question on how to Disable user edit in JTable .

Alternatively, you could look into overriding the keybindings. I've never done that personally, so I leave you a link or two and a StackOverflow question on JTable Key Bindings .

You could also do something clever by accessing the System's Clipboard from java.awt.toolkit. Maybe have it that whenever a user is editing a cell, their clipboard is set to an empty string or (if you don't want to screw over people editing cells but not trying to copy them) you could combine that with the keybindings so they think they're copying data but they end up pasting "Sorry. Copying is not allowed in this application."

Hope something here works.


问:
django.db.utils.IntegrityError:

django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value 'tutorial_series_id' that does not have a corresponding value in main_tutorialseries.id.

The above error shows up and cant migrate

These are my models:

```<code>    from django.db import models
    from datetime import datetime
    #Create your models here.

    class TutorialCategory(models.Model):
        tutorial_category = models.CharField(max_length=200)
        category_summary = models.CharField(max_length=200)
        category_slug = models.CharField(max_length=200, default=1)

        class Meta:
            #Gives the proper plural name for admin
            verbose_name_plural = "Categories"

        def __str__(self):
            return self.tutorial_category

    class TutorialSeries(models.Model):
        tutorial_series = models.CharField(max_length=200)
        tutorial_category = models.ForeignKey(TutorialCategory, default=1,verbose_name="Category", on_delete=models.SET_DEFAULT)
        series_summary = models.CharField(max_length=200)

        class Meta:
            #Otherwise we get "Tutorial Serie*ss* in admin"
            verbose_name_plural = "Series"

        def __str__(self):
            return self.tutorial_series

    class Tutorial(models.Model):
        tutorial_title = models.CharField(max_length=200)
        tutorial_content = models.TextField()
        tutorial_published = models.DateTimeField("date published", default = datetime.now())
        tutorial_series = models.ForeignKey(TutorialSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT)
        tutorial_slug = models.CharField(max_length=200,default=1)

        def __str__(self):
            return self.tutorial_title
</code>```

答:
In your Tutorial model, you are using a default value for the foreign key field ** tutorial_series **. This causes the migration to check if a record in TutorialSeries exists with id=1 but there is no such data present, so the error is occuring.

To avoid the error while migrating, remove the on_delete=models.SET_DEFAULT and default=1 from our fields to make your models as:

```<code>class TutorialSeries(models.Model):
    tutorial_series = models.CharField(max_length=200)
    tutorial_category = models.ForeignKey(TutorialCategory,verbose_name="Category")
    series_summary = models.CharField(max_length=200)

    class Meta:
        #Otherwise we get "Tutorial Serie*ss* in admin"
        verbose_name_plural = "Series"

    def __str__(self):
        return self.tutorial_series

class Tutorial(models.Model):
        tutorial_title = models.CharField(max_length=200)
        tutorial_content = models.TextField()
        tutorial_published = models.DateTimeField("date published", default = datetime.now())
        tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", blank=True, null=True) #<--changes
        tutorial_slug = models.CharField(max_length=200,default=1)

        def __str__(self):
            return self.tutorial_title
</code>```

After this, migrate your models. Then add data to TutorialCategory and TutorialSeries with id=1.

Then revert your models to your initial setup (keeping default=1 and on_delete=models.SET_DEFAULT). Then again run makemigrations and migrate your models. After this, your problem might be solved.

Title: django.db.utils.IntegrityError:

Body:
django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value 'tutorial_series_id' that does not have a corresponding value in main_tutorialseries.id.

The above error shows up and cant migrate

These are my models:

    from django.db import models
    from datetime import datetime
    #Create your models here.

    class TutorialCategory(models.Model):
        tutorial_category = models.CharField(max_length=200)
        category_summary = models.CharField(max_length=200)
        category_slug = models.CharField(max_length=200, default=1)

        class Meta:
            #Gives the proper plural name for admin
            verbose_name_plural = "Categories"

        def __str__(self):
            return self.tutorial_category

    class TutorialSeries(models.Model):
        tutorial_series = models.CharField(max_length=200)
        tutorial_category = models.ForeignKey(TutorialCategory, default=1,verbose_name="Category", on_delete=models.SET_DEFAULT)
        series_summary = models.CharField(max_length=200)

        class Meta:
            #Otherwise we get "Tutorial Serie*ss* in admin"
            verbose_name_plural = "Series"

        def __str__(self):
            return self.tutorial_series

    class Tutorial(models.Model):
        tutorial_title = models.CharField(max_length=200)
        tutorial_content = models.TextField()
        tutorial_published = models.DateTimeField("date published", default = datetime.now())
        tutorial_series = models.ForeignKey(TutorialSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT)
        tutorial_slug = models.CharField(max_length=200,default=1)

        def __str__(self):
            return self.tutorial_title

Body:
In your Tutorial model, you are using a default value for the foreign key field ** tutorial_series **. This causes the migration to check if a record in TutorialSeries exists with id=1 but there is no such data present, so the error is occuring.

To avoid the error while migrating, remove the on_delete=models.SET_DEFAULT and default=1 from our fields to make your models as:

class TutorialSeries(models.Model):
    tutorial_series = models.CharField(max_length=200)
    tutorial_category = models.ForeignKey(TutorialCategory,verbose_name="Category")
    series_summary = models.CharField(max_length=200)

    class Meta:
        #Otherwise we get "Tutorial Serie*ss* in admin"
        verbose_name_plural = "Series"

    def __str__(self):
        return self.tutorial_series

class Tutorial(models.Model):
        tutorial_title = models.CharField(max_length=200)
        tutorial_content = models.TextField()
        tutorial_published = models.DateTimeField("date published", default = datetime.now())
        tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", blank=True, null=True) #<--changes
        tutorial_slug = models.CharField(max_length=200,default=1)

        def __str__(self):
            return self.tutorial_title

After this, migrate your models. Then add data to TutorialCategory and TutorialSeries with id=1.

Then revert your models to your initial setup (keeping default=1 and on_delete=models.SET_DEFAULT). Then again run makemigrations and migrate your models. After this, your problem might be solved.


问:
Filter then copy and paste values to new Excel tab
I'm trying to use an autofilter to filter unique values, then copy and paste these values to a new Excel tab.

The macro stops working at this line of code.

```<code>Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
  CopyToRange:=Range("CA1"), Unique:=True
</code>```

```<code>Private Sub CommandButton3_Click()

Application.ScreenUpdating = False
Dim x As Range
Dim rng As Range
Dim last As Long
Dim sht As String

'specify sheet name in which the data is stored
sht = "data"

'change filter column in the following code
last = Sheets(sht).Cells(Rows.Count, "B").End(xlUp).Row
Set rng = Sheets(sht).Range("A1:AY" & last)
'set last column

Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
  CopyToRange:=Range("CA1"), Unique:=True

For Each x In Range([CA2], Cells(Rows.Count, "CA").End(xlUp))
    With rng
        .AutoFilter
        .AutoFilter Field:=1, Criteria1:=x.Value
        .SpecialCells(xlCellTypeVisible).Copy

        Sheets.Add(After:=Sheets(Sheets.Count)).Name = x.Value
        ActiveSheet.Paste
        ActiveSheet.Range("A1").Select
        ActiveSheet.Columns("A:A").Select
        Selection.ColumnWidth = 15

    End With
Next x

' Turn off filter
Sheets(sht).AutoFilterMode = False

With Application
    .CutCopyMode = False
    .ScreenUpdating = True
End With

End Sub
</code>```

答:
In my opinion i think:

You are missing an End Sub at the end of your code.

CopyToRange:=Range("CA1"), you dont mention the sheet name just the range.

Body:
I'm trying to use an autofilter to filter unique values, then copy and paste these values to a new Excel tab.

The macro stops working at this line of code.

Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
  CopyToRange:=Range("CA1"), Unique:=True

Private Sub CommandButton3_Click()

Application.ScreenUpdating = False
Dim x As Range
Dim rng As Range
Dim last As Long
Dim sht As String

'specify sheet name in which the data is stored
sht = "data"

'change filter column in the following code
last = Sheets(sht).Cells(Rows.Count, "B").End(xlUp).Row
Set rng = Sheets(sht).Range("A1:AY" & last)
'set last column

Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
  CopyToRange:=Range("CA1"), Unique:=True

For Each x In Range([CA2], Cells(Rows.Count, "CA").End(xlUp))
    With rng
        .AutoFilter
        .AutoFilter Field:=1, Criteria1:=x.Value
        .SpecialCells(xlCellTypeVisible).Copy

        Sheets.Add(After:=Sheets(Sheets.Count)).Name = x.Value
        ActiveSheet.Paste
        ActiveSheet.Range("A1").Select
        ActiveSheet.Columns("A:A").Select
        Selection.ColumnWidth = 15

    End With
Next x

' Turn off filter
Sheets(sht).AutoFilterMode = False

With Application
    .CutCopyMode = False
    .ScreenUpdating = True
End With

End Sub


问:
How to create backup of one database into another database using php
I want to create backup of my website database in which is in MySQL in another database on regular basis , is it possible to do it using php

Already tried exporting database using php but requirement is something else

答:
I think mysqldump is what you're looking for.

Export database A to SQL file to import to database B:

```<code>mysqldump --host=localhost --user=dbauser --password=dbapassword dba_name > /path/to/store/dba.sql
</code>```

Import database A dump into database B:

```<code>cp /path/to/store/dba.sql | mysql --host-localhost --user=dbbuser --password=dbbpassword dbb_name
</code>```

You can wrap these commands in a call to system() in a PHP script.

Body:
I think mysqldump is what you're looking for.

Export database A to SQL file to import to database B:

mysqldump --host=localhost --user=dbauser --password=dbapassword dba_name > /path/to/store/dba.sql

Import database A dump into database B:

cp /path/to/store/dba.sql | mysql --host-localhost --user=dbbuser --password=dbbpassword dbb_name

You can wrap these commands in a call to system() in a PHP script.


问:
Truncate inline HTML for Read More/Less Button
I am trying to truncate the text which is inside inline html by the length of the text (excluding html) / 2 and add read more button and reverse - add read less button and hide the half of the text. It works if the text is only raw paragraph. But when the text is inline html like below - with ol,ul,headings, it doesn't work. Can someone give a hand on this? Thank you! </p>

```<code><div class="truncate">
 <div class="toggledText" id="toggledText">
 <h1>Lorem Ipsum is simply </h1>
  <h2>Lorem Ipsum is simply </h2>
  <p><strong>Thank you for scanning. </strong></p>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text
    ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not
    only five
   <ol>
    <li>Lorem Ipsum is simply </li>
    <li>Lorem Ipsum is simply. </li>
   </ol>
   <ul>
    <li>Lorem Ipsum is simply </li>
    </ul>

   var numberOfToggled = document.getElementsByClassName('toggledText');

   for(i=0; i<numberOfToggled.length; i++){

    var el = numberOfToggled[i];

  var elText = el.innerHTML.trim();
  var charLimit = elText.length / 2;

        if(elText.length > charLimit){
            var showStr = elText.slice(0,charLimit);
            var hideStr = elText.slice(charLimit);
            el.innerHTML = showStr + '<span class="morePoints">...</span> <span class="trimmed">' + hideStr + '</span>';
            el.parentElement.innerHTML = el.parentElement.innerHTML + "<div class='read-more'><a href='#' class='more'></a>";
        }

    }

    window.onclick = function(event) {
        if (event.target.className == 'more') {
    event.preventDefault();
            event.target.parentElement.parentElement.classList.toggle('showAll');
        }
    }
</code>```

答: There is not perfect solution for this, better use CSS masking https://css-tricks.com/text-fade-read-more/ or just remove tags altogether before shortening.</p>

Body:
I am trying to truncate the text which is inside inline html by the length of the text (excluding html) / 2 and add read more button and reverse - add read less button and hide the half of the text. It works if the text is only raw paragraph. But when the text is inline html like below - with ol,ul,headings, it doesn't work. Can someone give a hand on this? Thank you!

Lorem Ipsum is simply

Lorem Ipsum is simply

Thank you for scanning.

Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text
    ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not
    only five

Lorem Ipsum is simply

Lorem Ipsum is simply.

Lorem Ipsum is simply

   var numberOfToggled = document.getElementsByClassName('toggledText');

   for(i=0; i<numberOfToggled.length; i++){

    var el = numberOfToggled[i];

  var elText = el.innerHTML.trim();
  var charLimit = elText.length / 2;

        if(elText.length > charLimit){
            var showStr = elText.slice(0,charLimit);
            var hideStr = elText.slice(charLimit);
            el.innerHTML = showStr + '... ' + hideStr + '';
            el.parentElement.innerHTML = el.parentElement.innerHTML + "
";
        }

    }

    window.onclick = function(event) {
        if (event.target.className == 'more') {
    event.preventDefault();
            event.target.parentElement.parentElement.classList.toggle('showAll');
        }
    }


问:
How to make the window full screen with Javascript (stretching all over the screen)
How can I make a visitor's browser go fullscreen using JavaScript, in a way that works with IE, Firefox and Opera?</p>

答:
Try screenfull.js. It's a nice cross-browser solution that should work for Opera browser as well.

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.

Demo.


答:
If your text should be truncated in case of that there is no available space, then you can use CSS properties:

```<code>.text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

<p class="text-ellipsis">
    Lorem Ipsum is simply dummy text of the printing and typesetting
                   industry. Lorem Ipsum has been the industry's standard dummy text
                   ever since the 1500s, when an unknown printer took a galley of type
                   and scrambled it to make a type specimen book. It has survived not
                   only five
</p>
</code>```

Output( please, see three dots at the end of row):

Title: Truncate inline HTML for Read More/Less Button

Body:
If your text should be truncated in case of that there is no available space, then you can use CSS properties:

.text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

<p class="text-ellipsis">
    Lorem Ipsum is simply dummy text of the printing and typesetting
                   industry. Lorem Ipsum has been the industry's standard dummy text
                   ever since the 1500s, when an unknown printer took a galley of type
                   and scrambled it to make a type specimen book. It has survived not
                   only five
</p>

Output( please, see three dots at the end of row):


问:
Change button background twice within one function
I'm trying to do "memoryGame" in javaFX. What I'm now dealing with is changing the background of a button, using CSS, twice in one function, after this button was clicked.

In this game I create a GridPane and in each cell I put buttons with pictures, for every picture there are two buttons. On top of it I put another empty buttons. If I click on a button it became transparent, so I can see the picture. Then I clicked another button and the same happens. Now, if the pictures are the same I get one point and the transparency does not change, but if the pictures are different, program waits one second one change both buttons to their primary stage (not transparent).

The problem is that if I change style of a button, wait a second and change it another time, the button does not change its style during this function, but it will happens after the function will ends. So we cannot see the first style, only the last one.

The code I'm sending is simplified version, that 'works' only for one button.

public void changeTransparent(ActionEvent event) {
        butCver01.setStyle("-fx-background-color: transparent");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}

        butCver01.setStyle("-fx-background-color: green");

    }
```

Now when we clicked butCver01, after one second it will change to green.

答:
As I mentioned in my comment, the JavaFX Application Thread cannot schedule the next frame render (i.e. a "pulse") while it's still executing your method. This is compounded by the fact you use Thread.sleep which blocks the FX thread meaning it can't do anything, let alone schedule the next pulse. A blocked FX thread equals a frozen UI and your user won't be able to click on any more cards to try and get a match.

You should use the animation API to do actions "over time" on the FX thread. Animations are executed "asynchronously" (on the FX thread) which means other actions can be processed while an animation is running. The call to start an animation also returns immediately. Here's an example that will reveal a shape underneath a rectangle for one second; however, there's no logic to determine if two matching shapes are revealed, that only two shapes are revealed at a time, and so on.

```<code>import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        HBox box = new HBox(10, createCard(true), createCard(true), createCard(false));
        box.setPadding(new Insets(100));
        primaryStage.setScene(new Scene(box));
        primaryStage.show();
    }

    private StackPane createCard(boolean circle) {
        Shape shape;
        if (circle) {
            shape = new Circle(50, Color.FORESTGREEN);
        } else {
            // create triangle
            shape = new Polygon(0, 0, 50, 100, -50, 100);
            shape.setFill(Color.FIREBRICK);
        }

        Rectangle cover = new Rectangle(0, 0, 100, 150);
        cover.mouseTransparentProperty()
                .bind(cover.fillProperty().isEqualTo(Color.TRANSPARENT));
        cover.setOnMouseClicked(event -> {
            event.consume();

            cover.setFill(Color.TRANSPARENT);

            PauseTransition pt = new PauseTransition(Duration.seconds(1));
            pt.setOnFinished(e -> cover.setFill(Color.BLACK));
            pt.playFromStart();
        });
        return new StackPane(shape, cover);
    }

}
</code>```

Body:
I'm trying to do "memoryGame" in javaFX. What I'm now dealing with is changing the background of a button, using CSS, twice in one function, after this button was clicked.

In this game I create a GridPane and in each cell I put buttons with pictures, for every picture there are two buttons. On top of it I put another empty buttons. If I click on a button it became transparent, so I can see the picture. Then I clicked another button and the same happens. Now, if the pictures are the same I get one point and the transparency does not change, but if the pictures are different, program waits one second one change both buttons to their primary stage (not transparent).

The problem is that if I change style of a button, wait a second and change it another time, the button does not change its style during this function, but it will happens after the function will ends. So we cannot see the first style, only the last one.

The code I'm sending is simplified version, that 'works' only for one button.

public void changeTransparent(ActionEvent event) {
        butCver01.setStyle("-fx-background-color: transparent");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}

        butCver01.setStyle("-fx-background-color: green");

    }

Now when we clicked butCver01, after one second it will change to green.

Body:
As I mentioned in my comment, the JavaFX Application Thread cannot schedule the next frame render (i.e. a "pulse") while it's still executing your method. This is compounded by the fact you use Thread.sleep which blocks the FX thread meaning it can't do anything, let alone schedule the next pulse. A blocked FX thread equals a frozen UI and your user won't be able to click on any more cards to try and get a match.

You should use the animation API to do actions "over time" on the FX thread. Animations are executed "asynchronously" (on the FX thread) which means other actions can be processed while an animation is running. The call to start an animation also returns immediately. Here's an example that will reveal a shape underneath a rectangle for one second; however, there's no logic to determine if two matching shapes are revealed, that only two shapes are revealed at a time, and so on.

import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        HBox box = new HBox(10, createCard(true), createCard(true), createCard(false));
        box.setPadding(new Insets(100));
        primaryStage.setScene(new Scene(box));
        primaryStage.show();
    }

    private StackPane createCard(boolean circle) {
        Shape shape;
        if (circle) {
            shape = new Circle(50, Color.FORESTGREEN);
        } else {
            // create triangle
            shape = new Polygon(0, 0, 50, 100, -50, 100);
            shape.setFill(Color.FIREBRICK);
        }

        Rectangle cover = new Rectangle(0, 0, 100, 150);
        cover.mouseTransparentProperty()
                .bind(cover.fillProperty().isEqualTo(Color.TRANSPARENT));
        cover.setOnMouseClicked(event -> {
            event.consume();

            cover.setFill(Color.TRANSPARENT);

            PauseTransition pt = new PauseTransition(Duration.seconds(1));
            pt.setOnFinished(e -> cover.setFill(Color.BLACK));
            pt.playFromStart();
        });
        return new StackPane(shape, cover);
    }

}


问:
Custom Attributed string action in swift
I want to make the attributed string action in swift. I want append my custom variable to table view cell data.

I added colour and line also for that string, now i want to add the link for that added attributed string.

Please find my code with the following.

I add this code into cell for row at Index path.

```<code> let value = NSMutableAttributedString(string: " tap here.", attributes:[NSAttributedStringKey.link: URL(string: "http://www.google.com")!]).withTextColor(UIColor.disSatifyclr).withUnderlineColor(UIColor.disSatifyclr).withUnderlineStyle(.styleSingle)

        if (cell.desclbl.text?.contains("more about donating, "))! {
            let description = descriptions[indexPath.section][indexPath.row]
            let attributedString = NSMutableAttributedString(string: description)
            attributedString.append(value)

            cell.desclbl.attributedText = attributedString
        }
</code>```

答:
Here you can handle action using UITextView instead of UILabel on tap of string

```<code>class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.attributedText = prepareLink()
        textView.tintColor = UIColor.black
        textView.isSelectable = true
        textView.isEditable = false
        textView.delegate = self
    }

    func prepareLink() -> NSMutableAttributedString {
        let formattedString = NSMutableAttributedString(string: " tap here ")
        let linkAttribute = [
            NSAttributedString.Key.foregroundColor: UIColor.green,
            NSAttributedString.Key.underlineColor: UIColor.green,
            NSAttributedString.Key.underlineStyle: 1,
            NSAttributedString.Key.link: URL(string: "http://www.google.com")!
            ] as [NSAttributedString.Key : Any]

        formattedString.addAttributes(linkAttribute, range: NSMakeRange(0, formattedString.length))
        return formattedString
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

        if (URL.absoluteString == "http://www.google.com") {
            // Do Something
        }
        return true
    }
}
</code>```

Note: If you have to continue with UILabel then you have to implement UITapGesture to handle action.

Body:
I want to make the attributed string action in swift. I want append my custom variable to table view cell data.

I added colour and line also for that string, now i want to add the link for that added attributed string.

Please find my code with the following.

I add this code into cell for row at Index path.

 let value = NSMutableAttributedString(string: " tap here.", attributes:[NSAttributedStringKey.link: URL(string: "http://www.google.com")!]).withTextColor(UIColor.disSatifyclr).withUnderlineColor(UIColor.disSatifyclr).withUnderlineStyle(.styleSingle)

        if (cell.desclbl.text?.contains("more about donating, "))! {
            let description = descriptions[indexPath.section][indexPath.row]
            let attributedString = NSMutableAttributedString(string: description)
            attributedString.append(value)

            cell.desclbl.attributedText = attributedString
        }

Body:
Here you can handle action using UITextView instead of UILabel on tap of string

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.attributedText = prepareLink()
        textView.tintColor = UIColor.black
        textView.isSelectable = true
        textView.isEditable = false
        textView.delegate = self
    }

    func prepareLink() -> NSMutableAttributedString {
        let formattedString = NSMutableAttributedString(string: " tap here ")
        let linkAttribute = [
            NSAttributedString.Key.foregroundColor: UIColor.green,
            NSAttributedString.Key.underlineColor: UIColor.green,
            NSAttributedString.Key.underlineStyle: 1,
            NSAttributedString.Key.link: URL(string: "http://www.google.com")!
            ] as [NSAttributedString.Key : Any]

        formattedString.addAttributes(linkAttribute, range: NSMakeRange(0, formattedString.length))
        return formattedString
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

        if (URL.absoluteString == "http://www.google.com") {
            // Do Something
        }
        return true
    }
}

Note: If you have to continue with UILabel then you have to implement UITapGesture to handle action.


问:
Flexible date/time parsing in Go (Adding default values in parsing)
Further to this question, I want to parse a date/time passed on the command line to a Go program. At the moment, I use the flag package to populate a string variable ts and then the following code:

```<code>if ts == "" {
    config.Until = time.Now()
} else {
    const layout = "2006-01-02T15:04:05"
    if config.Until, err = time.Parse(layout, ts); err != nil {
        log.Errorf("Could not parse %s as a time string: %s. Using current date/time instead.", ts, err.Error())
        config.Until = time.Now()
    }
}
</code>```

This works OK, provided the user passes exactly the right format - e.g. 2019-05-20T09:07:33 or some such.

However, what I would like, if possible, is the flexibility to pass e.g. 2019-05-20T09:07 or 2019-05-20T09 or maybe even 2019-05-20 and have the hours, minutes and seconds default to 0 where appropriate.

Is there a sane1 way to do this?

  1 not requiring me to essentially write my own parser

UPDATE

I've kind of got a solution to this, although it's not particularly elegant, it does appear to work for most of the cases I am likely to encounter.

```<code>package main

import (
    "fmt"
    "time"
)

func main() {

    const layout = "2006-01-02T15:04:05"
    var l string
    var input string

    for _, input = range []string{"2019-05-30", "2019-05-30T16", "2019-05-30T16:04", "2019-05-30T16:04:34",
                                "This won't work", "This is extravagantly long and won't work either"} {
        if len(input) < len(layout) {
            l = layout[:len(input)]
        } else {
            l = layout
        }
        if d, err := time.Parse(l, input); err != nil {
            fmt.Printf("Error %s\n", err.Error())
        } else {
            fmt.Printf("Layout %-20s gives time %v\n", l, d)
        }
    }
}
</code>```

答:
Just try each format, until one works. If none work, return an error.</p>

```<code>var formats = []string{"2006-01-02T15:04:05", "2006-01-02", ...}

func parseTime(input string) (time.Time, error) {
    for _, format := range formats {
        t, err := time.Parse(format, input)
        if err == nil {
            return t, nil
        }
    }
    return time.Time{}, errors.New("Unrecognized time format")
}
</code>```

Body:
Further to this question, I want to parse a date/time passed on the command line to a Go program. At the moment, I use the flag package to populate a string variable ts and then the following code:

if ts == "" {
    config.Until = time.Now()
} else {
    const layout = "2006-01-02T15:04:05"
    if config.Until, err = time.Parse(layout, ts); err != nil {
        log.Errorf("Could not parse %s as a time string: %s. Using current date/time instead.", ts, err.Error())
        config.Until = time.Now()
    }
}

This works OK, provided the user passes exactly the right format - e.g. 2019-05-20T09:07:33 or some such.

However, what I would like, if possible, is the flexibility to pass e.g. 2019-05-20T09:07 or 2019-05-20T09 or maybe even 2019-05-20 and have the hours, minutes and seconds default to 0 where appropriate.

Is there a sane1 way to do this?

  1 not requiring me to essentially write my own parser

UPDATE

I've kind of got a solution to this, although it's not particularly elegant, it does appear to work for most of the cases I am likely to encounter.

package main

import (
    "fmt"
    "time"
)

func main() {

    const layout = "2006-01-02T15:04:05"
    var l string
    var input string

    for _, input = range []string{"2019-05-30", "2019-05-30T16", "2019-05-30T16:04", "2019-05-30T16:04:34",
                                "This won't work", "This is extravagantly long and won't work either"} {
        if len(input) < len(layout) {
            l = layout[:len(input)]
        } else {
            l = layout
        }
        if d, err := time.Parse(l, input); err != nil {
            fmt.Printf("Error %s\n", err.Error())
        } else {
            fmt.Printf("Layout %-20s gives time %v\n", l, d)
        }
    }
}

Body:
Just try each format, until one works. If none work, return an error.

var formats = []string{"2006-01-02T15:04:05", "2006-01-02", ...}

func parseTime(input string) (time.Time, error) {
    for _, format := range formats {
        t, err := time.Parse(format, input)
        if err == nil {
            return t, nil
        }
    }
    return time.Time{}, errors.New("Unrecognized time format")
}


问:
Pass multiple lines of stdin input to interactive Java command line program, non-interactively
I have a command-line java program that takes a password and it's verification from stdin. Unfortunately, modifying the program isn't an option as it is proprietary.

I'm unable to pass the arguments from the unix command line using < since there are two prompts in the program, both asking for the same password. There are stdout statements asking for "Password" and "Password (validation):" on the command prompt.

How can I pass the password non-interactively to this program so that it can be executed automatically using a cron job / RC script?

Thanks!

答: Not sure by your question if Expect is acceptable or not.</p>


问:
Put a button inside the text box
I'm trying to design a form, with a button inside a text-box. I want that button to be inside the text-box. This is how I tried:

```<code><div class="row">
    <div class="col-sm-6">
        <div class="form-group required">
            <label for="PickList_Options" class="col-sm-4 control-label">Options</label>
            <div class="col-sm-4 buttonwrapper">
                <input type="text" class="form-control" id="PickList_Options" name="PickList_Options" value='' />
                <button>GO</button>
            </div>
        </div>
    </div>
    <div class="col-sm-6">
        <div class="result" id="mydiv"></div>
    </div>
</div>
</code>```

my css:

```<code>.buttonwrapper {
    display:inline-block;
}

input,
button {
    background-color:transparent;
    border:0;
}
</code>```

But, the problem is, the Go button is placed below the text-box. What should I do to place it inside the text-box?

I want that "Go" button to be inside the text-box.

答:
.buttonwrapper {
  display: inline-block;
}

input{
  background-color: transparent;
  border: 2px solid black;
}

button {
  margin-left: 200px;
  border: none;
  background-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-sm-6">
    <div class="form-group required">
      <label for="PickList_Options" class="col-sm-4 control-label">Options</label>

      <div class="col-sm-4 buttonwrapper">
        <input type="text" class="form-control" id="PickList_Options" name="PickList_Options" value='' />
        <button>GO</button>
      </div>
    </div>
  </div>
  <div class="col-sm-6">
    <div class="result" id="mydiv"></div>
  </div>
</div></code>```

Title: Put a button inside the text box

Body:
I'm trying to design a form, with a button inside a text-box. I want that button to be inside the text-box. This is how I tried:

            Options

                <input type="text" class="form-control" id="PickList_Options" name="PickList_Options" value='' />
                <button>GO</button>

my css:

.buttonwrapper {
    display:inline-block;
}

input,
button {
    background-color:transparent;
    border:0;
}

But, the problem is, the Go button is placed below the text-box. What should I do to place it inside the text-box?

I want that "Go" button to be inside the text-box.

Body:
.buttonwrapper {
  display: inline-block;
}

input{
  background-color: transparent;
  border: 2px solid black;
}

button {
  margin-left: 200px;
  border: none;
  background-color: transparent;
}

<div class="row">
  <div class="col-sm-6">
    <div class="form-group required">
      <label for="PickList_Options" class="col-sm-4 control-label">Options</label>

      <div class="col-sm-4 buttonwrapper">
        <input type="text" class="form-control" id="PickList_Options" name="PickList_Options" value='' />
        <button>GO</button>
      </div>
    </div>
  </div>
  <div class="col-sm-6">
    <div class="result" id="mydiv"></div>
  </div>
</div>


问:
Is `ng serve` command suitable for production?
I'm building a small project using Angular 7.  When you run

```<code>ng serve
</code>```

and a NodeJS server is spun up to handle requests, does each request block until processing is complete?  We are trying to evaluate how effective using this in production would be as opposed to using a more traditional application server.

答:
Run ng build --prod
It will generate minification code in "dist" folder. you have to upload the file content of this "dist" folder. It will give faster response for loading web pages.

For more details please refer Angular deployment guide

Body:
I'm building a small project using Angular 7.  When you run

ng serve

and a NodeJS server is spun up to handle requests, does each request block until processing is complete?  We are trying to evaluate how effective using this in production would be as opposed to using a more traditional application server.


问:
Cannot find element within iframe using Selenium
I'm trying to locate elements within the iframe but got no luck.

I think because of my code cannot switch to the iframe and that's why I couldn't locate the elements within it.

Below is my code.

I have tried

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '/html/body/iframe')))
driver.find_element_by_name('applicant.name').send_keys('email')

```

<p>I also tried this</p>

<pre class="lang-py prettyprint-override"><code>iframe = driver.find_element_by_xpath('/html/body/iframe')
driver.switch_to.frame(iframe)
driver.implicitly_wait(10)
driver.find_element_by_name('applicant.name').send_keys('email')
</code>```

I tried look for xpath, id of the applicant.name but notthing work so far. Any help or suggestions would be appreciated.

Here the site:
https://www.indeed.com/cmp/Paratus-Partners-LLC/jobs/Full-Stack-Developer-7814e52be25090f3?from=iaBackPress&q=software%20developer&vjs=3

答:
There are at least 2 iframes in the page you're trying to automate:

Therefore you need to

Amend your XPath Expression to uniquely identify first iframe like:

```<code>parentIframe = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH,"//iframe[contains(@id,'modal-iframe')]")))
</code>```

Switch to first iframe

```<code>driver.switch_to.frame(parentIframe)
</code>```

Locate second iframe and switch to it

```<code>childIframe =  WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH,"//iframe[contains(@src,'resumeapply')]")))
driver.switch_to.frame(childIframe)
</code>```

Once done you should be able to send text into the input fields.

Body:
I'm trying to locate elements within the iframe but got no luck.

I think because of my code cannot switch to the iframe and that's why I couldn't locate the elements within it.

Below is my code.

I have tried

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '/html/body/iframe')))
driver.find_element_by_name('applicant.name').send_keys('email')

I also tried this

iframe = driver.find_element_by_xpath('/html/body/iframe')
driver.switch_to.frame(iframe)
driver.implicitly_wait(10)
driver.find_element_by_name('applicant.name').send_keys('email')

I tried look for xpath, id of the applicant.name but notthing work so far. Any help or suggestions would be appreciated.

Here the site:
https://www.indeed.com/cmp/Paratus-Partners-LLC/jobs/Full-Stack-Developer-7814e52be25090f3?from=iaBackPress&q=software%20developer&vjs=3

Body:
There are at least 2 iframes in the page you're trying to automate:

Therefore you need to

Amend your XPath Expression to uniquely identify first iframe like:

parentIframe = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH,"//iframe[contains(@id,'modal-iframe')]")))

Switch to first iframe

driver.switch_to.frame(parentIframe)

Locate second iframe and switch to it

childIframe =  WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH,"//iframe[contains(@src,'resumeapply')]")))
driver.switch_to.frame(childIframe)

Once done you should be able to send text into the input fields.


问:
How can I fix the DatePicker Invalid prop value of type string error in my React with Redux and KendoUI Web Application?
I'm currently working on my React with REdux application for ASP.NET Core using the Kendo React UI from Telerik.  I'm using their grid widget, which, seems to be working ok until you try to edit one of the rows.  When you try to edit a row you get the following error:

Warning: Failed prop type: Invalid prop value of type String
  supplied to DatePicker, expected instance of Date.
      in DatePicker

I searched for an answer to this problem and found a couple of possibilities.

The first was to set the default value defaultValue to null which didn't work.

The second answer suggested setting the format to null i.e. format={null} but that didn't work either.

Here is my code.

ContactContainer

```<code>import * as React from 'react';
import { GridColumn, Grid } from '@progress/kendo-react-grid';
import { withState } from './ContactComponent';
import { CommandCell } from './CommandCell';

const ContactsGrid = withState(Grid);

class ContactContainer extends React.Component {
    render() {
        return (
            <div>
                <ContactsGrid
                    sortlable
                    pageable
                    pageSize={10}
                    editField="inEdit">
                    <GridColumn field="Id" title="Id" editable={false} width={100} />
                    <GridColumn field="FirstName" title="First Name" />
                    <GridColumn field="LastName" title="Last Name" />
                    <GridColumn field="Email" title="Email" />
                    <GridColumn field="CreatedUser" title="Created By" />
                    <GridColumn field="CreatedDate" title="Created Date" editor="date" format="{0:d}" defaultValue={null} />
                    <GridColumn
                        groupable={false}
                        sortable={false}
                        filterable={false}
                        resizable={false}
                        field="_command"
                        title=" "
                        width="180px"
                        cell={CommandCell}
                    />
                </ContactsGrid>
            </div>
        );
    }
}
export default ContactContainer;
</code>```

ContactComponent

```<code>import React from 'react';
import { toDataSourceRequestString, translateDataSourceResultGroups } from '@progress/kendo-data-query';
import { Grid, GridToolbar } from '@progress/kendo-react-grid';
import AddIcon from '@material-ui/icons/Add';
import Fab from '@material-ui/core/Fab';

export function withState() {
    return class StatefullGrid extends React.Component {
        constructor(props) {
            super(props);
            if (props.pageable === false) {
                this.state = {};
            } else {
                this.state = {
                    dataState: {
                        skip: 0,
                        take: 20
                    }
                };
            }
        }
        render() {
            return (
                <Grid
                    editField="_command"
                    {...this.props}
                    {...this.state.dataState}
                    total={this.state.total}
                    data={this.state.result}
                    onItemChange={this.itemChange}
                    onDataStateChange={this.onDataStateChange}>
                    <GridToolbar>
                        <Fab size="small" color="secondary" aria-label="Add" onClick={this.addContact}>
                            <AddIcon />
                        </Fab>
                    </GridToolbar>
                    {this.props.children}
                </Grid>
            );
        }

        componentDidMount() {
            this.fetchData(this.state.dataState);
        }

        addContact = () => {
            const data = this.state.result;
            data.unshift({ "_command": true, inEdit: true });
            this.setState({
                result: data
            })
        };
        enterEdit = (item) => {
            this.itemInEdit = Object.assign(item, {});
            item.inEdit = true;
            this.forceUpdate();
        };
        cancelEdit = (item) => {
            let data = this.state.result
            let mappedData = data.map(record => {
                if (record.Id === this.itemInEdit.Id) {
                    record = this.itemInEdit;
                    record.inEdit = false
                }
                return record
            })
            this.setState({
                result: mappedData
            })
        };

        handleDataStateChange = (changeEvent) => {
            this.setState({ dataState: changeEvent.Data });
            this.fetchData(changeEvent.data);
        };
        onDataStateChange = (changeEvent) => {
            this.setState({ dataState: changeEvent.Data });
            this.fetchData(changeEvent.Data);
        };
        serialize = (obj) => {
            var str = [];
            for (var p in obj)
                if (obj.hasOwnProperty(p)) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
            return str.join("&");
        };
        itemChange = (event) => {
            switch (event.value) {
                case "edit":
                    this.enterEdit(event.dataItem)
                    break;
                case "delete":
                    this.deleteItem(event.dataItem)
                    break;
                case "update":
                    if (event.dataItem.Id) {
                        this.updateItem(event.dataItem)
                    } else {
                        this.addContact(event.dataItem)
                    }
                    break;
                case "cancel":
                    this.cancelEdit(event.dataItem)
                    break;
                default:
                    const data = this.state.result.slice();
                    const index = data.findIndex(d => d.id === event.dataItem.id);
                    data[index] = { ...data[index], [event.field]: event.value };
                    this.setState({
                        result: data
                    });
            }

        };
        fetchData(dataState) {
            const queryStr = `${toDataSourceRequestString(dataState)}`;
            const hasGroups = dataState.group && dataState.group.length;
            const base_url = 'api/Contact/GetContacts';
            const init = { method: 'GET', accept: 'application/json', headers: {} };

            fetch(`${base_url}?${queryStr}`, init)
                .then(response => response.json())
                .then(({ Data, total }) => {
                    this.setState({
                        result: hasGroups ? translateDataSourceResultGroups(Data) : Data,
                        total,
                        dataState
                    });
                });
        };
    }
}
</code>```

CommandCell

```<code>import React from 'react';
import { GridCell } from '@progress/kendo-react-grid';
import IconButton from '@material-ui/core/IconButton';
import Fab from '@material-ui/core/Fab';
import EditIcon from '@material-ui/icons/Edit';
import DeleteIcon from '@material-ui/icons/Delete';
import DoneIcon from '@material-ui/icons/Done';
import CloseIcon from '@material-ui/icons/Close';

export class CommandCell extends GridCell {
    buttonClick = (e, command) => {
        this.props.onChange({ dataItem: this.props.dataItem, e, field: this.props.field, value: command });

    }
    render() {
        if (this.props.rowType !== "data") {
            return null;
        }

        if (this.props.dataItem.inEdit) {
            return (
                <td>
                    <IconButton color="secondary" className="k-grid-save-command"
                        onClick={(e) => this.buttonClick(e, "update")}>
                        <DoneIcon />
                    </IconButton>
                    <IconButton color="inherit" className="k-grid-cancel-command"
                        onClick={(e) => this.buttonClick(e, "cancel")}>
                        <CloseIcon />
                    </IconButton>
                </td>
            );
        }

        return (
            <td>
                <Fab color="secondary" aria-label="Edit" className="k-grid-edit-command" onClick={(e) => this.buttonClick(e, "edit")}>
                    <EditIcon />
                </Fab>
                <Fab color="secondary" aria-label="Delete" className="k-grid-remove-command" onClick={(e) => window.confirm('Confirm deleting: ' + this.props.dataItem.Name) && this.buttonClick(e, "delete")}>
                    <DeleteIcon />
                </Fab>
            </td>
        );
    }
}
</code>```

Can anyone help me with a solution to this problem or a workaround?

答:
i think problem is here you have assigned defaultValue={null} which throw warning. try passing date in defaultValue

<GridColumn field="CreatedDate" title="Created Date" editor="date" format="{0:d}" defaultValue={new Date()} />

Body:
I'm currently working on my React with REdux application for ASP.NET Core using the Kendo React UI from Telerik.  I'm using their grid widget, which, seems to be working ok until you try to edit one of the rows.  When you try to edit a row you get the following error:

Warning: Failed prop type: Invalid prop value of type String
  supplied to DatePicker, expected instance of Date.
      in DatePicker

I searched for an answer to this problem and found a couple of possibilities.

The first was to set the default value defaultValue to null which didn't work.

The second answer suggested setting the format to null i.e. format={null} but that didn't work either.

Here is my code.

ContactContainer

import * as React from 'react';
import { GridColumn, Grid } from '@progress/kendo-react-grid';
import { withState } from './ContactComponent';
import { CommandCell } from './CommandCell';

const ContactsGrid = withState(Grid);

class ContactContainer extends React.Component {
    render() {
        return (

                <ContactsGrid
                    sortlable
                    pageable
                    pageSize={10}
                    editField="inEdit">
                    <GridColumn field="Id" title="Id" editable={false} width={100} />
                    <GridColumn field="FirstName" title="First Name" />
                    <GridColumn field="LastName" title="Last Name" />
                    <GridColumn field="Email" title="Email" />
                    <GridColumn field="CreatedUser" title="Created By" />
                    <GridColumn field="CreatedDate" title="Created Date" editor="date" format="{0:d}" defaultValue={null} />
                    <GridColumn
                        groupable={false}
                        sortable={false}
                        filterable={false}
                        resizable={false}
                        field="_command"
                        title=" "
                        width="180px"
                        cell={CommandCell}
                    />
                </ContactsGrid>

        );
    }
}
export default ContactContainer;

ContactComponent

import React from 'react';
import { toDataSourceRequestString, translateDataSourceResultGroups } from '@progress/kendo-data-query';
import { Grid, GridToolbar } from '@progress/kendo-react-grid';
import AddIcon from '@material-ui/icons/Add';
import Fab from '@material-ui/core/Fab';

export function withState() {
    return class StatefullGrid extends React.Component {
        constructor(props) {
            super(props);
            if (props.pageable === false) {
                this.state = {};
            } else {
                this.state = {
                    dataState: {
                        skip: 0,
                        take: 20
                    }
                };
            }
        }
        render() {
            return (
                <Grid
                    editField="_command"
                    {...this.props}
                    {...this.state.dataState}
                    total={this.state.total}
                    data={this.state.result}
                    onItemChange={this.itemChange}
                    onDataStateChange={this.onDataStateChange}>
                    <GridToolbar>
                        <Fab size="small" color="secondary" aria-label="Add" onClick={this.addContact}>
                            <AddIcon />
                        </Fab>
                    </GridToolbar>
                    {this.props.children}
                </Grid>
            );
        }

        componentDidMount() {
            this.fetchData(this.state.dataState);
        }

        addContact = () => {
            const data = this.state.result;
            data.unshift({ "_command": true, inEdit: true });
            this.setState({
                result: data
            })
        };
        enterEdit = (item) => {
            this.itemInEdit = Object.assign(item, {});
            item.inEdit = true;
            this.forceUpdate();
        };
        cancelEdit = (item) => {
            let data = this.state.result
            let mappedData = data.map(record => {
                if (record.Id === this.itemInEdit.Id) {
                    record = this.itemInEdit;
                    record.inEdit = false
                }
                return record
            })
            this.setState({
                result: mappedData
            })
        };

        handleDataStateChange = (changeEvent) => {
            this.setState({ dataState: changeEvent.Data });
            this.fetchData(changeEvent.data);
        };
        onDataStateChange = (changeEvent) => {
            this.setState({ dataState: changeEvent.Data });
            this.fetchData(changeEvent.Data);
        };
        serialize = (obj) => {
            var str = [];
            for (var p in obj)
                if (obj.hasOwnProperty(p)) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
            return str.join("&");
        };
        itemChange = (event) => {
            switch (event.value) {
                case "edit":
                    this.enterEdit(event.dataItem)
                    break;
                case "delete":
                    this.deleteItem(event.dataItem)
                    break;
                case "update":
                    if (event.dataItem.Id) {
                        this.updateItem(event.dataItem)
                    } else {
                        this.addContact(event.dataItem)
                    }
                    break;
                case "cancel":
                    this.cancelEdit(event.dataItem)
                    break;
                default:
                    const data = this.state.result.slice();
                    const index = data.findIndex(d => d.id === event.dataItem.id);
                    data[index] = { ...data[index], [event.field]: event.value };
                    this.setState({
                        result: data
                    });
            }

        };
        fetchData(dataState) {
            const queryStr = `${toDataSourceRequestString(dataState)}`;
            const hasGroups = dataState.group && dataState.group.length;
            const base_url = 'api/Contact/GetContacts';
            const init = { method: 'GET', accept: 'application/json', headers: {} };

            fetch(`${base_url}?${queryStr}`, init)
                .then(response => response.json())
                .then(({ Data, total }) => {
                    this.setState({
                        result: hasGroups ? translateDataSourceResultGroups(Data) : Data,
                        total,
                        dataState
                    });
                });
        };
    }
}

CommandCell

import React from 'react';
import { GridCell } from '@progress/kendo-react-grid';
import IconButton from '@material-ui/core/IconButton';
import Fab from '@material-ui/core/Fab';
import EditIcon from '@material-ui/icons/Edit';
import DeleteIcon from '@material-ui/icons/Delete';
import DoneIcon from '@material-ui/icons/Done';
import CloseIcon from '@material-ui/icons/Close';

export class CommandCell extends GridCell {
    buttonClick = (e, command) => {
        this.props.onChange({ dataItem: this.props.dataItem, e, field: this.props.field, value: command });

    }
    render() {
        if (this.props.rowType !== "data") {
            return null;
        }

        if (this.props.dataItem.inEdit) {
            return (

                    <IconButton color="secondary" className="k-grid-save-command"
                        onClick={(e) => this.buttonClick(e, "update")}>
                        <DoneIcon />
                    </IconButton>
                    <IconButton color="inherit" className="k-grid-cancel-command"
                        onClick={(e) => this.buttonClick(e, "cancel")}>
                        <CloseIcon />
                    </IconButton>

            );
        }

        return (

                <Fab color="secondary" aria-label="Edit" className="k-grid-edit-command" onClick={(e) => this.buttonClick(e, "edit")}>
                    <EditIcon />
                </Fab>
                <Fab color="secondary" aria-label="Delete" className="k-grid-remove-command" onClick={(e) => window.confirm('Confirm deleting: ' + this.props.dataItem.Name) && this.buttonClick(e, "delete")}>
                    <DeleteIcon />
                </Fab>

        );
    }
}

Can anyone help me with a solution to this problem or a workaround?


问:
how to create short code to display particular testimonial using its post id?
i have created custom post type for testimonials in wordpress.i have added 89 testimonials and wants to display 2 which i wants to displany in home page .
so wanted to created shortcode which will display testimonials according to their Post ID.
can anyone please tell me the code for shortcode.

Below i am showing code i had written to create custom post type for testimonial . Pls tell me the code to create shortcode like this:-[testimonial posts_per_page="5" testimonial_id="123,145"]

```<code>function custom_post_testimonial_type() {

// Set UI labels for Custom Post Type
$labels = array(
    'name'=> _x( 'Testimonials', 'Post Type General Name', 'walker_theme' ),
 'singular_name'=> _x( 'Testimonial', 'Post Type Singular Name', 'walker_theme' ),
   'menu_name'=> __( 'Testimonials', 'walker_theme' ),
'parent_item_colon' => __( 'Testimonial', 'walker_theme' ),
'all_items'  => __( 'All Testimonials', 'walker_theme' ),
'view_item' => __( 'View Testimonial', 'walker_theme' ),
'add_new_item' => __( 'Add New Testimonial','walker_theme' ),
'add_new'  => __( 'Add New', 'walker_theme' ),
'edit_item'  => __( 'Edit Testimonial','walker_theme' ),
'update_item' => __( 'Update Testimonial','walker_theme' ),
'search_items' => __( 'Search Testimonial', 'walker_theme' ),
'not_found'           => __( 'Not Found', 'walker_theme' ),
'not_found_in_trash'  => __( 'Not found in Trash','walker_theme' ),
);

  // Set other options for Custom Post Type

$args = array(
'label'               => __( 'testimonials', 'walker_theme' ),
'description'         => __( 'Home page testimonials', 'walker_theme' ),
'labels'              => $labels,
    // Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'author','thumbnail', 'tags'),
    // You can associate this CPT with a taxonomy or custom
      taxonomy.
    'taxonomies'          => array( 'genres', 'post_tag' ),
    /* A hierarchical CPT is like Pages and can have
    * Parent and child items. A non-hierarchical CPT
    * is like Posts.
    */
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'menu_position'       => 5,
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page',
);

// Registering your Custom Post Type
register_post_type( 'testimonials', $args );

    }

    add_action( 'init', 'custom_post_testimonial_type', 0 );
</code>```

答:
Use the shortcode attributes with known attributes and fills in defaults when needed.

```<code> function testimonials($atts) {
    $a = shortcode_atts( array(
        'posts_per_page' => '',
        'testimonial_id'  =>  ''
    ), $atts );

    $testimonials = '';
    $post_in = esc_attr($a['testimonial_id']);
    $posts_per_page = esc_attr($a['posts_per_page']);

    $post_artay = explode(',', $post_in);
    $args = array(
        'post__in' => $post_artay,
        'posts_per_page' => $posts_per_page,
        'post_type'        => 'testimonials',
        'order_by' => 'post__in',
    );

    // the query
    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $testimonials.= '<div class="title">'.get_the_title().'</div>';
        $testimonials.= '<div class="content">'.get_the_content().'</div>';
        $testimonials.='<div class="date">'.get_the_date().'</div>';
        $testimonials.='<div class="author">'.get_the_author().'</div>';
    endwhile;
    endif;
    return $testimonials;
}
add_shortcode('testimonial', 'testimonials' );
</code>```

use the shortcode like.

```<code>[testimonial posts_per_page="5" testimonial_id="29,23"]
</code>```

Body:
i have created custom post type for testimonials in wordpress.i have added 89 testimonials and wants to display 2 which i wants to displany in home page .
so wanted to created shortcode which will display testimonials according to their Post ID.
can anyone please tell me the code for shortcode.

Below i am showing code i had written to create custom post type for testimonial . Pls tell me the code to create shortcode like this:-[testimonial posts_per_page="5" testimonial_id="123,145"]

function custom_post_testimonial_type() {

// Set UI labels for Custom Post Type
$labels = array(
    'name'=> _x( 'Testimonials', 'Post Type General Name', 'walker_theme' ),
 'singular_name'=> _x( 'Testimonial', 'Post Type Singular Name', 'walker_theme' ),
   'menu_name'=> __( 'Testimonials', 'walker_theme' ),
'parent_item_colon' => __( 'Testimonial', 'walker_theme' ),
'all_items'  => __( 'All Testimonials', 'walker_theme' ),
'view_item' => __( 'View Testimonial', 'walker_theme' ),
'add_new_item' => __( 'Add New Testimonial','walker_theme' ),
'add_new'  => __( 'Add New', 'walker_theme' ),
'edit_item'  => __( 'Edit Testimonial','walker_theme' ),
'update_item' => __( 'Update Testimonial','walker_theme' ),
'search_items' => __( 'Search Testimonial', 'walker_theme' ),
'not_found'           => __( 'Not Found', 'walker_theme' ),
'not_found_in_trash'  => __( 'Not found in Trash','walker_theme' ),
);

  // Set other options for Custom Post Type

$args = array(
'label'               => __( 'testimonials', 'walker_theme' ),
'description'         => __( 'Home page testimonials', 'walker_theme' ),
'labels'              => $labels,
    // Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'author','thumbnail', 'tags'),
    // You can associate this CPT with a taxonomy or custom
      taxonomy.
    'taxonomies'          => array( 'genres', 'post_tag' ),
    /* A hierarchical CPT is like Pages and can have
    * Parent and child items. A non-hierarchical CPT
    * is like Posts.
    */
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'menu_position'       => 5,
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page',
);

// Registering your Custom Post Type
register_post_type( 'testimonials', $args );

    }

    add_action( 'init', 'custom_post_testimonial_type', 0 );

Body:
Use the shortcode attributes with known attributes and fills in defaults when needed.

 function testimonials($atts) {
    $a = shortcode_atts( array(
        'posts_per_page' => '',
        'testimonial_id'  =>  ''
    ), $atts );

    $testimonials = '';
    $post_in = esc_attr($a['testimonial_id']);
    $posts_per_page = esc_attr($a['posts_per_page']);

    $post_artay = explode(',', $post_in);
    $args = array(
        'post__in' => $post_artay,
        'posts_per_page' => $posts_per_page,
        'post_type'        => 'testimonials',
        'order_by' => 'post__in',
    );

    // the query
    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $testimonials.= '<div class="title">'.get_the_title().'</div>';
        $testimonials.= '<div class="content">'.get_the_content().'</div>';
        $testimonials.='<div class="date">'.get_the_date().'</div>';
        $testimonials.='<div class="author">'.get_the_author().'</div>';
    endwhile;
    endif;
    return $testimonials;
}
add_shortcode('testimonial', 'testimonials' );

use the shortcode like.

[testimonial posts_per_page="5" testimonial_id="29,23"]


问:
in Azure service fabric is there a way to limit memory usage of micro service
We came across a situation where one of the microservice had memory issues and consumed all the memory in one of the vms in the cluster. This in turn affected all other microservics.

Is there a way to set a limit on how much memory the microservice can occupy?

These are all stateless microservices.

答: Check out Resource Governance Policies. You specify them in ApplicationManifest. You can set MemoryInMB or MemoryReservationInMB for example. According to the documentation the first one is rather "harsh" limit and the second one is "soft" limit. Not sure exactly what it means. (I assume if the first one reaches the limit the exception will be thrown). I recommend to play with these two and see if this will satisfy your needs.


问:
Different rows for results while using the SQL case statement for same value
The result should be in a single row with logged in and not logged in counts. Why it is coming in two different rows for same account?</p>

```<code>SELECT distinct  Account
     , SUM(CASE Val WHEN status='logged in' THEN  1 Else 0  END) AS 'Total logged in'
     , SUM(CASE Val WHEN status='not logged in' THEN  1 Else 0 END) AS 'total not logged in '
FROM TableAccount
GROUP BY Account

account    logged in    not logged in
A            21             0
A            0              2
</code>```

答:
This seems to be giving the result as desired if your table structure is same.</p>

```<code>create table test1(col1 varchar(10), col2 varchar(10))

insert into test1
values('A','L'),
('A','NL'),
('A','L'),
('A','L')

SELECT distinct  col1
     , SUM(CASE WHEN col2='L' THEN  1 Else 0  END) AS 'Total logged in'
     , SUM(CASE WHEN col2='NL' THEN  1 Else 0 END) AS 'total not logged in '
FROM test1
GROUP BY col1
</code>```

Body:
The result should be in a single row with logged in and not logged in counts. Why it is coming in two different rows for same account?

SELECT distinct  Account
     , SUM(CASE Val WHEN status='logged in' THEN  1 Else 0  END) AS 'Total logged in'
     , SUM(CASE Val WHEN status='not logged in' THEN  1 Else 0 END) AS 'total not logged in '
FROM TableAccount
GROUP BY Account

account    logged in    not logged in
A            21             0
A            0              2

Body:
This seems to be giving the result as desired if your table structure is same.

create table test1(col1 varchar(10), col2 varchar(10))

insert into test1
values('A','L'),
('A','NL'),
('A','L'),
('A','L')

SELECT distinct  col1
     , SUM(CASE WHEN col2='L' THEN  1 Else 0  END) AS 'Total logged in'
     , SUM(CASE WHEN col2='NL' THEN  1 Else 0 END) AS 'total not logged in '
FROM test1
GROUP BY col1


问:
AssertionError: View function mapping is overwriting an existing endpoint function: main
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this

```<code>app.add_url_rule('/',
                 view_func=Main.as_view('main'),
                 methods=["GET"])

app.add_url_rule('/<page>/',
                 view_func=Main.as_view('main'),
                 methods=["GET"])
</code>```

Traceback:

```<code>Traceback (most recent call last):
  File "demo.py", line 20, in <module> methods=["GET"])
  File ".../python2.6/site-packages/flask/app.py",
    line 62, in wrapper_func return f(self, *args, **kwargs)
  File ".../python2.6/site-packages/flask/app.py",
    line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
    function: main
</code>```

答:
Your view names need to be unique even if they are pointing to the same view method, or you can add from functools import wraps and use @wraps
https://docs.python.org/2/library/functools.html</p>

Body:
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this

app.add_url_rule('/',
                 view_func=Main.as_view('main'),
                 methods=["GET"])

app.add_url_rule('/<page>/',
                 view_func=Main.as_view('main'),
                 methods=["GET"])

Traceback:

Traceback (most recent call last):
  File "demo.py", line 20, in <module> methods=["GET"])
  File ".../python2.6/site-packages/flask/app.py",
    line 62, in wrapper_func return f(self, *args, **kwargs)
  File ".../python2.6/site-packages/flask/app.py",
    line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
    function: main


问:
How to get all controllers and request-mapping methods
In my Application, I wanted to list down all of my controllers and request method. Can anybody tell how can I detect the controller annotation in the application?</p>

答:
You could get a starting point by:

1) Injecting

```<code>@Autowired
private ApplicationContext applicationContext;
</code>```

2) Using

```<code>String[] getBeanNamesForType(@Nullable
                             Class<?> type)
</code>```

If your controllers all extend a common base.

3) Use the

```<code>String[] getBeanDefinitionNames()
</code>```

And then filter the ones ending in Controller.. if that is your common suffix for these.

For the methods themselves, you would most likely need to use reflection once you have the qualified controller class names.

Body:
You could get a starting point by:

1) Injecting

@Autowired
private ApplicationContext applicationContext;

2) Using

String[] getBeanNamesForType(@Nullable
                             Class<?> type)

If your controllers all extend a common base.

3) Use the

String[] getBeanDefinitionNames()

And then filter the ones ending in Controller.. if that is your common suffix for these.

For the methods themselves, you would most likely need to use reflection once you have the qualified controller class names.


问:
Linux : Can a directory rename be partially executed due to a power/transient mechanical failure in Server/Disk?
C/C++ rename function can be used to rename a directory.
Assume below situation (for Linux)
Directory X has files A, B and C.
X is renamed to Y (using C/C++ rename function). While the operation is in progress Server/Disk's power goes out. Then it is restarted.
Now is there a possibility of few files being in a directory X while others in Y.
e.g.
X : B
Y : A, C</p>

答:
Rename is only changing a name. The "id" of the file, and in linux a directory is a file which contains the "links" to other files and directories, stays the same!

As a file system is always directly relying to the physical block storage on any kind of hardware, always the complete block where the label is stored, must be rewritten and linked in the file system structure.

If a power fail happens in between, the "directory file" can be corrupted. This means, that more than the single renaming operations is involved!

BUT:
Modern file systems have many options to detect and repair such situations. E.G. ext4 has a journal in background. If any access may be interrupted, the journal has the information that these operation has started but not completed. By mounting such a partition/fs, the repair takes place automatically. If this is not possible, a fschk can do that job.

The situation, that only "some files" have been moved, is definitely never possible, because renaming a directory is not creating a new directory and moving the file names/links to the node id into the new directory, it is only a new name for an existing directory.

As a user: Simply use modern file systems and mostly all power down failures can be recovered by restart. You may find your filesystem in the "old" or the "new" version, but not in between.


问:
Hive managed tables are not drop on azure data lake store
I recently discover what I call a bug and I'd be sure it's a bug.

We work on an azure platform with HDInsight 3.6 with two separates storages : a blobstorage and a data lake store.
For most part of our work we use Hive.

From what we know when you drop a managed table the data under this table are drop too.
To be sure of this we tried this :

```<code>CREATE TABLE test(id String) PARTITIONED BY (part String) STORED AS ORC ;
INSERT INTO TABLE PARTITION(part='part1') VALUES('id1') ;
INSERT INTO TABLE PARTITION(part='part2') VALUES('id2') ;
INSERT INTO TABLE PARTITION(part='part3') VALUES('id3') ;
</code>```

These queries are executed on the default database i.e on the blob storage.
The data are well stored under the location of the table test : if we check we have three directories part=* with files under them.

Then i drop the table :

```<code>DROP TABLE test ;
</code>```

If we check the database directory there is no more directory named test so the data are well dropped and we expect this to be the correct hive behavior.

And now is the trick : For our work we use databases located on a datalake store and when we use this code :

```<code>use database_located_on_adl ;
CREATE TABLE test(id String) PARTITIONED BY (part String) STORED AS ORC ;
INSERT INTO TABLE PARTITION(part='part1') VALUES('id1') ;
INSERT INTO TABLE PARTITION(part='part2') VALUES('id2') ;
INSERT INTO TABLE PARTITION(part='part3') VALUES('id3') ;
DROP TABLE test ;
</code>```

The table are well created, the data are well stored BUT the data are not dropped on the DROP TABLE command ...

Am I missing something ? Or is this a normal behavior ?

答:
If anyone see this old post and have the same issue : Our problem was that we missed the write right on the hive trash (/user/hiveUserName/.Trash HDFS folder).

Hope this can help !

Body:
I recently discover what I call a bug and I'd be sure it's a bug.

We work on an azure platform with HDInsight 3.6 with two separates storages : a blobstorage and a data lake store.
For most part of our work we use Hive.

From what we know when you drop a managed table the data under this table are drop too.
To be sure of this we tried this :

CREATE TABLE test(id String) PARTITIONED BY (part String) STORED AS ORC ;
INSERT INTO TABLE PARTITION(part='part1') VALUES('id1') ;
INSERT INTO TABLE PARTITION(part='part2') VALUES('id2') ;
INSERT INTO TABLE PARTITION(part='part3') VALUES('id3') ;

These queries are executed on the default database i.e on the blob storage.
The data are well stored under the location of the table test : if we check we have three directories part=* with files under them.

Then i drop the table :

DROP TABLE test ;

If we check the database directory there is no more directory named test so the data are well dropped and we expect this to be the correct hive behavior.

And now is the trick : For our work we use databases located on a datalake store and when we use this code :

use database_located_on_adl ;
CREATE TABLE test(id String) PARTITIONED BY (part String) STORED AS ORC ;
INSERT INTO TABLE PARTITION(part='part1') VALUES('id1') ;
INSERT INTO TABLE PARTITION(part='part2') VALUES('id2') ;
INSERT INTO TABLE PARTITION(part='part3') VALUES('id3') ;
DROP TABLE test ;

The table are well created, the data are well stored BUT the data are not dropped on the DROP TABLE command ...

Am I missing something ? Or is this a normal behavior ?