问:
Android- setPeriodic for JobScheduler won't work
I've wrote an app for creating and reminding task which uses local SqliteDatabase.
I wrote a jobScheduler service to check the device time and date with tasks on the database and if matches shows a push notification.
What I want also is service to run in background and check the data every 5 seconds .
but when I write

builder.setPeriodic(5000);
builder.setPersisted(true);

the service stops checking data.

Here's my code

MainActivity

```<code>      public class MainActivity extends AppCompatActivity  {
ImageButton plusImageBtn;
DatabaseHelper databaseHelper;
BottomNavigationView navigation;
Toolbar toolbar;
private ComponentName mServiceComponent;
private int jobId=0;
private static final String TAG = MainActivity.class.getSimpleName();
public static final String WORK_DURATION_KEY =
        BuildConfig.APPLICATION_ID + ".WORK_DURATION_KEY";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    navigation = (BottomNavigationView) findViewById(R.id.navigation);
    plusImageBtn = (ImageButton) findViewById(R.id.plusImagBtn);
    toolbar= (Toolbar) findViewById(R.id.toolbar_main);
    setSupportActionBar(toolbar);

    mServiceComponent = new ComponentName(this, JobSchedulerService.class);

    databaseHelper= new DatabaseHelper(this);
    navigation.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                    Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.navigation_calendar:
                            selectedFragment = new CalendarFragment();
                            break;
                        case R.id.navigation_home:
                            selectedFragment = new ViewListContents();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;

                }
            });
    FragmentTransaction transaction =
     getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout,new  ViewListContents());
    transaction.commit();
    scheduleJob();

}

@Override
protected void onStart() {
    super.onStart();
    // Start service and provide it a way to communicate with this class.
    Intent startServiceIntent = new Intent(this, JobSchedulerService.class);
    startService(startServiceIntent);
}

@Override
protected void onStop() {
    stopService(new Intent(this,JobSchedulerService.class));
    super.onStop();
}

public void scheduleJob() {
    JobInfo.Builder builder = new JobInfo.Builder(jobId++, mServiceComponent);
 //  builder.setPeriodic(5000);
   // builder.setPersisted(true);

    builder.setMinimumLatency(1000);
    builder.setOverrideDeadline(1000);

    // Extras, work duration.
    PersistableBundle extras = new PersistableBundle();
    extras.putLong("",5000);
    builder.setExtras(extras);
    // Schedule job
    Log.d(TAG, "Scheduling job");
    JobScheduler tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        tm.schedule(builder.build());
    Toast.makeText(this, "Scheduling job  ", Toast.LENGTH_SHORT).show();

}}
</code>```

JobSchedulerService

```<code>  public class JobSchedulerService extends JobService {
int id;
String stringId;
String date;
String taskDate,taskTitle,taskTime,sepYear,sepMonth,
 sepDay,convert,DeviceDate;
Cursor taskDateCursor;
DatabaseHelper databaseHelper;
Roozh roozh;
String[] seperatedString;
int iYear,iMonth, iDay;
SimpleDateFormat dateFormat,  timeFormat;
private static final String TAG = JobSchedulerService.class.getSimpleName();

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "Service created");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i(TAG, "Service destroyed");   }

@Override
public boolean onStartJob(final JobParameters params) {
    stringId = String.valueOf(params.getJobId());
    id = params.getJobId();
    final long duration = params.getExtras().getLong(WORK_DURATION_KEY);
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            databaseHelper= new DatabaseHelper(getApplicationContext());

            taskDateCursor=databaseHelper.getDateForNotification();
            if (taskDateCursor.moveToFirst()){
                do {
                    taskTitle=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL2));
                    taskDate=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL3));
                    taskTime=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL4));

                    roozh= new Roozh();
                    seperatedString=taskDate.split("/");
                    sepYear=  seperatedString[0];
                    sepMonth=  seperatedString[1];
                    sepDay=  seperatedString[2].trim();
                    iYear= Integer.parseInt(sepYear);
                    iMonth= Integer.parseInt(sepMonth);
                    iDay= Integer.parseInt(sepDay);
                    roozh.PersianToGregorian(iYear,iMonth,iDay);
                    convert= roozh.toString();
                    dateFormat= new SimpleDateFormat(
                            "yyyy-MM-dd", Locale.getDefault());
                    DeviceDate= dateFormat.format(new Date());
                    timeFormat=new SimpleDateFormat("HH:m",Locale.getDefault());

                    String  deviceTime=timeFormat.format(new Date());

                    RemoteViews remoteViews= new RemoteViews(getPackageName(),R.layout.notification);
                    remoteViews.setImageViewResource(R.id.notif_image, R.mipmap.ic_launcher);
                    remoteViews.setTextViewText(R.id.title,taskTitle);
                    remoteViews.setTextViewText(R.id.text,taskTime);

                    if (DeviceDate.equals(convert)  && deviceTime.equals(taskTime) ){
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
                                .setSmallIcon(R.drawable.drawable_circle)
                                .setContent(remoteViews)
                                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                                .setColor(ContextCompat.getColor(getApplication(), R.color.primaryDarkColor))
                                .setShowWhen(true)
                                .setAutoCancel(true);
                        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
                        notificationManager.notify(0, mBuilder.build());

                    }

                    Log.i(TAG, "data " + DeviceDate+ "task" + convert+ " " + "dd" + " "+  taskTime + "dt" + "" + deviceTime);
                }while (taskDateCursor.moveToNext());
            }            }
    }, duration);
    Log.i(TAG, "on start job: " + params.getJobId());
   return true;    }

@Override
public boolean onStopJob(JobParameters params) {
    Log.i(TAG, "on stop job: " + params.getJobId());
    return true;    }
</code>```

答:
Refer this answer of mine:

https://stackoverflow.com/a/60295377/9166855

The minimum period is 15minutes!

Body:
I've wrote an app for creating and reminding task which uses local SqliteDatabase.
I wrote a jobScheduler service to check the device time and date with tasks on the database and if matches shows a push notification.
What I want also is service to run in background and check the data every 5 seconds .
but when I write

builder.setPeriodic(5000);
builder.setPersisted(true);

the service stops checking data.

Here's my code

MainActivity

      public class MainActivity extends AppCompatActivity  {
ImageButton plusImageBtn;
DatabaseHelper databaseHelper;
BottomNavigationView navigation;
Toolbar toolbar;
private ComponentName mServiceComponent;
private int jobId=0;
private static final String TAG = MainActivity.class.getSimpleName();
public static final String WORK_DURATION_KEY =
        BuildConfig.APPLICATION_ID + ".WORK_DURATION_KEY";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    navigation = (BottomNavigationView) findViewById(R.id.navigation);
    plusImageBtn = (ImageButton) findViewById(R.id.plusImagBtn);
    toolbar= (Toolbar) findViewById(R.id.toolbar_main);
    setSupportActionBar(toolbar);

    mServiceComponent = new ComponentName(this, JobSchedulerService.class);

    databaseHelper= new DatabaseHelper(this);
    navigation.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                    Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.navigation_calendar:
                            selectedFragment = new CalendarFragment();
                            break;
                        case R.id.navigation_home:
                            selectedFragment = new ViewListContents();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;

                }
            });
    FragmentTransaction transaction =
     getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout,new  ViewListContents());
    transaction.commit();
    scheduleJob();

}

@Override
protected void onStart() {
    super.onStart();
    // Start service and provide it a way to communicate with this class.
    Intent startServiceIntent = new Intent(this, JobSchedulerService.class);
    startService(startServiceIntent);
}

@Override
protected void onStop() {
    stopService(new Intent(this,JobSchedulerService.class));
    super.onStop();
}

public void scheduleJob() {
    JobInfo.Builder builder = new JobInfo.Builder(jobId++, mServiceComponent);
 //  builder.setPeriodic(5000);
   // builder.setPersisted(true);

    builder.setMinimumLatency(1000);
    builder.setOverrideDeadline(1000);

    // Extras, work duration.
    PersistableBundle extras = new PersistableBundle();
    extras.putLong("",5000);
    builder.setExtras(extras);
    // Schedule job
    Log.d(TAG, "Scheduling job");
    JobScheduler tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        tm.schedule(builder.build());
    Toast.makeText(this, "Scheduling job  ", Toast.LENGTH_SHORT).show();

}}

JobSchedulerService

  public class JobSchedulerService extends JobService {
int id;
String stringId;
String date;
String taskDate,taskTitle,taskTime,sepYear,sepMonth,
 sepDay,convert,DeviceDate;
Cursor taskDateCursor;
DatabaseHelper databaseHelper;
Roozh roozh;
String[] seperatedString;
int iYear,iMonth, iDay;
SimpleDateFormat dateFormat,  timeFormat;
private static final String TAG = JobSchedulerService.class.getSimpleName();

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "Service created");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i(TAG, "Service destroyed");   }

