悲凉≈

文章 评论 浏览 28

悲凉≈ 2025-02-20 19:14:16

考虑以下代码:

//The character array to store the string characters
char[] charArr = new char[range];

//Get the string
System.out.println("Please enter the characters: ");
String string = in.nextLine();

//Copy the string to the character array one letter at a time
for(int t = 0; t < string.length(); t++){
    charArr[t] = string.charAt(t); 
}

请注意,我们如何使用单个字符串存储输入 String string = in.nextline(); ,我们不需要字符串数组。一旦有字符串,我们就可以一次将一个字符传输到字符数组中。

如果要处理多个字符串以存储在字符串数组 string [] string = new String [range]; 中,那么我们可以使用嵌套循环:

Scanner in = new Scanner(System.in);
int range = 0;


System.out.print("How many strings do you want to process?");
range = Integer.parseInt(in.nextLine());

String[] string = new String[range];
for(int t = 0; t < range; t++){
    //We need a new char array for each input string
    char[] charArr = new char[range];

    //Get the text string
    System.out.println("Please enter the characters: ");
    string[t] = in.nextLine();

    //Copy the string to the character array one letter at a time
    for(int i = 0; i < string[t].length(); i++){
        charArr[i] = string[t].charAt(i); 
    }
    //Print the character array here or add it to an array of arrays...
    //...
}

Consider the following code:

//The character array to store the string characters
char[] charArr = new char[range];

//Get the string
System.out.println("Please enter the characters: ");
String string = in.nextLine();

//Copy the string to the character array one letter at a time
for(int t = 0; t < string.length(); t++){
    charArr[t] = string.charAt(t); 
}

Note how we use a single string to store the input String string = in.nextLine();, we don't need a string array. Once we have the string we can transfer the characters one at a time into the character array.

If you want to process multiple strings to store in a string array String[] string = new String[range]; then we can use a nested loop:

Scanner in = new Scanner(System.in);
int range = 0;


System.out.print("How many strings do you want to process?");
range = Integer.parseInt(in.nextLine());

String[] string = new String[range];
for(int t = 0; t < range; t++){
    //We need a new char array for each input string
    char[] charArr = new char[range];

    //Get the text string
    System.out.println("Please enter the characters: ");
    string[t] = in.nextLine();

    //Copy the string to the character array one letter at a time
    for(int i = 0; i < string[t].length(); i++){
        charArr[i] = string[t].charAt(i); 
    }
    //Print the character array here or add it to an array of arrays...
    //...
}

将输入在字符串阵列上传输到char数组

悲凉≈ 2025-02-20 17:38:59

使用链接器来帮助诊断错误,

大多数现代链接器都包含一个详细的选项,该选项在不同程度上打印出来;

  • 链接调用(命令行),
  • 链接阶段中包含哪些库的数据,
  • 库的位置,
  • 所使用的搜索路径。

对于GCC和Clang;您通常会在命令行中添加 -v -wl, - derbose -v -wl,-v 。可以在此处找到更多细节;

对于MSVC,/verbose (特别是/verbose:lib )被添加到链接命令行。

Use the linker to help diagnose the error

Most modern linkers include a verbose option that prints out to varying degrees;

  • Link invocation (command line),
  • Data on what libraries are included in the link stage,
  • The location of the libraries,
  • Search paths used.

For gcc and clang; you would typically add -v -Wl,--verbose or -v -Wl,-v to the command line. More details can be found here;

For MSVC, /VERBOSE (in particular /VERBOSE:LIB) is added to the link command line.

什么是未定义的参考/未解决的外部符号错误,我该如何修复?

悲凉≈ 2025-02-20 17:17:56

Intro

首先您有一个字符串。 JSON不是数组,对象或数据结构。 json 是一种基于文本的序列化格式 - 所以一个花式字符串,但仍然只是一个字符串。使用 json_decode() 将其解码。

 $data = json_decode($json);

在其中您可能会发现:

这些是JSON中可以编码的内容。或更准确地说,这些是可以在JSON中编码的事物的PHP版本。

