小嗷兮

文章 评论 浏览 26

小嗷兮 2025-02-16 22:53:37

简短且显而易见的答案是 vc.name nil ,它是一个隐含的未包装的可选。

问题是“为什么要零?,假设其他一切都是正确的,并且您已经连接了出口?

原因是在加载视图时将视图实例化并分配给出口属性。当 loadView 显式调用时,或者如果有对视图控制器的 view 属性的引用,则会发生这种情况。在您说 vc.name.text = ... 之前,这些事情都没有发生。

直接从另一个对象引用视图控制器的视图是违反封装的。它与详细信息控制器的实现细节紧密地耦合了您的表观视图控制器。

您会注意到,您的其他属性, selectionImage detail vctitle 就是这样。简单属性。视图控制器在 viewDidload 中使用它们。

您应该对自己的计数做同样的事情:

class DetailViewController: UIViewController {
    @IBOutlet var imageView: UIImageView!
    @IBOutlet var name: UILabel!
    
    var selectedImage : String?
    var detailVCTitle: String?
    var counter = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = detailVCTitle
        navigationItem.largeTitleDisplayMode = .never
        if let imageToLoad = selectedImage {
            imageView.image = UIImage(named: imageToLoad)
        }
        name.text = "It was shown \(counter) times"
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as?
        DetailViewController {
        counter += 1
        vc.selectedImage = pictures[indexPath.row]
        navigationController?.pushViewController(vc, animated: true)
        vc.detailVCTitle = "Picture \(indexPath.row + 1) of \(pictures.count)"
        vc.counter = counter
    }
}

现在,您的表观视图只是知道您的细节视图想要一个计数器。它不知道,也不需要知道如何使用该计数器。您的详细视图控制器可以在多个位置或不同的方式使用它,具体取决于其价值或任何内容...

The short, and obvious, answer is that vc.name is nil and it is an implicitly unwrapped optional.

The question is "Why is it nil?, assuming that everything else is correct and you have connected the outlet?"

The reason is that views are instantiated and assigned to the outlet properties when the view is loaded. This occurs when loadView is called explicitly or it occurs implicitly if there is a reference to a view controller's view property. Neither of these things have occurred before you say vc.name.text=... so you get a nil crash.

Referencing a view controller's views directly from another object is an encapsulation violation; it tightly couples your table view controller with an implementation detail of the detail view controller.

You will note that your other properties, selectedImage and detailVCTitle are just that; simple properties. The view controller does something with them in viewDidLoad.

You should do the same thing with your count:

class DetailViewController: UIViewController {
    @IBOutlet var imageView: UIImageView!
    @IBOutlet var name: UILabel!
    
    var selectedImage : String?
    var detailVCTitle: String?
    var counter = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = detailVCTitle
        navigationItem.largeTitleDisplayMode = .never
        if let imageToLoad = selectedImage {
            imageView.image = UIImage(named: imageToLoad)
        }
        name.text = "It was shown \(counter) times"
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as?
        DetailViewController {
        counter += 1
        vc.selectedImage = pictures[indexPath.row]
        navigationController?.pushViewController(vc, animated: true)
        vc.detailVCTitle = "Picture \(indexPath.row + 1) of \(pictures.count)"
        vc.counter = counter
    }
}

Now, your table view simply knows that your detail view wants a counter. It doesn't know, nor need to know, how that counter is used. Your detail view controller can use it in multiple places or in different ways depending on its value or whatever...

为什么我出乎意料地发现了零零。在我的应用中崩溃?

小嗷兮 2025-02-16 21:29:38

@Adyson我按照您的建议做了,当我有机会时,我详细介绍了错误。
这个问题简单地被证明是“ $ Captcharesult”中缺少的“ A”。

非常感谢您为我带来这么远,我非常感谢您的努力和建议,因为我无法自己实现这一目标。

如果对其他任何人都有帮助,则下面是工作的PHP代码(我还设法在功能上标记了在不勾选recaptacha的情况下提交表单的功能,然后在弹出窗口中扔出错误消息,然后将您发送给您完整的表格再次尝试):

