问:
Add form with validation using php and html to website
Update:  I'm using NicePage to create the website, and something in it is breaking the scriptgenerator.net code.  I'm getting this error in the browser.

```<code>Uncaught TypeError: $(...).validate is not a function
</code>```

Most of my experience in coding has been in COBOL, and I'm not that familiar with php and css.

I need to create a customer form on a website.  In order to do this I used the HTML-PHP-jQuery simple contact form v2 found on https://www.scriptgenerator.net

Here are the issues I'm having:

I can imbed the form.php into my webpage, but I haven't been able to
get the field labels to be left vertical justified as shown in the
generator's picture.

Also, the validation doesn't seem to do anything but reload the
page, no error messages or anything.

I'm not stuck using scriptgenerator.net, but would really appreciate any and all help.  I will also add a recaptcha to the page, but want to get the contact form working first.

The form generator shows this for a preview, which pretty much what I need.

Following the instructions, I downloaded the generator code and the js required.

Here is the form.php as copied from the generator.

```<code><title>Contact Form</title>
    <style type="text/css">
        #contact_wrapper {
            width:100%; /* you can change the form width by just changing this line */
            font-family:Arial, Helvetica, sans-serif;
            font-size:90%;
            margin-bottom:20px;
        }
        #contact_wrapper legend {
            display: inherit;
            border:none;
            width:auto;
            font-size:120%;
            font-weight:bold;
        }

        #contact_wrapper .genField {
            display: block;
            width: 100%;
            height: 34px;
            padding: 6px 20px;

            line-height: 1.42857143;
            color: #222;
            background-color: #fff;
            background-image: none;
            border: 1px solid #ccc;
            border-radius: 4px;
            -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
            box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
            -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
            -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
            transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
            -webkit-box-sizing:border-box;
            -moz-box-sizing:border-box;
            box-sizing:border-box;
        }
        #contact_wrapper .genField.auto { width:auto; }
        #contact_wrapper textarea.genField { min-height:200px; }

        #contact_wrapper .button {
            display: inline-block;
            padding: 6px 12px;
            margin-bottom: 0;
            font-size: 14px;
            font-weight: 400;
            line-height: 1.42857143;
            text-align: center;
            white-space: nowrap;
            vertical-align: middle;
            -ms-touch-action: manipulation;
            touch-action: manipulation;
            cursor: pointer;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            background-image: none;
            border: 1px solid transparent;
            border-radius: 4px;
            color: #fff;
        }
        #contact_wrapper .f_left { float:left; }
        #contact_wrapper .f_radio{ font-weight:normal; display:block; }

        #contact_wrapper .submit{ background-color: #337ab7; border-color: #2e6da4; padding:6px 30px; margin-left:10px; }
        #contact_wrapper .reset { background-color: #d9534f; border-color: #d43f3a; }

        #contact_wrapper .submit:hover{ background-color: #286090; }
        #contact_wrapper .reset:hover   { background-color: #C9302C; }

        #contact_wrapper input.error, #contact_wrapper textarea.error { border: 1px dashed #F41724; }

        #contact_wrapper label {
            display: block;
            width:auto;
            line-height: 1.8;
            vertical-align: top;
            cursor: pointer;
            color: #222;
            margin-top:12px;
        }
        #contact_wrapper label.error {font-size:80%; color:#F41724; margin-top:2px; float: right; }

        #contact_wrapper .buttons, #contact_wrapper .captcha { margin-top:15px; }

        #contact_wrapper .captcha label.f_left { margin:7px 10px inherit inherit;}

        #contact_wrapper #results p {
            padding: 20px;
            color: #FFFFFF;
            font-weight: bold;
            border-radius: 5px;
        }

        #contact_wrapper #results p.sending_success { background-color: #337AB7; }
        #contact_wrapper #results p.sending_error   { background-color: #D9534F; }

        .clearfix:after {
           content: ".";
           visibility: hidden;
           display: block;
           height: 0;
           clear: both;
        }
    </style>

</head>
<body>

<div id="contact_wrapper">

    <fieldset id="form_wrapper">
        <legend>Contact Form</legend>
        <form name="contactme" id="contactme" action="" method="post">
                        <label for="fname">First Name *</label>
            <input type="text" name="fname" id="fname" class="genField" />
                        <label for="email">Email *</label>
            <input type="text" name="email" id="email" class="genField" />

            <label for="subject">Subject *</label>
            <input type="text" name="subject" id="subject" class="genField" />

            <label for="message">Message *</label>
            <textarea name="message" id="message" class="genField"></textarea>

            <div class="clearfix"></div>
            <div class="buttons">
                <input type="reset" class="button reset" name="reset" value="X" />
                <input type="submit" class="button submit" name="submit" value="Submit Form" />

                <span style="float:right; margin-top:8px;">
                    <a href="http://scriptgenerator.net/html-php-jquery-simple-contact-form-v2/" title="Valid Contact Form">
                        <img    src="http://www.scriptgenerator.net/generator/html-php-contact-form-mailer-generator_files/validform.jpg"
                                alt="Valid Contact Form" width="20" height="20" />
                    </a>
                </span>
            </div>
        </form>

    </fieldset>

    <!-- We will output the results from process.php here -->
    <div id="results" style="display:none;"></div>

</div>

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var msj = "Please enter valid data"; // you can insert here a customized error message
        $('#contactme').validate({
            debug: false,
            rules: {
                // You can set rools to validatate fields here
                fname: { required: true, minlength:2 },
                email: { required: true, email: true },
                subject: { required: true, minlength:2 },
                message: { required: true, minlength:2 },

            },
            messages: {
                // You can also set a custom message for each field
                fname: "Please enter a valid Name",
                email: "Please enter a valid email address",
                subject: msj,
                message: msj,

            },
            submitHandler: function(form) {
                $("#form_wrapper").hide();
                // do adicional stuff of form validation
                $.post("process.php", $("#contactme").serialize(), function(data) {
                    $("#results").html(data).show(1000);
                });
            }
        });
    });
</script>
</code>```

and the process.php

```<code><?php
// Wait a second to simulate a some latency
usleep(500000);

function m($m, $t=NULL){
    return "<p class='".($t=="s"?"sending_success":"sending_error")."'>".$m."</p>";
}

global $email_send_to, $email_recived_from, $success_msj, $error_msj;

// edit email where contact form is sent
$email_send_to = "";
// edit your domain
$email_recived_from = "";

// edit message for a successfully sent contact form
$success_msj = "Your message has been sent. Thank you for your feedback. We will contact you shortly if needed";
// edit error message
$error_msj = "Ups, There has been an error while sending. Please try again in a few minutes or panic appropriately!";
// edit subject here. If user enters no subject, we will use this one
$standard_subject = "Someone contacted you on ".$email_recived_from;

//------------------------------------------------------------------------------------------------//
function secure($post) {
    if (is_array($post)):
        foreach($post as $item=>$value):
            $post[$item] = term( $value ); //This helps not to break code if single or doble cuotes are sent to process
            $post[$item] = trim( $value ); // Strip whitespace (or other characters) from the beginning and end of a string
        endforeach;
    else:
        $post = term( $post ); //This helps not to break code if single or doble cuotes are sent to process
        $post = trim( $post ); // Strip whitespace (or other characters) from the beginning and end of a string
    endif;
    $post = mynl2br($post);

    // insert here aditional security functions

    return $post;
}
//------------------------------------------------------------------------------------------------//
// if someone sends you cods or scripts via contact form, this will prevent it from being interpreted
function mynl2br($post) {
   return strtr($post, array("\t"=>"    ", "<"=>"<", ">"=>">", "\r\n" => "<br />", "\r" => "<br />", "\n" => "<br />"));
}

//------------------------------------------------------------------------------------------------//
function term($post){
//  DO NOT INDENT THIS. adicional spaces are interpreted. This helps not to break code if single or doble cuotes are sent to process
$post = <<<term
$post
term;
return $post;
}
//------------------------------------------------------------------------------------------------//

// Pull out data from contact form
$fname = (isset($_POST['fname'])?secure($_POST['fname']):'');
$email = (isset($_POST['email'])?secure($_POST['email']):'');
$subject = (isset($_POST['subject'])?secure($_POST['subject']):'');
$message = (isset($_POST['message'])?secure($_POST['message']):'');

//------------------------------------------------------------------------------------------------//
$email_recived_from  = str_replace ("http://", "", $email_recived_from );
$email_recived_from  = str_replace ("www.", "", $email_recived_from );

$from = $email_recived_from." <contact@".$email_recived_from.">";

$mail_subject = (empty($subject)?$standard_subject:$subject);
//------------------------------------------------------------------------------------------------//

//------------------------------------------------------------------------------------------------//
// setting HTML email function
function sendHTMLemail($body,$from, $to, $subject) {

    global $success_msj, $error_msj;
    $boundary = uniqid("HTMLEMAIL");

    $headers  = "From: $from\r\n";
    $headers .= "MIME-Version: 1.0\r\n";

    $headers .= "Content-Type: multipart/alternative;".
                "boundary = $boundary\r\n\r\n";
    $headers .= "This is a MIME encoded message.\r\n\r\n";

    $headers .= "--$boundary\r\n".
                "Content-Type: text/html; charset=utf-8\r\n".
                "Content-Transfer-Encoding: base64\r\n\r\n";

    $headers .= chunk_split(base64_encode($body));

    return ( mail($to,$subject,"",$headers,"-f".$from) ? m($success_msj,"s") : m($error_msj) );
}
//------------------------------------------------------------------------------------------------//

ob_start();?>
<html>
<head>
    <!--
        Lots of email clients strip all head information like CSS style classes.
        That is why we included all style directly into the body using span tags.
        Table was used for the layout to increase outlook compatibility and other old email clients.
    -->
</head>
<body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0" bgcolor="#8ED4F4" >

<table width="100%"  cellspacing="0" bgcolor="#8ED4F4" >
    <tr>
        <td valign="top" align="center">

            <table width="80%" style=" width:80%;min-width:326px;margin-top:10px;" cellpadding="20" cellspacing="0" bgcolor="#FFFFFF">
                <tr>
                    <td style="background-color:#337AB7; text-align:center; padding:10px;" align="center">
                        <span style="color:#fff;font-family:arial; font-size:140%;">A new person <span style="color:#FF9366">contacted</span> you:</span>
                    </td>

                </tr>

                <tr>

                    <td bgcolor="#FFFFFF">

                        <p>
                            <span style="font-size:12px;font-weight:normal;color:#666;font-family:arial;line-height:150%;">
                                                                <br /><strong>First Name:</strong> <?=$fname?>
                                <br /><strong>Email:</strong> <?=$email?>
                                <br /><strong>Subject:</strong> <?=$subject?>
                                <br /><strong>Message:</strong> <?=$message?>

                            </span>
                        </p>
                    </td>
                </tr>
                <tr>
                    <td style="background-color:#337AB7; text-align:center;" align="center" valign="top" colspan="2">
                        <span style="font-size:11px;color:#fff;line-height:200%;font-family:arial;text-decoration:none;">Contact service provided by <br />
                            <a style="color:#fff; font-weight:bold; font-size:110%; text-decoration:none;" href="http://scriptgenerator.net" title="scriptgenerator.net">
                                <span style="color:#FF9366">Script</span>Generator
                            </a>
                        </span>
                    </td>
                </tr>
            </table>

        </td>
    </tr>
</table>
</body>
</html>
<? $HTML = ob_get_clean();

// display succes or error message depending is email has been sent or not
echo sendHTMLemail($HTML,$from,$email_send_to,$mail_subject);
?>
</code>```