他们没有什么特别的。它们不是“ JSON对象”或“ JSON数组”。您已经解码了JSON-您现在拥有基本的日常php类型

对象将是 stdclass 的实例a href =“ https://stackoverflow.com/questions/931407/what-is-stdclass-in-php”> generic事情这并不重要。


访问对象属性

您访问 properties 这些对象之一与任何其他对象的公共非静态属性相同,例如 $ object-&gt;属性

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

访问阵列元素

您以其他任何数组的方式访问其中一个阵列的元素,例如。 rel =“ noreferrer”> $ array [0]

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

foreach 迭代。

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

玻璃
撒巧克力

内置阵列函数。


访问嵌套项目

对象的属性和数组的元素可能是更多对象和/或数组 - 您只需继续像往常一样继续访问其属性和成员,例如 $ object-&gt;数组[0] - &gt; etc

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

传递 true 作为第二个参数to json_decode()

您要这样做,而不是对象,您将获得关联数组 - 带有键字符串的数组。同样,您像往常一样访问其元素,例如 $ array ['key']

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

访问关联数组项目

将JSON 对象解码为关联PHP数组时,您可以使用

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

语法

键'foo'的值是'foo value'
关键“ bar”的值是“ bar value”
密钥“ baz”的价值是“ baz value'


不知道如何构建数据

读取文档,无论您从中获得了json。

查看JSON-您可以看到Curly Brackets {} 期望对象,您可以看到Square Brackets [] 期望一个数组。

用a print_r()

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

:告诉您您有对象的位置,有数组的位置以及其成员的名称和值。

如果您只能在迷路之前就已经走得太远了,请走那么远,然后用 print_r() 击中

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

这个方便的交互式JSON Explorer

将问题分解成更容易缠绕头的碎片。


json_decode()返回 null

这发生了,因为要么:

  1. JSON完全由此组成, null
  2. JSON无效 - 检查 JSON_LAST_ERROR_MSG 或通过 jsonlint
  3. 它包含嵌套超过512级深的元素。可以通过将整数作为第三个参数传递给 json_decode() >。

如果您需要更改最大深度,则可能解决了错误的问题。找出为什么您要获得如此深厚的数据(例如,您要查询的正在生成JSON的服务有一个错误),并使其不发生。


对象属性名称包含一个特殊字符

有时您会有一个包含连字符> - 或在sign @code>@的对象属性名称在字面标识符中使用。相反,您可以在卷曲括号中使用字符串文字来解决它。

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

如果您有一个整数作为属性,请参见:如何访问对象属性名称像整数一样?作为参考。


有人将JSON放入您的JSON

这很荒谬,但发生了 - JSON在您的JSON中编码为字符串。解码,像往常一样访问字符串,解码 ,并最终达到您需要的内容。

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

数据不适合内存

如果您的JSON太大,无法 JSON_DECODE()立即处理变得棘手。请参阅:


如何排序

请参阅:参考:在php 中对数组和数据进行排序和数据的所有基本方法。

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:


How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

如何通过PHP从JSON中提取和访问数据?

悲凉≈ 2025-02-20 10:31:53

如果您只想获得所有总销售额,则可以使用一个元。 此方法不按订单状态检查。

function get_total_sales_by_product_id( $atts ) {
    return get_post_meta($atts['id'], 'total_sales', true);
}
add_shortcode('sales', 'get_total_sales_by_product_id');

要按订单状态列表获得总销售

