问:
pivot_longer with groups of columns
I've got a dataset that looks like this:

```<code>df_start <- tribble(
    ~name,   ~age, ~x1_sn_ctrl1, ~x1_listing2_2, ~x1_affect1, ~x2_sn_ctrl1, ~x1_listing2_2, ~x2_affect1, ~number,
    "John",   28,        1,            1,             9,           4,            5,                9,       6,
    "Paul",   27,        2,            1,             4,           1,            3,                3,       4,
    "Ringo",  31,        3,            1,             2,           2,            5,                8,       9)
</code>```

I need to pivot_longer() while handling the groupings within my columns:

There are 2 x-values (1 and 2)

There are 3 questions (sn_ctrl1, listing2_2, affect1) for each x-value

In my actual dataset, there are 14 x's.

Essentially, what I'd like to do is to apply pivot_longer() to the x-values but leave my 3 questions (sn_ctrl1, listing2_2, affect1) wide.

What I'd like to end up with is this:

```<code>df_end <- tribble(
    ~name, ~age, ~xval, ~sn_ctrl1, ~listing2_2, ~affect1, ~number,
    "John", 28,    1,        1,         1,          9,       6,
    "John", 28,    2,        4,         5,          9,       6,
    "Paul", 27,    1,        2,         1,          4,       4,
    "Paul", 27,    2,        1,         3,          3,       4,
    "Ringo", 31,   1,        3,         1,          2,       9,
    "Ringo", 31,   2,        2,         5,          8,       9)
</code>```

I have tried lots of very unsuccessful attempts playing with regex in names_pattern & pivot_longer but am completely striking out.

Anyone know how to tackle this?

THANKS!

PS: Note that I tried to make a straightforward reproducible example. The actual names of my columns vary slightly. For instance, there is x1_sn_ctrl1 & x1_attr1_ctrl2.

答:
You can use :

```<code>tidyr::pivot_longer(df_start,
                    cols = -c(name, age, number),
                    names_to = c("xval", ".value"),
                    names_pattern = 'x(\\d+)_(.*)')
</code>```

Which yields

```<code># A tibble: 9 x 7
  name    age number xval  sn_ctrl1 listing2_2 affect1
  <chr> <dbl>  <dbl> <chr>    <dbl>      <dbl>   <dbl>
1 John     28      6 1            1          1       9
2 John     28      6 2            4         NA       9
3 John     28      6 1           NA          5      NA
4 Paul     27      4 1            2          1       4
5 Paul     27      4 2            1         NA       3
6 Paul     27      4 1           NA          3      NA
7 Ringo    31      9 1            3          1       2
8 Ringo    31      9 2            2         NA       8
9 Ringo    31      9 1           NA          5      NA
</code>```

Title: pivot_longer with groups of columns

Body:
I've got a dataset that looks like this:

df_start <- tribble(
    ~name,   ~age, ~x1_sn_ctrl1, ~x1_listing2_2, ~x1_affect1, ~x2_sn_ctrl1, ~x1_listing2_2, ~x2_affect1, ~number,
    "John",   28,        1,            1,             9,           4,            5,                9,       6,
    "Paul",   27,        2,            1,             4,           1,            3,                3,       4,
    "Ringo",  31,        3,            1,             2,           2,            5,                8,       9)

I need to pivot_longer() while handling the groupings within my columns:

There are 2 x-values (1 and 2)

There are 3 questions (sn_ctrl1, listing2_2, affect1) for each x-value

In my actual dataset, there are 14 x's.

Essentially, what I'd like to do is to apply pivot_longer() to the x-values but leave my 3 questions (sn_ctrl1, listing2_2, affect1) wide.

What I'd like to end up with is this:

df_end <- tribble(
    ~name, ~age, ~xval, ~sn_ctrl1, ~listing2_2, ~affect1, ~number,
    "John", 28,    1,        1,         1,          9,       6,
    "John", 28,    2,        4,         5,          9,       6,
    "Paul", 27,    1,        2,         1,          4,       4,
    "Paul", 27,    2,        1,         3,          3,       4,
    "Ringo", 31,   1,        3,         1,          2,       9,
    "Ringo", 31,   2,        2,         5,          8,       9)

I have tried lots of very unsuccessful attempts playing with regex in names_pattern & pivot_longer but am completely striking out.

Anyone know how to tackle this?

THANKS!

PS: Note that I tried to make a straightforward reproducible example. The actual names of my columns vary slightly. For instance, there is x1_sn_ctrl1 & x1_attr1_ctrl2.

Body:
You can use :

tidyr::pivot_longer(df_start,
                    cols = -c(name, age, number),
                    names_to = c("xval", ".value"),
                    names_pattern = 'x(\\d+)_(.*)')

Which yields

# A tibble: 9 x 7
  name    age number xval  sn_ctrl1 listing2_2 affect1
  <chr> <dbl>  <dbl> <chr>    <dbl>      <dbl>   <dbl>
1 John     28      6 1            1          1       9
2 John     28      6 2            4         NA       9
3 John     28      6 1           NA          5      NA
4 Paul     27      4 1            2          1       4
5 Paul     27      4 2            1         NA       3
6 Paul     27      4 1           NA          3      NA
7 Ringo    31      9 1            3          1       2
8 Ringo    31      9 2            2         NA       8
9 Ringo    31      9 1           NA          5      NA


来源: stackexchange

问:
Android, Why my html file doesn't show?
I have stored some of my information in an HTML file and put it in asset folder. However, when I want to show it, web page starts but it says that "Web page not available", while I have stored it in assets folder.

This is my code:

```<code>@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.am_culture);

        final FrameLayout frame01 = (FrameLayout) findViewById(R.id.ch_frame01);
        final WebView wv = new WebView(this);

        frame01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wv.loadUrl("file:///android_asset/people.html");
                setContentView(wv);
            }
        });
    }
</code>```

答:
```<code>    WebView mWebView = null;
    mWebView = (WebView) findViewById(R.id.wb1);
    mWebView.getSettings().setJavaScriptEnabled(true);
    InputStream is;
    try {
        is = getAssets().open("people.html");
        int size = is.available();
        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        // Convert the buffer into a string.
        String strContent = new String(buffer);
        mWebView.loadData(strContent, "text/html", "UTF-8");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android, Why my html file doesn't show?

Body:
I have stored some of my information in an HTML file and put it in asset folder. However, when I want to show it, web page starts but it says that "Web page not available", while I have stored it in assets folder.

This is my code:

@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.am_culture);

        final FrameLayout frame01 = (FrameLayout) findViewById(R.id.ch_frame01);
        final WebView wv = new WebView(this);

        frame01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wv.loadUrl("file:///android_asset/people.html");
                setContentView(wv);
            }
        });
    }


问:
Performing background tasking using Job Scheduler at exact time
I am working on News app. And I needed to get latest news once a day. For this I used Jobsheduler.Here is the code :

```<code>ComponentName componentName = new ComponentName(this, JobService.class);
        JobInfo jobInfo = new JobInfo.Builder(123, componentName)
                .setRequiresCharging(false)
                .setPeriodic(24 * 60 * 60 * 1000)
                .setPersisted(true)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .build();
        JobScheduler jobScheduler = (JobScheduler)getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
        int resultCode = jobScheduler.schedule(jobInfo);

        if (resultCode == JobScheduler.RESULT_SUCCESS){
            Log.d(TAG, "Job Scheduled");
        }
        else {
            Log.d(TAG, "Job Scheduling failed");
        }
</code>```

But now I need to do this work once in the morning after 6:00 when there will be internet connection.
Is there a way to do this with Job Scheduler. I know that I can do this using Alarm Manager but Job Scheduler is far more better than Alarm Manager in conditions like if there is connection, if device  charging. Or can I achieve this using Workmanager which uses Job Scheduler and AlarmManager if it needs to. Or is there another way of doing this??? Any suggestions are apprecieated.

答:
```<code>public static final String CUSTOM_INTENT = "com.test.intent.action.ALARM";
public static Context ctx = OfferlyApplication.getContext();