''''

<?php

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    require './src/Exception.php';
    require './src/PHPMailer.php';
    require './src/SMTP.php';

class CaptchaTest
{
  private $captchaSecretKey = 'XXXXX';

  //call this function and pass in the response value from the form in order to get Google to test the captcha. Will return true or false.
  public function testCaptchaResponse($captchaResponse)
  {
    //generate URL as per Google's documentation
    $createGoogleUrl = 'https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($this->captchaSecretKey).'&response='.urlencode($captchaResponse);
    //send request to Google and get back the raw JSON response.
    $verifyRecaptcha = $this->sendHttpRequest($createGoogleUrl);
    //decode the JSON into a PHP array so we can examine individual data items within it
    $decodeGoogleResponse = json_decode($verifyRecaptcha,true);

    //examine the response from Google and return true/false accordingly.
    if($decodeGoogleResponse['success'] == 1) return true;
    else return false;
  }
  
  //send a HTTP request to the specified URL using cURL
  private function sendHttpRequest($url)
  {
    $ch = curl_init();
    $getUrl = $url;
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $getUrl);
    curl_setopt($ch, CURLOPT_TIMEOUT, 80);
    
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
  }
}


//check form button and captcha field were submitted
if(isset($_POST['submit'], $_POST['g-recaptcha-response'])) {

  //test the captcha
  $cTest = new CaptchaTest();
  $captchaResult = $cTest->testCaptchaResponse($_POST['g-recaptcha-response']); }

  if ($captchaResult == true) {

        $mail = new PHPMailer(true);
        $mail->SMTPDebug = 0;
        $mail->Host = 'in-v3.mailjet.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'XXXXX';
        $mail->Password = 'XXXXX';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->setFrom($_POST['email'], $_POST['name']);
        $mail->addAddress('XXXXX');
        $mail->addReplyTo($_POST['email'], $_POST['name']);
        

//Attach multiple files one by one
    for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
     $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
     $filename = $_FILES['userfile']['name'][$ct];
       if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
          $mail->addAttachment($uploadfile, $filename);
        } }

        $mail->isHTML(true);
        $mail->Subject = 'Website Enquiry';
        $mail->Body = "<p>You received an enquiry from:</p>
    <b>Name:</b>  $_POST[name]<br><br>
    <b>Company:</b>  $_POST[company]<br><br>
    <b>Phone Number:</b>  $_POST[phone]<br><br>
    <b>E-Mail:</b> $_POST[email]<br><br>
    <b>Message:</b> $_POST[message]";
            
  
        try {
             $mail->send();
header('Location: thank.html');
exit('Redirecting you to thank.html');
        } catch (Exception $e) {
            echo "Your message could not be sent! PHPMailer Error: {$mail->ErrorInfo}";
        }
        
    } 
    
else
  {
    

    echo "<script>
          alert('Captcha Error!, returning you to the Contact page')
          history.back()
          </script>";
}

    
?>

'''

道歉,如果最终代码不那么优雅,那么我在php方面仍然处于次级级别...

@ADyson I did as you suggested and had a detailed look for errors when I got the opportunity.
The problem simply proved to be a missing 'a' in '$captchaResult'.

Thanks so much for getting me this far, I'm extremely grateful for your efforts and advice, as there's no way I could have achieved this on my own.

If it's helpful for anyone else, the working PHP code is below (I've also managed to tag on the feature where submitting the form without ticking the reCaptacha throws up an error message in a pop-up box, then sends you back to the completed form to try again):

'''

<?php

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    require './src/Exception.php';
    require './src/PHPMailer.php';
    require './src/SMTP.php';

class CaptchaTest
{
  private $captchaSecretKey = 'XXXXX';

  //call this function and pass in the response value from the form in order to get Google to test the captcha. Will return true or false.
  public function testCaptchaResponse($captchaResponse)
  {
    //generate URL as per Google's documentation
    $createGoogleUrl = 'https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($this->captchaSecretKey).'&response='.urlencode($captchaResponse);
    //send request to Google and get back the raw JSON response.
    $verifyRecaptcha = $this->sendHttpRequest($createGoogleUrl);
    //decode the JSON into a PHP array so we can examine individual data items within it
    $decodeGoogleResponse = json_decode($verifyRecaptcha,true);

    //examine the response from Google and return true/false accordingly.
    if($decodeGoogleResponse['success'] == 1) return true;
    else return false;
  }
  
  //send a HTTP request to the specified URL using cURL
  private function sendHttpRequest($url)
  {
    $ch = curl_init();
    $getUrl = $url;
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $getUrl);
    curl_setopt($ch, CURLOPT_TIMEOUT, 80);
    
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
  }
}


//check form button and captcha field were submitted
if(isset($_POST['submit'], $_POST['g-recaptcha-response'])) {

  //test the captcha
  $cTest = new CaptchaTest();
  $captchaResult = $cTest->testCaptchaResponse($_POST['g-recaptcha-response']); }

  if ($captchaResult == true) {

        $mail = new PHPMailer(true);
        $mail->SMTPDebug = 0;
        $mail->Host = 'in-v3.mailjet.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'XXXXX';
        $mail->Password = 'XXXXX';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->setFrom($_POST['email'], $_POST['name']);
        $mail->addAddress('XXXXX');
        $mail->addReplyTo($_POST['email'], $_POST['name']);
        

//Attach multiple files one by one
    for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
     $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
     $filename = $_FILES['userfile']['name'][$ct];
       if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
          $mail->addAttachment($uploadfile, $filename);
        } }

        $mail->isHTML(true);
        $mail->Subject = 'Website Enquiry';
        $mail->Body = "<p>You received an enquiry from:</p>
    <b>Name:</b>  $_POST[name]<br><br>
    <b>Company:</b>  $_POST[company]<br><br>
    <b>Phone Number:</b>  $_POST[phone]<br><br>
    <b>E-Mail:</b> $_POST[email]<br><br>
    <b>Message:</b> $_POST[message]";
            
  
        try {
             $mail->send();
header('Location: thank.html');
exit('Redirecting you to thank.html');
        } catch (Exception $e) {
            echo "Your message could not be sent! PHPMailer Error: {$mail->ErrorInfo}";
        }
        
    } 
    
else
  {
    

    echo "<script>
          alert('Captcha Error!, returning you to the Contact page')
          history.back()
          </script>";
}

    
?>

'''