function get_total_sales_by_product_id( $atts ){

    $atts = shortcode_atts( array(
        'id' => ''), $atts );
      
    $product_id = $atts['id'];

    if(empty($product_id)) return;

    //Add remove order statuses 
    $order_status = array( 'wc-completed', 'wc-processing' );

    global $wpdb;
    
    $order_ids = $wpdb->get_col("
        SELECT order_items.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as order_items
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
        AND order_items.order_item_type = 'line_item'
        AND order_item_meta.meta_key = '_product_id'
        AND order_item_meta.meta_value = '$product_id'
    ");
    
    $unique_order_ids = array_unique($order_ids);
    
    $total_sales = 0;
    foreach ($unique_order_ids as $order_id) {
        $order = wc_get_order($order_id);
        foreach ($order->get_items() as $item_key => $item ) {  
            if ($item->get_product()->get_id() == $product_id) {
                $total_sales = $total_sales +  $item->get_quantity();
            }
        }
    }
    
    return $total_sales;
}
add_shortcode('sales', 'get_total_sales_by_product_id');

If you just want to get all total sales there is a meta that you can use. This method doesnt check by order statuses.

function get_total_sales_by_product_id( $atts ) {
    return get_post_meta($atts['id'], 'total_sales', true);
}
add_shortcode('sales', 'get_total_sales_by_product_id');

To get total sales by list of order statuses try this

function get_total_sales_by_product_id( $atts ){

    $atts = shortcode_atts( array(
        'id' => ''), $atts );
      
    $product_id = $atts['id'];

    if(empty($product_id)) return;

    //Add remove order statuses 
    $order_status = array( 'wc-completed', 'wc-processing' );

    global $wpdb;
    
    $order_ids = $wpdb->get_col("
        SELECT order_items.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as order_items
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
        AND order_items.order_item_type = 'line_item'
        AND order_item_meta.meta_key = '_product_id'
        AND order_item_meta.meta_value = '$product_id'
    ");
    
    $unique_order_ids = array_unique($order_ids);
    
    $total_sales = 0;
    foreach ($unique_order_ids as $order_id) {
        $order = wc_get_order($order_id);
        foreach ($order->get_items() as $item_key => $item ) {  
            if ($item->get_product()->get_id() == $product_id) {
                $total_sales = $total_sales +  $item->get_quantity();
            }
        }
    }
    
    return $total_sales;
}
add_shortcode('sales', 'get_total_sales_by_product_id');

在WooCommerce短码中显示产品ID的总收入

悲凉≈ 2025-02-20 07:47:15

您添加了 Action 作为空白的表单标签中

<form action="" enctype="multipart/form-data" method="post" id="form">

添加适当的URL名称在表单标签中

<form action="{% url 'post_url_name' %}" enctype="multipart/form-data" method="post" id="form">

You added action as blank in form tag

<form action="" enctype="multipart/form-data" method="post" id="form">

add appropriate url name in form tag

<form action="{% url 'post_url_name' %}" enctype="multipart/form-data" method="post" id="form">

提交表格后,django未收到后端的任何请求

悲凉≈ 2025-02-20 01:29:51

通过使用附加 http客户端的方法解决了我的问题:

$ad_account_id = env("AD_ACCOUNT_ID");
$access_token = env("ACCESS_TOKEN");
$image = $request->file('image');

$response = Http::attach('filename', file_get_contents($image), 'image.jpg')
    ->post('https://graph.facebook.com/v14.0/act_' . $ad_account_id . '/adimages',
        [
            'access_token' => $access_token
        ]
    );

dd(json_decode($response->body()));

Solved my problem by using attach method of HTTP client:

$ad_account_id = env("AD_ACCOUNT_ID");
$access_token = env("ACCESS_TOKEN");
$image = $request->file('image');

$response = Http::attach('filename', file_get_contents($image), 'image.jpg')
    ->post('https://graph.facebook.com/v14.0/act_' . $ad_account_id . '/adimages',
        [
            'access_token' => $access_token
        ]
    );

dd(json_decode($response->body()));

提供的图像文件无效。请再次检查您的图像路径。 Facebook Graph API错误

悲凉≈ 2025-02-19 18:38:48
$calendar['Monday'] = [ 'Otto Monday', 'Anna Monday' ];
$calendar['Tuesday'] = [ 'Fritz Tuesday' ];
$calendar['Wednesday'] = [];
$calendar['Thursday'] = [ 'Christine Thursday', 'More Thursday', 'Third Thursday' ];
$calendar['Friday'] = [];
$calendar['Saturday'] = [ 'Otto Saturday' ];
$calendar['Sunday'] = [ 'Otto Sunday' ];

$countOfRows = max(array_map(fn($item) => count($item), $calendar));

for ($index = 0; $index < $countOfRows; $index++) {
  foreach ($calendar as $day => $items) {
    $rows[$index][$day] = ( array_key_exists($index, $items) ) ? $items[$index] : '';
  }
}

print_r($rows);

输出:

Array
(
    [0] => Array
        (
            [Monday] => Otto Monday
            [Tuesday] => Fritz Tuesday
            [Wednesday] => 
            [Thursday] => Christine Thursday
            [Friday] => 
            [Saturday] => Otto Saturday
            [Sunday] => Otto Sunday
        )

    [1] => Array
        (
            [Monday] => Anna Monday
            [Tuesday] => 
            [Wednesday] => 
            [Thursday] => More Thursday
            [Friday] => 
            [Saturday] => 
            [Sunday] => 
        )

    [2] => Array
        (
            [Monday] => 
            [Tuesday] => 
            [Wednesday] => 
            [Thursday] => Third Thursday
            [Friday] => 
            [Saturday] => 
            [Sunday] => 
        )

)

然后可以像这样生成HTML:

$thead = '<thead><tr>';
foreach(array_keys($calendar) as $day) {
  $thead .= "<th>$day</th>";
}
$thead .= '</tr></thead>';

$tbody = '<tbody>';
foreach($rows as $row) {
  $tbody .= "<tr>";
  foreach($row as $value) {
    $tbody .= "<td>$value</td>";
  }
  $tbody .= "</tr>";
}

$table = "<table>$thead$tbody</table>";

echo $table;
$calendar['Monday'] = [ 'Otto Monday', 'Anna Monday' ];
$calendar['Tuesday'] = [ 'Fritz Tuesday' ];
$calendar['Wednesday'] = [];
$calendar['Thursday'] = [ 'Christine Thursday', 'More Thursday', 'Third Thursday' ];
$calendar['Friday'] = [];
$calendar['Saturday'] = [ 'Otto Saturday' ];
$calendar['Sunday'] = [ 'Otto Sunday' ];

$countOfRows = max(array_map(fn($item) => count($item), $calendar));

for ($index = 0; $index < $countOfRows; $index++) {
  foreach ($calendar as $day => $items) {
    $rows[$index][$day] = ( array_key_exists($index, $items) ) ? $items[$index] : '';
  }
}

print_r($rows);

Output:

Array
(
    [0] => Array
        (
            [Monday] => Otto Monday
            [Tuesday] => Fritz Tuesday
            [Wednesday] => 
            [Thursday] => Christine Thursday
            [Friday] => 
            [Saturday] => Otto Saturday
            [Sunday] => Otto Sunday
        )

    [1] => Array
        (
            [Monday] => Anna Monday
            [Tuesday] => 
            [Wednesday] => 
            [Thursday] => More Thursday
            [Friday] => 
            [Saturday] => 
            [Sunday] => 
        )

    [2] => Array
        (
            [Monday] => 
            [Tuesday] => 
            [Wednesday] => 
            [Thursday] => Third Thursday
            [Friday] => 
            [Saturday] => 
            [Sunday] => 
        )

)

And the HTML can then be generated like this:

$thead = '<thead><tr>';
foreach(array_keys($calendar) as $day) {
  $thead .= "<th>$day</th>";
}
$thead .= '</tr></thead>';

$tbody = '<tbody>';
foreach($rows as $row) {
  $tbody .= "<tr>";
  foreach($row as $value) {
    $tbody .= "<td>$value</td>";
  }
  $tbody .= "</tr>";
}

$table = "<table>$thead$tbody</table>";

echo $table;

多维阵列每天作为HTML表条目

悲凉≈ 2025-02-19 05:02:30

您在代码中调用两个函数:

upper_limit = int(input('Give me an upper limit:'))
guess(upper_limit)

computer_guess(100)

会导致两个功能运行。如果您想运行其中一个,只需编写 If ,然后询问必须运行哪一个:

print("computer or user? 1.computer 2. user")
if int(input()) == 1:
    computer_guess(100)
else:
    upper_limit = int(input('Give me an upper limit:'))
    guess(upper_limit)

完成代码:

import random

def guess(x):
    random_number = random.randint(1, x)
    guess = 0
    while guess != random_number:
        guess = int(input(f'Guess a number between 1 and {x}:'))
        if guess < random_number:
            print('Sorry, guess again. Too low.')
        elif guess > random_number:
            print('Sorry, guess again. Too high.')
    
    print(f'You guessed it bro, it was {random_number}')

def computer_guess(x):
    low = 1
    high = x
    feedback = ''
    while feedback != 'c':
        if low != high:
            guess = random.randint(low, high)
        else:
            guess = low # could also be high b/c low = high
        feedback = input(f'Is {guess} too high (H), too low (L), or correct (C)?').lower()
        if feedback == 'h':
            high = guess - 1
        elif feedback == 'l': 
            low = guess + 1

    print(f'The computer guessed your number, {guess}, correctly')

print("computer or user? 1.computer 2. user")
if int(input()) == 1:
   computer_guess(100)
else:
    upper_limit = int(input('Give me an upper limit:'))
    guess(upper_limit)

You call both function in your code:

upper_limit = int(input('Give me an upper limit:'))
guess(upper_limit)

and

computer_guess(100)

That causes both of them to run. If you want to run one of them, simply write an if and ask which one must run:

print("computer or user? 1.computer 2. user")
if int(input()) == 1:
    computer_guess(100)
else:
    upper_limit = int(input('Give me an upper limit:'))
    guess(upper_limit)

complete code:

import random

def guess(x):
    random_number = random.randint(1, x)
    guess = 0
    while guess != random_number:
        guess = int(input(f'Guess a number between 1 and {x}:'))
        if guess < random_number:
            print('Sorry, guess again. Too low.')
        elif guess > random_number:
            print('Sorry, guess again. Too high.')
    
    print(f'You guessed it bro, it was {random_number}')

def computer_guess(x):
    low = 1
    high = x
    feedback = ''
    while feedback != 'c':
        if low != high:
            guess = random.randint(low, high)
        else:
            guess = low # could also be high b/c low = high
        feedback = input(f'Is {guess} too high (H), too low (L), or correct (C)?').lower()
        if feedback == 'h':
            high = guess - 1
        elif feedback == 'l': 
            low = guess + 1

    print(f'The computer guessed your number, {guess}, correctly')

print("computer or user? 1.computer 2. user")
if int(input()) == 1:
   computer_guess(100)
else:
    upper_limit = int(input('Give me an upper limit:'))
    guess(upper_limit)

我的代码有2个功能,我只想运行其中1个功能

悲凉≈ 2025-02-18 21:22:42

我会努力以下:

import re
import pandas

txt="""
[tab]e|------------------------------------------------------------------------|\r
\nB|----------3------5-------3----------------------------------------------|\r
\nG|---2-4---------------4----------4-2-0-----------------------------------|\r
\nD|---------------------------------------0---------------0-0--------------|\r
\nA|-----------------------------------------------------2------------------|\r
\nE|------------------------------------------------------------------------"""
pattern=r"(?<=e\|)[^|]*(?=\|%s)"%"\r"

matches=re.findall(pattern,txt)
dataframe=pandas.DataFrame([matches])

I would go for the following:

import re
import pandas

txt="""
[tab]e|------------------------------------------------------------------------|\r
\nB|----------3------5-------3----------------------------------------------|\r
\nG|---2-4---------------4----------4-2-0-----------------------------------|\r
\nD|---------------------------------------0---------------0-0--------------|\r
\nA|-----------------------------------------------------2------------------|\r
\nE|------------------------------------------------------------------------"""
pattern=r"(?<=e\|)[^|]*(?=\|%s)"%"\r"

matches=re.findall(pattern,txt)
dataframe=pandas.DataFrame([matches])

用正则提取标签数据

悲凉≈ 2025-02-18 11:54:03

您的主页课很好。 Homecontroller类需要一些更改。
我已经纠正了,并且按预期工作正常。代码在下面给出。

class HomeController extends GetxController {
  var selectedtIndex = 0.obs;
  var appBartitle = "".obs;

  @override
  void onInit() {
    super.onInit();
  }

  onTapNavigationBar(int index) {
    selectedtIndex.value = index;
    switch (index) {
      case 0:
        appBartitle.value = '1t';
        break;
      case 1:
        appBartitle.value = '2t';
        break;
      case 2:
        appBartitle.value = '3t';
        break;
      case 3:
        appBartitle.value = '4t';
        break;
    }
  }

  void onTabChanged(int index) {
    selectedtIndex.value = index;
  }
}

Your HomeView class is fine. There's need some changes in HomeController class.
I have corrected and it working fine as expected. The code is given below.

class HomeController extends GetxController {
  var selectedtIndex = 0.obs;
  var appBartitle = "".obs;

  @override
  void onInit() {
    super.onInit();
  }

  onTapNavigationBar(int index) {
    selectedtIndex.value = index;
    switch (index) {
      case 0:
        appBartitle.value = '1t';
        break;
      case 1:
        appBartitle.value = '2t';
        break;
      case 2:
        appBartitle.value = '3t';
        break;
      case 3:
        appBartitle.value = '4t';
        break;
    }
  }

  void onTabChanged(int index) {
    selectedtIndex.value = index;
  }
}

如何在切换屏幕时在底部导航屏幕中更改Appbar标题?

悲凉≈ 2025-02-18 10:48:46

VSCODE不是C ++编译器。它(主要是)文本编辑器和一些开发工具。它只是运行一些C ++编译器,以便实际编译和构建C ++代码。

您的实际C ++编译器是可以在哪里找到各种标头文件的最终权限。

无论出于何种原因,您的VSCODE配置都不知道Boost的标头文件已安装在哪里,所以这就是它告诉您的。您的编译器知道,但这是您的编译器,而不是VSCODE。

因此,不,VSCODE确实无法打开或找到这些标头文件。您的问题是:

我想知道为什么它这样做

因为它根本不知道。它不是您的C ++编译器,也不自动知道所有标头文件的安装位置。

以及如何修复

该问题...取决于您非常非常具体的计算机,操作系统(VSCODE可用于多个操作系统),无论您实际使用的C ++编译器与VSCODE使用哪个,以及如何 恰好< /strong> 您正在使用VSCODE(例如,我使用VSCODE来编辑甚至在同一台计算机上但通过SSH访问的文件)。这些因素中的每个因素都会影响一切的工作方式。

如果您知道Boost的标头文件的安装位置,这可能只是通过VSCODE的配置设置进行挖掘的问题,必须在某个地方进行设置,以告诉BOOST哪些目录包含要搜索的标头文件。如果您不知道安装了Boost的标头文件的位置,那么您的第一步将是在完成其他操作之前弄清楚该部分。

VSCode is not a C++ compiler. It is (mostly) a text editor, and some development tools. It merely runs some C++ compiler in order to actually compile and build C++ code.

Your actual C++ compiler is the final and ultimate authority on where it can find various header files.

For whatever reason, your VSCode configuration does not know where boost's header files are installed, so that's what it tells you. Your compiler knows, but that's your compiler, not VSCode.

So, no, VSCode really can't open or find these header files. Your question was:

I want to know why its doing it

Because it simply doesn't know. It's not your C++ compiler, and it doesn't automatically know where all header files are installed.

and how to fix it

That ...depends on your very, very specific computer, operating system (VSCode is available for multiple operating systems), whichever C++ compiler you are actually using with VSCode, and how exactly you are using VSCode (for a brief time, for example, I used VSCode to edit files that weren't even on the same computer, but accessed via ssh). Each one of these factors affects the how everything works, together.

If you know where boost's header files are installed, this may simply be a matter of digging through VSCode's configuration settings, there must be a setting somewhere that tells boost which directories contain header files to search for. If you don't know where boost's header files are installed, your first step will be to figure that part out, before anything else can be done.

C&#x2B;&#x2B; vscode说它在真正可以的时候无法开源文件

悲凉≈ 2025-02-18 08:11:24

当数组中没有值时,您会遇到错误。因此,当您使用数组时,请先先检查它。

if (!empty($screens['kc-css']))

You get errors when you don't have values in the array. So when you use array try to check it first.

if (!empty($screens['kc-css']))

为什么我在网站上收到此通知

悲凉≈ 2025-02-18 04:32:03

Hashmap不保证地图的顺序;特别是,它不能保证随着时间的流逝,订单将保持恒定。
改用LinkedHashMap,这看起来像:

Map sortedMap = new LinkedHashMap();
originalHashMap.entrySet().stream()
     .sorted(Comparator.comparingInt(e -> e.getValue().size()))
     .forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));

现在,预期排序的映射为SortedMap

HashMap makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Using LinkedHashMap instead and that will look like:

Map sortedMap = new LinkedHashMap();
originalHashMap.entrySet().stream()
     .sorted(Comparator.comparingInt(e -> e.getValue().size()))
     .forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));