There are 2 js files, jquery-1.4.2-mini.js and jquery.validate.min.js, which I can provide if necessary, but can also be downloaded from the form generator website.

Here's what it looks like when I imbed it.

答:
When I preview you code of process.php everything looks like on the provided preview screenshot, as you can see in the following snippet:

<!DOCTYPE html>

  <title>Contact Form</title>

    <fieldset id="form_wrapper">
      <legend>Contact Form</legend>
      <form name="contactme" id="contactme" action="" method="post">
        First Name *
        <input type="text" name="fname" id="fname" class="genField" />
        Email *
        <input type="text" name="email" id="email" class="genField" />

        Subject *
        <input type="text" name="subject" id="subject" class="genField" />

        Message *
        <textarea name="message" id="message" class="genField"></textarea>

          <input type="reset" class="button reset" name="reset" value="X" />
          <input type="submit" class="button submit" name="submit" value="Submit Form" />

      </form>
    </fieldset>

```

Body:
Update:  I'm using NicePage to create the website, and something in it is breaking the scriptgenerator.net code.  I'm getting this error in the browser.

Uncaught TypeError: $(...).validate is not a function

Most of my experience in coding has been in COBOL, and I'm not that familiar with php and css.

I need to create a customer form on a website.  In order to do this I used the HTML-PHP-jQuery simple contact form v2 found on https://www.scriptgenerator.net

Here are the issues I'm having:

I can imbed the form.php into my webpage, but I haven't been able to
get the field labels to be left vertical justified as shown in the
generator's picture.

Also, the validation doesn't seem to do anything but reload the
page, no error messages or anything.

I'm not stuck using scriptgenerator.net, but would really appreciate any and all help.  I will also add a recaptcha to the page, but want to get the contact form working first.

The form generator shows this for a preview, which pretty much what I need.

Following the instructions, I downloaded the generator code and the js required.

Here is the form.php as copied from the generator.

<title>Contact Form</title>

    <fieldset id="form_wrapper">
        <legend>Contact Form</legend>
        <form name="contactme" id="contactme" action="" method="post">
                        First Name *
            <input type="text" name="fname" id="fname" class="genField" />
                        Email *
            <input type="text" name="email" id="email" class="genField" />

            Subject *
            <input type="text" name="subject" id="subject" class="genField" />

            Message *
            <textarea name="message" id="message" class="genField"></textarea>

                <input type="reset" class="button reset" name="reset" value="X" />
                <input type="submit" class="button submit" name="submit" value="Submit Form" />

        </form>

    </fieldset>

and the process.php

<?php
// Wait a second to simulate a some latency
usleep(500000);

function m($m, $t=NULL){
    return "
".$m."
";
}

global $email_send_to, $email_recived_from, $success_msj, $error_msj;

// edit email where contact form is sent
$email_send_to = "";
// edit your domain
$email_recived_from = "";

// edit message for a successfully sent contact form
$success_msj = "Your message has been sent. Thank you for your feedback. We will contact you shortly if needed";
// edit error message
$error_msj = "Ups, There has been an error while sending. Please try again in a few minutes or panic appropriately!";
// edit subject here. If user enters no subject, we will use this one
$standard_subject = "Someone contacted you on ".$email_recived_from;

//------------------------------------------------------------------------------------------------//
function secure($post) {
    if (is_array($post)):
        foreach($post as $item=>$value):
            $post[$item] = term( $value ); //This helps not to break code if single or doble cuotes are sent to process
            $post[$item] = trim( $value ); // Strip whitespace (or other characters) from the beginning and end of a string
        endforeach;
    else:
        $post = term( $post ); //This helps not to break code if single or doble cuotes are sent to process
        $post = trim( $post ); // Strip whitespace (or other characters) from the beginning and end of a string
    endif;
    $post = mynl2br($post);

    // insert here aditional security functions

    return $post;
}
//------------------------------------------------------------------------------------------------//
// if someone sends you cods or scripts via contact form, this will prevent it from being interpreted
function mynl2br($post) {
   return strtr($post, array("\t"=>"    ", "<"=>"<", ">"=>">", "\r\n" => "
", "\r" => "
", "\n" => "
"));
}

//------------------------------------------------------------------------------------------------//
function term($post){
//  DO NOT INDENT THIS. adicional spaces are interpreted. This helps not to break code if single or doble cuotes are sent to process
$post = <<<term
$post
term;
return $post;
}
//------------------------------------------------------------------------------------------------//

// Pull out data from contact form
$fname = (isset($_POST['fname'])?secure($_POST['fname']):'');
$email = (isset($_POST['email'])?secure($_POST['email']):'');
$subject = (isset($_POST['subject'])?secure($_POST['subject']):'');
$message = (isset($_POST['message'])?secure($_POST['message']):'');

//------------------------------------------------------------------------------------------------//
$email_recived_from  = str_replace ("http://", "", $email_recived_from );
$email_recived_from  = str_replace ("www.", "", $email_recived_from );

$from = $email_recived_from." <contact@".$email_recived_from.">";

$mail_subject = (empty($subject)?$standard_subject:$subject);
//------------------------------------------------------------------------------------------------//

//------------------------------------------------------------------------------------------------//
// setting HTML email function
function sendHTMLemail($body,$from, $to, $subject) {

    global $success_msj, $error_msj;
    $boundary = uniqid("HTMLEMAIL");

    $headers  = "From: $from\r\n";
    $headers .= "MIME-Version: 1.0\r\n";

    $headers .= "Content-Type: multipart/alternative;".
                "boundary = $boundary\r\n\r\n";
    $headers .= "This is a MIME encoded message.\r\n\r\n";

    $headers .= "--$boundary\r\n".
                "Content-Type: text/html; charset=utf-8\r\n".
                "Content-Transfer-Encoding: base64\r\n\r\n";

    $headers .= chunk_split(base64_encode($body));

    return ( mail($to,$subject,"",$headers,"-f".$from) ? m($success_msj,"s") : m($error_msj) );
}
//------------------------------------------------------------------------------------------------//

ob_start();?>

                        A new person contacted you:

First Name: <?=$fname?>

Email: <?=$email?>

Subject: <?=$subject?>

Message: <?=$message?>

                        Contact service provided by

                                ScriptGenerator

<? $HTML = ob_get_clean();

// display succes or error message depending is email has been sent or not
echo sendHTMLemail($HTML,$from,$email_send_to,$mail_subject);
?>

There are 2 js files, jquery-1.4.2-mini.js and jquery.validate.min.js, which I can provide if necessary, but can also be downloaded from the form generator website.

Here's what it looks like when I imbed it.

Body:
When I preview you code of process.php everything looks like on the provided preview screenshot, as you can see in the following snippet:

<!DOCTYPE html>
<html>

<head>
  <title>Contact Form</title>
  <style type="text/css">
    #contact_wrapper {
      width: 100%;
      /* you can change the form width by just changing this line */
      font-family: Arial, Helvetica, sans-serif;
      font-size: 90%;
      margin-bottom: 20px;
    }

    #contact_wrapper legend {
      display: inherit;
      border: none;
      width: auto;
      font-size: 120%;
      font-weight: bold;
    }

    #contact_wrapper .genField {
      display: block;
      width: 100%;
      height: 34px;
      padding: 6px 20px;
      line-height: 1.42857143;
      color: #222;
      background-color: #fff;
      background-image: none;
      border: 1px solid #ccc;
      border-radius: 4px;
      -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
      box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
      -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
      -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
      transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
    }

    #contact_wrapper .genField.auto {
      width: auto;
    }

    #contact_wrapper textarea.genField {
      min-height: 200px;
    }

    #contact_wrapper .button {
      display: inline-block;
      padding: 6px 12px;
      margin-bottom: 0;
      font-size: 14px;
      font-weight: 400;
      line-height: 1.42857143;
      text-align: center;
      white-space: nowrap;
      vertical-align: middle;
      -ms-touch-action: manipulation;
      touch-action: manipulation;
      cursor: pointer;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      background-image: none;
      border: 1px solid transparent;
      border-radius: 4px;
      color: #fff;
    }

    #contact_wrapper .f_left {
      float: left;
    }

    #contact_wrapper .f_radio {
      font-weight: normal;
      display: block;
    }

    #contact_wrapper .submit {
      background-color: #337ab7;
      border-color: #2e6da4;
      padding: 6px 30px;
      margin-left: 10px;
    }

    #contact_wrapper .reset {
      background-color: #d9534f;
      border-color: #d43f3a;
    }

    #contact_wrapper .submit:hover {
      background-color: #286090;
    }

    #contact_wrapper .reset:hover {
      background-color: #C9302C;
    }

    #contact_wrapper input.error,
    #contact_wrapper textarea.error {
      border: 1px dashed #F41724;
    }

    #contact_wrapper label {
      display: block;
      width: auto;
      line-height: 1.8;
      vertical-align: top;
      cursor: pointer;
      color: #222;
      margin-top: 12px;
    }

    #contact_wrapper label.error {
      font-size: 80%;
      color: #F41724;
      margin-top: 2px;
      float: right;
    }

    #contact_wrapper .buttons,
    #contact_wrapper .captcha {
      margin-top: 15px;
    }

    #contact_wrapper .captcha label.f_left {
      margin: 7px 10px inherit inherit;
    }

    #contact_wrapper #results p {
      padding: 20px;
      color: #FFFFFF;
      font-weight: bold;
      border-radius: 5px;
    }

    #contact_wrapper #results p.sending_success {
      background-color: #337AB7;
    }

    #contact_wrapper #results p.sending_error {
      background-color: #D9534F;
    }

    .clearfix:after {
      content: ".";
      visibility: hidden;
      display: block;
      height: 0;
      clear: both;
    }
  </style>

</head>

<body>

  <div id="contact_wrapper">

    <fieldset id="form_wrapper">
      <legend>Contact Form</legend>
      <form name="contactme" id="contactme" action="" method="post">
        <label for="fname">First Name *</label>
        <input type="text" name="fname" id="fname" class="genField" />
        <label for="email">Email *</label>
        <input type="text" name="email" id="email" class="genField" />

        <label for="subject">Subject *</label>
        <input type="text" name="subject" id="subject" class="genField" />

        <label for="message">Message *</label>
        <textarea name="message" id="message" class="genField"></textarea>

        <div class="clearfix"></div>
        <div class="buttons">
          <input type="reset" class="button reset" name="reset" value="X" />
          <input type="submit" class="button submit" name="submit" value="Submit Form" />

          <span style="float:right; margin-top:8px;">
                        <a href="http://scriptgenerator.net/html-php-jquery-simple-contact-form-v2/"
                            title="Valid Contact Form">
                            <img src="http://www.scriptgenerator.net/generator/html-php-contact-form-mailer-generator_files/validform.jpg"
                                alt="Valid Contact Form" width="20" height="20" />
                        </a>
                    </span>
        </div>
      </form>
    </fieldset>
  </div>
</body>

</html>


来源: stackexchange

问:
How to read connection string from key vault for Service Bus?
Here is how I instantiate the client in my Configure method:

```<code>services.AddSingleton<ServiceBusClient>(x => new ServiceBusClient(configuration.GetSection("ServiceBus:ConnectionString").Value, serviceBusClientOptions));
</code>```

And this how my appsettings looks like:

```<code>{
  "ServiceBus:ConnectionString": "@Microsoft.KeyVault(VaultName=MyVaultName;SecretName=MySecretName)"
}
</code>```

However, I am getting the following exception:

```<code>The connection string used for an Service Bus client must specify the Service Bus namespace host and either a Shared Access Key (both the name and value) OR a Shared Access Signature to be valid. (Parameter 'connectionString'
</code>```

What am I missing here?

答:
Have you created a managed identity for you application and added access policies such that your app can GET this secret value from key vault?

Check out the official documentaion for this here : https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references

Also on a side note, have you tried directly adding the secret value as the appsetting value instead of referencing it from KV and see if that worked? (if yes then definitely its a permissions issue and NOT a problem with your C# app code.

ContentLicense: CC BY-SA 4.0

Body:
Here is how I instantiate the client in my Configure method:

services.AddSingleton<ServiceBusClient>(x => new ServiceBusClient(configuration.GetSection("ServiceBus:ConnectionString").Value, serviceBusClientOptions));

And this how my appsettings looks like:

{
  "ServiceBus:ConnectionString": "@Microsoft.KeyVault(VaultName=MyVaultName;SecretName=MySecretName)"
}

However, I am getting the following exception:

The connection string used for an Service Bus client must specify the Service Bus namespace host and either a Shared Access Key (both the name and value) OR a Shared Access Signature to be valid. (Parameter 'connectionString'

What am I missing here?


问:
SVN branching problems
I have a /Trunk in my Project X. On rev 69 we had to revert changes in three earlier revisions (61,63,64).

What I did was a reverse merge on the revisions 61,63,64 and committed this to rev 69. Then we could deploy again and everyone was happy.

Now we have learned that developing new features in a separate branch is a neat idea, and then the Trunk is always ready to deploy to production (and doing hotfixes on current release).

So now I have made a "/Branches/X"(rev 70) from the HEAD revision in the /Trunk (which is rev 69), but I want to have with me the changes I undid in the /Trunk (61,63,64)

What is the correct way to this?

btw, have I made meself clear about? :)

答:
Generally speaking, suppose that you want to merge some change-sets from branch X to branch Y. do the following steps using TortoiseSVN:

Get Y in working folder Y-WF.

Go to Y-WF.

Right click and choose merge.

For the source url, enter the URL of the X branch.

Select your change-sets you want to merge.

Press OK.

Now, the changes have been applied to your working folder. (in the case of no conflicts)

Check-in all of your changes.

ContentLicense: CC BY-SA 3.0

Title: SVN branching problems


问:
Unmarshalling YAML to ordered maps
I am trying to unmarshal the following YAML with Go YAML v3.

```<code>model:
  name: mymodel
  default-children:
  - payment

  pipeline:
    accumulator_v1:
      by-type:
        type: static
        value: false
      result-type:
        type: static
        value: 3

    item_v1:
      amount:
        type: schema-path
        value: amount
      start-date:
        type: schema-path
        value: start-date
</code>```

Under pipeline is an arbitrary number of ordered items. The struct to which this should be unmarshalled looks like this:

```<code>type PipelineItemOption struct {
        Type string
        Value interface{}
}

type PipelineItem struct {
        Options map[string]PipelineItemOption
}

type Model struct {
        Name string
        DefaultChildren []string `yaml:"default-children"`
        Pipeline orderedmap[string]PipelineItem    // "pseudo code"
}
</code>```

How does this work with Golang YAML v3? In v2 there was MapSlice, but that is gone in v3.

答:
For me it was a bit of a learning curve to figure out what v3 expects instead of MapSlice. Similar to answer from @flyx, the yaml.Node tree needs to be walked, particularly its []Content.

Here is a utility to provide an ordered map[string]interface{} that is a little more reusable and tidy. (Though it is not as constrained as the question specified.)

Per structure above, redefine Pipeline generically:

type Model struct {
    Name string
    DefaultChildren []string `yaml:"default-children"`
    Pipeline *yaml.Node
}
```
<p>Use a utility fn to traverse <code>yaml.Node</code> content:</p>
<pre class="lang-golang prettyprint-override"><code>// fragment
var model Model
if err := yaml.Unmarshal(&model) ; err != nil {
    return err
}

om, err := getOrderedMap(model.Pipeline)
if err != nil {
    return err
}

for _,k := range om.Order {
    v := om.Map[k]
    fmt.Printf("%s=%v\n", k, v)
}
</code>```

The utility fn:

type OrderedMap struct {
    Map map[string]interface{}
    Order []string
}

func getOrderedMap(node *yaml.Node) (om *OrderedMap, err error) {
    content := node.Content
    end := len(content)
    count := end / 2

    om = &OrderedMap{
        Map: make(map[string]interface{}, count),
        Order: make([]string, 0, count),
    }

    for pos := 0 ; pos < end ; pos += 2 {
        keyNode := content[pos]
        valueNode := content[pos + 1]

        if keyNode.Tag != "!!str" {
            err = fmt.Errorf("expected a string key but got %s on line %d", keyNode.Tag, keyNode.Line)
            return
        }

        var k string
        if err = keyNode.Decode(&k) ; err != nil {
            return
        }

        var v interface{}
        if err = valueNode.Decode(&v) ; err != nil {
            return
        }

        om.Map[k] = v
        om.Order = append(om.Order, k)
    }

    return
}
```

Title: Unmarshalling YAML to ordered maps

Body:
I am trying to unmarshal the following YAML with Go YAML v3.

model:
  name: mymodel
  default-children:
  - payment

  pipeline:
    accumulator_v1:
      by-type:
        type: static
        value: false
      result-type:
        type: static
        value: 3

    item_v1:
      amount:
        type: schema-path
        value: amount
      start-date:
        type: schema-path
        value: start-date

Under pipeline is an arbitrary number of ordered items. The struct to which this should be unmarshalled looks like this:

type PipelineItemOption struct {
        Type string
        Value interface{}
}

type PipelineItem struct {
        Options map[string]PipelineItemOption
}

type Model struct {
        Name string
        DefaultChildren []string `yaml:"default-children"`
        Pipeline orderedmap[string]PipelineItem    // "pseudo code"
}

How does this work with Golang YAML v3? In v2 there was MapSlice, but that is gone in v3.

Body:
For me it was a bit of a learning curve to figure out what v3 expects instead of MapSlice. Similar to answer from @flyx, the yaml.Node tree needs to be walked, particularly its []Content.

Here is a utility to provide an ordered map[string]interface{} that is a little more reusable and tidy. (Though it is not as constrained as the question specified.)

Per structure above, redefine Pipeline generically:

type Model struct {
    Name string
    DefaultChildren []string `yaml:"default-children"`
    Pipeline *yaml.Node
}

Use a utility fn to traverse yaml.Node content:

// fragment
var model Model
if err := yaml.Unmarshal(&model) ; err != nil {
    return err
}

om, err := getOrderedMap(model.Pipeline)
if err != nil {
    return err
}

for _,k := range om.Order {
    v := om.Map[k]
    fmt.Printf("%s=%v\n", k, v)
}

The utility fn:

type OrderedMap struct {
    Map map[string]interface{}
    Order []string
}

func getOrderedMap(node *yaml.Node) (om *OrderedMap, err error) {
    content := node.Content
    end := len(content)
    count := end / 2

    om = &OrderedMap{
        Map: make(map[string]interface{}, count),
        Order: make([]string, 0, count),
    }

    for pos := 0 ; pos < end ; pos += 2 {
        keyNode := content[pos]
        valueNode := content[pos + 1]

        if keyNode.Tag != "!!str" {
            err = fmt.Errorf("expected a string key but got %s on line %d", keyNode.Tag, keyNode.Line)
            return
        }

        var k string
        if err = keyNode.Decode(&k) ; err != nil {
            return
        }

        var v interface{}
        if err = valueNode.Decode(&v) ; err != nil {
            return
        }

        om.Map[k] = v
        om.Order = append(om.Order, k)
    }

    return
}


问:
what and how about firestore document field updates in batch
Documentation says that writing to firestore documents is limited to 1 second per document.

Updating different fields of the document fast enough could cause data loss if device A is updating field A and device B is updating field B in the same time ?

Will a batch that updates multiple documents on one or many fields fields fail if one of the documents is busy ?

Does a batch that update document fields fail if one of the documents is busy ?

If the batch update is used offline, what happens if the one of the documents included in the batch is busy when the user gets back online ?

in this video
https://youtu.be/dOVSr0OsAoU?t=240
it is stated that hybrid state of the data is impossible when using batches but if a batch was run offline does it get passed as a batch to the server when the user gets back online ?

#askfirebase

答:
Updating different fields of the document fast enough could cause data loss if device A is updating field A and device B is updating field B in the same time ?

It doesn't matter which fields are being updated.  If you exceed the rate limits for updates on the document in any way, the updates might fail.

Does a batch that update document fields fail if one of the documents is busy ?

If any part of a batch write fails, the entire batch fails.  There is never partial success for batch writes and transactions.

If the batch update is used offline, what happens if the one of the documents included in the batch is busy ?

The limits only apply to documents written to the cloud-based service.  They don't apply to documents cached locally which the app is offline.

If the app is offline, then no documents are written to the cloud.  If no documents are written to the cloud, then no write limits can be exceeded.


问:
Visual Studio 2019 Community toolbox has no webbrowser control
My Visual Studio toolbox

I have a WinForms app, when I design a form, the toolbox shows no webbrowser control. The framework is .NET 5.0. I use Visual Studio 2019 Community latest version v16.8.6, as shown in the screenshot.

Can anyone help me?

答:
I have VS 2022 and .NET 6.0 and it is not in the toolbox there either. I was able to add it by editing the MyForm.Designer.cs file. There are 4 sections of the file that I added code to.
this.webBrowser1 = new System.Windows.Forms.WebBrowser();

```<code>        //
        // webBrowser1
        //
        this.webBrowser1.Location = new System.Drawing.Point(1064, 24);
        this.webBrowser1.Margin = new System.Windows.Forms.Padding(5, 3, 5, 3);
        this.webBrowser1.MinimumSize = new System.Drawing.Size(27, 27);
        this.webBrowser1.Name = "webBrowser1";
        this.webBrowser1.Size = new System.Drawing.Size(405, 506);
        this.webBrowser1.TabIndex = 27;
</code>```

this.Controls.Add(this.webBrowser1);

private System.Windows.Forms.WebBrowser webBrowser1;

Body:
I have VS 2022 and .NET 6.0 and it is not in the toolbox there either. I was able to add it by editing the MyForm.Designer.cs file. There are 4 sections of the file that I added code to.
this.webBrowser1 = new System.Windows.Forms.WebBrowser();

        //
        // webBrowser1
        //
        this.webBrowser1.Location = new System.Drawing.Point(1064, 24);
        this.webBrowser1.Margin = new System.Windows.Forms.Padding(5, 3, 5, 3);
        this.webBrowser1.MinimumSize = new System.Drawing.Size(27, 27);
        this.webBrowser1.Name = "webBrowser1";
        this.webBrowser1.Size = new System.Drawing.Size(405, 506);
        this.webBrowser1.TabIndex = 27;

this.Controls.Add(this.webBrowser1);

private System.Windows.Forms.WebBrowser webBrowser1;


问:
Smarty substring after last occurrence?
Need to get the style number out of text string:

'The style number is A456RT'
'Style A456RT'
'Style number is A456RT'

Need to get the A456RT part only, i.e. after the last space. Tried to adapt similar answers but no luck:

```<code>{$product.name|regex_replace:"/^\d+ /":""}
</code>```

Is there an easy way to achieve this?

答:
How about the much simpler:

```<code>/[^ ]+$/gm
</code>```

That is...

```<code>[^ ] any character other than a space
+ One or more times
$ at the end of the line
</code>```

Title: Smarty substring after last occurrence?

Body:
Need to get the style number out of text string:

'The style number is A456RT'
'Style A456RT'
'Style number is A456RT'

Need to get the A456RT part only, i.e. after the last space. Tried to adapt similar answers but no luck:

{$product.name|regex_replace:"/^\d+ /":""}

Is there an easy way to achieve this?

Body:
How about the much simpler:

/[^ ]+$/gm

That is...

[^ ] any character other than a space
+ One or more times
$ at the end of the line


问:
How can I tell if a date is before a certain time in Java?
For example given a java.util.Date how could I test if the time was before 12.30 PM that day?</p>

答: Use the GregorianCalendar class.

Body: Use the GregorianCalendar class.


问:
Trying to export tickets/incidents from SCSM to csv file using powershell
I am trying to do a simple ticket/incident file export using PowerShell. All of our tickets go into the Service manager 2019 Console.

What I am trying to do is be able to filter and export our tickets using certain date range.  Our senior system engineer was able to help me get started and I am trying to figure out the best way to do this.  So this is what he sent me:

____________________________________________
you always want to filter / where as far left as possible to reduce processing overhead
also Tab is your friend when typing cmdlets - usually something like
Get-SCSMIncident -<Tab>
and it will show you your options
or Get-SCSMIncident -Help
you can also use Where-Object to filter once you have the correct subitems
Get-SCSMIncident | Where-Object {$_.Status -eq "Active"}
because you're doing the filter AFTER Get-SCSMIncident, it's going to find ALL incidents in the background, THEN filter them (slow/bad)
____________________________________________

So I tried a few things.  He suggested to do the following below, create variables, store them and pull the data later.

$allincidents = Get-SCSMIncident
$resolved = $allincdients | Where-Object {$_.Status -eq "Resolved"}
$active = $allincdients | Where-Object {$_.Status -eq "Active"

Then I would export the info such as below to a csv file

$active | export-csv c:\temp\scsm_incidents.csv -nti

The issue is that when I execute it, the initial storing of the variables it is taking too long, because we have obviously thousands and thousands of tickets.

I then thought what if I did the following below
Create the date variables first and store them.

$startDate = Get-Date -Year 2022 -Month 1 -Day 1

$endDate = Get-Date -Year 2022 -Month 2 -Day 2

Get-SCSMIncident | Where-Object {($_.createddate.date -le $endDate) -and ($_.createddate.date -ge $startDate)} | Export-Csv C:\Temp\SCSM-tickets.csv -nti

And given the logic that my Senior Engineer told me, it is going through all the tickets first because of the Get-SCSMIncident and then filtering and then storing into an csv file.

So my question is there a way to sort of go backwards?  I know computer language wise it wouldn't make sense because it doesn't know what object it is being pointed to.

Like for example

Where-Object {($_.createddate.date -le $endDate) -and ($_.createddate.date -ge $startDate)} |  Get-SCSMIncident | Export-Csv C:\Temp\SCSM-tickets.csv -nti

The end result is that I want to be able to pull data on a weekly basis using just a date range, without have to run through all the tickets every time.  Since new tickets are being generated everyday, each time I run through it, it will take longer and longer and longer.  I am by no means expert with powershell at all and looking for any insight on export data files much simpler or faster.  If anyone has any ideas I would greatly appreciate it.

FYI I know I can pull each ticket at a time, our naming scheme used is INC##### so for example to pull any ticket

Get-SCSMIncident -id "INC10105"

This would pull up this one ticket in powershell.

I don't know all the powershell commands and searching through the library is confusing

If anyone knows a way of how to do something like this pulling tickets in sets that would be helpful.

Get-SCSMIncident -id "INC00001" TO -id "INC00500" | Export-Csv C:\Temp\SCSM-tickets.csv -nti

Or evening pulling data by date.

Apologize for the super long post.  Also if anyone knows how to export tickets in Service Manager Console please let me know too!!!  I searched everywhere and seems like I can't export anything

答:
As stated in my comments, unless the cmdlet Get-SCSMIncident has filtering by DateTime range capabilities, it is unlikely that there is a way around having to go through all the collection, however, there are ways the code could be improved so it can do the filtering faster. A foreach loop (enumeration) loop in addition to an if condition (filtering condition) is much faster than Where-Object.

$startDate = Get-Date -Year 2022 -Month 1 -Day 1
$endDate = Get-Date -Year 2022 -Month 2 -Day 2

$incs = foreach($inc in Get-SCSMIncident)
{
    if($inc.CreatedDate -gt $endDate -or $inc.CreatedDate -lt $startDate)
    {
        # If the Incident's CreatedDate is greater than `$endDate` OR
        # lower than `$startDate` go to the next Incident.
        # In other words, skip this Incident.
        continue
    }

    [pscustomobjct]@{
        ID           = $inc.ID
        Status       = $inc.Status
        Title        = $inc.Title
        Description  = $inc.Description -replace '\r?\n', ' '
        AffectedUser = $inc.AffectedUser
        AssignedTo   = $inc.AssignedTo
        CreatedDate  = $inc.CreatedDate
        TierQueue    = $inc.TierQueue
        Urgency      = $inc.Urgency
        Priority     = $inc.Properity
    }
}

$incs | Export-Csv path/to/exported.csv -NoTypeInformation
```


问:
Why @JsonIgnore annotation doesn't work during deserializing data?
I have a data https://gist.githubusercontent.com/iva-nova-e-katerina/fc1067e971c71a73a0b525a21b336694/raw/954477261bb5ac2f52cee07a8bc45a2a27de1a8c/data2.json a List with seven CheckResultItem elements.
I trying to parse them this way:

```<code>import com.fasterxml.jackson.module.kotlin.readValue
...
val res = restHelper.objectMapper.readValue<List<CheckResultItem>>(text)
</code>```

which gives me the following error:

```<code>com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class com.fmetric.validation.api.Brick] value failed for JSON property upperLevelBricks due to missing (therefore NULL) value for creator parameter upperLevelBricks which is a non-nullable type
 at [Source: (StringReader); line: 1, column: 714] (through reference chain: java.util.ArrayList[0]->com.fmetric.validation.api.checking.CheckResultItem["brick"]->com.fmetric.validation.api.Brick["upperLevelBricks"])

    at com.fasterxml.jackson.module.kotlin.KotlinValueInstantiator.createFromObjectWith(KotlinValueInstantiator.kt:116)
</code>```

There is @JsonIgnore annotation in data class :

```<code>data class Brick(
        val id: UUID?,
        val name: String,
        val type: BrickType,
        val propertyValues: List<ProjectBrickPropertyValue<*>>,

        @JsonIgnore
        val upperLevelBricks: ArrayList<Brick>,
        val downLevelBricks: ArrayList<Brick>,
        var drawingDetails: List<BrickDrawingDetails>?

) {
</code>```

But it seems it doesn't work. Could you explain me what is wrong?

UPD: Also I have tried @JsonIgnoreProperties({"upperLevelBricks"})  class annotation but it doesn't work. My solution was to set a default value

```<code>val upperLevelBricks: ArrayList<Brick> = arrayListOf(),
</code>```

But I think that annotations should work!

答:
Actually, it works, but not the way you think. During deserialization @JsonIgnore ignores the respectful field in JSON, like it wasn't there (but it's doesn't make sense in this case, because it's initially absent in JSON).

In Java, Jackson would've just instantiated class with null value for the absent field (because all object types in Java are nullable, which means they allow the value to be set to null). But in Kotlin, a property should be explicitly marked as nullable (val upperLevelBricks: List<Brick>?) or have a default value (val upperLevelBricks: List<Brick> = emptyList()) so that Jackson could create a class instance in this case.

Note that approach with default value for property won't work (unless you additionally mark it with @JsonIgnore) if this field is present in JSON but explicitly set to null:

{
  ...
  "upperLevelBricks": null,
  ...
}
```
<p>Anyway, if you don't want to change the API of your <code>Brick</code> class you may provide a default value for this field only when it's created during Jackson deserialization (and only if it's absent/<code>null</code> in JSON) via custom deserializer:</p>
<pre class="lang-kotlin prettyprint-override"><code>object EmptyListAsDefault : JsonDeserializer<List<Brick>>() {
    override fun deserialize(jsonParser: JsonParser, context: DeserializationContext): List<Brick> =
        jsonParser.codec.readValue(
            jsonParser,
            context.typeFactory.constructCollectionType(List::class.java, Brick::class.java)
        )

    override fun getNullValue(context: DeserializationContext): List<Brick> = emptyList()
}

data class Brick(
    //...
    @JsonDeserialize(using = EmptyListAsDefault::class)
    val upperLevelBricks: List<Brick>,
    //...
)
</code>```

Body:
I have a data https://gist.githubusercontent.com/iva-nova-e-katerina/fc1067e971c71a73a0b525a21b336694/raw/954477261bb5ac2f52cee07a8bc45a2a27de1a8c/data2.json a List with seven CheckResultItem elements.
I trying to parse them this way:

import com.fasterxml.jackson.module.kotlin.readValue
...
val res = restHelper.objectMapper.readValue<List<CheckResultItem>>(text)

which gives me the following error:

com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class com.fmetric.validation.api.Brick] value failed for JSON property upperLevelBricks due to missing (therefore NULL) value for creator parameter upperLevelBricks which is a non-nullable type
 at [Source: (StringReader); line: 1, column: 714] (through reference chain: java.util.ArrayList[0]->com.fmetric.validation.api.checking.CheckResultItem["brick"]->com.fmetric.validation.api.Brick["upperLevelBricks"])

    at com.fasterxml.jackson.module.kotlin.KotlinValueInstantiator.createFromObjectWith(KotlinValueInstantiator.kt:116)

There is @JsonIgnore annotation in data class :

data class Brick(
        val id: UUID?,
        val name: String,
        val type: BrickType,
        val propertyValues: List<ProjectBrickPropertyValue<*>>,

        @JsonIgnore
        val upperLevelBricks: ArrayList<Brick>,
        val downLevelBricks: ArrayList<Brick>,
        var drawingDetails: List<BrickDrawingDetails>?

) {

But it seems it doesn't work. Could you explain me what is wrong?

UPD: Also I have tried @JsonIgnoreProperties({"upperLevelBricks"})  class annotation but it doesn't work. My solution was to set a default value

val upperLevelBricks: ArrayList<Brick> = arrayListOf(),

But I think that annotations should work!

Body:
Actually, it works, but not the way you think. During deserialization @JsonIgnore ignores the respectful field in JSON, like it wasn't there (but it's doesn't make sense in this case, because it's initially absent in JSON).

In Java, Jackson would've just instantiated class with null value for the absent field (because all object types in Java are nullable, which means they allow the value to be set to null). But in Kotlin, a property should be explicitly marked as nullable (val upperLevelBricks: List<Brick>?) or have a default value (val upperLevelBricks: List<Brick> = emptyList()) so that Jackson could create a class instance in this case.

Note that approach with default value for property won't work (unless you additionally mark it with @JsonIgnore) if this field is present in JSON but explicitly set to null:

{
  ...
  "upperLevelBricks": null,
  ...
}

Anyway, if you don't want to change the API of your Brick class you may provide a default value for this field only when it's created during Jackson deserialization (and only if it's absent/null in JSON) via custom deserializer:

object EmptyListAsDefault : JsonDeserializer<List<Brick>>() {
    override fun deserialize(jsonParser: JsonParser, context: DeserializationContext): List<Brick> =
        jsonParser.codec.readValue(
            jsonParser,
            context.typeFactory.constructCollectionType(List::class.java, Brick::class.java)
        )

    override fun getNullValue(context: DeserializationContext): List<Brick> = emptyList()
}

data class Brick(
    //...
    @JsonDeserialize(using = EmptyListAsDefault::class)
    val upperLevelBricks: List<Brick>,
    //...
)


问:
Firebase CLI not deploying any Cloud Functions
I have an Angular project where I am trying to deploy a single firebase function.

This is what my functions directory looks like:

When I deploy these function with the command firebase deploy --only functions the output looks normal and no errors:

```<code>PS C:\Users\project-directory> firebase deploy --only functions

=== Deploying to 'firebase-project-name'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run build

> build
> tsc

+  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
+  functions: required API cloudfunctions.googleapis.com is enabled
+  functions: required API cloudbuild.googleapis.com is enabled
i  functions: cleaning up build files...

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/project-name/overview
</code>```

src/user/index.ts file with the function I am trying to deploy:

```<code>import functions = require('firebase-functions');
import admin = require('firebase-admin');

// import * as functions from "firebase-functions";
// import * as admin from 'firebase-admin';

const FieldValue = require('firebase-admin').firestore.FieldValue;

const db = admin.firestore();

/**
 * Add user to firestore
 */
export const createProfile = async (userRecord: any) => {
    const uid = userRecord.uid;
    const admin = false;
    const email = userRecord.email;
    const photoURL = userRecord.photoUrl || 'enter shortened url for default image';
    const name = userRecord.displayName || 'New User';
    const spouse = userRecord.spouse || 'TBA';
    const forumUserName = userRecord.forumUserName || 'New Username set by admin';
    const address = userRecord.address || 'TBA';
    const suburb = userRecord.suburb || 'TBA';
    const state = userRecord.state || 'QLD';
    const postCode = userRecord.postCode || '2000';
    const homePhone = userRecord.homePhone || '02 1234 5678';
    const mobilePhone = userRecord.mobilePhone || '0400 123 456';
    const memNum = userRecord.memNum || 123;
    const timestamp = FieldValue.serverTimestamp();
    const memType = userRecord.memType || 'Nominated';
    const memStatus = userRecord.memStatus || `Pending`;
    const isStateCoord = userRecord.isStateCoord || false;
    const stateCoordState = userRecord.stateCoordState || 'QLD';
    //const newUserRef = db.doc(`users/${uid}`)

    // Convert any date to timestamp for consistency

    try {
        return await db
            .collection(`users`)
            .doc(userRecord.uid)
            .set({
                uid: uid,
                email: email,
                photoURL: photoURL,
                fullName: name,
                mDOB: timestamp,
                spouse: spouse,
                sDOB: timestamp,
                forumUserName: forumUserName,
                address: address,
                suburb: suburb,
                state: state,
                postCode: postCode,
                homePhone: homePhone,
                mobilePhone: mobilePhone,
                memNum: memNum,
                memType: memType,
                memStatus: memStatus,
                memDueDate: timestamp,
                lastLoginDate: timestamp,
                joined: timestamp,
                updated: timestamp,
                admin: admin,
                isAdmin: admin,
                isStateCoord: isStateCoord,
                stateCoordState: stateCoordState,
            });
    } catch (message) {
        return console.error(message);
    }
};

exports.authOnCreate = functions.auth.user().onCreate(createProfile);
</code>```

src/index.ts file imports the above file:

```<code>import * as user from './user';
export const createProfile = user.createProfile
</code>```

The issue is that I am not seeing the function appear in the Firebase console.

What am I overlooking?

答:
You have two different export syntaxes in src/user/index.ts:

```<code>export const createProfile = async (userRecord: any) => { /* ... */ }
</code>```
```<code>exports.authOnCreate = functions.auth.user().onCreate(createProfile);
</code>```

Use one, or the other, not both. They are incompatible with each other.

```<code>export const createProfile = async (userRecord: any) => { /* ... */ }
export const authOnCreate = functions.auth.user().onCreate(createProfile);
</code>```

Then in your main src/index.ts, import the Cloud Function export, not the plain function:

```<code>import { authOnCreate } from './user'; // import specific parts for the best performance when transpiled
export const createProfile = authOnCreate;
</code>```

Body:
I have an Angular project where I am trying to deploy a single firebase function.

This is what my functions directory looks like:

When I deploy these function with the command firebase deploy --only functions the output looks normal and no errors:

PS C:\Users\project-directory> firebase deploy --only functions

=== Deploying to 'firebase-project-name'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run build

> build
> tsc

+  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
+  functions: required API cloudfunctions.googleapis.com is enabled
+  functions: required API cloudbuild.googleapis.com is enabled
i  functions: cleaning up build files...

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/project-name/overview

src/user/index.ts file with the function I am trying to deploy:

import functions = require('firebase-functions');
import admin = require('firebase-admin');

// import * as functions from "firebase-functions";
// import * as admin from 'firebase-admin';

const FieldValue = require('firebase-admin').firestore.FieldValue;

const db = admin.firestore();

/**
 * Add user to firestore
 */
export const createProfile = async (userRecord: any) => {
    const uid = userRecord.uid;
    const admin = false;
    const email = userRecord.email;
    const photoURL = userRecord.photoUrl || 'enter shortened url for default image';
    const name = userRecord.displayName || 'New User';
    const spouse = userRecord.spouse || 'TBA';
    const forumUserName = userRecord.forumUserName || 'New Username set by admin';
    const address = userRecord.address || 'TBA';
    const suburb = userRecord.suburb || 'TBA';
    const state = userRecord.state || 'QLD';
    const postCode = userRecord.postCode || '2000';
    const homePhone = userRecord.homePhone || '02 1234 5678';
    const mobilePhone = userRecord.mobilePhone || '0400 123 456';
    const memNum = userRecord.memNum || 123;
    const timestamp = FieldValue.serverTimestamp();
    const memType = userRecord.memType || 'Nominated';
    const memStatus = userRecord.memStatus || `Pending`;
    const isStateCoord = userRecord.isStateCoord || false;
    const stateCoordState = userRecord.stateCoordState || 'QLD';
    //const newUserRef = db.doc(`users/${uid}`)

    // Convert any date to timestamp for consistency

    try {
        return await db
            .collection(`users`)
            .doc(userRecord.uid)
            .set({
                uid: uid,
                email: email,
                photoURL: photoURL,
                fullName: name,
                mDOB: timestamp,
                spouse: spouse,
                sDOB: timestamp,
                forumUserName: forumUserName,
                address: address,
                suburb: suburb,
                state: state,
                postCode: postCode,
                homePhone: homePhone,
                mobilePhone: mobilePhone,
                memNum: memNum,
                memType: memType,
                memStatus: memStatus,
                memDueDate: timestamp,
                lastLoginDate: timestamp,
                joined: timestamp,
                updated: timestamp,
                admin: admin,
                isAdmin: admin,
                isStateCoord: isStateCoord,
                stateCoordState: stateCoordState,
            });
    } catch (message) {
        return console.error(message);
    }
};

exports.authOnCreate = functions.auth.user().onCreate(createProfile);

src/index.ts file imports the above file:

import * as user from './user';
export const createProfile = user.createProfile

The issue is that I am not seeing the function appear in the Firebase console.

What am I overlooking?

Body:
You have two different export syntaxes in src/user/index.ts:

export const createProfile = async (userRecord: any) => { /* ... */ }

exports.authOnCreate = functions.auth.user().onCreate(createProfile);

Use one, or the other, not both. They are incompatible with each other.

export const createProfile = async (userRecord: any) => { /* ... */ }
export const authOnCreate = functions.auth.user().onCreate(createProfile);

Then in your main src/index.ts, import the Cloud Function export, not the plain function:

import { authOnCreate } from './user'; // import specific parts for the best performance when transpiled
export const createProfile = authOnCreate;


答: You must use the function before() from java.util.Date and set the date to compare which a combination of Calendar.settime() function

Title: How can I tell if a date is before a certain time in Java?

Body: For example given a java.util.Date how could I test if the time was before 12.30 PM that day?


问:
Why can't I create a Java Class in Android Studio
I am trying to create a new Java Class in one of my folders in Android Studio. When I right click, and click the option 'new', it offers me the option of creating a new C++ class, but does not offer any option to creating a Java Class.

How do I create a new Java Class?

答: I discovered at least one reason why android studio may not offer you the option to create a new Java Class.  If you have an unresolved gradle build sync issue the option to create a new Java Class may not be offered up as an option by Android Studio. That happened to me using Android Studio 2021.1.1.  The problem went away once I fixed the issue with my gradle.build script.  In my case, I had a dependency that I hadn't resolved properly.  It's a bit odd to see that happen especially since the project was created as a Java Project.  At any rate, there appears to be some dependency on having your gradle build not have any issues before Android Studio can determine that the project is a Java Project. I'm not sure if this problem happens in every circumstance because it was a new empty java library module that I observed that problem and I was trying to add my first class to that module.</p>


问:
Parse txt eliminate header and footer Apache-Hop
I´m trying Apache HOP Desktop and I´m stuck in a pipeline where I have to clean and parse this one column txt. First eliminating header and footer then parsing according to position and lenght.

```<code>name:  Initial_Pos: Lenght:
N1     2            10
N2     12           24
N3     108          30
</code>```

i´m trying to use 'Text File Input' as a transform but no luck. Any suggestions?
Thanks in advance

答:
The text file input transform has a wide variety of options you can use.
Under the content tab you can set the filetype to a fixed with file, add the number of header/footer lines and special things like encoding.
text file input content tab

Then under the fields tab you can set the position and length of each field it has to read.

After a bit of fiddling you should be able to extract the information you need.

Body:
I´m trying Apache HOP Desktop and I´m stuck in a pipeline where I have to clean and parse this one column txt. First eliminating header and footer then parsing according to position and lenght.

name:  Initial_Pos: Lenght:
N1     2            10
N2     12           24
N3     108          30

i´m trying to use 'Text File Input' as a transform but no luck. Any suggestions?
Thanks in advance


问:
git clone hangs forever on github
When I follow point 5 (Test everything out) in the github guide, the ssh command also hangs forever. According to the guide, I should be presented with a message that "Github does not provide shell access". Below is my output from ssh -vT git@github.com</p>

```<code>debug1: Authentication succeeded (publickey).
Authenticated to github.com ([207.97.227.239]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LC_MESSAGES = en_US.UTF-8
debug1: Sending env LC_COLLATE = en_US.UTF-8
debug1: Sending env LANG = da_DK.UTF-8
debug1: Sending env LC_CTYPE = en_US.UTF-8
</code>```

答: Mine dumb case was that, I changed default SSH port in /etc/ssh/ssh_config instead of /etc/ssh/sshd_config

Title: git clone hangs forever on github

Body:
When I follow point 5 (Test everything out) in the github guide, the ssh command also hangs forever. According to the guide, I should be presented with a message that "Github does not provide shell access". Below is my output from ssh -vT git@github.com

debug1: Authentication succeeded (publickey).
Authenticated to github.com ([207.97.227.239]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LC_MESSAGES = en_US.UTF-8
debug1: Sending env LC_COLLATE = en_US.UTF-8
debug1: Sending env LANG = da_DK.UTF-8
debug1: Sending env LC_CTYPE = en_US.UTF-8


问:
What is the point of salt and hashing if database is accessible?
I just learned the concept of hashing ("Hey! don't forget the salt!") and using salt to make the password secured.

Hashing it is a one way encryption (actually not encryption but hashing) so it cannot be reversed engineered. Salting is prefixing or appending randomly created values to the password before hashing 'coz the problem in hashing (just hashing) is, some genius has provided a hash table of words from the dictionary so that they'll just compare the hash from that dictionary to the user's table from the database to login - W-wait? did I say table from the database? So it means somebody can access the database so we have to use salt? If that so, then why would the hacker recover the password if he already has access to the database? If I were him, I'll just get all the details I want from the database, why would I use the key I've stolen from a house to open the door if I can access the house already through the window?

So, why hash? why salt? I don't understand. Please, somebody help me.

Thanks in advance.

Important Note: I'm not against hashing or salting, I just want to clarify things.

答:
To be in possession of the user records from the database does not necessarily mean you have access to the database. Through some leak in the website (hello, SQL injection) you may be able to get access to data you shouldn't have access to without necessarily compromising the whole server. Badly handled backups, shared servers, incompetent or malicious employees may all make that possible.

Also and possibly more importantly, you need to protect your customer's passwords on other sites. People unfortunately reuse their passwords all over the place. If your tiny chat room database gets compromised, people's passwords at their banking sites may be compromised with it.


问:
How to repair corrupt git repository - fatal: Not a git repository?
I looked at many other questions to no avail.

My laptop froze during git reset --hard or git checkout branch. Not sure. After the hard reset I see

```<code>$ git fsck
fatal: not a git repository (or any parent up to mount point /)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
</code>```

I saw that .git/index was an empty file. Deleting it yields no results.

Any ideas how to restore? I have most my stuff pushed to a remote but I prefer to keep my branches and stashes. I have some useful stuff in there and even if I can track most of it remotely, would be hard.

答:
I figured it out. Also my .git/HEAD file was empty. I've put inside it

```<code>ref: refs/heads/master
</code>```

Then I've run (be careful with these, in case you had uncommitted changes, you can copy your modified files safely somewhere else first).

```<code>git reset --hard
git clean -f
</code>```

I found out what the issue is by running strace git status and noticed that it tries to find HEAD file in the directory path. Then it was easy.

P.S. after the fact I see that my branch where I tried to do git reset --hard another_branch is missing. So apparently issue happened while doing reset.

Body:
I looked at many other questions to no avail.

My laptop froze during git reset --hard or git checkout branch. Not sure. After the hard reset I see

$ git fsck
fatal: not a git repository (or any parent up to mount point /)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).

I saw that .git/index was an empty file. Deleting it yields no results.

Any ideas how to restore? I have most my stuff pushed to a remote but I prefer to keep my branches and stashes. I have some useful stuff in there and even if I can track most of it remotely, would be hard.

Body:
I figured it out. Also my .git/HEAD file was empty. I've put inside it

ref: refs/heads/master

Then I've run (be careful with these, in case you had uncommitted changes, you can copy your modified files safely somewhere else first).

git reset --hard
git clean -f

I found out what the issue is by running strace git status and noticed that it tries to find HEAD file in the directory path. Then it was easy.

P.S. after the fact I see that my branch where I tried to do git reset --hard another_branch is missing. So apparently issue happened while doing reset.


问:
Org-mode export to Latex: page break at each section and subsection
I want the pdf document to always have a page break at a section and subsection. I could add

#+latex: \clearpage

before each heading and sub-heading on org-mode. However, I think it makes my org document kind of confusing and visually dirty.

Is there a way to do it all at once, i.e., to force a page break so that all sections and subsections begin always on a new page?

I'd be glad if anyone help me.

答:
Try this:</p>
```<code>#+LATEX_HEADER: \let\oldsection\section
#+LATEX_HEADER: \renewcommand{\section}{\clearpage\oldsection}
#+LATEX_HEADER: \let\oldsubsection\subsection
#+LATEX_HEADER: \renewcommand{\subsection}{\clearpage\oldsubsection}
</code>```

Body:
Try this:

#+LATEX_HEADER: \let\oldsection\section
#+LATEX_HEADER: \renewcommand{\section}{\clearpage\oldsection}
#+LATEX_HEADER: \let\oldsubsection\subsection
#+LATEX_HEADER: \renewcommand{\subsection}{\clearpage\oldsubsection}


问:
Column span in nebula XViewer
I am using using nebula XViewer to display a data in grid format. I have an issue when i am trying to perform column span. Can any one help me to sort out this issue.

Thanks

答:
If i understood your question correctly, you can define your custom Content Provider:

```<code>contentProvider = new CustomXViewerContentProvider();
</code>```

where CustomXViewerContentProvider implements ITreeContentProvider

```<code>public class CustomXViewerContentProvider implements ITreeContentProvider {
</code>```

in this class you can @Override method getChildren, getParent, hasChildren depending on your data model.
With these methods you can create the parent and child hierarchy

Once the content provider has been created you assign it to the xviewer:

```<code>XViewer.setContentProvider (contentProvider );
</code>```

Title: Column span in nebula XViewer

Body:
If i understood your question correctly, you can define your custom Content Provider:

contentProvider = new CustomXViewerContentProvider();

where CustomXViewerContentProvider implements ITreeContentProvider

public class CustomXViewerContentProvider implements ITreeContentProvider {

in this class you can @Override method getChildren, getParent, hasChildren depending on your data model.
With these methods you can create the parent and child hierarchy

Once the content provider has been created you assign it to the xviewer:

XViewer.setContentProvider (contentProvider );


问:
NOT IN Dax equivalent
still very new to DAX and hate it so far. where is the logic?

I have an expression below that creates data for a column based on if the data meets the criteria. What I have is a WORKING example of the opposite of what I'm trying to accomplish. I really, really want to be able to type "NOT IN" but it seems like that is not an option in DAX syntax. So basically, how do I EXCLUDE these values?

```<code>Column =

    IF ( MMP_Dashboards_WMH_PBI[Revenue_Center] IN {"FillRate","CancelRt","NoShowRt","ExamRt"}, MMP_Dashboards_WMH_PBI[NewUnits] )
</code>```

Would love for THIS to work:

```<code>Column =

    IF ( MMP_Dashboards_WMH_PBI[Revenue_Center] NOT IN {"FillRate","CancelRt","NoShowRt","ExamRt"}, MMP_Dashboards_WMH_PBI[NewUnits] )
</code>```

答:
Try this:</p>
```<code>IF ( NOT ( MMP_Dashboards_WMH_PBI[Revenue_Center] IN {"FillRate","CancelRt","NoShowRt","ExamRt"} ), MMP_Dashboards_WMH_PBI[NewUnits] )
</code>```

Title: NOT IN Dax equivalent

Body:
still very new to DAX and hate it so far. where is the logic?

I have an expression below that creates data for a column based on if the data meets the criteria. What I have is a WORKING example of the opposite of what I'm trying to accomplish. I really, really want to be able to type "NOT IN" but it seems like that is not an option in DAX syntax. So basically, how do I EXCLUDE these values?

Column =

    IF ( MMP_Dashboards_WMH_PBI[Revenue_Center] IN {"FillRate","CancelRt","NoShowRt","ExamRt"}, MMP_Dashboards_WMH_PBI[NewUnits] )

Would love for THIS to work:

Column =

    IF ( MMP_Dashboards_WMH_PBI[Revenue_Center] NOT IN {"FillRate","CancelRt","NoShowRt","ExamRt"}, MMP_Dashboards_WMH_PBI[NewUnits] )

Body:
Try this:

IF ( NOT ( MMP_Dashboards_WMH_PBI[Revenue_Center] IN {"FillRate","CancelRt","NoShowRt","ExamRt"} ), MMP_Dashboards_WMH_PBI[NewUnits] )


问:
Tone.js release/stop sampler
EDIT: Update on other attempts. The key bit of the question below is the line sampler.triggerRelease(["A1"], 'now') which is not working. Other things I've tried include:

sampler.releaseAll(Tone.now())

sampler.releaseAll()

sampler.triggerRelease(["A1"], Tone.now())

The relevant part of the Tone.js docs is here.

What won't work is sampler.dispose(), because it essentially disconnects the sampler instrument from the output. But I need to continue using the sampler to retrigger the same note shortly after turning it off.

I'm trying to use a button press to stop the playing of a 'Sampler' note while it's currently playing. I thought that triggering the release phase would do this (as in my code below) but this doesn't seem to have any effect. I've tried lots of methods. This question doesn't answer mine, partly because it's for the 'Polysynth' not the 'Sampler'. Thanks in advance!

const readyOverlay = document.querySelector('#readyOverlay')
readyOverlay.addEventListener('click', async () => {
    readyOverlay.style.display = 'none'
    await Tone.start()

    const sampler = new Tone.Sampler({
        urls: {
            A1: "A1.mp3"
        },
        baseUrl: "https://tonejs.github.io/audio/casio/",
        onload: () => {
            sampler.triggerAttackRelease(["A1"], 5);
        }
    }).toDestination();
    sampler.release = 0
    document.querySelector('#stop').addEventListener('click', () => {
        sampler.triggerRelease(["A1"], 'now')
    })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>        #readyOverlay {
    position: absolute;
    z-index: 9;
    width: 100%;
    height: 100%;
    background: white;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
}</code>```

Press anywhere to start!

    <button id="stop" >stop</button>```

答:
Replacing triggerAttackRelease with just triggerAttack does work:

const readyOverlay = document.querySelector('#readyOverlay')
readyOverlay.addEventListener('click', async () => {
    readyOverlay.style.display = 'none'
    await Tone.start()

    const sampler = new Tone.Sampler({
        urls: {
            A1: "A1.mp3"
        },
        baseUrl: "https://tonejs.github.io/audio/casio/",
        onload: () => {
            sampler.triggerAttack(["A1"]);
        }
    }).toDestination();
    sampler.release = 0;
    document.querySelector('#stop').addEventListener('click', () => {
        sampler.triggerRelease(["A1"]);
    })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>        #readyOverlay {
    position: absolute;
    z-index: 9;
    width: 100%;
    height: 100%;
    background: white;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
}</code>```

Press anywhere to start!

    <button id="stop" >stop</button>```

triggerAttackRelease is just a sequence of triggerAttack and triggerRelease calls. It means you have already scheduled a note release in the onload callback in your initial example.

Tone.js ignores the second release call because sampler has already marked "A1" as released (this if statement makes sure note is released only once after the attack).

Title: Tone.js release/stop sampler

Body:
EDIT: Update on other attempts. The key bit of the question below is the line sampler.triggerRelease(["A1"], 'now') which is not working. Other things I've tried include:

sampler.releaseAll(Tone.now())

sampler.releaseAll()

sampler.triggerRelease(["A1"], Tone.now())

The relevant part of the Tone.js docs is here.

What won't work is sampler.dispose(), because it essentially disconnects the sampler instrument from the output. But I need to continue using the sampler to retrigger the same note shortly after turning it off.

I'm trying to use a button press to stop the playing of a 'Sampler' note while it's currently playing. I thought that triggering the release phase would do this (as in my code below) but this doesn't seem to have any effect. I've tried lots of methods. This question doesn't answer mine, partly because it's for the 'Polysynth' not the 'Sampler'. Thanks in advance!

const readyOverlay = document.querySelector('#readyOverlay')
readyOverlay.addEventListener('click', async () => {
    readyOverlay.style.display = 'none'
    await Tone.start()

    const sampler = new Tone.Sampler({
        urls: {
            A1: "A1.mp3"
        },
        baseUrl: "https://tonejs.github.io/audio/casio/",
        onload: () => {
            sampler.triggerAttackRelease(["A1"], 5);
        }
    }).toDestination();
    sampler.release = 0
    document.querySelector('#stop').addEventListener('click', () => {
        sampler.triggerRelease(["A1"], 'now')
    })
})

        #readyOverlay {
    position: absolute;
    z-index: 9;
    width: 100%;
    height: 100%;
    background: white;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

Press anywhere to start!

    <button id="stop" >stop</button>

Body:
Replacing triggerAttackRelease with just triggerAttack does work:

const readyOverlay = document.querySelector('#readyOverlay')
readyOverlay.addEventListener('click', async () => {
    readyOverlay.style.display = 'none'
    await Tone.start()

    const sampler = new Tone.Sampler({
        urls: {
            A1: "A1.mp3"
        },
        baseUrl: "https://tonejs.github.io/audio/casio/",
        onload: () => {
            sampler.triggerAttack(["A1"]);
        }
    }).toDestination();
    sampler.release = 0;
    document.querySelector('#stop').addEventListener('click', () => {
        sampler.triggerRelease(["A1"]);
    })
})

        #readyOverlay {
    position: absolute;
    z-index: 9;
    width: 100%;
    height: 100%;
    background: white;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

<script src="https://unpkg.com/tone@14.7.77/build/Tone.js"></script>
    <div id="readyOverlay">Press anywhere to start!</div>
    <button id="stop" >stop</button>

triggerAttackRelease is just a sequence of triggerAttack and triggerRelease calls. It means you have already scheduled a note release in the onload callback in your initial example.

Tone.js ignores the second release call because sampler has already marked "A1" as released (this if statement makes sure note is released only once after the attack).


问:
Error bars look huge in R, but not in Excel
I am having an issue with my error bars. they look gigantic in R, but look much more accurate in Excel. Example in R:

Example in Excel:

Code

```<code>Graph = subset(dat,dat$Condition != "z" & dat$Environment != "a")
    Graph %>%
      group_by(Gate = fct_inorder(Gate), Sound, Block) %>%
      summarize(Accuracy = mean(Correct),
                sd = sd(Correct)) %>%
      ggplot(aes(x = Gate, y = Accuracy, color = Sound, group = Sound)) +
      geom_line() +
      geom_errorbar(aes(ymin = Accuracy - sd, ymax = Accuracy + sd,)) +
      scale_y_continuous(labels = scales::percent)+
      facet_wrap(~Block) +
      theme_minimal()
</code>```

Reproducible sample

```<code>        set.seed(42)
    n <- 100
    dat <- data.frame(Participant=1:n,
                      Environment=rep(LETTERS[1:2], n/2),
                      Condition=rep(LETTERS[25:26], n/2),
                      Gate= sample(1:5, n, replace=TRUE),
                      Block= sample(1:2,n, replace=TRUE),
                      Sound=rep(LETTERS[3:4], n/2),
                      Correct=sample(0:1, n, replace=TRUE)
)
</code>```

答:
As the other answer points out, you should be looking at the standard error (sd/sqrt(n)) rather than the standard deviation. Here is  a slightly more compact way to run your code, using stat_summary() to compute the summary statistics (mean_cl_normal normally plots the Normal 95% CIs, mult = 1 tells it to plot ±1 SE instead).  If you want the end-caps on your error bars to be narrower, use the width= argument to adjust them.

(My plot still has large error bars but I assume that's because of the size of your reproducible example.)

library(tidyverse)
filter(dat, Condition != "z" & Environment != "a") %>%
  mutate(across(Gate = fct_inorder)) %>%
  ggplot(aes(Gate, Correct, colour = Sound)) +
  stat_summary(geom="line", fun = mean) +
  stat_summary(geom="errorbar", fun.data = \(x) mean_cl_normal(x, mult=1)) +
  facet_wrap(~ Block)
```

Body:
I am having an issue with my error bars. they look gigantic in R, but look much more accurate in Excel. Example in R:

Example in Excel:

Code

Graph = subset(dat,dat$Condition != "z" & dat$Environment != "a")
    Graph %>%
      group_by(Gate = fct_inorder(Gate), Sound, Block) %>%
      summarize(Accuracy = mean(Correct),
                sd = sd(Correct)) %>%
      ggplot(aes(x = Gate, y = Accuracy, color = Sound, group = Sound)) +
      geom_line() +
      geom_errorbar(aes(ymin = Accuracy - sd, ymax = Accuracy + sd,)) +
      scale_y_continuous(labels = scales::percent)+
      facet_wrap(~Block) +
      theme_minimal()

Reproducible sample

        set.seed(42)
    n <- 100
    dat <- data.frame(Participant=1:n,
                      Environment=rep(LETTERS[1:2], n/2),
                      Condition=rep(LETTERS[25:26], n/2),
                      Gate= sample(1:5, n, replace=TRUE),
                      Block= sample(1:2,n, replace=TRUE),
                      Sound=rep(LETTERS[3:4], n/2),
                      Correct=sample(0:1, n, replace=TRUE)
)


问:
Javascript Property with three dots (...)
I have a problem with code I am supposed to work with. I found a syntax I am not familiar with and I have trouble googling the documentation:

```<code>export const Something = class Something {
    constructor(someObject = {}) {
        this.someObject = {...Something.someObjectDefaultAsStaticMethod,...someThing};
    };
// The rest of the class
};
</code>```

I have problems understanding what the three dots (...) in front of the parameter do. And "dots in parameter javascript" is a bad search term. Can someone help me, maybe tell me what this syntax is actually called or just directly link me to documentation?

答:
You can use "..." in an object. In this example below, "...data" gets 'name: "John", age: 24':

const data= { name: "John", age: 24 };

const newData = {
  ...data, // Here
  sex: "Male"
}

console.log(newData);```
</div>
</div>
</p>
<p>This is the result:</p>
<pre class="lang-js prettyprint-override"><code>{ name: "John", age: 24, sex: "Male" }
</code>```

This is other example with "...data[key]" to add "id" to each object in an array:

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: Number(key),
    ...data[key] // Here
  }

  newData.push(obj);
}

console.log(newData);```
</div>
</div>
</p>
<p>This is the result:</p>
<pre class="lang-js prettyprint-override"><code>[
  { id: 0, name: "John", age: 24 },
  { id: 1, name: 'Marry', age: 18 },
  { id: 2, name: 'Tom', age: 15 }
]
</code>```

Body:
I have a problem with code I am supposed to work with. I found a syntax I am not familiar with and I have trouble googling the documentation:

export const Something = class Something {
    constructor(someObject = {}) {
        this.someObject = {...Something.someObjectDefaultAsStaticMethod,...someThing};
    };
// The rest of the class
};

I have problems understanding what the three dots (...) in front of the parameter do. And "dots in parameter javascript" is a bad search term. Can someone help me, maybe tell me what this syntax is actually called or just directly link me to documentation?

Body:
You can use "..." in an object. In this example below, "...data" gets 'name: "John", age: 24':

const data= { name: "John", age: 24 };

const newData = {
  ...data, // Here
  sex: "Male"
}

console.log(newData);

This is the result:

{ name: "John", age: 24, sex: "Male" }

This is other example with "...data[key]" to add "id" to each object in an array:

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: Number(key),
    ...data[key] // Here
  }

  newData.push(obj);
}

console.log(newData);

This is the result:

[
  { id: 0, name: "John", age: 24 },
  { id: 1, name: 'Marry', age: 18 },
  { id: 2, name: 'Tom', age: 15 }
]


问:
Doubly circular linked list strange behaviour
I use the following code snippet to add an element to the back of my doubly circular linked list.

```<code>typedef struct node
{
    int nb;
    struct node *prev;
    struct node *next;
} st_node;

void add_back(st_node *origin, st_node *node)
{
    st_node *tmp;

    if (!origin || !node)
        exit(1);
    tmp = origin;
    while (tmp->next != origin)
        tmp = tmp->next;
    tmp->next = node;
    node->prev = tmp;
    node->next = origin;
    origin->prev = node;
}
</code>```

Then I print my list with the folling function :

```<code>void    printer(st_node *origin)
{
    st_node *node;

    node = origin;
    while (node->next != origin)
    {
        printf("%d\n", node->nb);
        node = node->next;
    }
    printf("%d\n", node->nb);
}
</code>```

I got the origin value with printf and then random values in a loop. I don't know what to do and I realized origin->prev = node; was causing the problem inside the add_back function but I don't know why.

Here's the main:

```<code>int main(int ac, char **av)
{
    st_node     *stack;
    int         i;

    if (ac <= 2)
        return (1);
    stack = create_element(atoi(av[1]));
    i = 2;
    while (i < ac)
        add_back(stack, create_element(atoi(av[i++])));
    printf("Stack:\n");
    printer(stack);
}
</code>```
```<code>st_node *create_element(int nb)
{
    st_node *element;
    element = malloc(sizeof(st_node *));
    element->nb = nb;
    element->next = element;
    element->prev = element;
    return (element);
}

</code>```

答:
Your create_element() function is wrong.  It does not allocate enough memory for each node.  This ...

```<code>    st_node *element;
    element = malloc(sizeof(st_node *));
</code>```

... should be ...

```<code>    st_node *element;
    element = malloc(sizeof(st_node));
</code>```

... or, better ...

```<code>    st_node *element;
    element = malloc(sizeof(*element));
</code>```

With that correction, and adding a closing brace to main(), your program works for me.

Body:
I use the following code snippet to add an element to the back of my doubly circular linked list.

typedef struct node
{
    int nb;
    struct node *prev;
    struct node *next;
} st_node;

void add_back(st_node *origin, st_node *node)
{
    st_node *tmp;

    if (!origin || !node)
        exit(1);
    tmp = origin;
    while (tmp->next != origin)
        tmp = tmp->next;
    tmp->next = node;
    node->prev = tmp;
    node->next = origin;
    origin->prev = node;
}

Then I print my list with the folling function :

void    printer(st_node *origin)
{
    st_node *node;

    node = origin;
    while (node->next != origin)
    {
        printf("%d\n", node->nb);
        node = node->next;
    }
    printf("%d\n", node->nb);
}

I got the origin value with printf and then random values in a loop. I don't know what to do and I realized origin->prev = node; was causing the problem inside the add_back function but I don't know why.

Here's the main:

int main(int ac, char **av)
{
    st_node     *stack;
    int         i;

    if (ac <= 2)
        return (1);
    stack = create_element(atoi(av[1]));
    i = 2;
    while (i < ac)
        add_back(stack, create_element(atoi(av[i++])));
    printf("Stack:\n");
    printer(stack);
}

st_node *create_element(int nb)
{
    st_node *element;
    element = malloc(sizeof(st_node *));
    element->nb = nb;
    element->next = element;
    element->prev = element;
    return (element);
}

Body:
Your create_element() function is wrong.  It does not allocate enough memory for each node.  This ...

    st_node *element;
    element = malloc(sizeof(st_node *));

... should be ...

    st_node *element;
    element = malloc(sizeof(st_node));

... or, better ...

    st_node *element;
    element = malloc(sizeof(*element));

With that correction, and adding a closing brace to main(), your program works for me.


问:
How can build independent dll's that depend on the same source?
I am building a few different C# libraries that both depend on a single C# file we'll call Dep.cs, and these dll's need to be used together in a Unity project. I'd like to set up these projects in the following way:

The C# libraries can be built independently of one another using Visual Studio

C# libraries (i.e. dll's) can be imported into a Unity project without conflicting symbols

The C# library projects (i.e. the source code for each library via git submodule for example) can be imported into a Unity project without conflicting sources.

I've solved (1) by including Dep.cs in each library project that requires it, though this causes issue with (2). And I've solved (3) by putting the dependency in a folder like Dependencies~ so that Unity ignores the file (this way no duplicate classes are found).

I'm having trouble solving (2) however. I thought I'd be able to add Dep.cs as reference in the VS solution but This doesn't seem to work. I've heard of Assembly References but I am not sure if they do what I need.

答:
You can use "Add File as Link" from Visual Studio "Add Existing File" screen. It also works well with git submodule, just place Dep.cs anywhere in a parent folder or in the solution's root directory.

To get the same result you can also directly edit the .csproj file and add a compile instruction:

```<code><ItemGroup>
  <Compile Include="..\..\Path\To\YourFile.cs" Link="YourFile.cs" />
</ItemGroup>
</code>```

This method solves all the issues you mentioned.

Body:
You can use "Add File as Link" from Visual Studio "Add Existing File" screen. It also works well with git submodule, just place Dep.cs anywhere in a parent folder or in the solution's root directory.

To get the same result you can also directly edit the .csproj file and add a compile instruction:

<ItemGroup>
  <Compile Include="..\..\Path\To\YourFile.cs" Link="YourFile.cs" />
</ItemGroup>

This method solves all the issues you mentioned.


问:
How to use Get request with DTO in NestJs?
I am trying to write a function to handle the Get request, here is my code:

```<code>  @Get('/find')
  async find(@Param() testname: NameDto) {
    console.log(testname.name);
  }
</code>```

Here is my dto:

```<code>export class NameDto {
  @IsString()
  @ApiProperty({ required: true })
  name: string;
}
</code>```

I am using the Swagger to test this API :

When I input a signle a , I got the following response:

```<code>{
  "statusCode": 400,
  "message": [
    "name must be a string"
  ],
  "error": "Bad Request"
}
</code>```

here are more input example :

They all return the same response.

Then, I change the find function like this with @Query:

```<code>  @Get('/find')
  async find(@Query() testname: NameDto) {
    console.log(testname.name);
  }
</code>```

here is my input :

I can have the 200-ok response.
Here is another example:

I enter 1 as the input, and I still can get the 200 response. The dto is not working as expected.

Am I missing something?
Any help would be appreciate.

答:
you are sending nothing in param

you can read in Nestjs document

try this one:

@Get('/find/:testname')
  async find(@Param('testname') testname: NameDto) {
    console.log(testname.name);
  }```

Body:
I am trying to write a function to handle the Get request, here is my code:

  @Get('/find')
  async find(@Param() testname: NameDto) {
    console.log(testname.name);
  }

Here is my dto:

export class NameDto {
  @IsString()
  @ApiProperty({ required: true })
  name: string;
}

I am using the Swagger to test this API :

When I input a signle a , I got the following response:

{
  "statusCode": 400,
  "message": [
    "name must be a string"
  ],
  "error": "Bad Request"
}

here are more input example :

They all return the same response.

Then, I change the find function like this with @Query:

  @Get('/find')
  async find(@Query() testname: NameDto) {
    console.log(testname.name);
  }

here is my input :

I can have the 200-ok response.
Here is another example:

I enter 1 as the input, and I still can get the 200 response. The dto is not working as expected.

Am I missing something?
Any help would be appreciate.