Apologies if the final code isn't as elegant as it could be, I'm still at sub-Dummy level when it comes to PHP...

PHP Mailer 6联系表发送消息和附件,但Recaptcha V2被忽略

小嗷兮 2025-02-16 00:54:44

SED 可以工作

$ sed s'/\[\([^][]*\)/[\n\1\n/g;s/]/&\n/' input_file
[
"12000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx12000",
[
"127.0.0.1:12000"
]
]

vim

:s/\[\([^][]*\)/[\r\1\r/g|s/]/&\r/

This sed may work

$ sed s'/\[\([^][]*\)/[\n\1\n/g;s/]/&\n/' input_file
[
"12000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx12000",
[
"127.0.0.1:12000"
]
]

Or vim

:s/\[\([^][]*\)/[\r\1\r/g|s/]/&\r/

如何使用vim命令与SED进行括号? - 除非第一个字符发行

小嗷兮 2025-02-15 13:23:51

您已经在收件箱标签中提出了手表请求,
当收件箱中收到消息时,您可能会收到通知,第二个可能是在读取或移动消息时。

另外,请确保您没有发表多个手表请求

该手表方法(订阅有关用户收件箱的通知)应该是不应该的。尽管情况很广泛,但如果您同时发送多个手表请求,则最终获得了多个订阅,这意味着该用户的每个事件都会多次将其推向您的端点!

确保停止上一个手表请求或如果您保存了手表响应,则手表响应包括到期时间使用该响应,以使下一个手表请求

You have made a watch request in INBOX label,
you might be receiving notification when a message is received in the inbox and the second maybe when the message is read or moved.

also make sure you are not making multiple watch requests

The watch method (which subscribes to notifications regarding a user’s inbox) is supposed to be idempotent. While that’s broadly the case, if you send multiple watch requests simultaneously, you end up with multiple subscriptions, meaning every event for that user gets pushed to your endpoint multiple times!

make sure to stop the previous watch request or if you are saving the watch response, the watch response includes an expiration time use that to make the next watch request

收到新电子邮件时Gmail API/Pub子发送2条消息

小嗷兮 2025-02-15 07:03:09

您不需要此代码的懒惰。您可以用懒惰实现它,但是您必须重新编写代码。

const FetchProducts = (input) => {
    
    const { data, loading, error } =  useQuery(GET_PRODUCTS_QUERY, {
      variables: {name: input}
    })

    
    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error :(</p>;
  return products.results.map(({ id, name }) => (
    <div key={id}>
      <p>
        {name}
      </p>
    </div>
  ));
  }; 

You don't need a LazyQuery with this code. You can implement it with a LazyQuery but you'll have to rework your code.

const FetchProducts = (input) => {
    
    const { data, loading, error } =  useQuery(GET_PRODUCTS_QUERY, {
      variables: {name: input}
    })

    
    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error :(</p>;
  return products.results.map(({ id, name }) => (
    <div key={id}>
      <p>
        {name}
      </p>
    </div>
  ));
  }; 

当用户将文本键入输入文本字段时

小嗷兮 2025-02-14 20:58:25

您可以注册自己的错误处理程序 php中。例如,在这些晦涩的情况下,将所有错误倾倒到文件中可能会为您提供帮助。请注意,无论您的当前 noreferrer“> error_reporting 设置为。非常基本的示例:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');

You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');

如何在PHP中获取有用的错误消息?

小嗷兮 2025-02-14 18:27:23

您可以尝试这样的事情不确定是否会对您有所帮助。

如果您知道有多少人,那么您可以给他们一个动态名称,例如 example_1 其中示例_ 1 是静态的特定个人的 id ,您可以在@noam在评论中所说的JavaScript的帮助下使用。

var dynamic_number = 2;
var elm_name = "example_" +dynamic_number;
console.log(elm_name);
var elements = document.getElementsByName( elm_name );
var value = elements[0].getAttribute( 'id' );
alert("Time for individule " + dynamic_number +" is: "+ value);
<div class="example" name="example_1" id="130" >
<div class="example" name="example_2" id="240" >
<div class="example" name="example_3" id="15" >
<div class="example" name="example_4" id="870" >
<div class="example" name="example_5" id="640" >

You can try something like this not sure about this will help you or not.

If you know how many individuals are then you can give them a dynamic name something like example_1 where example_ and 1 is static with that you can fetch a specific individual's id then you can use with the help of JavaScript as @Noam said in the comments.

var dynamic_number = 2;
var elm_name = "example_" +dynamic_number;
console.log(elm_name);
var elements = document.getElementsByName( elm_name );
var value = elements[0].getAttribute( 'id' );
alert("Time for individule " + dynamic_number +" is: "+ value);
<div class="example" name="example_1" id="130" >
<div class="example" name="example_2" id="240" >
<div class="example" name="example_3" id="15" >
<div class="example" name="example_4" id="870" >
<div class="example" name="example_5" id="640" >

将HTML ID分配给SASS变量为值

小嗷兮 2025-02-14 13:34:05

首先,删除&lt; br&gt; &lt; div id =“ page”&gt; ,因为此(可能)破坏了Bootstrap容器&gt; row&gt; row&gt; col布局。

<div class="container-fluid" id="container">
    <br />
    <div id="page" style="color: #373737">
        <div class="row justify-content-around" id="selectFieldsDiv">

然后,因为datepicker位于bootstrap容器内部,并以适当的行和列启动布局,以将表单/datepicker包裹在此类中:

<div id="addTaskFieldsDiv" class="row">
    <div id="addTaskFieldsDiv" class="col">
        <form>
            <label for="birthday">Birthday:</label>
            <input type="date" id="birthday" name="birthday" />
        </form>
    </div>
</div>

请确保在整个文档中重复此模式(容器&gt; row&gt; col),并查看是否适合您的需要。

First of all remove the <br> and <div id="page"> because this (might) breaks the Bootstrap container>row>col layout.

<div class="container-fluid" id="container">
    <br />
    <div id="page" style="color: #373737">
        <div class="row justify-content-around" id="selectFieldsDiv">

Then because the datepicker is located within the Bootstrap container start the layout with a proper row and column to wrap the form/datepicker in like so:

<div id="addTaskFieldsDiv" class="row">
    <div id="addTaskFieldsDiv" class="col">
        <form>
            <label for="birthday">Birthday:</label>
            <input type="date" id="birthday" name="birthday" />
        </form>
    </div>
</div>

Make sure to repeat this pattern (container>row>col) throughout the document and see if fits your needs.

如何在容器(bootstrap)的另一个顶部显示DIV?

小嗷兮 2025-02-14 05:52:29

呼叫.spop(true)有效,但我相信,如果您继续向动画的方向滚动,从而延长动画的持续时间,可能会引起中间动画的问题。另外,您可以执行以下操作以确保动画在执行另一个动画之前完成。

(function(jQuery) {
        let position = '';
        let scrolling = false;
        let animationDuration = 1200;
        jQuery(window).bind('mousewheel', function(event){
            if (event.originalEvent.wheelDelta > 0) {
                // scroll up
                if (scrolling || position === 'top')
                    return;

                //console.log("scroll up");
                scrolling = true; //Prevents any scrolling when scrolling is active
                position = 'top'; //Prevents scrolling up when already at the top
                jQuery('html,body').animate(
                    {
                        scrollTop: jQuery("#top").offset().top
                    },
                    animationDuration,
                    'linear',
                    function () {
                        scrolling = false; //After the animation is complete, set scroling to false
                    },
                );
            }
            else {
                // scroll down

                if (scrolling || position === 'bottom')
                    return;

                //console.log("scroll down");
                scrolling = true;
                position = 'bottom';
                jQuery('html,body').animate(
                    {
                        scrollTop: jQuery("#bottom").offset().top
                    },
                    animationDuration,
                    'linear',
                    function () {
                        scrolling = false;
                    },
                );
            }
        });
    })($);
<div id="top" style="height:100vh;background-color: #2196f3;"></div>
<div id="bottom" style="height:100vh;background-color: #009688;"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

Calling .stop(true) works, but I believe it might cause issues mid animation if you keep scrolling in the direction of the animation, extending the duration of the animation. Alternatively you can do the following to ensure the animation completes before doing another animation.

(function(jQuery) {
        let position = '';
        let scrolling = false;
        let animationDuration = 1200;
        jQuery(window).bind('mousewheel', function(event){
            if (event.originalEvent.wheelDelta > 0) {
                // scroll up
                if (scrolling || position === 'top')
                    return;

                //console.log("scroll up");
                scrolling = true; //Prevents any scrolling when scrolling is active
                position = 'top'; //Prevents scrolling up when already at the top
                jQuery('html,body').animate(
                    {
                        scrollTop: jQuery("#top").offset().top
                    },
                    animationDuration,
                    'linear',
                    function () {
                        scrolling = false; //After the animation is complete, set scroling to false
                    },
                );
            }
            else {
                // scroll down

                if (scrolling || position === 'bottom')
                    return;

                //console.log("scroll down");
                scrolling = true;
                position = 'bottom';
                jQuery('html,body').animate(
                    {
                        scrollTop: jQuery("#bottom").offset().top
                    },
                    animationDuration,
                    'linear',
                    function () {
                        scrolling = false;
                    },
                );
            }
        });
    })($);
<div id="top" style="height:100vh;background-color: #2196f3;"></div>
<div id="bottom" style="height:100vh;background-color: #009688;"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

滚动动画的行为不稳定地上下,可能的输入滞后在鼠标轮上

小嗷兮 2025-02-13 17:38:59

对于Python 3.9+:

out = [t | i for t, i in zip(title, image)]
print(out)

打印:

[
    {"title": "Title Text One", "image": "happy.jpg"},
    {"title": "Title Text Two", "image": "smile.jpg"},
    {"title": "Title Text Three", "image": "angry.jpg"},
]

或:

out = [{**t, **i} for t, i in zip(title, image)]

For Python 3.9+:

out = [t | i for t, i in zip(title, image)]
print(out)

Prints:

[
    {"title": "Title Text One", "image": "happy.jpg"},
    {"title": "Title Text Two", "image": "smile.jpg"},
    {"title": "Title Text Three", "image": "angry.jpg"},
]

Or:

out = [{**t, **i} for t, i in zip(title, image)]

如何将两个命令纳入一个命令?

小嗷兮 2025-02-13 11:54:34

静态添加到 int n; 时说:“此 n 在所有程序执行中持续存在。”它没有说“此 n 是整个程序中唯一的 n 。”在 void deleteelement(int arr [],int n,int index)中,参数 n 被声明了从 n 中的 main 中。

但是,即使没有使用名称 n 声明参数, n 内部声明 main 在任何其他功能中都看不到。要在整个程序中使用相同的 n ,您需要声明 int n; static int n; 在任何功能之外,在任何函数之外,之前的任何位置使用 n 的第一个功能,并且您不需要声明任何其他 n

那可能会为您解决这个问题。但是,将外部标识符用于对象是不好的做法。相反,您应在 Main 中使用 int n; 和修改 deleteelement ,以便它提供 main 带有更新的值。它可以通过返回 int 而不是 void 来做到这一点,或者您可以修改 deleteelement 将指针用于 int 而不是通过制作参数 int *n 而不是 int 。然后,您必须将其用作*n 而不是 n 的函数。

Adding static to int n; says “This n persists through all of program execution.” it does not say “This n is the only n in the whole program.” Where a parameter n is declared, as in void deleteElement(int arr[], int n, int index), that creates an n different from the n in main.

However, even if no parameter is declared with the name n, an n declared inside main is not visible in any other function. To use the same n throughout the program, you need to declare int n; or static int n; outside of any function, anywhere before the first function that uses n, and you need to not declare any other n.

That would likely solve this problem for you. However, it is bad practice to use external identifiers for objects. Instead, you should use int n; in main and modify deleteElement so that it provides main with the updated value. It could do this by returning an int instead of void, or you could modify deleteElement to take a pointer to an int instead of taking an int, by making the parameter int *n. Then you would have to use it inside the function as *n instead of n.

静态关键字在C(Visual Studio)中不起作用

小嗷兮 2025-02-13 01:41:37

正如汉斯指出的那样,问题源于被捕获的变量。

由于我们的变量正在迭代,因此lambda表达式无法正确捕获它,因此给出了上面提到的错误。

以下是更新的buildactions函数,具有临时变量,该变量具有临时I的值,即使迭代器更改分配和执行之间的值,临时变量仍然允许lambda表达式在lambda表达式中使用。功能正确。

public void BuildActions(TestHUDPanel panel)
{
    for (int i = 0; i < panel.buttonActions.Count; i++)
    {
        var tempIDX = i;
        GameObject panelObject = Instantiate(functionPrefab);
        panelObject.transform.SetParent(functionPanel.transform);
        Button button = panelObject.GetComponent<Button>();
        panelObject.GetComponentInChildren<TextMeshProUGUI>().text = panel.buttonLabels[i];
        button.onClick.AddListener(() => panel.buttonActions[tempIDX]());
    }
}

我还将将文档链接到lambda表达式中的捕获变量以进行进一步说明。

捕获外部变量和lambda表达式中的变量范围

As Hans pointed out, the issue was stemming from a captured variable.

As our variable was iterating up, the lambda expression wasn't correctly capturing it and was therefore giving the error mentioned above.

Below is the updated BuildActions function, with a temporary variable which holds the value of i temporarily to allow it to be used within the lambda expression, even if the iterator changes value between assignment and execution, the temporary variable will still allow the lambda expression to function correctly.

public void BuildActions(TestHUDPanel panel)
{
    for (int i = 0; i < panel.buttonActions.Count; i++)
    {
        var tempIDX = i;
        GameObject panelObject = Instantiate(functionPrefab);
        panelObject.transform.SetParent(functionPanel.transform);
        Button button = panelObject.GetComponent<Button>();
        panelObject.GetComponentInChildren<TextMeshProUGUI>().text = panel.buttonLabels[i];
        button.onClick.AddListener(() => panel.buttonActions[tempIDX]());
    }
}

I'll also link the documentation for captured variables in lambda expressions for further explanation.

Capture of outer variables and variable scope in lambda expressions

单击范围异常的参数,该按钮调用一个不使用索引的函数

小嗷兮 2025-02-12 20:16:36

您的闪亮应用程序是冗长的。

您应该为要完成的工作创建一个函数,然后将这些功能传递给渲染函数。

我通过创建两个功能来清理您的代码,一个用于绘图 myPlot ,一个用于文本 myText 。我使用胶水包来插入字符串,并通过 RenderPrint 使用数据。

library(tidyverse)
library(shiny)
library(glue)

myPlot <- function(data, x, y, ptsize, axsize) {

  p <- ggplot(data = data, aes(x = .data[[x]], y = .data[[y]])) +
    geom_point(size = ptsize) +
    theme(axis.title = element_text(size = axsize))
  
 
  
  return(p)
}

myText <- function(data, x, y, ptsize, axsize) {
  
    myString <- glue("ggplot(data = data, aes(x = {x}, y = {y})) +
    geom_point(size = {ptsize}) +
    theme(axis.title = element_text(size = {axsize}))")
    
    
    return(myString)
}



ui = fluidPage(
  titlePanel("Explore the Iris Data"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput("species", label = "Choose Species",
                  choices = c(unique(as.character(iris$Species)), "All_species")),
      selectInput("trait1", label = "Choose Trait1",
                  choices = colnames(iris)[1:4]),
      selectInput("trait2", label = "Choose Trait2",
                  choices = colnames(iris)[1:4]),
      selectInput("theme_Choice", label = "Theme", 
                  choices = c("Default", "Classic", "Black/White")),
      sliderInput("pt_size",
                  label = "Point size", 
                  min = 0.5, max = 10,
                  value = .4),
      sliderInput("axis_sz",
                  label = "Axis title size", 
                  min = 8, max = 30,
                  value = 1)
    ),
    
    mainPanel(
      plotOutput("Species_plot"),
      verbatimTextOutput("code1"),
      verbatimTextOutput("code2")
    )
  )
  
)

server <- function(input,output) {
  
  data <- reactive(iris)
  
  output$Species_plot <- renderPlot({
    myPlot(data(), input$trait1, input$trait2, input$pt_size, input$axis_sz )
  })
  
  output$code1 <- renderPrint({
    myText(data(), input$trait1, input$trait2, input$pt_size, input$axis_sz )
  })
  
}

shinyApp(ui, server)

Your shiny app is verbose.

You should create a function for what you're trying to accomplish and then pass those functions to the render functions.

I cleaned up your code by creating two functions, one for the plot myPlot and one for the text myText. I used the glue package to interpolate the string and the data the be used by renderPrint.

library(tidyverse)
library(shiny)
library(glue)

myPlot <- function(data, x, y, ptsize, axsize) {

  p <- ggplot(data = data, aes(x = .data[[x]], y = .data[[y]])) +
    geom_point(size = ptsize) +
    theme(axis.title = element_text(size = axsize))
  
 
  
  return(p)
}

myText <- function(data, x, y, ptsize, axsize) {
  
    myString <- glue("ggplot(data = data, aes(x = {x}, y = {y})) +
    geom_point(size = {ptsize}) +
    theme(axis.title = element_text(size = {axsize}))")
    
    
    return(myString)
}



ui = fluidPage(
  titlePanel("Explore the Iris Data"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput("species", label = "Choose Species",
                  choices = c(unique(as.character(iris$Species)), "All_species")),
      selectInput("trait1", label = "Choose Trait1",
                  choices = colnames(iris)[1:4]),
      selectInput("trait2", label = "Choose Trait2",
                  choices = colnames(iris)[1:4]),
      selectInput("theme_Choice", label = "Theme", 
                  choices = c("Default", "Classic", "Black/White")),
      sliderInput("pt_size",
                  label = "Point size", 
                  min = 0.5, max = 10,
                  value = .4),
      sliderInput("axis_sz",
                  label = "Axis title size", 
                  min = 8, max = 30,
                  value = 1)
    ),
    
    mainPanel(
      plotOutput("Species_plot"),
      verbatimTextOutput("code1"),
      verbatimTextOutput("code2")
    )
  )
  
)

server <- function(input,output) {
  
  data <- reactive(iris)
  
  output$Species_plot <- renderPlot({
    myPlot(data(), input$trait1, input$trait2, input$pt_size, input$axis_sz )
  })
  
  output$code1 <- renderPrint({
    myText(data(), input$trait1, input$trait2, input$pt_size, input$axis_sz )
  })
  
}

shinyApp(ui, server)

是否有更有效的方法可以用r Shiny编程GGPLOT?

小嗷兮 2025-02-12 17:00:25

我能够使用以下语法解决此问题:

graph = Graph('neo4j://localhost:7687', user="neo4j", password="999")

但是,我现在在以下块上遇到问题:

empty_db_query = """
MATCH(n) DETACH
DELETE(n)
"""
tx = graph.begin(autocommit=True)
tx.evaluate(empty_db_query)

对于py2neo的较新版本,graph.begin参数将readOnly = f取代而不是autocommit = true,但是无论如何,我现在有一个错误:

    ServiceUnavailable                        Traceback (most recent call last)
/home/myname/Project1/graph_import.ipynb Cell 13' in <cell line: 6>()
      1 empty_db_query = """
      2     MATCH(n) DETACH
      3     DELETE(n)
      4     """
----> 6 tx = graph.begin(readonly=False)
      7 tx.evaluate(empty_db_query)

File ~/.local/lib/python3.8/site-packages/py2neo/database.py:351, in Graph.begin(self, readonly)
    340 def begin(self, readonly=False,
    341           # after=None, metadata=None, timeout=None
    342           ):
    343     """ Begin a new :class:`~py2neo.Transaction`.
    344 
    345     :param readonly: if :py:const:`True`, will begin a readonly
   (...)
    349     removed. Use the 'auto' method instead.*
    350     """
--> 351     return Transaction(self, autocommit=False, readonly=readonly,
    352                        # after, metadata, timeout
    353                        )

File ~/.local/lib/python3.8/site-packages/py2neo/database.py:915, in Transaction.__init__(self, graph, autocommit, readonly)
    913     self._ref = None
    914 else:
--> 915     self._ref = self._connector.begin(self.graph.name, readonly=readonly,
    916                                       # after, metadata, timeout
    917                                       )
    918 self._readonly = readonly
    919 self._closed = False

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1357, in Connector.begin(self, graph_name, readonly)
   1345 def begin(self, graph_name, readonly=False,
   1346           # after=None, metadata=None, timeout=None
   1347           ):
   1348     """ Begin a new explicit transaction.
   1349 
   1350     :param graph_name:
   (...)
   1355     :raises Failure: if the server signals a failure condition
   1356     """
-> 1357     cx = self._acquire(graph_name)
   1358     try:
   1359         return cx.begin(graph_name, readonly=readonly,
   1360                         # after=after, metadata=metadata, timeout=timeout
   1361                         )

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1111, in Connector._acquire(self, graph_name, readonly)
   1109     return self._acquire_ro(graph_name)
   1110 else:
-> 1111     return self._acquire_rw(graph_name)

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1203, in Connector._acquire_rw(self, graph_name)
   1199 # TODO: exit immediately if the server/cluster is in readonly mode
   1201 while True:
-> 1203     ro_profiles, rw_profiles = self._get_profiles(graph_name, readonly=False)
   1204     if rw_profiles:
   1205         # There is at least one writer, so collect the pools
   1206         # for those writers. In all implementations to date,
   1207         # a Neo4j cluster will only ever contain at most one
   1208         # writer (per database). But this algorithm should
   1209         # still survive if that changes.
   1210         pools = [pool for profile, pool in list(self._pools.items())
   1211                  if profile in rw_profiles]

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1016, in Connector._get_profiles(self, graph_name, readonly)
   1014         rt.wait_until_updated()
   1015 else:
-> 1016     self.refresh_routing_table(graph_name)

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1064, in Connector.refresh_routing_table(self, graph_name)
   1062                 cx.release()
   1063     else:
-> 1064         raise ServiceUnavailable("Cannot connect to any known routers")
   1065 finally:
   1066     rt.set_not_updating()

ServiceUnavailable: Cannot connect to any known routers

感谢解决此问题的任何帮助。谢谢你!

I was able to resolve this with the following syntax:

graph = Graph('neo4j://localhost:7687', user="neo4j", password="999")

However, I am now having an issue with the following block:

empty_db_query = """
MATCH(n) DETACH
DELETE(n)
"""
tx = graph.begin(autocommit=True)
tx.evaluate(empty_db_query)

For the newer version of py2neo, the graph.begin argument takes readonly = F instead of autocommit = True, but in any case, I have this error now:

    ServiceUnavailable                        Traceback (most recent call last)
/home/myname/Project1/graph_import.ipynb Cell 13' in <cell line: 6>()
      1 empty_db_query = """
      2     MATCH(n) DETACH
      3     DELETE(n)
      4     """
----> 6 tx = graph.begin(readonly=False)
      7 tx.evaluate(empty_db_query)

File ~/.local/lib/python3.8/site-packages/py2neo/database.py:351, in Graph.begin(self, readonly)
    340 def begin(self, readonly=False,
    341           # after=None, metadata=None, timeout=None
    342           ):
    343     """ Begin a new :class:`~py2neo.Transaction`.
    344 
    345     :param readonly: if :py:const:`True`, will begin a readonly
   (...)
    349     removed. Use the 'auto' method instead.*
    350     """
--> 351     return Transaction(self, autocommit=False, readonly=readonly,
    352                        # after, metadata, timeout
    353                        )

File ~/.local/lib/python3.8/site-packages/py2neo/database.py:915, in Transaction.__init__(self, graph, autocommit, readonly)
    913     self._ref = None
    914 else:
--> 915     self._ref = self._connector.begin(self.graph.name, readonly=readonly,
    916                                       # after, metadata, timeout
    917                                       )
    918 self._readonly = readonly
    919 self._closed = False

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1357, in Connector.begin(self, graph_name, readonly)
   1345 def begin(self, graph_name, readonly=False,
   1346           # after=None, metadata=None, timeout=None
   1347           ):
   1348     """ Begin a new explicit transaction.
   1349 
   1350     :param graph_name:
   (...)
   1355     :raises Failure: if the server signals a failure condition
   1356     """
-> 1357     cx = self._acquire(graph_name)
   1358     try:
   1359         return cx.begin(graph_name, readonly=readonly,
   1360                         # after=after, metadata=metadata, timeout=timeout
   1361                         )

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1111, in Connector._acquire(self, graph_name, readonly)
   1109     return self._acquire_ro(graph_name)
   1110 else:
-> 1111     return self._acquire_rw(graph_name)

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1203, in Connector._acquire_rw(self, graph_name)
   1199 # TODO: exit immediately if the server/cluster is in readonly mode
   1201 while True:
-> 1203     ro_profiles, rw_profiles = self._get_profiles(graph_name, readonly=False)
   1204     if rw_profiles:
   1205         # There is at least one writer, so collect the pools
   1206         # for those writers. In all implementations to date,
   1207         # a Neo4j cluster will only ever contain at most one
   1208         # writer (per database). But this algorithm should
   1209         # still survive if that changes.
   1210         pools = [pool for profile, pool in list(self._pools.items())
   1211                  if profile in rw_profiles]

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1016, in Connector._get_profiles(self, graph_name, readonly)
   1014         rt.wait_until_updated()
   1015 else:
-> 1016     self.refresh_routing_table(graph_name)

File ~/.local/lib/python3.8/site-packages/py2neo/client/__init__.py:1064, in Connector.refresh_routing_table(self, graph_name)
   1062                 cx.release()
   1063     else:
-> 1064         raise ServiceUnavailable("Cannot connect to any known routers")
   1065 finally:
   1066     rt.set_not_updating()

ServiceUnavailable: Cannot connect to any known routers

Appreciate any help in resolving this. Thank you!

PY2NEO问题:ConnectionUnavailable:无法打开连接到Connection Profile(&#x27; bolt:// localhost:7687&#x27;)

小嗷兮 2025-02-12 14:58:22

我将总结

作者 “ rel =“ nofollow noreferrer”>@angular-builders 当前正在v14支持,PR链接:

要暂时解决问题,您可以删除此文件夹:

  • Node_modules \ @gangular-builders \ \ @gangular-builders \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Custom-webpack \ node_modules

如果使用纱线插头和播放:

  • 您可以使用纱线分辨率来处理它,但强烈建议您等待V14兼容版本的正式版本。

I will sum up the thread mentioned in @R. Richards' comment.

Author of @angular-builders is currently working on v14 support, PR link:

To temporarily fix the problem, you can delete this folder:

  • node_modules\ @angular-builders\custom-webpack\node_modules

If using yarn plug and play:

  • You can work it around with Yarn resolutions, but highly recommemded to wait for the official release of v14 compatible version.

Angular Migration V13使用 @Angular-Builders/custom-webpack到V14

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文