@Override
public boolean onStartJob(final JobParameters params) {
    stringId = String.valueOf(params.getJobId());
    id = params.getJobId();
    final long duration = params.getExtras().getLong(WORK_DURATION_KEY);
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            databaseHelper= new DatabaseHelper(getApplicationContext());

            taskDateCursor=databaseHelper.getDateForNotification();
            if (taskDateCursor.moveToFirst()){
                do {
                    taskTitle=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL2));
                    taskDate=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL3));
                    taskTime=taskDateCursor.getString(taskDateCursor.getColumnIndex(DatabaseHelper.COL4));

                    roozh= new Roozh();
                    seperatedString=taskDate.split("/");
                    sepYear=  seperatedString[0];
                    sepMonth=  seperatedString[1];
                    sepDay=  seperatedString[2].trim();
                    iYear= Integer.parseInt(sepYear);
                    iMonth= Integer.parseInt(sepMonth);
                    iDay= Integer.parseInt(sepDay);
                    roozh.PersianToGregorian(iYear,iMonth,iDay);
                    convert= roozh.toString();
                    dateFormat= new SimpleDateFormat(
                            "yyyy-MM-dd", Locale.getDefault());
                    DeviceDate= dateFormat.format(new Date());
                    timeFormat=new SimpleDateFormat("HH:m",Locale.getDefault());

                    String  deviceTime=timeFormat.format(new Date());

                    RemoteViews remoteViews= new RemoteViews(getPackageName(),R.layout.notification);
                    remoteViews.setImageViewResource(R.id.notif_image, R.mipmap.ic_launcher);
                    remoteViews.setTextViewText(R.id.title,taskTitle);
                    remoteViews.setTextViewText(R.id.text,taskTime);

                    if (DeviceDate.equals(convert)  && deviceTime.equals(taskTime) ){
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
                                .setSmallIcon(R.drawable.drawable_circle)
                                .setContent(remoteViews)
                                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                                .setColor(ContextCompat.getColor(getApplication(), R.color.primaryDarkColor))
                                .setShowWhen(true)
                                .setAutoCancel(true);
                        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
                        notificationManager.notify(0, mBuilder.build());

                    }

                    Log.i(TAG, "data " + DeviceDate+ "task" + convert+ " " + "dd" + " "+  taskTime + "dt" + "" + deviceTime);
                }while (taskDateCursor.moveToNext());
            }            }
    }, duration);
    Log.i(TAG, "on start job: " + params.getJobId());
   return true;    }

@Override
public boolean onStopJob(JobParameters params) {
    Log.i(TAG, "on stop job: " + params.getJobId());
    return true;    }


来源: stackexchange

问:
Uber cool Linear Gradients in CSS3
Is it possible to create (without images), really cool looking linear gradients like the ones you see in the Ribbon menu controls?

Does anyone know of any tutorials, articles resources or samples that demonstrate/show off this kinda gradient?

答:
http://www.colorzilla.com/gradient-editor/

I've used this in the past.  It is nice because it makes a number of flavors of the gradient, since exact syntax isn't well defined yet.

ContentLicense: CC BY-SA 3.0

Title: Uber cool Linear Gradients in CSS3


问:
How to allocate memory of triple pointer in a C function
I am new to C and have a case where I want to read in a simple text file with one word per row and I want to save this into an array.  However, I want to declare a double pointer in function main and then pass that by reference to another function to allocate the memory and populate the double pointer.  I can't seem to get it to work without throwing segmentation faults.  Any advice would be much appreciated.

Here is what I've tried:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
test.txt = content between the "---"
---
first
second
third
fourth
fifth
sixth
seventh
---
*/

void allocmem (char ***tptr) {

    FILE *infile = fopen("test.txt", "r");
    int bufferLength = 5;
    char *buffer = malloc(sizeof(char) * bufferLength);

    int c, i, row, rows;
    c = i = row = 0;
    rows = 7;

/*
    I want to allocate an array of char strings to store the list from test.txt in
    I have tried different variants here
*/

    tptr = malloc(sizeof(char**) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char*) * bufferLength);
    }

/*
    // another attempt
    *tptr = malloc(sizeof(char*) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char) * bufferLength);
    }
*/

    while ((c = getc(infile)) != EOF) {

        if (c == '\n') {
            buffer[++i] = '\0';
            printf("buffer: %s\n", buffer);

            // I am also a little unsure how to append my buffer to the pointer array here too
            strcpy(*tptr[row++], buffer);
            memset(buffer, '\0', bufferLength);
            i = 0;
        } else {
            buffer[i++] = c;
        }

    }

    fclose(infile);

}

int main () {

    // double pointer to hold array value from test.txt in
    char **dptr;

    // allocate memory and read test.txt and store each row into the array
    allocmem(&dptr);

/*
    print each element of dptr here yielding the expected results of:

    first
    second
    third
    fourth
    fifth
    sixth
    seventh
*/

    return 0;
}
</code>```

答:
To answer your question, it is possible to allocate a triple pointer by type ***ptr (as @David C. Rankin stated), but it is simply not practical. The function can simply allocate memory with malloc or calloc and store the result, at the end write the pointer to the result to the pointer given by the argument by dereferencing it, like *argument_ptr = result_pointer. I've rewritten the code to avoid segmentation faults. Here's the code:

```<code>void allocmem (char ***tptr) {
    // The aim of this function is to return the array of strings read from the file
    FILE *infile = fopen("test.txt", "r"); // Read text file
    const int bufferLength = 10, number_of_strings = 7; // Read string 7 times, for a maximum length of 10
    char **array = (char**)calloc(sizeof(char*), number_of_strings); // Allocate memory for a bunch of strings (char*), but the memory for the characters are not initialized
    for (int i = 0; i < number_of_strings; i++){
        char *string = (char*)calloc(sizeof(char), bufferLength); // Memory for the string, a.k.a. character array
        fgets(string, bufferLength, infile); // Read the string (word) from file
        char *c;
        if (c = strchr(string, '\n')) *c = '\0'; // Remove the newline character if exists
        array[i] = string; // Assign the string to the array
    }
    fclose(infile); // Close the file
    *tptr = array; // Return the array created by modifying the given pointer
}
</code>```

I can't seem to get it to work without throwing segmentation faults.

The segmentation faults on line 35 and 53 are caused by wrong dereferencing. On line 35, you should simply use tptr[r] to access the char** pointers, and it is the same case on line 53.

ContentLicense: CC BY-SA 4.0

Body:
I am new to C and have a case where I want to read in a simple text file with one word per row and I want to save this into an array.  However, I want to declare a double pointer in function main and then pass that by reference to another function to allocate the memory and populate the double pointer.  I can't seem to get it to work without throwing segmentation faults.  Any advice would be much appreciated.

Here is what I've tried:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
test.txt = content between the "---"
---
first
second
third
fourth
fifth
sixth
seventh
---
*/

void allocmem (char ***tptr) {

    FILE *infile = fopen("test.txt", "r");
    int bufferLength = 5;
    char *buffer = malloc(sizeof(char) * bufferLength);

    int c, i, row, rows;
    c = i = row = 0;
    rows = 7;

/*
    I want to allocate an array of char strings to store the list from test.txt in
    I have tried different variants here
*/

    tptr = malloc(sizeof(char**) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char*) * bufferLength);
    }

/*
    // another attempt
    *tptr = malloc(sizeof(char*) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char) * bufferLength);
    }
*/

    while ((c = getc(infile)) != EOF) {

        if (c == '\n') {
            buffer[++i] = '\0';
            printf("buffer: %s\n", buffer);

            // I am also a little unsure how to append my buffer to the pointer array here too
            strcpy(*tptr[row++], buffer);
            memset(buffer, '\0', bufferLength);
            i = 0;
        } else {
            buffer[i++] = c;
        }

    }

    fclose(infile);

}

int main () {

    // double pointer to hold array value from test.txt in
    char **dptr;

    // allocate memory and read test.txt and store each row into the array
    allocmem(&dptr);

/*
    print each element of dptr here yielding the expected results of:

    first
    second
    third
    fourth
    fifth
    sixth
    seventh
*/

    return 0;
}

Body:
To answer your question, it is possible to allocate a triple pointer by type ***ptr (as @David C. Rankin stated), but it is simply not practical. The function can simply allocate memory with malloc or calloc and store the result, at the end write the pointer to the result to the pointer given by the argument by dereferencing it, like *argument_ptr = result_pointer. I've rewritten the code to avoid segmentation faults. Here's the code:

void allocmem (char ***tptr) {
    // The aim of this function is to return the array of strings read from the file
    FILE *infile = fopen("test.txt", "r"); // Read text file
    const int bufferLength = 10, number_of_strings = 7; // Read string 7 times, for a maximum length of 10
    char **array = (char**)calloc(sizeof(char*), number_of_strings); // Allocate memory for a bunch of strings (char*), but the memory for the characters are not initialized
    for (int i = 0; i < number_of_strings; i++){
        char *string = (char*)calloc(sizeof(char), bufferLength); // Memory for the string, a.k.a. character array
        fgets(string, bufferLength, infile); // Read the string (word) from file
        char *c;
        if (c = strchr(string, '\n')) *c = '\0'; // Remove the newline character if exists
        array[i] = string; // Assign the string to the array
    }
    fclose(infile); // Close the file
    *tptr = array; // Return the array created by modifying the given pointer
}

I can't seem to get it to work without throwing segmentation faults.

The segmentation faults on line 35 and 53 are caused by wrong dereferencing. On line 35, you should simply use tptr[r] to access the char** pointers, and it is the same case on line 53.


问:
How to combined similar-named nested classes from a derived and its base class
I was working on a small project where I created standard implementations of add-ons for a system. These standard implementations would set up things like logging, configuration, etc. all in a uniform way. All with maintainability and re-usability in mind.

Now the thing I am struggling with right now is how to handle names of settings. Before I always created a nested class Settings in with I declared some const string values like

public const string BananaSetting = "BananaSetting";

so I pretty much never could misspell a setting's name ever again.

I however have an base class which should have a setting called DEBUG, to use as a generic debug-enabling setting; but also add-on specific settings, which only exist for that one specific add-on.
Seeing as I base every derived class on the class that has the DEBUG setting nested class, any derived class that tries to declare a similar nested class called Settings will trigger a compiler warning:

DerivedClass.Settings hides inherited member 'BaseClass.Settings'. Use the new keyword if hiding was intended.

But I do not want to hide it. What I would really like to do is combine the two Settings classes into one. Is there any way to do this, or is there an existing design pattern of some sort to do this correctly?

```<code>public abstract class BaseClass
{
    public class Settings
    {
        public const string BananaSetting = "BananaSetting";
    }

    public abstract void BaseAbstractMethod();
    public void BaseMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
    }
}