Now, expected sorted map is sortedMap

根据嵌套在给定的hashmap内部的每个hashmap的大小,按顺序打印hashmap的内容

悲凉≈ 2025-02-17 10:36:33

如果将更改为 &amp;:Hover 嵌套的选择器将按预期进行编译。在您的原始代码中,:Hover 选择器嵌套在.nav-link中,但是由于嵌套时未直接引用父链选择器,因此它将其编译为两个独立的选择器,例如,EG .nav -link:悬停

使用 sass ampersand &amp; 我们可以执行“可以执行”链接的“筑巢。 &amp; 在嵌套时始终引用父选择器。您可以将其视为指向父选择器的指针,其中&amp; 在您的示例中指的是 .nav-link 。因此,当我们这样做时:

.nav-link {
    &:hover {
        color: #f06;
    }
}

它将其编译到 .nav-link:Hover {} 作为&amp; 使嵌套:Hover定义直接参考父母选择器 .nav-link 。以下是更新的代码:

.nav-link {
    color: $color_light;
    font-weight: 600;
    font-size: 1.5em;

    &:hover {
      color: $color_vLight;
    }
}

If you change :hover to &:hover the nested selector will compile as expected. In your original code, the :hover selector was nested in .nav-link but because it didn't refer directly to the parent selector when nesting, it compiles as two separate selectors e.g. .nav-link :hover.