@Override
public void onReceive(Context context, Intent intent) {
    /* enqueue the job */
    AlarmJobIntentService.enqueueWork(context, intent);
}
public static void cancelAlarm() {
    AlarmManager alarm = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);

    /* cancel any pending alarm */
    alarm.cancel(getPendingIntent());
}
public static void setAlarm(boolean force) {
    cancelAlarm();
    AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    // EVERY X MINUTES
    long delay = (1000 * 60 * 60);
    long when = System.currentTimeMillis();
    if (!force) {
        when += delay;
    }
    /* fire the broadcast */
    PendingIntent pendingIntent = getPendingIntent();
    int SDK_INT = Build.VERSION.SDK_INT;
    if (SDK_INT < Build.VERSION_CODES.KITKAT)
        alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingIntent);
    else if (SDK_INT < Build.VERSION_CODES.M)
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, when, pendingIntent);
    else {
        Log.d("JOB_SCHEDULING","waking device");
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, when, pendingIntent);
    }
}
private static PendingIntent getPendingIntent() {
    //Context ctx;   /* get the application context */
    Intent alarmIntent = new Intent(ctx, AlarmReceiver.class);
    alarmIntent.setAction(CUSTOM_INTENT);
    return PendingIntent.getBroadcast(ctx, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}
</code>```

or using work manager for periodic workers

```<code> Constraints myConstraints = new Constraints.Builder()
            .setRequiresDeviceIdle(false)
            .setRequiresCharging(false)
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresBatteryNotLow(true)
            .setRequiresStorageNotLow(true)
            .build();

    PeriodicWorkRequest saveRequest =
            new PeriodicWorkRequest.Builder(NotificationWorker.class, 60, TimeUnit.MINUTES)
                    .setConstraints(myConstraints)
                    .build();

    WorkManager.getInstance()
            .enqueue(saveRequest);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on News app. And I needed to get latest news once a day. For this I used Jobsheduler.Here is the code :

ComponentName componentName = new ComponentName(this, JobService.class);
        JobInfo jobInfo = new JobInfo.Builder(123, componentName)
                .setRequiresCharging(false)
                .setPeriodic(24 * 60 * 60 * 1000)
                .setPersisted(true)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .build();
        JobScheduler jobScheduler = (JobScheduler)getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
        int resultCode = jobScheduler.schedule(jobInfo);

        if (resultCode == JobScheduler.RESULT_SUCCESS){
            Log.d(TAG, "Job Scheduled");
        }
        else {
            Log.d(TAG, "Job Scheduling failed");
        }

But now I need to do this work once in the morning after 6:00 when there will be internet connection.
Is there a way to do this with Job Scheduler. I know that I can do this using Alarm Manager but Job Scheduler is far more better than Alarm Manager in conditions like if there is connection, if device  charging. Or can I achieve this using Workmanager which uses Job Scheduler and AlarmManager if it needs to. Or is there another way of doing this??? Any suggestions are apprecieated.

Body:
public static final String CUSTOM_INTENT = "com.test.intent.action.ALARM";
public static Context ctx = OfferlyApplication.getContext();

@Override
public void onReceive(Context context, Intent intent) {
    /* enqueue the job */
    AlarmJobIntentService.enqueueWork(context, intent);
}
public static void cancelAlarm() {
    AlarmManager alarm = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);

    /* cancel any pending alarm */
    alarm.cancel(getPendingIntent());
}
public static void setAlarm(boolean force) {
    cancelAlarm();
    AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    // EVERY X MINUTES
    long delay = (1000 * 60 * 60);
    long when = System.currentTimeMillis();
    if (!force) {
        when += delay;
    }
    /* fire the broadcast */
    PendingIntent pendingIntent = getPendingIntent();
    int SDK_INT = Build.VERSION.SDK_INT;
    if (SDK_INT < Build.VERSION_CODES.KITKAT)
        alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingIntent);
    else if (SDK_INT < Build.VERSION_CODES.M)
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, when, pendingIntent);
    else {
        Log.d("JOB_SCHEDULING","waking device");
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, when, pendingIntent);
    }
}
private static PendingIntent getPendingIntent() {
    //Context ctx;   /* get the application context */
    Intent alarmIntent = new Intent(ctx, AlarmReceiver.class);
    alarmIntent.setAction(CUSTOM_INTENT);
    return PendingIntent.getBroadcast(ctx, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}

or using work manager for periodic workers

 Constraints myConstraints = new Constraints.Builder()
            .setRequiresDeviceIdle(false)
            .setRequiresCharging(false)
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresBatteryNotLow(true)
            .setRequiresStorageNotLow(true)
            .build();

    PeriodicWorkRequest saveRequest =
            new PeriodicWorkRequest.Builder(NotificationWorker.class, 60, TimeUnit.MINUTES)
                    .setConstraints(myConstraints)
                    .build();

    WorkManager.getInstance()
            .enqueue(saveRequest);


问:
License information could not be obtained from Elasticsearch for the [data] cluster
I have installed elasticsearch 7.5.1 and the same version of Kibana. My es cluster seems fine, but Kibana is not able to connect to the elasticsearch.

Kiabana.yml is as below:

```<code>server.port: 5601
server.host: "<IP of the kibana instance>"
server.name: "<Name of the kibana instance>"
elasticsearch.hosts: [ "https://<IP of ES instance 1>:443" , "https://<IP of ES instance 2>:443" ]
elasticsearch.username: "<kibana_user>"
elasticsearch.password: "<kibana_user_password>"
server.ssl.enabled: true
server.ssl.certificate:
server.ssl.key:
xpack.security.enabled: true
xpack.reporting.kibanaServer.port: 443
xpack.reporting.kibanaServer.protocol: https
elasticsearch.ssl.certificateAuthorities: [ "" ]
elasticsearch.ssl.verificationMode: certificate
logging.dest: /etc/kibana/log/kibana.log
</code>```

I have tried both kibana_oss and the non_oss, but I get the same error.

答:
This can be happen if ES cluster master node has not set correctly. </p>

<p>Test ES cluster health first </p>

```<code>curl <ES_IP:PORT>/_cluster/health?pretty
</code>```

Body:
I have installed elasticsearch 7.5.1 and the same version of Kibana. My es cluster seems fine, but Kibana is not able to connect to the elasticsearch.

Kiabana.yml is as below:

server.port: 5601
server.host: "<IP of the kibana instance>"
server.name: "<Name of the kibana instance>"
elasticsearch.hosts: [ "https://<IP of ES instance 1>:443" , "https://<IP of ES instance 2>:443" ]
elasticsearch.username: "<kibana_user>"
elasticsearch.password: "<kibana_user_password>"
server.ssl.enabled: true
server.ssl.certificate:
server.ssl.key:
xpack.security.enabled: true
xpack.reporting.kibanaServer.port: 443
xpack.reporting.kibanaServer.protocol: https
elasticsearch.ssl.certificateAuthorities: [ "" ]
elasticsearch.ssl.verificationMode: certificate
logging.dest: /etc/kibana/log/kibana.log

I have tried both kibana_oss and the non_oss, but I get the same error.

Body:
This can be happen if ES cluster master node has not set correctly.

Test ES cluster health first

curl <ES_IP:PORT>/_cluster/health?pretty


问:
Black background slide up
It is probably very simple but i'm stuck trying to make a homepage automatic background slider like here : https://www.jackdavison.co.uk

That's probably Jquery but I found a way to have something similar with html and Css, only it keeps repeating.

Any help ?

You can see my code here:

HTML

```<code><div class="wrapper">
  <div class="sliding-background"></div>
</div>
</code>```

CSS:

```<code>.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  height: 560px;
  width: 100%;
  animation: slide 2s linear infinite;
  animation-delay: 4000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);

  }
  100%{
    transform: translate3d(0px, -2000px, 0px);

  }

}
</code>```

See on Codepen here

Thank you !

答:
You just need a minor change in your CSS. Just change animation: slide 2s linear infinite; to animation: slide 0.6s ease-out forwards;. Also, I have changed in -2000px to 100% in @keyframes in case if you have a full-height background.

animation-fill-mode: forwards; Let your element retain the style values from the last keyframe when the animation ends.

.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  height: 560px;
  width: 100%;
  animation: slide 0.6s ease-out forwards;
  animation-delay: 2000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);
  }
  100%{
    transform: translate3d(0px, -100%, 0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="sliding-background"></div>
</div></code>```

Please let me know if this helps.

Title: Black background slide up

Body:
It is probably very simple but i'm stuck trying to make a homepage automatic background slider like here : https://www.jackdavison.co.uk

That's probably Jquery but I found a way to have something similar with html and Css, only it keeps repeating.

Any help ?

You can see my code here:

HTML

CSS:

.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  height: 560px;
  width: 100%;
  animation: slide 2s linear infinite;
  animation-delay: 4000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);

  }
  100%{
    transform: translate3d(0px, -2000px, 0px);

  }

}

See on Codepen here

Thank you !

Body:
You just need a minor change in your CSS. Just change animation: slide 2s linear infinite; to animation: slide 0.6s ease-out forwards;. Also, I have changed in -2000px to 100% in @keyframes in case if you have a full-height background.

animation-fill-mode: forwards; Let your element retain the style values from the last keyframe when the animation ends.

.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  height: 560px;
  width: 100%;
  animation: slide 0.6s ease-out forwards;
  animation-delay: 2000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);
  }
  100%{
    transform: translate3d(0px, -100%, 0px);
  }
}

<div class="wrapper">
  <div class="sliding-background"></div>
</div>

Please let me know if this helps.


问:
How do I fix this challenge of have any password login a user in on codeigniter
I had been trying to fix a challenge I am having on my code which will allow any password to login a user to the dashboard. For instance, any user registered on the platform can use his email and any password to login in. The password is saved as hash in the database but when I want to login, in any password can login the user which should not be. For example 123456 will log in the user, and 656565656 can login in the same user. Please help me I know I am not getting it right somewhere but I can't figure out where I am going wrong.

Here is my controller:

```<code>public function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->helper('url');
}

public function index()
{
    $this->form_validation->set_rules('emailid','Email id','required|valid_email');
    $this->form_validation->set_rules('password','Password','required|min_length[6]');
    if($this->form_validation->run())
    {
        $emailid=$this->input->post('emailid');
        $password=password_verify($this->input->post('password'),$account->password);
        $status=1;

        $this->load->model('User_Login_Model');
        $validate=$this->User_Login_Model->validatelogin($emailid,$password,$status);
        if($validate)
        {
            $this->session->set_userdata('uid',$validate);
            redirect('user/dashboard');
        } else
        {
            $this->session->set_flashdata('error', 'Invalid details. Please try again with valid details');
            redirect('user/login');
        }
    }
}
</code>```

Here is my model file for user login

```<code>public function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->helper('url');
}