public class DerivedClass : BaseClass
{
    public class Settings
    {
        public const string DerivedBananaSetting = "DerivedBananaSetting";
    }

    public override void BaseAbstractMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
        var subSettingValue = settingsDictionary[Settings.DerivedBananaSetting];
    }
}
</code>```

答:
If I understand you correctly you want to extend the baseclass with some more settings:

```<code>public class SettingBase
{
     public SettingDerived()
     {
         _settingNamesWithValues.Add("BananaSetting", new object());
     }

    private Dictionairy<string, object> _settingNamesWithValues = new Dictionairy<string, object>();

    public Dictionairy<string, object>() SettingNamesWithValues
    {
         get
         {
            return _settingNameWithValue;
         }
    }
}
</code>```

Derived class:

```<code>public class SettingDerived : SettingBase
{
     public SettingDerived()
     {
         _settingNamesWithValues.Add("DerivedBananaSetting", new object());
     }

     private Dictionairy<string, object> _settingNamesWithValues = new Dictionairy<string, object>();

     //Hide the base SettingNamesWithValues, as we add the values to the derived collection anyways
     public new Dictionairy<string, object>() SettingNamesWithValues
     {
         get
         {
            foreach(var keyValue in base.SettingNamesWithValues)
            {
                 _settingNameWithValue.Add(keyValue.Key, keyValue.Value);
            }
            return _settingNameWithValue;
         }
     }
}
</code>```

You then could access all settings using theire name.

```<code>var derived = new SettingsDerived();
var derivedBanana = derived.SettingNamesWithValues["DerivedBananaSetting"];
var banana = derived.SettingNamesWithValues["BananaSetting"];
</code>```

Body:
I was working on a small project where I created standard implementations of add-ons for a system. These standard implementations would set up things like logging, configuration, etc. all in a uniform way. All with maintainability and re-usability in mind.

Now the thing I am struggling with right now is how to handle names of settings. Before I always created a nested class Settings in with I declared some const string values like

public const string BananaSetting = "BananaSetting";

so I pretty much never could misspell a setting's name ever again.

I however have an base class which should have a setting called DEBUG, to use as a generic debug-enabling setting; but also add-on specific settings, which only exist for that one specific add-on.
Seeing as I base every derived class on the class that has the DEBUG setting nested class, any derived class that tries to declare a similar nested class called Settings will trigger a compiler warning:

DerivedClass.Settings hides inherited member 'BaseClass.Settings'. Use the new keyword if hiding was intended.

But I do not want to hide it. What I would really like to do is combine the two Settings classes into one. Is there any way to do this, or is there an existing design pattern of some sort to do this correctly?

public abstract class BaseClass
{
    public class Settings
    {
        public const string BananaSetting = "BananaSetting";
    }

    public abstract void BaseAbstractMethod();
    public void BaseMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
    }
}

public class DerivedClass : BaseClass
{
    public class Settings
    {
        public const string DerivedBananaSetting = "DerivedBananaSetting";
    }

    public override void BaseAbstractMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
        var subSettingValue = settingsDictionary[Settings.DerivedBananaSetting];
    }
}

Body:
If I understand you correctly you want to extend the baseclass with some more settings:

public class SettingBase
{
     public SettingDerived()
     {
         _settingNamesWithValues.Add("BananaSetting", new object());
     }

    private Dictionairy<string, object> _settingNamesWithValues = new Dictionairy<string, object>();

    public Dictionairy<string, object>() SettingNamesWithValues
    {
         get
         {
            return _settingNameWithValue;
         }
    }
}

Derived class:

public class SettingDerived : SettingBase
{
     public SettingDerived()
     {
         _settingNamesWithValues.Add("DerivedBananaSetting", new object());
     }

     private Dictionairy<string, object> _settingNamesWithValues = new Dictionairy<string, object>();

     //Hide the base SettingNamesWithValues, as we add the values to the derived collection anyways
     public new Dictionairy<string, object>() SettingNamesWithValues
     {
         get
         {
            foreach(var keyValue in base.SettingNamesWithValues)
            {
                 _settingNameWithValue.Add(keyValue.Key, keyValue.Value);
            }
            return _settingNameWithValue;
         }
     }
}

You then could access all settings using theire name.

var derived = new SettingsDerived();
var derivedBanana = derived.SettingNamesWithValues["DerivedBananaSetting"];
var banana = derived.SettingNamesWithValues["BananaSetting"];


问:
Check string indentation?
I'm building an analyzer for a series of strings.
I need to check how much each line is indented (either by tabs or by spaces).

Each line is just a string in a text editor.
How do I check by how much a string is indented?

Or rather, maybe I could check how much whitespace or \t are before a string, but I'm unsure of how.

答:
The len() method will count tab (\t) as one. In some case, it will not behave expectedly. So my way is to use re.sub and then count the space(s).</p>

```<code>indent_count = re.sub(r'^([\s]*)[\s]+.*$', r'\g<1>', line).count(' ')
</code>```

Title: Check string indentation?

Body:
The len() method will count tab (\t) as one. In some case, it will not behave expectedly. So my way is to use re.sub and then count the space(s).

indent_count = re.sub(r'^([\s]*)[\s]+.*$', r'\g<1>', line).count(' ')


问:
Laravel how to add a function from a view to the controller (Business Logic Layer)
I currently have this function in my view:

```<code></tr>
  @foreach ($data as $i )
     <tr>
       <td>
         {{$i->AanvraagID}}
       </td>
       <td>
         {{$i->Status}}
       </td>
       <td>
         {{$i->StartDatum}}
       </td>
       <td>
         {{$i->EindDatum}}
       </td>
       <td>
         {{$i->Leverancier}}
       </td>
       <td>
         {{$i->Product}}
       </td>
       <td>
         {{$i->Validatie}}
       </td>
       <td>
         {{$i->TypeCertificaat}}
       </td>
       <td class="wrong">
            @php
                $date = new DateTime($i->EindDatum);
                $now = new DateTime();

                if($date < $now)  echo  'Certificaat verlopen';

                if ($date < $now && $i->email_send == 0) {

                $user=App\User::find(1);
                $user->notify(new App\Notifications\TaksComplete);

                }
       @endphp
   </td>
</tr>
</code>```

I would like to know if its possible to add this to my controller so my view only has to display the result.

This is my controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class sslController extends Controller
{
    function SSL(){
        $data = DB::table('SSL')->where('userID', Auth::id())->get();
        return view('SSL',['data'=>$data]);
    }
}
</code>```

this is my model:

```<code><?php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class sslModel extends Model
{
    use Notifiable;

    protected $table='SSL';
    protected $fillable = [
         'email_send',
    ];
}
</code>```

Now the problem is the controller doesn't know stuff like DateTime()

What the function does is if the users has something which is past the current date it will send an email to the user. But now each time the user reloads the page it send the email again. This function is there to stop that but it doesn't work in my view:

```<code>$SSL=App\sslModel::find(1);
$SSL->email_send = 1;
$SSL->save();
</code>```

This does not change the column email_send to 1 from 0 in the table SSL in my database.

Is it possible to add this code to my controller(or model)? and so that the column does update in the database?

my user table migration:

```<code>class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
</code>```

答:
Fixed my issue..
I just changed my controller to:</p>

```<code>public function SSL(){

        $data = DB::table('SSL')->where('userID', Auth::id())->get();
        $models = \App\sslModel::where('userID', Auth::id())->get();

        foreach($models as $model) {
             if ($model->EindDatum < Carbon::now() && $model->email_send == 0) {
                DB::table('SSL')
                ->where('userID', Auth::id())
                ->where('EindDatum', '<', Carbon::now())
                ->update(['email_send' => 1]);
                $model->user()->first()->notify(new \App\Notifications\TaksComplete);
             }
        }

        return view('SSL',['data'=>$data]);
    }

</code>```

Body:
I currently have this function in my view:

  @foreach ($data as $i )

         {{$i->AanvraagID}}

         {{$i->Status}}

         {{$i->StartDatum}}

         {{$i->EindDatum}}

         {{$i->Leverancier}}

         {{$i->Product}}

         {{$i->Validatie}}

         {{$i->TypeCertificaat}}

            @php
                $date = new DateTime($i->EindDatum);
                $now = new DateTime();

                if($date < $now)  echo  'Certificaat verlopen';

                if ($date < $now && $i->email_send == 0) {

                $user=App\User::find(1);
                $user->notify(new App\Notifications\TaksComplete);

                }
       @endphp

I would like to know if its possible to add this to my controller so my view only has to display the result.

This is my controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class sslController extends Controller
{
    function SSL(){
        $data = DB::table('SSL')->where('userID', Auth::id())->get();
        return view('SSL',['data'=>$data]);
    }
}

this is my model:

<?php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class sslModel extends Model
{
    use Notifiable;

    protected $table='SSL';
    protected $fillable = [
         'email_send',
    ];
}

Now the problem is the controller doesn't know stuff like DateTime()

What the function does is if the users has something which is past the current date it will send an email to the user. But now each time the user reloads the page it send the email again. This function is there to stop that but it doesn't work in my view:

$SSL=App\sslModel::find(1);
$SSL->email_send = 1;
$SSL->save();

This does not change the column email_send to 1 from 0 in the table SSL in my database.

Is it possible to add this code to my controller(or model)? and so that the column does update in the database?

my user table migration:

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Body:
Fixed my issue..
I just changed my controller to:

public function SSL(){

        $data = DB::table('SSL')->where('userID', Auth::id())->get();
        $models = \App\sslModel::where('userID', Auth::id())->get();

        foreach($models as $model) {
             if ($model->EindDatum < Carbon::now() && $model->email_send == 0) {
                DB::table('SSL')
                ->where('userID', Auth::id())
                ->where('EindDatum', '<', Carbon::now())
                ->update(['email_send' => 1]);
                $model->user()->first()->notify(new \App\Notifications\TaksComplete);
             }
        }

        return view('SSL',['data'=>$data]);
    }


问:
How to import SFTP (File.tar.gz) to Nifi
I have a tar.gz file which contains a set of CSV files in it. How do I read only one file into nifi?</p>

答: GetFile -> compressContent with decompress mode gzip -> unpackContent with tar format -> routeOnAttribut with ${fileName}.


问:
How to pass nested JSON to Spring Controller
I have my JSON in following format:

```<code>    "Organization":{
             "legalname" : "",
              "dba" : "",
              "fein" : ""
        }
</code>```

From my Jquery code i am passing the AJAX call as:

```<code>    $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "OMS/ConfirmationR",
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (JSONText) {
               alert('success');
               console.log("SUCCESS: ", data);
            },
            error: function(xhr, status, error){
                var errorMessage = xhr.status + ': ' + xhr.statusText
                alert('Error - ' + errorMessage);
            }
   });
</code>```

This code runs fine when the json is not nested and has value as:

```<code>{"legalname":"test","dba":"dba","fein":"123"},
</code>```

the values are getting printed in controller,
but when the JSON is in following format, i see null for these values:

```<code>{"Organization":{"legalname":"test","dba":"dba","fein":"123"}}
</code>```

Please advise

The controller code:

```<code>@RequestMapping("OMS/ConfirmationR")
public ResponseEntity<?> goToOrgConfReg(@RequestBody OrgVODummy org, Model model) {
    System.out.println("In goToOrgConfReg!!! getLegalName : " + org.getLegalname() + " DBA: " + org.getDba()
            + " FEIN:" + org.getFein());
    AjaxResponse result = new AjaxResponse();
    if (org.getLegalname() == null) {
        System.out.println("@RequestBody is null");
        result.setMsg(" Failed");
    } else {
        System.out.println("@RequestBody is not null");
        result.setMsg(" Pass");
    }

    return ResponseEntity.ok(result);
}
</code>```

答:
Probably your OrgVODummy class looks like below:

class OrgVODummy {
  private String legalname;
  private String dba;
  private String fein;
// getters and setters
}
```

<p>But you should have something like that:</p>

<pre class="lang-java prettyprint-override"><code>class OrganizationDummy {
  private OrgVODummy organization;
// getters and setters
}
</code>```

Than in your controller change to this:

public ResponseEntity<?> goToOrgConfReg(@RequestBody OrganizationDummy org, Model model) {
```

<p>And this should work with this json (<code>organization</code> starts with lower letter):</p>

```{"organization":{"legalname":"test","dba":"dba","fein":"123"}}
```

Body:
I have my JSON in following format:

    "Organization":{
             "legalname" : "",
              "dba" : "",
              "fein" : ""
        }

From my Jquery code i am passing the AJAX call as:

    $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "OMS/ConfirmationR",
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (JSONText) {
               alert('success');
               console.log("SUCCESS: ", data);
            },
            error: function(xhr, status, error){
                var errorMessage = xhr.status + ': ' + xhr.statusText
                alert('Error - ' + errorMessage);
            }
   });

This code runs fine when the json is not nested and has value as:

{"legalname":"test","dba":"dba","fein":"123"},

the values are getting printed in controller,
but when the JSON is in following format, i see null for these values:

{"Organization":{"legalname":"test","dba":"dba","fein":"123"}}

Please advise

The controller code:

@RequestMapping("OMS/ConfirmationR")
public ResponseEntity<?> goToOrgConfReg(@RequestBody OrgVODummy org, Model model) {
    System.out.println("In goToOrgConfReg!!! getLegalName : " + org.getLegalname() + " DBA: " + org.getDba()
            + " FEIN:" + org.getFein());
    AjaxResponse result = new AjaxResponse();
    if (org.getLegalname() == null) {
        System.out.println("@RequestBody is null");
        result.setMsg(" Failed");
    } else {
        System.out.println("@RequestBody is not null");
        result.setMsg(" Pass");
    }

    return ResponseEntity.ok(result);
}

Body:
Probably your OrgVODummy class looks like below:

class OrgVODummy {
  private String legalname;
  private String dba;
  private String fein;
// getters and setters
}

But you should have something like that:

class OrganizationDummy {
  private OrgVODummy organization;
// getters and setters
}

Than in your controller change to this:

public ResponseEntity<?> goToOrgConfReg(@RequestBody OrganizationDummy org, Model model) {

And this should work with this json (organization starts with lower letter):

{"organization":{"legalname":"test","dba":"dba","fein":"123"}}


问:
Using two array values in foreach loop
I have the following loop:

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});
</code>```

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

```<code>$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');
</code>```

My output looks like this:

```<code><option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>
</code>```

Whereas I'm looking for:

```<code><option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</code>```

答:
You are not using the indexes while passing the array. Instead, you are passing the whole array.</p>

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr,index) {
  $(".department").append('<option value="' + arr + '">' + textArray[index] + '</option>');
});
</code>```

Title: Using two array values in foreach loop

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');

My output looks like this:

<option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>

Whereas I'm looking for:

<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>

Body:
You are not using the indexes while passing the array. Instead, you are passing the whole array.

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr,index) {
  $(".department").append('<option value="' + arr + '">' + textArray[index] + '</option>');
});


答:
Is there any need to have them in the sub classes? You could easily achieve your goal doing the following:</p>

```<code>public abstract class BaseClass
{
    public const string BananaSetting = "BananaSetting";

    public abstract void BaseAbstractMethod();
    public void BaseMethod()
    {
    }
}

public class DerivedClass : BaseClass
{
    public const string DerivedBananaSetting = "DerivedBananaSetting";

    public override void BaseAbstractMethod()
    {
    }
}
</code>```

Title: How to combined similar-named nested classes from a derived and its base class

Body:
Is there any need to have them in the sub classes? You could easily achieve your goal doing the following:

public abstract class BaseClass
{
    public const string BananaSetting = "BananaSetting";

    public abstract void BaseAbstractMethod();
    public void BaseMethod()
    {
    }
}

public class DerivedClass : BaseClass
{
    public const string DerivedBananaSetting = "DerivedBananaSetting";

    public override void BaseAbstractMethod()
    {
    }
}


问:
Using the g++ C++ compiler from cygwin
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

```<code>#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}
</code>```

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

And here is what I get when I try to compile the program in the cygwin shell:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

答:
I wrote a tutorial about this a few years ago, which might help:

http://www.codeguru.com/cpp/misc/misc/compilerandpre-compiler/print.php/c8107__1/

Did you install g++? It's not installed by the default settings of the Cygwin installer.

ContentLicense: CC BY-SA 2.5

Title: Using the g++ C++ compiler from cygwin

Body:
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

And here is what I get when I try to compile the program in the cygwin shell:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

LastEditorDisplayName: Rich B

OwnerDisplayName: Earwicker

LastEditorDisplayName: Earwicker


问:
dictionary to keyword argument unpacking
I want to pass a dictionary contains unknown numbers of key/pair to a function called save, and inside the function, all the key/pair from the dictionary will be unpacked into keyword arguments for a class.

How can I achieve something like this?

```<code>def save(my_dict):
   my_model = MyMode(k1=v1, k2=v2, k3=v3...)
</code>```

答:
I tried passing a dictionary to a Button class init function for both simulation and tkinter. I noticed a difference: with simulation = True (my own Button class), I have to pass in as keyword arguments **dict, but with tkinter's Button class (simulation = False), I can pass in with or without **. Is there any explanation to that?

```<code>simulation = True
dictA = dict(text="Print my name with button click", command=lambda: print("My name is here"), fg="blue")
dictB = dict(text="Print your name with button click", command=lambda: print("Your name is there"),
             fg="white", bg="black")
if simulation == False:
    import tkinter as tk
    root = tk.Tk()
    dict = [dictA, dictB]
    for d in dict:
        # btn = tk.Button(root, d)  # This works too!?
        btn = tk.Button(root, **d)
        btn.pack()
    root.mainloop()
else:
    class   Button:
        def __init__(self, **kwArgs):
            if (kwArgs.get('text') == None):
                self.text = "button"
            else:
                self.text = kwArgs['text']

            if (kwArgs.get('command') == None):
                self.command = lambda arg: print(arg)
            else:
                self.command = kwArgs['command']

            if (kwArgs.get('fg') == None):
                self.fg = "black"
            else:
                self.fg = kwArgs['fg']

            if (kwArgs.get('bg') == None):
                self.bg = "white"
            else:
                self.bg = kwArgs['bg']

            print("text = {0}, command inline function = {1}, fg color = {2}, bg color = {3}".
                format(self.text, self.command, self.fg, self.bg))

    btnDefault = Button()
    btnDictA = Button(**dictA)
    btnDictB = Button(**dictB)