Using the Sass Ampersand & we can perform "chained" nesting. The & always refers to the parent selector when nesting. You can think of it as a pointer to the parent selector where & refers to .nav-link in your example. Therefore, when we do:

.nav-link {
    &:hover {
        color: #f06;
    }
}

It compiles to .nav-link:hover {} as the & makes the nested :hover definition refer directly to the parent selector .nav-link. Below is the updated code:

.nav-link {
    color: $color_light;
    font-weight: 600;
    font-size: 1.5em;

    &:hover {
      color: $color_vLight;
    }
}

NPM Run Dev从SCSS文件生成错误的CSS代码

悲凉≈ 2025-02-16 16:14:40

重要的!

#ID是独一无二的!

页面上的#id不超过相同的#id之一,因为它是:

  • 无效的html
  • 语义上的粗略
  • 行为变得不可预测的
  • JavaScript,如果不是立即,但最终破坏了
  • 恐怖分子的胜利

,就像OP中的一吨一样:

<button type="submit" id="myButton">+</button> <!--

IMPORTANT!

#IDs ARE UNIQUE!

Do not have more than one of the same #id on a page because it's:

  • invalid HTML
  • semantically gross
  • behavior becomes unpredictable
  • JavaScript if not immediately but eventually break
  • the terrorists win