public function validatelogin($emailid,$password,$status)
{

    $query=$this->db->where(['emailId'=>$emailid,'userPassword'=>$password]);
    $account=$this->db->get('tblusers')->row();
    if($account!=NULL)
    {
        $dbstatus=$account->isActive;
        //verifying status
        if( $dbstatus==$status)
        {
            return $account->id;
        }
        else
        {
            return NULL;
            $this->session->set_flashdata('error', 'Your accounis is not active contact admin');
            redirect('user/login');
        }
    }
    return NULL;
}
</code>```

答:
Try it:-

The controller

```<code>public function index()
{
    $this->form_validation->set_rules('email', 'E-mail address', 'required|valid_email')
        ->set_rules('password', 'Password', 'required');

    if ($this->form_validation->run() == false)
    {
        // validation errors
        var_dump(validation_errors());
    }
    else
    {

        $this->load->model('user_login_model');
        $user = $this->user_login_model->validatelogin($this->input->post('email'));

        if (!empty($user))
        {
            $verify_hash = password_verify($this->input->post('password'), $user->userPassword);

            if($user->isActive != 1)
            {
                $this->session->set_flashdata('error', 'Your accounis is not active contact admin');
                redirect('user/login');
            }
            else if ($verify_hash)
            {
                // login success
                $this->session->set_userdata('uid', $user->id);
                redirect('user/dashboard');
            }
        }

        $this->session->set_flashdata('error', 'Invalid credentials');
        redirect('user/login');
    }
}
</code>```

The Model

```<code>public function validatelogin($email)
{
    return $this->db->get_where('tblusers', array('emailId' => $email))
        ->row();
}
</code>```

Body:
I had been trying to fix a challenge I am having on my code which will allow any password to login a user to the dashboard. For instance, any user registered on the platform can use his email and any password to login in. The password is saved as hash in the database but when I want to login, in any password can login the user which should not be. For example 123456 will log in the user, and 656565656 can login in the same user. Please help me I know I am not getting it right somewhere but I can't figure out where I am going wrong.

Here is my controller:

public function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->helper('url');
}

public function index()
{
    $this->form_validation->set_rules('emailid','Email id','required|valid_email');
    $this->form_validation->set_rules('password','Password','required|min_length[6]');
    if($this->form_validation->run())
    {
        $emailid=$this->input->post('emailid');
        $password=password_verify($this->input->post('password'),$account->password);
        $status=1;

        $this->load->model('User_Login_Model');
        $validate=$this->User_Login_Model->validatelogin($emailid,$password,$status);
        if($validate)
        {
            $this->session->set_userdata('uid',$validate);
            redirect('user/dashboard');
        } else
        {
            $this->session->set_flashdata('error', 'Invalid details. Please try again with valid details');
            redirect('user/login');
        }
    }
}

Here is my model file for user login

public function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->helper('url');
}

public function validatelogin($emailid,$password,$status)
{

    $query=$this->db->where(['emailId'=>$emailid,'userPassword'=>$password]);
    $account=$this->db->get('tblusers')->row();
    if($account!=NULL)
    {
        $dbstatus=$account->isActive;
        //verifying status
        if( $dbstatus==$status)
        {
            return $account->id;
        }
        else
        {
            return NULL;
            $this->session->set_flashdata('error', 'Your accounis is not active contact admin');
            redirect('user/login');
        }
    }
    return NULL;
}

Body:
Try it:-

The controller

public function index()
{
    $this->form_validation->set_rules('email', 'E-mail address', 'required|valid_email')
        ->set_rules('password', 'Password', 'required');

    if ($this->form_validation->run() == false)
    {
        // validation errors
        var_dump(validation_errors());
    }
    else
    {

        $this->load->model('user_login_model');
        $user = $this->user_login_model->validatelogin($this->input->post('email'));

        if (!empty($user))
        {
            $verify_hash = password_verify($this->input->post('password'), $user->userPassword);

            if($user->isActive != 1)
            {
                $this->session->set_flashdata('error', 'Your accounis is not active contact admin');
                redirect('user/login');
            }
            else if ($verify_hash)
            {
                // login success
                $this->session->set_userdata('uid', $user->id);
                redirect('user/dashboard');
            }
        }

        $this->session->set_flashdata('error', 'Invalid credentials');
        redirect('user/login');
    }
}

The Model

public function validatelogin($email)
{
    return $this->db->get_where('tblusers', array('emailId' => $email))
        ->row();
}


问:
Unable to add decimal like 0.25 with EditText Android
I have an app with editText and I want to insert decimal numbers that start from (0.25-0.50-0.75 and so on) because I want to calculate it with other editText numbers, till now I can only insert numbers like 1-2-3...
Any idea please?

MyCode

```<code>price_per_piece.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @SuppressLint("DefaultLocale")
            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().equals("")) {
                    //case_qty = v.findViewById(R.id.et_add_item_case_quanitiy); this line for understanding
                    //Note : case_qty is EditText which i want to insert decimal numbers
                    String qty_txt = case_qty.getText().toString();
                    if (qty_txt.equals("")){
                        qty_txt = "1";
                       // qty_txt = "0.25";
                    }
                    float qty = Float.parseFloat(qty_txt);
                    float p = Float.valueOf(s.toString());
                    price_per_case.setText(String.valueOf(qty * p));
                }
            }
        });
</code>```

Thanks in Advance

答: Add android:inputType="numberDecimal" to your EditText xml declaration if you have not done so already. Then try use Double.parseDouble() instead of the float

Body:
I have an app with editText and I want to insert decimal numbers that start from (0.25-0.50-0.75 and so on) because I want to calculate it with other editText numbers, till now I can only insert numbers like 1-2-3...
Any idea please?

MyCode

price_per_piece.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @SuppressLint("DefaultLocale")
            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().equals("")) {
                    //case_qty = v.findViewById(R.id.et_add_item_case_quanitiy); this line for understanding
                    //Note : case_qty is EditText which i want to insert decimal numbers
                    String qty_txt = case_qty.getText().toString();
                    if (qty_txt.equals("")){
                        qty_txt = "1";
                       // qty_txt = "0.25";
                    }
                    float qty = Float.parseFloat(qty_txt);
                    float p = Float.valueOf(s.toString());
                    price_per_case.setText(String.valueOf(qty * p));
                }
            }
        });

Thanks in Advance


问:
Is execution of `_dl_init` (program initialization) single-threaded in C/C++?
I have several C++ source files where some data/callbacks are registered in a map in a header.

// foo.h

class Foo final {
public:
    static void Register(...) { ... }

private:
    inline static std::map<...> g_map{};
};

// a.cc, b.cc, etc.

#include "foo.h"

namespace {

struct Init {
    Init() {
        Foo::Register(...);
    }
};

Init g_init{}; // the inversion-of-control trick

}
```

So is it neccessary to use locks to protect the g_map?  My intuition is that the execution of _dl_init (runtime call that is prior to main) is single-threaded, although the order a.cc, b.cc, ... is unknown, am I right?

答:
If non local static variables are initialized before main starts, then they will be initialized in the thread defined in [basic.start.main] (ref. draft n4659 for C++20):

Executing a program starts a main thread of execution (4.7, 33.3) in which the main function is invoked, and in which variables of static storage duration might be initialized (6.6.2) and destroyed (6.6.4).

But C++ initialization of static variables is not that simple :-(. Same draft says later in [basic.start.dynamic] §4 (emphasize mine):

It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static
  storage duration is sequenced before the first statement of main or is deferred. If it is deferred, it strongly
  happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the
  same translation unit as the variable to be initialized. It is implementation-defined in which threads and
  at which points in the program such deferred dynamic initialization occurs.

My reading is that the standard makes its best to prevent a programmer to make assumptions on the moment of the initialization of a static variable. If the implementation is programmer friendly, it will initialize all non local static variables before main in a single thread - the standard allows it. But unfortunately it would be non portable because the standard does not mandate it.

TL/DR: If you target one single implementation which guarantees to initialize non local static variables before calling main, then you can be sure that this initialization will occur in a single thread. If you are brave, you can try to understand what means it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized and how you could use it. And it you only want to have a portable and robust code, accept the fact that dragons are hidden near static initialization and that it could happen in any thread...

Body:
I have several C++ source files where some data/callbacks are registered in a map in a header.

// foo.h

class Foo final {
public:
    static void Register(...) { ... }

private:
    inline static std::map<...> g_map{};
};

// a.cc, b.cc, etc.

#include "foo.h"

namespace {

struct Init {
    Init() {
        Foo::Register(...);
    }
};

Init g_init{}; // the inversion-of-control trick

}

So is it neccessary to use locks to protect the g_map?  My intuition is that the execution of _dl_init (runtime call that is prior to main) is single-threaded, although the order a.cc, b.cc, ... is unknown, am I right?


问:
Javascript regex to check if a value begins with a number followed by anything else
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

```<code>var validaddress = /^[0-9][A-Za-z0-9]+$/;
</code>```

But this isn't the right way. Im new to this, help anyone?

答:
when you say "any character follow" -- do you mean any alphanumeric character or just anything (i.e. including space, comma, slash etc)?
if it is the latter, how about this:</p>

```<code>var validaddress = /^[0-9].+$/;
</code>```

Body:
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

var validaddress = /^[0-9][A-Za-z0-9]+$/;

But this isn't the right way. Im new to this, help anyone?

Body:
when you say "any character follow" -- do you mean any alphanumeric character or just anything (i.e. including space, comma, slash etc)?
if it is the latter, how about this:

var validaddress = /^[0-9].+$/;


问:
Why does Clang not allow "and" as function name?
I'm developing a program for some time now, using Visual Studio 2017. Lately I installed the Clang Power Tool extension in order to check the quality of my code.
Part of my program consists in emulating the opcodes of a cpu. I created a stripped down example below.

The following example works fine :

```<code>class C{};

inline void andi(C& s);

int main()
{
    std::cout << "Hello, world!\n";
}
</code>```

This one does not :

```<code>class C{};

inline void and(C& s);

int main()
{
    std::cout << "Hello, world!\n";
}
</code>```

I'm getting these errors on Clang 3.8.0 (I'm using version 9.0.1 on my program, and errors are similar) :

```<code>source_file.cpp:9:18: error: expected ')'
inline void and(C& s);
                 ^
source_file.cpp:9:16: note: to match this '('
inline void and(C& s);
               ^
source_file.cpp:9:13: error: cannot form a reference to 'void'
inline void and(C& s);
            ^
source_file.cpp:9:1: error: 'inline' can only appear on functions
inline void and(C& s);
</code>```

Looks like that functions named after binary operations (like and, not, or and xor) trigger a wrong behaviour in the compiler.
No errors are shown using the Visual Studio compiler, and the program works as expected.

Is there something I can do to prevent this from happening ? Or is this a bug in Clang ?
Adding NOLINT to the line doesn't help as it's the compiler which raises the error ...

You can test the case here : https://rextester.com/TXU19618

Thanks !

答:
and is a reserved keyword in C++ which means it cannot be used for a function name. This is standard C++ behavior, not an error.

https://en.cppreference.com/w/cpp/keyword

Body:
I'm developing a program for some time now, using Visual Studio 2017. Lately I installed the Clang Power Tool extension in order to check the quality of my code.
Part of my program consists in emulating the opcodes of a cpu. I created a stripped down example below.

The following example works fine :

class C{};

inline void andi(C& s);

int main()
{
    std::cout << "Hello, world!\n";
}

This one does not :

class C{};

inline void and(C& s);

int main()
{
    std::cout << "Hello, world!\n";
}

I'm getting these errors on Clang 3.8.0 (I'm using version 9.0.1 on my program, and errors are similar) :

source_file.cpp:9:18: error: expected ')'
inline void and(C& s);
                 ^
source_file.cpp:9:16: note: to match this '('
inline void and(C& s);
               ^
source_file.cpp:9:13: error: cannot form a reference to 'void'
inline void and(C& s);
            ^
source_file.cpp:9:1: error: 'inline' can only appear on functions
inline void and(C& s);

Looks like that functions named after binary operations (like and, not, or and xor) trigger a wrong behaviour in the compiler.
No errors are shown using the Visual Studio compiler, and the program works as expected.