</code>```

Body:
I want to pass a dictionary contains unknown numbers of key/pair to a function called save, and inside the function, all the key/pair from the dictionary will be unpacked into keyword arguments for a class.

How can I achieve something like this?

def save(my_dict):
   my_model = MyMode(k1=v1, k2=v2, k3=v3...)

Body:
I tried passing a dictionary to a Button class init function for both simulation and tkinter. I noticed a difference: with simulation = True (my own Button class), I have to pass in as keyword arguments **dict, but with tkinter's Button class (simulation = False), I can pass in with or without **. Is there any explanation to that?

simulation = True
dictA = dict(text="Print my name with button click", command=lambda: print("My name is here"), fg="blue")
dictB = dict(text="Print your name with button click", command=lambda: print("Your name is there"),
             fg="white", bg="black")
if simulation == False:
    import tkinter as tk
    root = tk.Tk()
    dict = [dictA, dictB]
    for d in dict:
        # btn = tk.Button(root, d)  # This works too!?
        btn = tk.Button(root, **d)
        btn.pack()
    root.mainloop()
else:
    class   Button:
        def __init__(self, **kwArgs):
            if (kwArgs.get('text') == None):
                self.text = "button"
            else:
                self.text = kwArgs['text']

            if (kwArgs.get('command') == None):
                self.command = lambda arg: print(arg)
            else:
                self.command = kwArgs['command']

            if (kwArgs.get('fg') == None):
                self.fg = "black"
            else:
                self.fg = kwArgs['fg']

            if (kwArgs.get('bg') == None):
                self.bg = "white"
            else:
                self.bg = kwArgs['bg']

            print("text = {0}, command inline function = {1}, fg color = {2}, bg color = {3}".
                format(self.text, self.command, self.fg, self.bg))

    btnDefault = Button()
    btnDictA = Button(**dictA)
    btnDictB = Button(**dictB)


问:
How to set all the bits in a char array to zeros?
I am creating a char pointer to an array and wanted to initilaize it so that all elements in the array have 0 (in bits). So for example:

```<code>char* buffer = new char[bufferSize];
</code>```

buffer[0] to buffer[bufferSize] will have '00000000' stored in each index. I am trying to store 8 bits of zeros in each cell.

How can i initialize it? I am also supposed to use fill().

So far,

```<code>fill(&buffer, &buffer[bufferSize], 0)
</code>```

doesn't work.

答:
You can use fill, but you must remember it accepts a pair of iterators. A pointer to the array elements is an iterator of the array already. There is no need to take the address of an iterator to pass it, so your first argument is incorrect. The more correct form would be

```<code>std::fill(buffer, buffer + bufferSize, 0);
</code>```

or

```<code>std::fill_n(buffer, bufferSize, 0);
</code>```

Alternatively, you can just zero initialize the array in the new expression itself

```<code>char* buffer = new char[bufferSize] {} ;
                                  // ^ - initializer, for char this will zero out the array.
</code>```

Body:
I am creating a char pointer to an array and wanted to initilaize it so that all elements in the array have 0 (in bits). So for example:

char* buffer = new char[bufferSize];

buffer[0] to buffer[bufferSize] will have '00000000' stored in each index. I am trying to store 8 bits of zeros in each cell.

How can i initialize it? I am also supposed to use fill().

So far,

fill(&buffer, &buffer[bufferSize], 0)

doesn't work.

Body:
You can use fill, but you must remember it accepts a pair of iterators. A pointer to the array elements is an iterator of the array already. There is no need to take the address of an iterator to pass it, so your first argument is incorrect. The more correct form would be

std::fill(buffer, buffer + bufferSize, 0);

or

std::fill_n(buffer, bufferSize, 0);

Alternatively, you can just zero initialize the array in the new expression itself

char* buffer = new char[bufferSize] {} ;
                                  // ^ - initializer, for char this will zero out the array.


答:
you can use round built-in function with list comprehension:

```<code>l_b = [[[round(e, 2) for e in j] for j in i] for i in l_b]
</code>```

Title: How to round floats in a nested list to 2 decimal places?

Body:
I have coordinate lists of several polygons as listed below:

l_b =  [[[57.5, 2.875],
   [83.75, 4.1875],
   [83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 2.875]],
  [[83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 34.08695652173913],
   [83.75, 34.54347826086956],
   [83.75, 18.70923913043478]],
  [[0.0, 0.0],
   [18.125, 0.90625],
   [18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [0.0, 0.0]],
  [[18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [-5.0, 33.0],
   [18.125, 33.40217391304348],
   [18.125, 16.70108695652174]]]

How can I make all the numbers in list to round to 2 decimal places while keeping its format?

I've tried l_b = [ '%.2f' % elem for elem in l_b ] but it's giving me TypeError: must be real number, not list

Body:
you can use round built-in function with list comprehension:

l_b = [[[round(e, 2) for e in j] for j in i] for i in l_b]


问:
iPhone Programming setNeedsDisplay not working
Implemented my own drawRect method and I'm trying to redraw the shape from a Controller class and I can't figure out how to correctly implement setNeedsDisplay to redraw the UIView.  Please help!!

I know the code is ugly, but here is the custom method:

```<code>- (void)drawRect:(CGRect)rect{
// Drawing code
NSArray *kyle = [self pointsForPolygonInRect:rect numberOfSides:[pshape numberOfSides]];
CGContextRef c = UIGraphicsGetCurrentContext();

int counter = [kyle count];
NSLog(@"counter: %d",counter);
int i = 0;
BOOL first = YES;

NSValue *kylevalue;
CGPoint thePoint;
for (i = 0; i < counter; i++) {
    kylevalue = [kyle objectAtIndex:i];
    thePoint = [kylevalue CGPointValue];
    if (first) { //start.
        CGContextMoveToPoint(c, thePoint.x, thePoint.y+5.0);
        first = NO;
    } else { //do the rest
        CGContextAddLineToPoint(c,  thePoint.x, thePoint.y+5.0);
    }
}
CGContextClosePath(c); //solid color
CGContextDrawPath(c, kCGPathFillStroke);
</code>```

}

答:
Sometimes reason can be very simple: File's owner has no connection to UIView object. i.e. it's Outlet is not setup properly.
Use IB, ctrl button and drag method :) </p>

OwnerDisplayName: kylepott

Body:
Implemented my own drawRect method and I'm trying to redraw the shape from a Controller class and I can't figure out how to correctly implement setNeedsDisplay to redraw the UIView.  Please help!!

I know the code is ugly, but here is the custom method:

- (void)drawRect:(CGRect)rect{
// Drawing code
NSArray *kyle = [self pointsForPolygonInRect:rect numberOfSides:[pshape numberOfSides]];
CGContextRef c = UIGraphicsGetCurrentContext();

int counter = [kyle count];
NSLog(@"counter: %d",counter);
int i = 0;
BOOL first = YES;

NSValue *kylevalue;
CGPoint thePoint;
for (i = 0; i < counter; i++) {
    kylevalue = [kyle objectAtIndex:i];
    thePoint = [kylevalue CGPointValue];
    if (first) { //start.
        CGContextMoveToPoint(c, thePoint.x, thePoint.y+5.0);
        first = NO;
    } else { //do the rest
        CGContextAddLineToPoint(c,  thePoint.x, thePoint.y+5.0);
    }
}
CGContextClosePath(c); //solid color
CGContextDrawPath(c, kCGPathFillStroke);

}


问:
Laravel where in an update statement in the controller
I have this function in my controller which works:

```<code>foreach($models as $model) {
    if ($model->EindDatum < Carbon::now() && $model->email_send == 0) {
        DB::table('SSL')->where('userID', Auth::id())->update(['email_send' => 1]);
        $model->user()->first()->notify(new \App\Notifications\TaksComplete);
    }
}
</code>```

Now I would like to change the update statement to this:

```<code>DB::table('SSL')->where('userID', Auth::id(), 'EindDatum' < Carbon::now())->update(['email_send' => 1]);
</code>```

But this doesn't work.. its in my where statement but I don't know what I am doing wrong?

But this still updates all of the email_send columns in my database. even though it now should only update the ones in the past.

I dont get an error message

答:
The where statement doesn't work like this

->where('userID', Auth::id(), 'EindDatum' < Carbon::now())

The problem is that the where clause doesn't know how to mach your expression.

You need to udpate your code like this

```<code> DB::table('SSL')
 ->where('userID', Auth::id())
 ->where('EindDatum', '<', Carbon::now())
 ->update(['email_send' => 1]);
</code>```

The result will be
Where Userid = Auth::id() AND EindDatum < Carbon::now()

Where Auth::id() and Carbon::now are replaced with the values returned from the facades.

Edit: Made the code easier to read.

More about the where clauses

Body:
I have this function in my controller which works:

foreach($models as $model) {
    if ($model->EindDatum < Carbon::now() && $model->email_send == 0) {
        DB::table('SSL')->where('userID', Auth::id())->update(['email_send' => 1]);
        $model->user()->first()->notify(new \App\Notifications\TaksComplete);
    }
}

Now I would like to change the update statement to this:

DB::table('SSL')->where('userID', Auth::id(), 'EindDatum' < Carbon::now())->update(['email_send' => 1]);

But this doesn't work.. its in my where statement but I don't know what I am doing wrong?

But this still updates all of the email_send columns in my database. even though it now should only update the ones in the past.

I dont get an error message

Body:
The where statement doesn't work like this

->where('userID', Auth::id(), 'EindDatum' < Carbon::now())

The problem is that the where clause doesn't know how to mach your expression.

You need to udpate your code like this

 DB::table('SSL')
 ->where('userID', Auth::id())
 ->where('EindDatum', '<', Carbon::now())
 ->update(['email_send' => 1]);

The result will be
Where Userid = Auth::id() AND EindDatum < Carbon::now()

Where Auth::id() and Carbon::now are replaced with the values returned from the facades.

Edit: Made the code easier to read.

More about the where clauses


答:
var html = '<option value="">default</option>';
var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];
for (var i = 0; i < array.length; i++) {
  html += '<option value="' + array[i] + '"';

  html += '>' + textArray[i] + '</option>';

}

document.getElementById('select').innerHTML = html;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="HelmAtt1" id="select"></select></code>```

Title: Using two array values in foreach loop

Body:
var html = '<option value="">default</option>';
var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];
for (var i = 0; i < array.length; i++) {
  html += '<option value="' + array[i] + '"';

  html += '>' + textArray[i] + '</option>';

}