There's like a ton of these in OP:

<button type="submit" id="myButton">+</button> <!--????-->

Try to avoid using #id at all -- use .class instead.
In the example below the function insertCol() is versatile and reusable. The <table> has a <tfoot> for demonstration purposes. Details are commented in the example.

// This object stores content for insertCol() to fill a table
let content = {
  cap: {
    text: 'TEXT',
    side: '',
    act: 0 // 1='use data' 0='skip data'
  },
  tH: {
    th: 'tH',
    act: 0
  },
  tB: {
    th: '',
    td: `<td><button class="btn btn-sm btn-info add">➕</button></td>`,
    act: 1
  },
  tF: {
    td: 'tF',
    act: 0
  }
};

/**
 * @desc - Inserts a column into a given table
 * @param {number} index - Index to inert new column at
 * @param {object} content - Object that stores content
 * @param {string<selector>} selector - CSS Selector of a 
 *        tag if undefined @default is "table"
 */
function insertCol(index, content, selector = 'table') {
  // Reference <table>
  const table = document.querySelector(selector);
  // Collect all <tr> into an array
  const rowArray = [...table.rows];
  let cols = rowArray[0].cells.length;
  let size = rowArray.length;
  //console.log(size);
  //console.log(cols);

  /*
  If content.tB is active (1)...
  ... .foreach() <tr> add <td> and content at the index
  */
  if (content.tB.act) {
    rowArray.forEach(tr => {
      tr.insertCell(index).innerHTML = content.tB.td;
    });
  }
  /*
  If there's a <thead> AND content.tH.act === 1...
  ... .removeCell() at index...
  ... add <th> with content
  */
  if (table.tHead && content.tH.act) {
    rowArray[0].deleteCell(index);
    rowArray[0].insertCell(index).outerHTML = `<th>${content.tH.th}</th>`;
  }
  // The same as above for <tfoot>
  if (table.tFoot && content.tF.act) {
    rowArray[size - 1].deleteCell(index);
    rowArray[size - 1].insertCell(index).innerHTML = content.tF.td;
  }
  // This block is for <caption>
  if (table.caption && content.cap.act) {
    table.caption.innerHTML = content.cap.text;
    table.caption.style.captionSide = content.cap.side;
  }
}