Is there something I can do to prevent this from happening ? Or is this a bug in Clang ?
Adding NOLINT to the line doesn't help as it's the compiler which raises the error ...

You can test the case here : https://rextester.com/TXU19618

Thanks !


问:
How to convert LocalDateTime to Date ignored timezone?
I want to subtract hours from LocalDateTime and convert to Date, but my way always gets around the TimeZone factor.

```<code>Date fromDate = request.getFromDate();
LocalDateTime reqFromDate = LocalDateTime.ofInstant(fromDate.toInstant(), ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS);
Date fromDateArg = Date.from(reqFromDate.minusHours(11).toInstant(ZoneOffset.UTC));
</code>```

E.g:

2020-01-01T20:00 >> I want exactly: 2020-01-01T9:00 date that independent with timezone.

Timezone included can affect the result that passes to the query as a bind parameter. How do I get rid of it?

答: Have you tried "OffsetDateTime"? Is a date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system,</p>

Body:
I want to subtract hours from LocalDateTime and convert to Date, but my way always gets around the TimeZone factor.

Date fromDate = request.getFromDate();
LocalDateTime reqFromDate = LocalDateTime.ofInstant(fromDate.toInstant(), ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS);
Date fromDateArg = Date.from(reqFromDate.minusHours(11).toInstant(ZoneOffset.UTC));

E.g:

2020-01-01T20:00 >> I want exactly: 2020-01-01T9:00 date that independent with timezone.

Timezone included can affect the result that passes to the query as a bind parameter. How do I get rid of it?


问:
Comparing a bit to a boolean
Say I have a set of flags, encoded in a uint16_t flags. For example, AMAZING_FLAG = 0x02.
Now, I have a function. This function needs to check if I want to change the flag, because if I want to do that, I need to write to flash. And that is expensive. Therefore, I want a check which tells me if flags & AMAZING_FLAG is equal to doSet. This is the first idea:

```<code>setAmazingFlag(bool doSet)
{
    if ((flags & AMAZING_FLAG) != (doSet ? AMAZING_FLAG : 0)) {
        // Really expensive thing
        // Update flags
    }
}
</code>```

This is not an intuitive if statement.
I feel like there should be a better way, something like:

```<code>if ((flags & AMAZING_FLAG) != doSet){

}
</code>```

But this does not actually work, true seems to be equal to 0x01.

So, is there a neat way to compare a bit to a boolean?

答:
From a logical point of view, flags & AMAZING_FLAG is only a bit operation masking all other flags. The result is a numerical value.

To receive to a boolean value, you would use a comparison

```<code>(flags & AMAZING_FLAG) == AMAZING_FLAG
</code>```

and can now compare this logical value to doSet.

```<code>if (((flags & AMAZING_FLAG) == AMAZING_FLAG) != doSet)
</code>```

In C there may be abbreviations, because of the implicit conversion rules of numbers to boolean values. So you could also write

```<code>if (!(flags & AMAZING_FLAG) == doSet)
</code>```

to write that more terse. But the former version is better in terms of readability.

Title: Comparing a bit to a boolean

Body:
Say I have a set of flags, encoded in a uint16_t flags. For example, AMAZING_FLAG = 0x02.
Now, I have a function. This function needs to check if I want to change the flag, because if I want to do that, I need to write to flash. And that is expensive. Therefore, I want a check which tells me if flags & AMAZING_FLAG is equal to doSet. This is the first idea:

setAmazingFlag(bool doSet)
{
    if ((flags & AMAZING_FLAG) != (doSet ? AMAZING_FLAG : 0)) {
        // Really expensive thing
        // Update flags
    }
}

This is not an intuitive if statement.
I feel like there should be a better way, something like:

if ((flags & AMAZING_FLAG) != doSet){

}

But this does not actually work, true seems to be equal to 0x01.

So, is there a neat way to compare a bit to a boolean?

Body:
From a logical point of view, flags & AMAZING_FLAG is only a bit operation masking all other flags. The result is a numerical value.

To receive to a boolean value, you would use a comparison

(flags & AMAZING_FLAG) == AMAZING_FLAG

and can now compare this logical value to doSet.

if (((flags & AMAZING_FLAG) == AMAZING_FLAG) != doSet)

In C there may be abbreviations, because of the implicit conversion rules of numbers to boolean values. So you could also write

if (!(flags & AMAZING_FLAG) == doSet)

to write that more terse. But the former version is better in terms of readability.


问:
FileService was not defined
On my stackblitz i have weird issue. Console telling me "FileService was not defined". In my opinion everything should work. Can you tell me whats wrong there?</p>

答:
You need to inject the service and remove declare.

```<code>@Injectable()
export class FileService implements IFileService
</code>```

Add fileservice to providers array in main.ts.

```<code>import {CdkDragDropSortingExample, FileService} from './app/cdk-drag-drop-sorting- example';
providers: [
FileService,
{ provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { appearance: 'fill' } },
]
</code>```

Move fileservice implementation to a new file if possible.

Title: FileService was not defined

Body:
You need to inject the service and remove declare.

@Injectable()
export class FileService implements IFileService

Add fileservice to providers array in main.ts.

import {CdkDragDropSortingExample, FileService} from './app/cdk-drag-drop-sorting- example';
providers: [
FileService,
{ provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { appearance: 'fill' } },
]

Move fileservice implementation to a new file if possible.


问:
Javascript function logs but doesnt do anything
I am trying to change some attributes when a button is pressed using Javascript. The thing is I can use console.log and it displays the data. Here's my function and HTML