document.getElementById('select').innerHTML = html;

<select name="HelmAtt1" id="select"></select>


问:
how to crop some portion of scaled, rotated image-view
I am unable to crop he image from image view, which is scaled and rotated before cropping. used existing cropping methods.but its applicable only for image-view which is fixed.Hope code will helpful.</p>

答:
Try This(if you need to crop the corners):

```<code>UIImageView *imageSubview = [[UIImageView alloc] initWithFrame:CGRectMake(50.0f, 5.0f,80.0f, 60.0f)];

[imageSubview setImage:actualImage];
[imageSubview setContentMode:UIViewContentModeScaleToFill];
[imageSubview.layer setCornerRadius:10.0];
[imageSubview.layer setMasksToBounds:YES];
[cell addSubview:imageSubview];
</code>```

Just increase the radius and you will make it circle, or walk on this path you'll get your actual solution.:)

Body:
Try This(if you need to crop the corners):

UIImageView *imageSubview = [[UIImageView alloc] initWithFrame:CGRectMake(50.0f, 5.0f,80.0f, 60.0f)];

[imageSubview setImage:actualImage];
[imageSubview setContentMode:UIViewContentModeScaleToFill];
[imageSubview.layer setCornerRadius:10.0];
[imageSubview.layer setMasksToBounds:YES];
[cell addSubview:imageSubview];

Just increase the radius and you will make it circle, or walk on this path you'll get your actual solution.:)


问:
After Add a CustomView to navigationItem, CustomView always return nil
Bellow code is adding a customView to navigationItem successfully, but when trying to access the customView it always return nil

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let customView = getCustomView() // supposed that the function return a custom view
    let actionButton = UIBarButtonItem(customView: customView)
    self.navigationItem.rightBarButtonItem = actionButton // successfully added customView
    print(navigationItem.rightBarButtonItem?.customView)  // print always nil
}
</code>```

Result :

```<code>nil
</code>```

答:
I found out that the best way to access our customView (custom rightBarButtonItem), we have to access through Swift standard way:

After adding the customView, we can access the customView via : self.navigationItem.rightBarButtonItems array only.

In my case to get customView back from navigationItem :

let customView = navigationItem.rightBarButtonItems?.first?.customView // access the first
  added customView

Body:
Bellow code is adding a customView to navigationItem successfully, but when trying to access the customView it always return nil

override func viewDidLoad() {
    super.viewDidLoad()
    let customView = getCustomView() // supposed that the function return a custom view
    let actionButton = UIBarButtonItem(customView: customView)
    self.navigationItem.rightBarButtonItem = actionButton // successfully added customView
    print(navigationItem.rightBarButtonItem?.customView)  // print always nil
}

Result :

nil


问:
IDEA maven dependency package cannot be downloaded
I used unused images to download the files, and having below errors. In general, there were both.

Could not transfer artifact org.springframework:spring-context:pom:5.1.7.RELEASE from/to nexus-aliyun (http://maven.aliyun.com/nexus/content/groups/public): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Return code is: 501 , ReasonPhrase:HTTPS Required

答:
I guess the problem is that your nexus proxies mavencentral trough http, but mavencentral  dropped http support
I guess your nexus is not configured properly now proxy to Maven Central repo


问:
Android - Media Scanner not working on api 28-29
I'm scanning files using MediaScanner. But API 28 and 29 don't work.

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file));
```

<p>I used <code>Broadcast</code>, but it didn't work the same way. Because it is "deprecated".</p>

```java public static class FilesScanner extends ContextWrapper implements MediaScannerConnection.MediaScannerConnectionClient{

        private MediaScannerConnection connection = null;
        private String SCAN_FILE_PATH = "";
        private String SCAN_FILE_MIME_TYPE = "*/*";

        public static FilesScanner with(Context context, String SCAN_FILE_PATH){ return new FilesScanner(context, SCAN_FILE_PATH, "*/*"); }
        public static FilesScanner with(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){ return new FilesScanner(context, SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE); }
        private FilesScanner(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){
            super(context);
            this.SCAN_FILE_PATH = SCAN_FILE_PATH;
            if (SCAN_FILE_PATH == null){
                this.SCAN_FILE_PATH = FilePaths.ROOT_DIR;
            }
            this.SCAN_FILE_MIME_TYPE = SCAN_FILE_MIME_TYPE;
            if (SCAN_FILE_MIME_TYPE == null){
                this.SCAN_FILE_MIME_TYPE = "*/*";
            }
            connection = new MediaScannerConnection(this, this);
            connection.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            MyLog.d("onMediaScannerConnected");
            connection.scanFile(SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            MyLog.d("onScanCompleted" + " URI : " + uri.getPath());
            connection.disconnect();
        }
    }
FilesScanner.with(this, path, "image/*");
```

答:
Have you defined FileProvider entry in your AndroidManifest.xml?

You need to specify <files-path> in that you need to make available to other apps.

Refer this file sharing training and FileProvider reference

Body:
I'm scanning files using MediaScanner. But API 28 and 29 don't work.

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file));

I used Broadcast, but it didn't work the same way. Because it is "deprecated".

java public static class FilesScanner extends ContextWrapper implements MediaScannerConnection.MediaScannerConnectionClient{

        private MediaScannerConnection connection = null;
        private String SCAN_FILE_PATH = "";
        private String SCAN_FILE_MIME_TYPE = "*/*";

        public static FilesScanner with(Context context, String SCAN_FILE_PATH){ return new FilesScanner(context, SCAN_FILE_PATH, "*/*"); }
        public static FilesScanner with(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){ return new FilesScanner(context, SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE); }
        private FilesScanner(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){
            super(context);
            this.SCAN_FILE_PATH = SCAN_FILE_PATH;
            if (SCAN_FILE_PATH == null){
                this.SCAN_FILE_PATH = FilePaths.ROOT_DIR;
            }
            this.SCAN_FILE_MIME_TYPE = SCAN_FILE_MIME_TYPE;
            if (SCAN_FILE_MIME_TYPE == null){
                this.SCAN_FILE_MIME_TYPE = "*/*";
            }
            connection = new MediaScannerConnection(this, this);
            connection.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            MyLog.d("onMediaScannerConnected");
            connection.scanFile(SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            MyLog.d("onScanCompleted" + " URI : " + uri.getPath());
            connection.disconnect();
        }
    }
FilesScanner.with(this, path, "image/*");


问:
Find the appropriate strings to use for azure Python 3.6 API for azure
I'm trying to set up reading event hub messages via the Azure event hub API.

I believe I have the event hub and storage containers set up properly.  But I don't know how to find the exact information it's looking for here....

connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'

consumer_group = '<< CONSUMER GROUP >>'

eventhub_name = '<< NAME OF THE EVENT HUB >>'

storage_connection_str = '<< CONNECTION STRING OF THE STORAGE >>'

container_name = '<< STORAGE CONTAINER NAME>>'

Thanks in advance.

答:
Regarding the issue, please refer to the following steps

Get the EnvetEvent Hub Namespace connection string

a. Sign in to Azure portal.

b. Select All services on the left navigational menu.

c. Select Event Hubs in the Analytics section.

d. In the list of event hubs, select your event hub.

e. Get connection string

Get your Event Hub name

Get the storage  Container Name

Get the storage  Container connection string. If you know the container in one storage account, please refer to the following steps to get the connection string

a. Locate your storage account.

b. Get connection string

Otherwise, please reset a container fro the event hub then you use the above steps to get the connection string.

Consumer group


问:
Tool Tip jQuery to appear outside slide element
I have a jQuery conundrum that I'm not sure can be resolved. Inside a content slider I have absolutely positioned divs creating a tool-tip style pop-up on hover. Because the containing content slider overflow must be set to hidden, the tool-tip pop-up gets cut off where it overflows. I would like the pop-up to display in full when overlapping the slider it is contained within. If anyone has a workaround for this I'd be very appreciative!

Here's a link to my working file from which you can see the problem and the code.

Many thanks for any advice.

答:
Your animation inside 'slidesContainer' relies on overflow:hidden so the large image doesn't stick out of the div and the only way for you to get the balloons pop out is to remove that overflow:hidden and make it visible

I don't think you can have the two at the same time


问:
I cannot pass data to view it show http error 500 in laravel
Hi guyz i am kind of new to laravel and im trying to show the reviews posted by users . Now i checked with dd() and indeed i am able to get that data however when i send it to the view laravel responds with Http error 500. Previously i was only sending the doctors data which was working fine but when i tried to pass the reviews this happened.
This is my show Profile function

```<code>     public function profile($id)
    {
    $doctor=Doctor::find($id);
    $reviews=Review::where('doctor_id',$doctor->account_id)->get();

   // dd($doctor,$reviews);
    //  foreach($reviews as $review)
    //  {
    //      dd($doctor,$review);
    //  }
   // dd($reviews);
   // dd(DB::select("select * from reviews where doctor_id='D-1'"));
    //dd(Review::all()->where('doctor_id',$doctor->account_id));
   // $reviews=;
  // $array=['reviews'=>$reviews];
    return View('pages.doctorProfile',['reviews'=>$reviews])->with('doctor',$doctor);
}
</code>```

and this is the section of the view where i was trying to show the review

```<code>@foreach($reviews as $review)
    <!-- Comment List -->
    <li>
    <div class="comment">
        <img class="avatar avatar-sm rounded-circle" alt="User Image" src="/storage/images/patients/{{$review->patient->image}}">
        <div class="comment-body">
            <div class="meta-data">
                <span class="comment-author">{{$review->patient->first_name}} {{$review->patient->last_name}}</span>
                <span class="comment-date">{{$review->created_at}}</span>

            </div>
            <div  class="review-count rating">
                <?php $rating=explode('-',$review->rating)  ?>
                @for($i=1;$i<=5;$i++)
                    @for($i=1;$i<=$rating[1];$i++)
                        <i class="fas fa-star filled"></i>
                    @endfor
                    <i class="fas fa-star"></i>
                @endfor
                {{-- <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star"></i> --}}
            </div>
            <p class="comment-content">
               {{$review->content}}
            </p>
            <div class="comment-reply">
                <a class="comment-btn" href="#">
                    <i class="fas fa-reply"></i> Reply
                </a>

            </div>
        </div>
    </div>
    </li>
    <!-- /Comment List -->
@endforeach
</code>```

Need this solved quick. Please help

答:
I see several things here, the code should be like this:

```<code>$doctor=Doctor::find($id);
$reviews=Review::where('doctor_id',$doctor->account_id)->with('patient')->get();
return view('pages.doctorProfile',['reviews'=>$reviews]);
</code>```

I don't see anything strange in the view, check if changing that makes the work.

Body:
Hi guyz i am kind of new to laravel and im trying to show the reviews posted by users . Now i checked with dd() and indeed i am able to get that data however when i send it to the view laravel responds with Http error 500. Previously i was only sending the doctors data which was working fine but when i tried to pass the reviews this happened.
This is my show Profile function

     public function profile($id)
    {
    $doctor=Doctor::find($id);
    $reviews=Review::where('doctor_id',$doctor->account_id)->get();

   // dd($doctor,$reviews);
    //  foreach($reviews as $review)
    //  {
    //      dd($doctor,$review);
    //  }
   // dd($reviews);
   // dd(DB::select("select * from reviews where doctor_id='D-1'"));
    //dd(Review::all()->where('doctor_id',$doctor->account_id));
   // $reviews=;
  // $array=['reviews'=>$reviews];
    return View('pages.doctorProfile',['reviews'=>$reviews])->with('doctor',$doctor);
}

and this is the section of the view where i was trying to show the review

@foreach($reviews as $review)

        patient->image}}">

                {{$review->patient->first_name}} {{$review->patient->last_name}}
                {{$review->created_at}}

                <?php $rating=explode('-',$review->rating)  ?>
                @for($i=1;$i<=5;$i++)
                    @for($i=1;$i<=$rating[1];$i++)

                    @endfor

                @endfor
                {{--

                 --}}

               {{$review->content}}

                     Reply