// -1 is the index after the last index
insertCol(-1, content);
<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <style></style>
</head>

<body>
  <main class="container scrollingTable">
    <section class="row justify-content-center">
      <div class="col-md-8 col-lg-8 mb-8">
        <label class='form-label' for='search'>Search</label>
        <input id="search" class='form-control mb-2' type="text" placeholder="Search for names..">
        <table class='table table-striped table-hover'>
          <caption></caption>
          <thead>
            <tr>
              <th title="Field #1">drinkName</th>
              <th title="Field #2">drinkSizeInFlOz</th>
              <th title="Field #3">calories</th>
              <th title="Field #4">caffeineInMg</th>
              <th title="Field #5">caffeineInMgPerFloz</th>
              <th title="Field #6">type</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>28 Black Energy Drink</td>
              <td>8.46</td>
              <td>125</td>
              <td>80</td>
              <td>9.5</td>
              <td>ED</td>
            </tr>
            <tr>
              <td>3 Water </td>
              <td>16.9</td>
              <td>0</td>
              <td>50</td>
              <td>3.0</td>
              <td>W</td>
            </tr>
            <tr>
              <td>3D Energy Drink</td>
              <td>16</td>
              <td>15</td>
              <td>200</td>
              <td>12.5</td>
              <td>ED</td>
            </tr>
            <tr>
              <td>4 Purpose Energy Drink</td>
              <td>8.46</td>
              <td>70</td>
              <td>70</td>
              <td>8.3</td>
              <td>ED</td>
            </tr>
            <tr>
              <td>4C Energy Drink Mix</td>
              <td>16.9</td>
              <td>15</td>
              <td>170</td>
              <td>10.1</td>
              <td>ED</td>
            </tr>
            <tr>
              <td>5 Hour Energy</td>
              <td>1.93</td>
              <td>4</td>
              <td>200</td>
              <td>103.6</td>
              <td>ES</td>
            </tr>
            <tr>
              <td>5 Hour Energy Extra Strength</td>
              <td>1.93</td>
              <td>0</td>
              <td>230</td>
              <td>119.2</td>
              <td>ES</td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td>FOOT</td>
              <td>FOOT</td>
              <td>FOOT</td>
              <td>FOOT</td>
              <td>FOOT</td>
              <td>FOOT</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </section>
  </main>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script></script>
</body>

</html>

在JavaScript中的特定列中添加行

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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