function change(e){
  console.log(e);
  e.disabled = true;
  e.innerText = 'Active';
  e.nextElementSibling.checked = true;
  if(e.getAttribute('id') == 'expanded-button'){
    let expanded = document.getElementById('expanded-button');
    expanded.innerText = 'Activate';
    expanded.disabled = false;
    expanded.nextElementSibling.checked = false;
  }else{
    let reversed = document.getElementById('reversed-button');
    reversed.innerText = 'Activate';
    reversed.disabled = false;
    reversed.nextElementSibling.checked = false;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="kiwi-reviews-template-options">
  <div class="kiwi-review-option">
    <div class="kiwi-review-option-header">
      <h2>Expanded</h2>
    </div>
    <div class="image-container">
      <img src=""/>
    </div>
    <div class="kiwi-option-footer">
      <button type="button" onclick="change(this)" id="expanded-button">Activate
    </button>
    <input type="radio" name="template" id="expanded-template" value="expanded"/>
    </div>
  </div>
  <div class="kiwi-review-option">
    <div class="kiwi-review-option-header">
      <h2>Reversed</h2>
    </div>
    <div class="image-container">
      <img src=""/>
    </div>
    <div class="kiwi-option-footer">
      <button type="button" onclick="change(this)" id="reversed-button">Activate
      </button>
      <input type="radio" name="template" id="reversed-template" value="reversed"/>
    </div>
  </div>
</div></code>```

```<code><div class="kiwi-reviews-template-options">
  <div class="kiwi-review-option">
    <div class="kiwi-review-option-header">
      <h2>Expanded</h2>
    </div>
    <div class="image-container">
      <img src=""/>
    </div>
    <div class="kiwi-option-footer">
      <button type="button" onclick="change(this)" id="expanded-button">Activate
    </button>
    <input type="radio" name="template" id="expanded-template" value="expanded"/>
    </div>
  </div>
  <div class="kiwi-review-option">
    <div class="kiwi-review-option-header">
      <h2>Reversed</h2>
    </div>
    <div class="image-container">
      <img src=""/>
    </div>
    <div class="kiwi-option-footer">
      <button type="button" onclick="change(this)" id="reversed-button">Activate
      </button>
      <input type="radio" name="template" id="reversed-template" value="reversed"/>
    </div>
  </div>
</div>

<script>

function change(e){
  console.log(e);
  e.disabled = true;
  e.innerText = 'Active';
  e.nextElementSibling.checked = true;
  if(e.getAttribute('id') == 'expanded-button'){
    let expanded = document.getElementById('expanded-button');
    expanded.innerText = 'Activate';
    expanded.disabled = false;
    expanded.nextElementSibling.checked = false;
  }else{
    let reversed = document.getElementById('reversed-button');
    reversed.innerText = 'Activate';
    reversed.disabled = false;
    reversed.nextElementSibling.checked = false;
  }
}
</script>
</code>```

When i use console.log(e) it displays <button id="expanded-button" type="button" onclick="change(this)"> and its the correct button. But when i press the button it wont add the disabled attribute nor disable the other button for some reason.

答:
You're re-enabling the same button:

```<code>if(e.getAttribute('id') == 'expanded-button'){
// −−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^
  let expanded = document.getElementById('expanded-button');
  // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^
</code>```

You want to (re)enable the other button:

```<code>if(e.getAttribute('id') == 'expanded-button'){
// −−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^
  let expanded = document.getElementById('reversed-button');
  // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^
</code>```

(And the similar change in else.)

You can also simplify that code, since your if and else blocks are doing the same thing, just with different elements:

function change(e){
  e.disabled = true;
  e.innerText = 'Active';
  e.nextElementSibling.checked = true;
  var otherId = e.id === 'expanded-button' ? 'reversed-button' : 'expanded-button';
  var other = document.getElementById(otherId);
  other.innerText = 'Activate';
  other.disabled = false;
  other.nextElementSibling.checked = false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" onclick="change(this)" id="expanded-button" disabled>
    Active
</button>
<input type="checkbox" checked>
<button type="button" onclick="change(this)" id="reversed-button">
    Activate
</button>
<input type="checkbox"></code>```

Body:
I am trying to change some attributes when a button is pressed using Javascript. The thing is I can use console.log and it displays the data. Here's my function and HTML

function change(e){
  console.log(e);
  e.disabled = true;
  e.innerText = 'Active';
  e.nextElementSibling.checked = true;
  if(e.getAttribute('id') == 'expanded-button'){
    let expanded = document.getElementById('expanded-button');
    expanded.innerText = 'Activate';
    expanded.disabled = false;
    expanded.nextElementSibling.checked = false;
  }else{
    let reversed = document.getElementById('reversed-button');
    reversed.innerText = 'Activate';
    reversed.disabled = false;
    reversed.nextElementSibling.checked = false;
  }
}

Expanded

      <button type="button" onclick="change(this)" id="expanded-button">Activate
    </button>
    <input type="radio" name="template" id="expanded-template" value="expanded"/>

Reversed

      <button type="button" onclick="change(this)" id="reversed-button">Activate
      </button>
      <input type="radio" name="template" id="reversed-template" value="reversed"/>

Expanded

      <button type="button" onclick="change(this)" id="expanded-button">Activate
    </button>
    <input type="radio" name="template" id="expanded-template" value="expanded"/>

Reversed

      <button type="button" onclick="change(this)" id="reversed-button">Activate
      </button>
      <input type="radio" name="template" id="reversed-template" value="reversed"/>

When i use console.log(e) it displays <button id="expanded-button" type="button" onclick="change(this)"> and its the correct button. But when i press the button it wont add the disabled attribute nor disable the other button for some reason.

Body:
You're re-enabling the same button:

if(e.getAttribute('id') == 'expanded-button'){
// −−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^
  let expanded = document.getElementById('expanded-button');
  // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^

You want to (re)enable the other button:

if(e.getAttribute('id') == 'expanded-button'){
// −−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^
  let expanded = document.getElementById('reversed-button');
  // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^

(And the similar change in else.)

You can also simplify that code, since your if and else blocks are doing the same thing, just with different elements:

function change(e){
  e.disabled = true;
  e.innerText = 'Active';
  e.nextElementSibling.checked = true;
  var otherId = e.id === 'expanded-button' ? 'reversed-button' : 'expanded-button';
  var other = document.getElementById(otherId);
  other.innerText = 'Activate';
  other.disabled = false;
  other.nextElementSibling.checked = false;
}

<button type="button" onclick="change(this)" id="expanded-button" disabled>
    Active
</button>
<input type="checkbox" checked>
<button type="button" onclick="change(this)" id="reversed-button">
    Activate
</button>
<input type="checkbox">


问:
How to generate time based UUIDs?
I want to generate time-based universally unique identifier (UUID) in Java.

The method java.util.UUID.randomUUID() generates a UUID Version 4 where 122 of the 128 bits are from a cryptographically-strong random number generator.

How to generate a Version 1 (time based) UUID ? Is there a separate library for that or is it some how provided in the Java 7 API and I am missing it.

答:
To generate time based UUIDs in maven project you have add the dependency of Generator that is generate time based UUIDs.

```<code>    <dependency>
        <groupId>com.fasterxml.uuid</groupId>
        <artifactId>java-uuid-generator</artifactId>
        <version>3.1.4</version>
    </dependency>
</code>```

If you have a normal java project you have to import library of Generator
 java-uuid-generator.

Then generate the UUID:

```<code>UUID uuid= Generators.timeBasedGenerator().generate();
</code>```

Now if you want to check the UUID time and date check here.

Enter generated UUID and your current time zone.

Title: How to generate time based UUIDs?

Body:
To generate time based UUIDs in maven project you have add the dependency of Generator that is generate time based UUIDs.

    <dependency>
        <groupId>com.fasterxml.uuid</groupId>
        <artifactId>java-uuid-generator</artifactId>
        <version>3.1.4</version>
    </dependency>

If you have a normal java project you have to import library of Generator
 java-uuid-generator.

Then generate the UUID:

UUID uuid= Generators.timeBasedGenerator().generate();

Now if you want to check the UUID time and date check here.

Enter generated UUID and your current time zone.


问:
Nested form components are not set with initial values on submit
I am trying to implement nested form components in angular with reactive forms using ControlValueAccessors, and I have been following this guide: https://blog.angularindepth.com/angular-nested-reactive-forms-using-cvas-b394ba2e5d0d

I have got everything to work except one major issue. If my form is pre-populated, i.e. the form is used to edit existing data instead of creating, then the initial data is not set on the form's value upon submit if the corresponding child component form values hasn't been changed.

I have an example setup on the following link (Open up the console in the down right corner):
https://stackblitz.com/edit/angular-nested-forms-cva-izbrht

As you can see, if you press submit immediately, the form value contains two properties which value is just two empty strings. If you edit e.g. the first name and then submit you will see that the basicInfo property now has been properly set with its values.

答:
here is my solution,

change registerOnChange to this:

```<code>registerOnChange(fn) {
  this.onChange = fn;
}
</code>```

then call the onChange method in your child component ngOnInit hook like this:

```<code> setTimeout(() => {
  this.onChange(this.form.value);
});
</code>```

done! notice using setTimeout wrap, otherwise it won't work.

Body:
here is my solution,

change registerOnChange to this:

registerOnChange(fn) {
  this.onChange = fn;
}

then call the onChange method in your child component ngOnInit hook like this:

 setTimeout(() => {
  this.onChange(this.form.value);
});

done! notice using setTimeout wrap, otherwise it won't work.


问:
What is the scala equivalent of Set in java?
Which type in scala can be the equivalent of Set in java? Is Set or List, or something else?
I think Seq might be the correct answer, but I need to use collectFirst method, can anyone help me with that?</p>

答:
scala.jdk.CollectionConverters documents Set conversions like so

```<code>scala.collection.mutable.Set <=> java.util.Set  // two-wayconversion via asScala and asJava
scala.collection.Set          => java.util.Set  // one-way conversion via asJava
</code>```

Body:
scala.jdk.CollectionConverters documents Set conversions like so

scala.collection.mutable.Set <=> java.util.Set  // two-wayconversion via asScala and asJava
scala.collection.Set          => java.util.Set  // one-way conversion via asJava


问:
Hamburger menu doesn't close after click on anchor tag
After clicking on some anchor item in the menu I want to be able to close the menu, but it doesn't work. The remove method in javascript is not working for some reason. If I go through pages the menu closes itself but not on the index page and it stays open. I'm still learning Javascript so bear with me. Here's the additional CSS

const netflix_open_btn = document.querySelector('.netflix-open-btn');
const netflix_close_btn = document.querySelector('.netflix-close-btn');
const netflix_nav = document.querySelectorAll('.netflix-nav');

netflix_open_btn.addEventListener('click', () => {
 netflix_nav.forEach(nav_el => { nav_el.classList.add('visible') });
});

netflix_close_btn.addEventListener('click', () => {
 netflix_nav.forEach(nav_el => { nav_el.classList.remove('visible') });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.netflix-text {
 text-transform: uppercase;
}

.netflix-list li a:hover{
  color: #d6aa55;
}

.netflix-nav-btn {
 border: 0;
 background: transparent;
 cursor: pointer;
  font-size: 20px;
  z-index: 10;
}

.netflix-open-btn {
 position: fixed;
 top: 30px;
  left: 10px;
  z-index: 10;
}

.netflix-nav {
 position: fixed;
 top: 0;
 left: 0;
 height: 100vh;
 transform: translateX(-100%);
  transition: transform .3s ease-in-out;
  z-index: 10;
}

.netflix-nav.visible {
 transform: translateX(0);
}

.netflix-nav-black {
 background-color: black;
 width: 60%;
 max-width: 480px;
 min-width: 320px;
 transition-delay: .4s;
}

.netflix-nav-black.visible {
 transition-delay: 0s;
}

.netflix-nav-red {
 background-color: rgb(214, 170, 85);
 transition-delay: .2s;
 width: 95%;
}

.netflix-nav-red.visible {
 transition-delay: .2s;
}

.netflix-nav-white {
 background-color: #fff;
 padding: 40px;
 position: relative;
 transition-delay: 0s;
 width: 95%;
}

.netflix-nav-white.visible {
 transition-delay: .4s;
}

.netflix-close-btn {
 opacity: 0.3;
 position: absolute;
 top: 40px;
 right: 30px;
}

.netflix-logo {
 width: 245px;
}

@media (max-width:768px){
  .netflix-logo{
    width: 197px;
  }
}

.netflix-list {
 list-style-type: none;
 padding: 0;
}

.netflix-list li {
 margin: 20px 0;
}

.netflix-list li a {
 color: rgb(34, 31, 31);
 font-size: 19px;
 text-decoration: none;
 text-transform: uppercase;
}

.netflix-list ul {
 list-style-type: none;
 padding-left: 20px;
}</code>```

<button class="netflix-nav-btn netflix-open-btn">

  </button>

        <button class="netflix-nav-btn netflix-close-btn">

        </button>

Home

About

Services

Tattoo

Beauty

Piercing

Contact

                            Danish

```

答:
Meybe it doesnt close because there is no page change, thus no reload.
You could use some js to close it manually. Your example there is not close function related to item click. Ex.:</p>

```<code>netflix_nav.addEventListener('click', () => {
    netflix_nav.forEach(nav_el => { nav_el.classList.remove('visible') });
});
</code>```

Body:
After clicking on some anchor item in the menu I want to be able to close the menu, but it doesn't work. The remove method in javascript is not working for some reason. If I go through pages the menu closes itself but not on the index page and it stays open. I'm still learning Javascript so bear with me. Here's the additional CSS

const netflix_open_btn = document.querySelector('.netflix-open-btn');
const netflix_close_btn = document.querySelector('.netflix-close-btn');
const netflix_nav = document.querySelectorAll('.netflix-nav');

netflix_open_btn.addEventListener('click', () => {
 netflix_nav.forEach(nav_el => { nav_el.classList.add('visible') });
});

netflix_close_btn.addEventListener('click', () => {
 netflix_nav.forEach(nav_el => { nav_el.classList.remove('visible') });
});

.netflix-text {
 text-transform: uppercase;
}

.netflix-list li a:hover{
  color: #d6aa55;
}

.netflix-nav-btn {
 border: 0;
 background: transparent;
 cursor: pointer;
  font-size: 20px;
  z-index: 10;
}

.netflix-open-btn {
 position: fixed;
 top: 30px;
  left: 10px;
  z-index: 10;
}

.netflix-nav {
 position: fixed;
 top: 0;
 left: 0;
 height: 100vh;
 transform: translateX(-100%);
  transition: transform .3s ease-in-out;
  z-index: 10;
}

.netflix-nav.visible {
 transform: translateX(0);
}

.netflix-nav-black {
 background-color: black;
 width: 60%;
 max-width: 480px;
 min-width: 320px;
 transition-delay: .4s;
}

.netflix-nav-black.visible {
 transition-delay: 0s;
}

.netflix-nav-red {
 background-color: rgb(214, 170, 85);
 transition-delay: .2s;
 width: 95%;
}

.netflix-nav-red.visible {
 transition-delay: .2s;
}

.netflix-nav-white {
 background-color: #fff;
 padding: 40px;
 position: relative;
 transition-delay: 0s;
 width: 95%;
}

.netflix-nav-white.visible {
 transition-delay: .4s;
}

.netflix-close-btn {
 opacity: 0.3;
 position: absolute;
 top: 40px;
 right: 30px;
}

.netflix-logo {
 width: 245px;
}

@media (max-width:768px){
  .netflix-logo{
    width: 197px;
  }
}

.netflix-list {
 list-style-type: none;
 padding: 0;
}

.netflix-list li {
 margin: 20px 0;
}

.netflix-list li a {
 color: rgb(34, 31, 31);
 font-size: 19px;
 text-decoration: none;
 text-transform: uppercase;
}

.netflix-list ul {
 list-style-type: none;
 padding-left: 20px;
}

<button class="netflix-nav-btn netflix-open-btn">

  </button>

        <button class="netflix-nav-btn netflix-close-btn">

        </button>

Home

About

Services

Tattoo

Beauty

Piercing

Contact

                            Danish

Body:
Meybe it doesnt close because there is no page change, thus no reload.
You could use some js to close it manually. Your example there is not close function related to item click. Ex.:

netflix_nav.addEventListener('click', () => {
    netflix_nav.forEach(nav_el => { nav_el.classList.remove('visible') });
});


问:
How to properly display the checked attributes in another div with different styles?
I am very new to jQuery. The first part of the code is to check the inputs and after checked it should display the checked items the below format. How can do this with the help of jquery.

Name

Initiator

          <input name="one" type="checkbox" id="one" />

```

<p>After checked it should displays in this format. </p>

<pre class="lang-html prettyprint-override"><code><div class="col-xl-6 col-lg-6 col-md-6 offset-xl-1">
  <h6 class="heading--form mb-2 mt-3 mt-sm-0">
    User
  </h6>
  <ul class="approval approval_scrolltab mt-3">
    <li>
      <div class="approval--member">
        <img src="assets/images/user.jpg" class="user--image" />
        <div class="w-100">
          <h6 class="approval--name">Name</h6>
          <p>Initiator</p>
        </div>

          <span class="ic-close"></span>

      </div>
    </li>
  </ul>
</div>
</code>```

I tried like this.It was working fine for the names but got no idea how can display this user image attached with name and also there is a cancel icon too near the name.I am only being able to display name with this code.

```

<p><strong>UPDATE</strong>
With this close  button I want to remove this from checked list(which works great) as well as I want to uncheck this from checked in input.</p>

``` $('body').on('click', '.ic-close', function() {
    $(this).closest('li').remove()
    $(this).closest('li').prop('checked',false) #didn't worked
  });
```

答:
This script below might be helpful for you. I only added an ID to the user-list and removed the a tag from the close button in your HTML. The JavaScript appends the HTML you wish with the name and the image to the list. If you click the close span, the item will be removed.

UPDATE:
To uncheck the checkbox by closing its user-list item, you have to add an attribute like data-name="Initiator" to the checkbox. In the JavaScript if have added two lines into the click listener of the ic-close item, see below.

$('input[type="checkbox"]').on('change', function() {
  var image_url = $(this).closest( '.approval--member' ).find( 'img' ).attr('src');
  var name = $(this).closest( '.approval--member' ).find( '.approval--name ~ p' ).text();

  if($(this).prop('checked')) {

    $('ul#user-list').append(
    '
' +
      '
' +
        '' +
        '
' +
          '
Name
' +
          '
' + name + '
' +
        '
' +
        'Close' +
      '
' +
    '
');

  } else {
    $('ul#user-list #' + name).remove();
  }

  $('body').on('click', '.ic-close', function() {
    var name = $(this).closest('li').find('.approval--name ~ p' ).text();
    $('input[data-name="' + name + '"]').prop( "checked", false );

    $(this).closest('li').remove();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="approval approval_scrolltab mt-3">
  <li>
    <div class="approval--member">
      <img src="assets/images/user.jpg" class="user--image" />
      <div class="w-100">
        <h6 class="approval--name">Name</h6>
        <p>Initiator</p>
      </div>
      <div class="form-group">
        <div class="checkbox">
          <input data-name="Initiator" name="one" type="checkbox" id="one" />
          <label for="one"></label>
        </div>
      </div>

    </div>
  </li>
</ul>

<div class="col-xl-6 col-lg-6 col-md-6 offset-xl-1">
  <h6 class="heading--form mb-2 mt-3 mt-sm-0">
    User
  </h6>
  <ul id="user-list" class="approval approval_scrolltab mt-3">
  </ul>
</div></code>```

Body:
I am very new to jQuery. The first part of the code is to check the inputs and after checked it should display the checked items the below format. How can do this with the help of jquery.

Name

Initiator

          <input name="one" type="checkbox" id="one" />

After checked it should displays in this format.

    User

Name

Initiator

I tried like this.It was working fine for the names but got no idea how can display this user image attached with name and also there is a cancel icon too near the name.I am only being able to display name with this code.

UPDATE
With this close  button I want to remove this from checked list(which works great) as well as I want to uncheck this from checked in input.

 $('body').on('click', '.ic-close', function() {
    $(this).closest('li').remove()
    $(this).closest('li').prop('checked',false) #didn't worked
  });

Body:
This script below might be helpful for you. I only added an ID to the user-list and removed the a tag from the close button in your HTML. The JavaScript appends the HTML you wish with the name and the image to the list. If you click the close span, the item will be removed.

UPDATE:
To uncheck the checkbox by closing its user-list item, you have to add an attribute like data-name="Initiator" to the checkbox. In the JavaScript if have added two lines into the click listener of the ic-close item, see below.

$('input[type="checkbox"]').on('change', function() {
  var image_url = $(this).closest( '.approval--member' ).find( 'img' ).attr('src');
  var name = $(this).closest( '.approval--member' ).find( '.approval--name ~ p' ).text();

  if($(this).prop('checked')) {

    $('ul#user-list').append(
    '<li id="' + name + '">' +
      '<div class="approval--member">' +
        '<img src="' + image_url + '" class="user--image" />' +
        '<div class="w-100">' +
          '<h6 class="approval--name">Name</h6>' +
          '<p>' + name + '</p>' +
        '</div>' +
        '<span class="ic-close">Close</span>' +
      '</div>' +
    '</li>');

  } else {
    $('ul#user-list #' + name).remove();
  }

  $('body').on('click', '.ic-close', function() {
    var name = $(this).closest('li').find('.approval--name ~ p' ).text();
    $('input[data-name="' + name + '"]').prop( "checked", false );

    $(this).closest('li').remove();
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="approval approval_scrolltab mt-3">
  <li>
    <div class="approval--member">
      <img src="assets/images/user.jpg" class="user--image" />
      <div class="w-100">
        <h6 class="approval--name">Name</h6>
        <p>Initiator</p>
      </div>
      <div class="form-group">
        <div class="checkbox">
          <input data-name="Initiator" name="one" type="checkbox" id="one" />
          <label for="one"></label>
        </div>
      </div>

    </div>
  </li>
</ul>

<div class="col-xl-6 col-lg-6 col-md-6 offset-xl-1">
  <h6 class="heading--form mb-2 mt-3 mt-sm-0">
    User
  </h6>
  <ul id="user-list" class="approval approval_scrolltab mt-3">
  </ul>
</div>


问:
Call to a member function getQuery() on null symfony
I'm following this tuto about CSV export on EasyAdmin bundle in symfony (link)
and I'm stuck at this point:

```<code>$queryBuilder = $this->createListQueryBuilder(

        Employee::class,
        $sortDirection,
        $this->request->query->get('sortField'),
        $this->entity['list']['dql_filter']
    );
        return $this->csvExporter->getResponseFromQueryBuilder(
        $queryBuilder,
        Employee::class,
        'employees.csv'
    );
</code>```

UPDATE:
I'm overwriting the method createListQueryBuilder

```<code>protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null   , $dqlFilter = null){}
</code>```

and in the csvExporter i'm defining a function getResponseFormQueryBuilder

```<code>public function getResponseFromQueryBuilder(QueryBuilder $queryBuilder, $columns, $filename)
</code>```

I'm having a bug that says that:

Expected parameter of type '\Doctrine\ORM\QueryBuilder', 'void' provided

答:
i was overwriting the wrong funtion
you should define it like this (before you overwrite it)

```<code>protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
/**
 * Performs a database query based on the search query provided by the user.
 * It supports pagination and field sorting.
 *
 * @param string      $entityClass
 * @param string      $searchQuery
 * @param array       $searchableFields
 * @param int         $page
 * @param int         $maxPerPage
 * @param string|null $sortField
 * @param string|null $sortDirection
 * @param string|null $dqlFilter
 *
 * @return Pagerfanta The paginated query results
 */    {
    return $this->get('easyadmin.query_builder')->createListQueryBuilder($this->entity, $sortField, $sortDirection, $dqlFilter);
}
</code>```

Body:
I'm following this tuto about CSV export on EasyAdmin bundle in symfony (link)
and I'm stuck at this point:

$queryBuilder = $this->createListQueryBuilder(

        Employee::class,
        $sortDirection,
        $this->request->query->get('sortField'),
        $this->entity['list']['dql_filter']
    );
        return $this->csvExporter->getResponseFromQueryBuilder(
        $queryBuilder,
        Employee::class,
        'employees.csv'
    );

UPDATE:
I'm overwriting the method createListQueryBuilder

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null   , $dqlFilter = null){}

and in the csvExporter i'm defining a function getResponseFormQueryBuilder

public function getResponseFromQueryBuilder(QueryBuilder $queryBuilder, $columns, $filename)

I'm having a bug that says that:

Expected parameter of type '\Doctrine\ORM\QueryBuilder', 'void' provided

Body:
i was overwriting the wrong funtion
you should define it like this (before you overwrite it)

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
/**
 * Performs a database query based on the search query provided by the user.
 * It supports pagination and field sorting.
 *
 * @param string      $entityClass
 * @param string      $searchQuery
 * @param array       $searchableFields
 * @param int         $page
 * @param int         $maxPerPage
 * @param string|null $sortField
 * @param string|null $sortDirection
 * @param string|null $dqlFilter
 *
 * @return Pagerfanta The paginated query results
 */    {
    return $this->get('easyadmin.query_builder')->createListQueryBuilder($this->entity, $sortField, $sortDirection, $dqlFilter);
}


问:
Extract link from an element found by XPAth,using BrowserSessions, C# and Selenium drivers
How do I extract a link's URL using XPath, I am using browser.Sessions, I want to extract it and use it somewhere-else.

Xpath of the element with url being"//tbody/tr/td[1]/a"

I have tried ...FindXPath("//tbody/tr/td[1]/a").Text

which gives me the inner text, InnerHTML, location and not getting it.

答:
The link is usually stored in the href tag. So you can fetch the url using the getAttribute method.

You can do it like:

```<code>string url = driver.FindElement(By.XPath("//tbody/tr/td[1]/a")).GetAttribute("href");
</code>```

Body:
The link is usually stored in the href tag. So you can fetch the url using the getAttribute method.

You can do it like:

string url = driver.FindElement(By.XPath("//tbody/tr/td[1]/a")).GetAttribute("href");


问:
Login Page Step Disabled, But Rest Of The Tests Still Run in JMeter
I am running a simple login and logout test in JMeter for our application.
I have disabled some initial steps in the thread and run the tests which still runs without any problem.
The tests that are running successfully should not be running as they are dependent on login step.
Can someone help me clarify this doubt?

答:
Add as a parent an If Controller for the dependent samplers,

You can easily mark requests and

Right Click -> Insert Parent -> Logic Controller -> If Controller

Check that login wasn't failed using condition:

```<code> ${JMeterThread.last_sample_ok}
</code>```

Body:
Add as a parent an If Controller for the dependent samplers,

You can easily mark requests and

Right Click -> Insert Parent -> Logic Controller -> If Controller

Check that login wasn't failed using condition:

 ${JMeterThread.last_sample_ok}


问:
BigQuery How to remove inherited access to a dataset
I have been providing access to datasets in BigQuery using the Share Dataset option for some time now. No problem.

But now, I have a specific requirement: I need to provide access to specific people/account/group but I don't want inherited access to work on this dataset.

I mean, I really need to provide access only to specific people to this dataset, so that not even inherited access work.

Is that possible? And if so, how can I do that?

To add more context. There is a dataset which should be available only for one Service Account (the one populating it) and some specific consumer account (HR) as it will contain sensitive data.

Problem is that our project already contains a couple of BigQuery Admin accounts and they of course inherit permissions over the dataset.

答: I don't think it would be possible as Project level roles are inherited automatically. Making new project may be helpful.</p>


问:
Admissible Heuristic Modification
I am currently working on a project involving a puzzle and various pathfinding algorithms. The puzzle is represented using a 2d array, and has a specific form factor. Each cell in the 2d array has a jump value, and that is the number of spaces you can move up, down, left, or right from the cell.

I am currently working on implementing A* search on this puzzle. I was thinking of using manhattan distance as an admissible heuristic for this problem, but I do not think that the conventional manhattan distance will work since movement is limited to a specific number of moves.

For example:

```<code>2   2   2   1   1
1   1   1   2   2
3   1   2   1   1
3   1   2   1   1
2   1   1   1   0
</code>```

Is a possible grid. You start from the 2 in the top left cell and are trying to get to the 0 in the bottom right cell. From the start cell, you can move right two or down 2 to new spaces which have different jump values. This process repeats until the goal is reached if the puzzle is solvable.

How can I modify the manhattan distance abs(x1-x2) + abs(y1-y2) to incorporate moving a specific number of spaces?

答:
As you have observed Manhattan distance isn't an admissible heuristic, e.g. starting from P = (3,2) you have:

```<code>Manhattan(P, Target) = abs(3 - 4) + abs(2 - 4) = 1 + 2 = 3
</code>```

but the real distance is just 2.

An admissible heuristic is:

```<code>h(P) = (P_x != Target_x) + (P_y != Target_y)
</code>```

where

```<code>           | 1    if x == y
(x != y) = |
           | 0    otherwise
</code>```

This works since for every component of the current-position-vector that doesn't match the corresponding component in target vector you have to take at least 1 move.

Title: Admissible Heuristic Modification

Body:
I am currently working on a project involving a puzzle and various pathfinding algorithms. The puzzle is represented using a 2d array, and has a specific form factor. Each cell in the 2d array has a jump value, and that is the number of spaces you can move up, down, left, or right from the cell.

I am currently working on implementing A* search on this puzzle. I was thinking of using manhattan distance as an admissible heuristic for this problem, but I do not think that the conventional manhattan distance will work since movement is limited to a specific number of moves.

For example:

2   2   2   1   1
1   1   1   2   2
3   1   2   1   1
3   1   2   1   1
2   1   1   1   0

Is a possible grid. You start from the 2 in the top left cell and are trying to get to the 0 in the bottom right cell. From the start cell, you can move right two or down 2 to new spaces which have different jump values. This process repeats until the goal is reached if the puzzle is solvable.

How can I modify the manhattan distance abs(x1-x2) + abs(y1-y2) to incorporate moving a specific number of spaces?

Body:
As you have observed Manhattan distance isn't an admissible heuristic, e.g. starting from P = (3,2) you have:

Manhattan(P, Target) = abs(3 - 4) + abs(2 - 4) = 1 + 2 = 3

but the real distance is just 2.

An admissible heuristic is:

h(P) = (P_x != Target_x) + (P_y != Target_y)

where

           | 1    if x == y
(x != y) = |
           | 0    otherwise

This works since for every component of the current-position-vector that doesn't match the corresponding component in target vector you have to take at least 1 move.


问:
Codeigniter: does $this->db->last_query(); execute a query?
Does query execution happen at the get_where() clause of the following codeigniter active record statement?

```<code>$this->db->select('*');
    $q = $this->db->get_where('Contacts', array('id' => $contact_id));

    $sql = $this->db->last_query();
</code>```

Or does it happens once you call the result_array()?

And is $this->db->last_query(); a reliable way in getting the query string.

答:
For me save_queries option was turned off so,

```<code>$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
</code>```

Ref: Can't get result from $this->db->last_query(); codeigniter

Body:
Does query execution happen at the get_where() clause of the following codeigniter active record statement?

$this->db->select('*');
    $q = $this->db->get_where('Contacts', array('id' => $contact_id));

    $sql = $this->db->last_query();

Or does it happens once you call the result_array()?

And is $this->db->last_query(); a reliable way in getting the query string.

Body:
For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter


问:
RSVP hash using vanilla promises
RSVP lib has a hash of promises helper that allows to "retrieve" promises references:

var promises = {
  posts: getJSON("/posts.json"),
  users: getJSON("/users.json")
};

RSVP.hash(promises).then(function(results) {
  console.log(results.users) // print the users.json results
  console.log(results.posts) // print the posts.json results
});
```

Is there a way to do such a thing with vanilla promises (in modern ES)?

答: OOTB? No, there's only Promise.all, but it accepts an array, not a dictionary. But you could create a helper function that accepts a dictionary of promises, converts to array, runs Promise.all on it, and processes it with one more then converting the results array back into a dictionary.

Title: RSVP hash using vanilla promises

Body:
RSVP lib has a hash of promises helper that allows to "retrieve" promises references:

var promises = {
  posts: getJSON("/posts.json"),
  users: getJSON("/users.json")
};

RSVP.hash(promises).then(function(results) {
  console.log(results.users) // print the users.json results
  console.log(results.posts) // print the posts.json results
});

Is there a way to do such a thing with vanilla promises (in modern ES)?


问:
How can one use one's own SVG in Font Awesome?
I have a custom made .svg file called "carport.svg". I would like to use it as if it was already included in FontAwesome and therefore use the FontAwesome infrastructure. I have placed my file in the \svgs\solid folder.

What more do I need to do to import it fully? I would like to then write in my HTML:

```<code><i class="fas fa-carport"></i>
</code>```

答:
You can find the steps in the following link. You will need to have you SVG path define as only one path element and nothing more (like any SVG icon) then you simply add the following code:

```<code>var CustomIcon = {
  prefix: 'fac', /* your own prefix OR use any of the exiting ones (fab, far, fas)*/
  iconName: 'custom-icon', /* The name of your icon*/
  icon: [150, 150, [], 'e105', 'M ...'] /* The viewbox, the unicode, the path*/
}

FontAwesome.library.add(
  CustomIcon
)
</code>```

Simple example of adding a triangle icon:

var faTriangle = {
  prefix: 'fas',
  iconName: 'tri',
  icon: [64, 64, [], 'e521', 'M8 48 L56 48 L32 12 Z']
}

FontAwesome.library.add(
  faTriangle
)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>i,svg {
  color: red;
}</code>```

```

Body:
You can find the steps in the following link. You will need to have you SVG path define as only one path element and nothing more (like any SVG icon) then you simply add the following code:

var CustomIcon = {
  prefix: 'fac', /* your own prefix OR use any of the exiting ones (fab, far, fas)*/
  iconName: 'custom-icon', /* The name of your icon*/
  icon: [150, 150, [], 'e105', 'M ...'] /* The viewbox, the unicode, the path*/
}

FontAwesome.library.add(
  CustomIcon
)

Simple example of adding a triangle icon:

var faTriangle = {
  prefix: 'fas',
  iconName: 'tri',
  icon: [64, 64, [], 'e521', 'M8 48 L56 48 L32 12 Z']
}

FontAwesome.library.add(
  faTriangle
)

i,svg {
  color: red;
}

<script src="https://use.fontawesome.com/releases/v5.12.0/js/all.js"></script>

<i class="fas fa-tri fa-5x"></i>
<i class="fas fa-tri fa-8x"></i>
<i class="fas fa-tri fa-10x"></i>


问:
GSuite - Google Classroom API - List all courses in a domain
I'm trying to list all courses in the domain using Google API python, but I can only list the courses associated with the user who makes the authentication.

what should I do?

Here is the code:

```<code>def connect():
    """Shows basic usage of the Classroom API.
    Prints the names of the first 10 courses the user has access to.
    """
    global service
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('classroom', 'v1', credentials=creds)

def listCourses()->None:
    global service

    courses = []
    page_token = None

    while True:
        response = service.courses().list(pageToken=page_token,
                                          pageSize=100).execute()
        courses.extend(response.get('courses', []))
        page_token = response.get('nextPageToken', None)
        if not page_token:
            break

    if not courses:
        print('No courses found.')
    else:
        print('Courses:')
        for course in courses:
            print('{0} ({1})'.format(course.get('name'), course.get('id')))
</code>```

答:
As the Docs at Manage Courses states in Retrieve course details:

Note: Students and teachers can only retrieve their own courses. Administrators can retrieve all courses.

Therefore you will need to use a user with admin access in order to be able to retrieve all courses in your domain.

Body:
I'm trying to list all courses in the domain using Google API python, but I can only list the courses associated with the user who makes the authentication.

what should I do?

Here is the code:

def connect():
    """Shows basic usage of the Classroom API.
    Prints the names of the first 10 courses the user has access to.
    """
    global service
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('classroom', 'v1', credentials=creds)

def listCourses()->None:
    global service

    courses = []
    page_token = None

    while True:
        response = service.courses().list(pageToken=page_token,
                                          pageSize=100).execute()
        courses.extend(response.get('courses', []))
        page_token = response.get('nextPageToken', None)
        if not page_token:
            break

    if not courses:
        print('No courses found.')
    else:
        print('Courses:')
        for course in courses:
            print('{0} ({1})'.format(course.get('name'), course.get('id')))


问:
SQL syntax near WHERE?
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?</p>

```<code>protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}
</code>```

答:
You need to use UPDATE, not INSERT
INSERT insert new row, therefore WHERE makes no sense</p>

Title: SQL syntax near WHERE?

Body:
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?

protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}


问:
c++ method parameter change it self only in release mode at linux
in c++ h file:

```<code>bool getIntValue(QString name,int& dest,int default_value,bool set_default=true);
</code>```

in c++ cpp file:

```<code>bool CoinConfig::getIntValue(QString name, int& dest, int default_value, bool set_default)
{
    qDebug() << "1 getIntValue set_default=" << set_default;
    if (_Platform_Config->contains(name)) {
        dest = _Platform_Config->value(name).toInt();
        qDebug() << "2 getIntValue dest" << dest;
        return true;
    }
    else if (set_default) {
        qDebug() << "3 set_default=" << set_default;
        qDebug() << "4 getIntValue dest default" << dest;
        dest = default_value;
        qDebug() << "5 getIntValue dest default" << dest;
        return false;
    }
}
</code>```

////////////////////////
run bellow code :

```<code>int b;
getIntValue("timer", b, -1, false); //_Platform_Config->contains(name) return false
</code>```

got the output:

```<code>1 getIntValue set_default = false  // at first set_default is false
3 set_default= true                // change to true  ???
4 getIntValue dest default 1000
5 getIntValue dest default -1
b 2 -1
</code>```

The set_default parameter change from false to true !!!
the system is linux , in debug mode it is right , but in release mode it is error.

why?

答:
There is a missing return statement in getIntValue. Try adding return true or return false at the end of the function:

```<code>bool CoinConfig::getIntValue(QString name, int& dest, int default_value, bool set_default)
{
    qDebug() << "1 getIntValue set_default=" << set_default;
    if (_Platform_Config->contains(name)) {
        dest = _Platform_Config->value(name).toInt();
        qDebug() << "2 getIntValue dest" << dest;
        return true;
    }
    else if (set_default) {
        qDebug() << "3 set_default=" << set_default;
        qDebug() << "4 getIntValue dest default" << dest;
        dest = default_value;
        qDebug() << "5 getIntValue dest default" << dest;
        return false;
    }
    return false; // <--- this is missing in your code
}
</code>```

I recommend that you enable compiler warnings, then the problem is found easily:

```<code>prog.cc: In function 'bool getIntValue(QString, int&, int, bool)':
prog.cc:27:1: warning: control reaches end of non-void function [-Wreturn-type]
</code>```

Body:
in c++ h file:

bool getIntValue(QString name,int& dest,int default_value,bool set_default=true);

in c++ cpp file:

bool CoinConfig::getIntValue(QString name, int& dest, int default_value, bool set_default)
{
    qDebug() << "1 getIntValue set_default=" << set_default;
    if (_Platform_Config->contains(name)) {
        dest = _Platform_Config->value(name).toInt();
        qDebug() << "2 getIntValue dest" << dest;
        return true;
    }
    else if (set_default) {
        qDebug() << "3 set_default=" << set_default;
        qDebug() << "4 getIntValue dest default" << dest;
        dest = default_value;
        qDebug() << "5 getIntValue dest default" << dest;
        return false;
    }
}

////////////////////////
run bellow code :

int b;
getIntValue("timer", b, -1, false); //_Platform_Config->contains(name) return false

got the output:

1 getIntValue set_default = false  // at first set_default is false
3 set_default= true                // change to true  ???
4 getIntValue dest default 1000
5 getIntValue dest default -1
b 2 -1

The set_default parameter change from false to true !!!
the system is linux , in debug mode it is right , but in release mode it is error.

why?

Body:
There is a missing return statement in getIntValue. Try adding return true or return false at the end of the function:

bool CoinConfig::getIntValue(QString name, int& dest, int default_value, bool set_default)
{
    qDebug() << "1 getIntValue set_default=" << set_default;
    if (_Platform_Config->contains(name)) {
        dest = _Platform_Config->value(name).toInt();
        qDebug() << "2 getIntValue dest" << dest;
        return true;
    }
    else if (set_default) {
        qDebug() << "3 set_default=" << set_default;
        qDebug() << "4 getIntValue dest default" << dest;
        dest = default_value;
        qDebug() << "5 getIntValue dest default" << dest;
        return false;
    }
    return false; // <--- this is missing in your code
}

I recommend that you enable compiler warnings, then the problem is found easily:

prog.cc: In function 'bool getIntValue(QString, int&, int, bool)':
prog.cc:27:1: warning: control reaches end of non-void function [-Wreturn-type]


问:
I have created a counter throught jQuery but is start working as soon as i load the page i want to execute it when the section appear on screen
code for counter but it start working after page is loaded i want to work it when the section is visiable:-</p>

```<code>$(document).ready(function() {

var counters = $(".counter");
var countersQuantity = counters.length;
var counter = [];

for (i = 0; i < countersQuantity; i++) {
counter[i] = parseInt(counters[i].innerHTML);
}

var count = function(start, value, id) {
var localStart = start;
setInterval(function() {
if (localStart < value) {
localStart++;
counters[id].innerHTML = localStart;
}
}, 80);
}
for (j = 0; j < countersQuantity; j++) {
count(0, counter[j], j);
}
});
</code>```

答:
The $(document).ready(function() { will run the callback only after the initial DOM has fully loaded. On a large page, this may be some time after the initial elements are visible to the user.

Make sure jQuery is included above (maybe in the ), then after the final .counter element in the HTML, put in a script tag immediately, so that it runs as soon as the element is created in the DOM, without waiting for the rest of the page to load:

content

content

100

200

300

400

content
```
</div>
</div>
</p>

<p>Note that you can significantly clean up your code, if you wish, and there's no need to require a big library like jQuery just to select elements:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>content</div>
<div>content</div>
<div class="counter">100</div>
<div class="counter">200</div>
<div class="counter">300</div>
<div class="counter">400</div>
<script>
for (const counter of document.querySelectorAll('.counter')) {
  const target = Number(counter.textContent);
  counter.textContent = 0;
  const interval = setInterval(() => {
    const curr = Number(counter.textContent);
    if (curr < target) counter.textContent = curr + 1;
    else clearInterval(interval);
  }, 80);
}
</script>
<div>content</div></code>```

Body:
code for counter but it start working after page is loaded i want to work it when the section is visiable:-

$(document).ready(function() {

var counters = $(".counter");
var countersQuantity = counters.length;
var counter = [];

for (i = 0; i < countersQuantity; i++) {
counter[i] = parseInt(counters[i].innerHTML);
}

var count = function(start, value, id) {
var localStart = start;
setInterval(function() {
if (localStart < value) {
localStart++;
counters[id].innerHTML = localStart;
}
}, 80);
}
for (j = 0; j < countersQuantity; j++) {
count(0, counter[j], j);
}
});

Body:
The $(document).ready(function() { will run the callback only after the initial DOM has fully loaded. On a large page, this may be some time after the initial elements are visible to the user.

Make sure jQuery is included above (maybe in the <head>), then after the final .counter element in the HTML, put in a script tag immediately, so that it runs as soon as the element is created in the DOM, without waiting for the rest of the page to load:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>content</div>
<div>content</div>
<div class="counter">100</div>
<div class="counter">200</div>
<div class="counter">300</div>
<div class="counter">400</div>
<script>
var counters = $(".counter");
var countersQuantity = counters.length;
var counter = [];

for (i = 0; i < countersQuantity; i++) {
  counter[i] = parseInt(counters[i].innerHTML);
}

var count = function(start, value, id) {
  var localStart = start;
  setInterval(function() {
    if (localStart < value) {
      localStart++;
      counters[id].innerHTML = localStart;
    }
  }, 80);
}
for (j = 0; j < countersQuantity; j++) {
  count(0, counter[j], j);
}
</script>
<div>content</div>

Note that you can significantly clean up your code, if you wish, and there's no need to require a big library like jQuery just to select elements:

<div>content</div>
<div>content</div>
<div class="counter">100</div>
<div class="counter">200</div>
<div class="counter">300</div>
<div class="counter">400</div>
<script>
for (const counter of document.querySelectorAll('.counter')) {
  const target = Number(counter.textContent);
  counter.textContent = 0;
  const interval = setInterval(() => {
    const curr = Number(counter.textContent);
    if (curr < target) counter.textContent = curr + 1;
    else clearInterval(interval);
  }, 80);
}
</script>
<div>content</div>


问:
What's the biggest R-gotcha you've run across?
Is there a certain R-gotcha that had you really surprised one day? I think we'd all gain from sharing these.

Here's mine: in list indexing, my.list[[1]] is not my.list[1]. Learned this in the early days of R.

答:
This one!

```<code>all(c(1,2,3,4) == NULL)
$[1] TRUE
</code>```

I had this check in my code, I really need both tables to have the same column names:

```<code>stopifnot(all(names(x$x$env) == names(x$obsx$env)))
</code>```

But the check passed (evaluated to TRUE) when x$x$env didn't even exist!

Body:
This one!

all(c(1,2,3,4) == NULL)
$[1] TRUE

I had this check in my code, I really need both tables to have the same column names:

stopifnot(all(names(x$x$env) == names(x$obsx$env)))

But the check passed (evaluated to TRUE) when x$x$env didn't even exist!