@endforeach

Need this solved quick. Please help

Body:
I see several things here, the code should be like this:

$doctor=Doctor::find($id);
$reviews=Review::where('doctor_id',$doctor->account_id)->with('patient')->get();
return view('pages.doctorProfile',['reviews'=>$reviews]);

I don't see anything strange in the view, check if changing that makes the work.


答:
One of the ways that will give you the result that you want

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

const options = Object.assign({}, ...array.map((key, index) => {
  return {
    [key]: textArray[index]
  };
}));

Object.keys(options).forEach(optionKey => {
   $(".department").append('<option value="' + optionKey + '">' + options[optionKey] + '</option>');
});
</code>```

Another solution

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

const options = Object.assign({}, ...array.map((key, index) => {
  return {
    [key]: textArray[index]
  };
}));

Object.entries(options).forEach(option => {
   $(".department").append('<option value="' + option[0] + '">' + option[1] + '</option>');
});
</code>```

Title: Using two array values in foreach loop

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');

My output looks like this:

<option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>

Whereas I'm looking for:

<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>

Body:
One of the ways that will give you the result that you want

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

const options = Object.assign({}, ...array.map((key, index) => {
  return {
    [key]: textArray[index]
  };
}));

Object.keys(options).forEach(optionKey => {
   $(".department").append('<option value="' + optionKey + '">' + options[optionKey] + '</option>');
});

Another solution

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

const options = Object.assign({}, ...array.map((key, index) => {
  return {
    [key]: textArray[index]
  };
}));

Object.entries(options).forEach(option => {
   $(".department").append('<option value="' + option[0] + '">' + option[1] + '</option>');
});


问:
change default font SSRS Visual Studio
I have been searching hi and lo, within and outside internet but it seems I cannot find a definitive answer:
Can I change the default layout-items in SSRS reports? If so, how?

So that a textbox does not have Arial 10 as default fontsize but has fontsize 8?

So that tablixes have default properties like 'show column-headers on each page' enabled?

and so on?

I am familiar with custom templates (.rdl) but they do not offer the possibility of changing layout-items like default font and colors and properties of report parts and such.

In VS 2005 there was the StyleTemplate to play with but that is only effective when using the wizard.
It seems it is the same way with VS 2010.

I prefer to hear that it can be done and instructions how to, I would be satisfied with tips how to circumvent the problem of manually changing those properties eacht time and I will be grateful for a definitive answer. Right now it is driving me crazy :)

I am working with VS2010 (latest updates and such) icm SQL 2008, 2008R2 and (local) 2012BI

Thanks for thinking with me!

答: At the start of the XML for the RDL file (what you see if you select View Code on the file) there's a tag <df:DefaultFontFamily> which defines the default font. If you change this to the family you want and re-save the XML file, any future textboxes you create will pick up this default font family.

Title: change default font SSRS Visual Studio


问:
How to compare two string value and give back which is not exits?
Here I have two string as:

string a1 = "A1,A2,A3,B1-1,B2-1";
string a2 = "A1,A2,A3,B1-1,B2-1,A4,A5";
```

<p>Here <code>A4</code> and <code>A5</code> do not exist in <code>a1</code>. How can I find them as new values?</p>

<pre class="lang-cs prettyprint-override"><code>string finalValue = string.compare(a1, a2);
</code>```

Here I'm getting numeric value.

答:
separate both the string by using Split method and compare both list

```<code>List<string> list1 =  Arrays.asList(a1.Split(','));
List<string> list2 =  Arrays.asList(a2.Split(','));
</code>```

If you want to get items from the first list except items in the second list, use

```<code>var differences = list1.Except(list2);
</code>```

Body:
Here I have two string as:

string a1 = "A1,A2,A3,B1-1,B2-1";
string a2 = "A1,A2,A3,B1-1,B2-1,A4,A5";

Here A4 and A5 do not exist in a1. How can I find them as new values?

string finalValue = string.compare(a1, a2);

Here I'm getting numeric value.

Body:
separate both the string by using Split method and compare both list

List<string> list1 =  Arrays.asList(a1.Split(','));
List<string> list2 =  Arrays.asList(a2.Split(','));

If you want to get items from the first list except items in the second list, use

var differences = list1.Except(list2);


问:
check for end of execution of class in java
I have written a small program to validate 3 data files and convert them into a csv file.

-Every file is converted by a different class file

-There is a main class which instantiates all the other classes for processing files one after other

How do i make sure that the next file is processed only after the previous file is done?

The pseudocode for my program is as follows

```<code>mainExecute Class()
{
    executeFile1converter();
    executeFile2Converter();
    executeFile3Converter();
}
</code>```

答: As long as the different class files don't start threads to do the work, you needn't bothter. Sequential work is the default.</p>

Body:
I have written a small program to validate 3 data files and convert them into a csv file.

-Every file is converted by a different class file

-There is a main class which instantiates all the other classes for processing files one after other

How do i make sure that the next file is processed only after the previous file is done?

The pseudocode for my program is as follows

mainExecute Class()
{
    executeFile1converter();
    executeFile2Converter();
    executeFile3Converter();
}


问:
Can I add a directory containing a jar and its dependant jars as a maven dependency?
I am working on a small codebase (maven project) which requires libraries provided by the creator of the system my project integrates with. Now the library comes in the following form:

```<code>com.example.library.client_1.2.3.v20190123/ (just a directory)
├── lib/
│   ├── some-dependency-3.2.1.jar
│   ├── ....jar
│   └── another-dependency-1.2.3.jar
├── META-INF/
│   └── MANIFEST.MF
└── some.library.jar
</code>```

How was this library built?

How can I add a "proper" dependency to such a package using maven so that I can later build a big/uber jar? I know with a single jar there are a few ways e.g. I can install it to my local repository using mvn install:install-file .... But how can I add the above structure as a dependency to also include the libraries inside the lib directory (the transitive dependencies)? Can I repackage the above strucutre for better usage?

Would I need to add all those lib jars to my local maven repository individually?

If of interest, the manifest has the following form:

```<code>Manifest-Version: 1.0
Bundle-SymbolicName: com.example.library....;singleton:=true
Export-Package: com.example.library...
Bundle-Name: ...
Bundle-Version: 1.2.3.v20190123
Bundle-ClassPath: lib/some-dependency-3.2.1.jar,lib/...
.jar,lib/another-dependency-1.2.3.jar
Bundle-ManifestVersion: 2
Bundle-ActivationPolicy: lazy
Bundle-Vendor: ...
</code>```

答:
The Manifest tells you that the jar of this library contains the dependencies. If you install this library jar into OSGi it should work as it has all dependencies embedded.

If you plan to use this library outside of OSGi then this kind of packaging with embedded libraries makes no sense. Maybe they also offer just the library and you can install the dependencies via maven (if they are well known open source libs).

Body:
I am working on a small codebase (maven project) which requires libraries provided by the creator of the system my project integrates with. Now the library comes in the following form:

com.example.library.client_1.2.3.v20190123/ (just a directory)
├── lib/
│   ├── some-dependency-3.2.1.jar
│   ├── ....jar
│   └── another-dependency-1.2.3.jar
├── META-INF/
│   └── MANIFEST.MF
└── some.library.jar

How was this library built?

How can I add a "proper" dependency to such a package using maven so that I can later build a big/uber jar? I know with a single jar there are a few ways e.g. I can install it to my local repository using mvn install:install-file .... But how can I add the above structure as a dependency to also include the libraries inside the lib directory (the transitive dependencies)? Can I repackage the above strucutre for better usage?

Would I need to add all those lib jars to my local maven repository individually?

If of interest, the manifest has the following form:

Manifest-Version: 1.0
Bundle-SymbolicName: com.example.library....;singleton:=true
Export-Package: com.example.library...
Bundle-Name: ...
Bundle-Version: 1.2.3.v20190123
Bundle-ClassPath: lib/some-dependency-3.2.1.jar,lib/...
.jar,lib/another-dependency-1.2.3.jar
Bundle-ManifestVersion: 2
Bundle-ActivationPolicy: lazy
Bundle-Vendor: ...


问:
connection timed out; no servers could be reached when connect CoreDNS server
When I using dig command to test the CoreDNS server,it shows: connection timed out; no servers could be reached:

```<code>[root@ops001 ~]# /opt/k8s/bin/kubectl exec -ti soa-user-service-5c8b744d6d-7p9hr -n dabai-fat /bin/sh
/ # dig -t A kubernetes.default.svc.cluster.local. @10.254.0.2

; <<>> DiG 9.12.4-P2 <<>> -t A kubernetes.default.svc.cluster.local. @10.254.0.2
;; global options: +cmd
;; connection timed out; no servers could be reached
</code>```

when I ping server,it success.

```<code>[root@ops001 ~]# /opt/k8s/bin/kubectl exec -ti soa-user-service-5c8b744d6d-7p9hr -n dabai-fat /bin/sh
/ # ping 10.254.0.2
PING 10.254.0.2 (10.254.0.2): 56 data bytes
64 bytes from 10.254.0.2: seq=0 ttl=64 time=0.100 ms
64 bytes from 10.254.0.2: seq=1 ttl=64 time=0.071 ms
64 bytes from 10.254.0.2: seq=2 ttl=64 time=0.094 ms
64 bytes from 10.254.0.2: seq=3 ttl=64 time=0.087 ms
</code>```

why the dig could not connect to DNS server althrough the network is ok?This is my CoreDNS service:

when azshara-k8s03‘s node connection to CoreDNS server:

```<code>/ # telnet 10.254.0.2 53
Connection closed by foreign host
</code>```

when azshara-k8s02‘s and azshara-k8s01‘s node connection to CoreDNS server:

```<code>/ # telnet 10.254.0.2 53
telnet: can't connect to remote host (10.254.0.2): Connection refused
</code>```

I just confusing why port 53 is not open,when I scan from host using same command,the port 53 is open:

答:
I finally find some server's kube-proxy not start,and the route foward rule not refresh,using this command to start kube-proxy fix this problem:</p>

```<code>systemctl start kube-proxy
</code>```

Body:
When I using dig command to test the CoreDNS server,it shows: connection timed out; no servers could be reached:

[root@ops001 ~]# /opt/k8s/bin/kubectl exec -ti soa-user-service-5c8b744d6d-7p9hr -n dabai-fat /bin/sh
/ # dig -t A kubernetes.default.svc.cluster.local. @10.254.0.2

; <<>> DiG 9.12.4-P2 <<>> -t A kubernetes.default.svc.cluster.local. @10.254.0.2
;; global options: +cmd
;; connection timed out; no servers could be reached

when I ping server,it success.

[root@ops001 ~]# /opt/k8s/bin/kubectl exec -ti soa-user-service-5c8b744d6d-7p9hr -n dabai-fat /bin/sh
/ # ping 10.254.0.2
PING 10.254.0.2 (10.254.0.2): 56 data bytes
64 bytes from 10.254.0.2: seq=0 ttl=64 time=0.100 ms
64 bytes from 10.254.0.2: seq=1 ttl=64 time=0.071 ms
64 bytes from 10.254.0.2: seq=2 ttl=64 time=0.094 ms
64 bytes from 10.254.0.2: seq=3 ttl=64 time=0.087 ms

why the dig could not connect to DNS server althrough the network is ok?This is my CoreDNS service:

when azshara-k8s03‘s node connection to CoreDNS server:

/ # telnet 10.254.0.2 53
Connection closed by foreign host

when azshara-k8s02‘s and azshara-k8s01‘s node connection to CoreDNS server:

/ # telnet 10.254.0.2 53
telnet: can't connect to remote host (10.254.0.2): Connection refused

I just confusing why port 53 is not open,when I scan from host using same command,the port 53 is open:

Body:
I finally find some server's kube-proxy not start,and the route foward rule not refresh,using this command to start kube-proxy fix this problem:

systemctl start kube-proxy


问:
How to set a button to fill a whole row using gridbox layout?
I'm working with Python 3 and PyQt5. I use GridBoxLayout for arranging my buttons. But I need a Button to fill a whole row, which I can't do with GridBoxLayout.

Any one can help?

```<code>    gridLayout.addWidget(self.btn_startCapture, 0, 0)
    gridLayout.addWidget(self.btn_endCapture, 0, 1)
    gridLayout.addWidget(self.btn_startRecording, 0, 2)
    gridLayout.addWidget(self.btn_endRecording, 0, 3)
    gridLayout.addWidget(self.btn_takePicture, 0, 4)
    gridLayout.addWidget(self.btn_loadVideo, 0, 5)
    gridLayout.addWidget(self.linedit_getPicDir, 1, 0) # I want this button to fill the whole second row
    gridLayout.addWidget(self.linedit_getVideoDir, 2, 1)
    gridLayout.addWidget(self.btn_getVideoDir, 2, 2)
    gridLayout.addWidget(self.btn_getPicDir, 2, 3)
</code>```

I get this :

but I need that the image Dir lien edit be stretched all over the second row

答:
With QGridLayout you can set a widget to span multiple rows or columns. For example, addWidget(QPushButton(), 0, 0, 3, 1)
 will position a button at (0, 0) that spans 3 rows and 1 column.

In your code, you can just add the row and col spans to that line:

```<code>gridLayout.addWidget(self.linedit_getPicDir, 1, 0, 1, 6)
</code>```

Body:
I'm working with Python 3 and PyQt5. I use GridBoxLayout for arranging my buttons. But I need a Button to fill a whole row, which I can't do with GridBoxLayout.

Any one can help?

    gridLayout.addWidget(self.btn_startCapture, 0, 0)
    gridLayout.addWidget(self.btn_endCapture, 0, 1)
    gridLayout.addWidget(self.btn_startRecording, 0, 2)
    gridLayout.addWidget(self.btn_endRecording, 0, 3)
    gridLayout.addWidget(self.btn_takePicture, 0, 4)
    gridLayout.addWidget(self.btn_loadVideo, 0, 5)
    gridLayout.addWidget(self.linedit_getPicDir, 1, 0) # I want this button to fill the whole second row
    gridLayout.addWidget(self.linedit_getVideoDir, 2, 1)
    gridLayout.addWidget(self.btn_getVideoDir, 2, 2)
    gridLayout.addWidget(self.btn_getPicDir, 2, 3)

I get this :

but I need that the image Dir lien edit be stretched all over the second row

Body:
With QGridLayout you can set a widget to span multiple rows or columns. For example, addWidget(QPushButton(), 0, 0, 3, 1)
 will position a button at (0, 0) that spans 3 rows and 1 column.

In your code, you can just add the row and col spans to that line:

gridLayout.addWidget(self.linedit_getPicDir, 1, 0, 1, 6)


Body:
I have coordinate lists of several polygons as listed below:

l_b =  [[[57.5, 2.875],
   [83.75, 4.1875],
   [83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 2.875]],
  [[83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 34.08695652173913],
   [83.75, 34.54347826086956],
   [83.75, 18.70923913043478]],
  [[0.0, 0.0],
   [18.125, 0.90625],
   [18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [0.0, 0.0]],
  [[18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [-5.0, 33.0],
   [18.125, 33.40217391304348],
   [18.125, 16.70108695652174]]]

How can I make all the numbers in list to round to 2 decimal places while keeping its format?

I've tried l_b = [ '%.2f' % elem for elem in l_b ] but it's giving me TypeError: must be real number, not list

Body:
Try this numpy approach:

l_b = np.array( [[[57.5, 2.875],
   [83.75, 4.1875],
   [83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 2.875]],
  [[83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 34.08695652173913],
   [83.75, 34.54347826086956],
   [83.75, 18.70923913043478]],
  [[0.0, 0.0],
   [18.125, 0.90625],
   [18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [0.0, 0.0]],
  [[18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [-5.0, 33.0],
   [18.125, 33.40217391304348],
   [18.125, 16.70108695652174]]])

Shape of array is (4,5,2)

apply map to round the decimals upto 2 digits

a=list(map(lambda x :round(x,2),l_b.flatten() ))

convert back to original shape

np.array(a).reshape(4,5,2)

or

A much simpler way suggested by Georgy

l_b.round(2)


问:
Laravel Socialite - Difference between SocialiteProvider Microsoft Graph and Microsoft Azure
I want to make an app for my organisation using SSO via Office365. I found the Socialite plugin for Laravel and now I am wondering: What is the difference between Microsoft Graph and Microsoft Azure Provider? </p>

答:
Here are some usefull informations:
https://developer.microsoft.com/en-us/office/blogs/microsoft-graph-or-azure-ad-graph/

TLDR: Use Microsoft Graph instead of Azure, because the Azure Version will be deprecated.