问:
Rails RSpec form datepicker and select failing test assertion
I'm getting to grips with testing in rails, and I've been following this tutorial.

However, unlike the tutorial in my form I have a date select field. This seems to be causing a problem where the assert_select doesn't recognise it, and so the test is failing.

The code in new.html.erb_spec:

```<code>
RSpec.describe "aquatics/new", type: :view do
  current_user = User.first_or_create!(email: 'me@mail.com', password: 'password', password_confirmation: 'password')

  before(:each) do
    assign(:aquatic, Aquatic.new(
        nick_name: "nickname",
        common_name: "common name",
        scientific_name: "scientific name",
        sex: 'male',
        purchased_on: '2022-02-02',
        length: 10,
        max_lifespan: 5,
        user: current_user,
        notes: "These are the testing notes"
    ))
  end

  it "renders new aquatic form" do
    render
    assert_select "form[action=?][method=?]", aquatics_path, "post" do
      assert_select "input[name=?]", "aquatic[nick_name]"
      assert_select "input[name=?]", "aquatic[common_name]"
      assert_select "input[name=?]", "aquatic[scientific_name]"
      assert_select "input[name=?]", "aquatic[purchased_on]"
      assert_select "input[name=?]", "aquatic[sex]"
      assert_select "input[name=?]", "aquatic[length]"
      assert_select "input[name=?]", "aquatic[max_lifespan]"
      assert_select "input[name=?]", "aquatic[notes]"
    end
  end
end
</code>```

The failure:

```<code>  1) aquatics/new renders new aquatic form
     Failure/Error: assert_select "input[name=?]", "aquatic[purchased_on]"

     Minitest::Assertion:
       Expected at least 1 element matching "input[name="aquatic[purchased_on]"]", found 0..
       Expected 0 to be >= 1.
     # ./spec/views/aquatics/new.html.erb_spec.rb:26:in `block (3 levels) in <main>'
     # ./spec/views/aquatics/new.html.erb_spec.rb:22:in `block (2 levels) in <main>'
</code>```

I assume this is something to do with it being a selection field rather than an input, because if I comment out the purchased_on test line it throws the same error for the sex field.

I've tried changing the input[name=?] to date_select[name=?] and similar actions, but no luck. TIA.

答:
date_select adds 3 select tags for Year, Month, and Date

You are verifying input tag, you should verify select tags.

```<code>date_select("aquatic", "purchased_on")
</code>```

Above date_select will generate below html

```<code><select id="aquatic_purchased_on_1i" name="aquatic[purchased_on(1i)]">
    ...
    <option value="2021">2021</option>
    <option value="2022" selected="selected">2022</option>
    <option value="2023">2023</option>
    ...
</select>
<select id="aquatic_purchased_on_2i" name="aquatic[purchased_on(2i)]">
    <option value="1">January</option>
    <option value="2" selected="selected">February</option>
    ...
    <option value="12">December</option>
</select>
<select id="aquatic_purchased_on_3i" name="aquatic[purchased_on(3i)]">
    ...
    <option value="10">10</option>
    <option value="11" selected="selected">11</option>
    <option value="12">12</option>
    ...
</select>
</code>```

You can verify it as below

```<code>assert_select "select[name=?]", "aquatic[purchased_on(1i)]"
assert_select "select[name=?]", "aquatic[purchased_on(2i)]"
assert_select "select[name=?]", "aquatic[purchased_on(3i)]"
</code>```

Body:
I'm getting to grips with testing in rails, and I've been following this tutorial.

However, unlike the tutorial in my form I have a date select field. This seems to be causing a problem where the assert_select doesn't recognise it, and so the test is failing.

The code in new.html.erb_spec:

RSpec.describe "aquatics/new", type: :view do
  current_user = User.first_or_create!(email: 'me@mail.com', password: 'password', password_confirmation: 'password')

  before(:each) do
    assign(:aquatic, Aquatic.new(
        nick_name: "nickname",
        common_name: "common name",
        scientific_name: "scientific name",
        sex: 'male',
        purchased_on: '2022-02-02',
        length: 10,
        max_lifespan: 5,
        user: current_user,
        notes: "These are the testing notes"
    ))
  end

  it "renders new aquatic form" do
    render
    assert_select "form[action=?][method=?]", aquatics_path, "post" do
      assert_select "input[name=?]", "aquatic[nick_name]"
      assert_select "input[name=?]", "aquatic[common_name]"
      assert_select "input[name=?]", "aquatic[scientific_name]"
      assert_select "input[name=?]", "aquatic[purchased_on]"
      assert_select "input[name=?]", "aquatic[sex]"
      assert_select "input[name=?]", "aquatic[length]"
      assert_select "input[name=?]", "aquatic[max_lifespan]"
      assert_select "input[name=?]", "aquatic[notes]"
    end
  end
end

The failure:

  1) aquatics/new renders new aquatic form
     Failure/Error: assert_select "input[name=?]", "aquatic[purchased_on]"

     Minitest::Assertion:
       Expected at least 1 element matching "input[name="aquatic[purchased_on]"]", found 0..
       Expected 0 to be >= 1.
     # ./spec/views/aquatics/new.html.erb_spec.rb:26:in `block (3 levels) in '
     # ./spec/views/aquatics/new.html.erb_spec.rb:22:in `block (2 levels) in '

I assume this is something to do with it being a selection field rather than an input, because if I comment out the purchased_on test line it throws the same error for the sex field.

I've tried changing the input[name=?] to date_select[name=?] and similar actions, but no luck. TIA.

Body:
date_select adds 3 select tags for Year, Month, and Date

You are verifying input tag, you should verify select tags.

date_select("aquatic", "purchased_on")

Above date_select will generate below html

<select id="aquatic_purchased_on_1i" name="aquatic[purchased_on(1i)]">
    ...
    <option value="2021">2021</option>
    <option value="2022" selected="selected">2022</option>
    <option value="2023">2023</option>
    ...
</select>
<select id="aquatic_purchased_on_2i" name="aquatic[purchased_on(2i)]">
    <option value="1">January</option>
    <option value="2" selected="selected">February</option>
    ...
    <option value="12">December</option>
</select>
<select id="aquatic_purchased_on_3i" name="aquatic[purchased_on(3i)]">
    ...
    <option value="10">10</option>
    <option value="11" selected="selected">11</option>
    <option value="12">12</option>
    ...
</select>

You can verify it as below

assert_select "select[name=?]", "aquatic[purchased_on(1i)]"
assert_select "select[name=?]", "aquatic[purchased_on(2i)]"
assert_select "select[name=?]", "aquatic[purchased_on(3i)]"


来源: stackexchange

问:
Can't access form data in PHP
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

```<code><?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>
            <table style='width: 50%;' border='0'>
                <tbody>
                    <tr>
                        <td><label for='name'>name: </label></td>
                        <td><input type='Text' name='name' value='anon' /></td>
                    </tr>
                    <tr>
                        <td><input type='submit' name='send' value='Send' /></td>
                    </tr>
                </tbody>
            </table>
        </form>
    ";
?>
</code>```

Form Process:

```<code><?php
    echo "Hello, World 1!";
    echo "<br/>";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>
</code>```

Result:

```<code>Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }
</code>```

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

答:
You are using the incorrect syntax for $_POST. It should be

```<code> <?php
    $name = $_POST["name"];
    echo "hello $name !";
 ?>
</code>```

You are accessing it like a function instead of an array.

ContentLicense: CC BY-SA 4.0

Title: Can't access form data in PHP

Body:
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

<?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>

                        name:
                        <input type='Text' name='name' value='anon' />

                        <input type='submit' name='send' value='Send' />

        </form>
    ";
?>

Form Process:

<?php
    echo "Hello, World 1!";
    echo "
";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>

Result:

Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

Body:
You are using the incorrect syntax for $_POST. It should be

 <?php
    $name = $_POST["name"];
    echo "hello $name !";
 ?>

You are accessing it like a function instead of an array.

ContentLicense: CC BY-SA 3.0


问:
How to group datapoints independently from coloring in plotly without splitting the legend?
I want to plot multiple points connected by lines in plotly. While there should be exactly one line per id-group (as defined in the dataset), the color of those lines should depend on a different column in the data.

Consider this example data:

 df <- data.frame(
   x = c(1,2,3,4,5,6),
   y = c(0,0,3,1,4,5),
   id= c(1,1,2,2,3,3), # defines belonging to line
   group = c("A","A","A","A","B","B") # defines color of the point and line
 )
```
<p>if I plot it this way, it kind of works:</p>
<pre class="lang-r prettyprint-override"><code> plot_ly(df,type = "scatter", mode = "lines+markers",
         x = ~x,
         y = ~y,
         split = ~id,
         color = ~group)

</code>```

Unfortunately, the legend is also split along split and color:

I only want it to display the color part of the legend. In this example case the legend would only have two entries. One for "A" and one for "B".

Is there a simple way to do this that I am not seeing here?

Addendum: An id is always linked to one group only. There are no id values, that are shared bewtween multiple different group values

答:
plotly's color parameter will always create traces based on the provided data (just like split, but with colors mapped).

However, we can combine the separate legend items via legendgroup and display only one of them:

```<code>library(plotly)

DF <- data.frame(
  x = c(1,2,3,4,5,6),
  y = c(0,0,3,1,4,5),
  id= c(1,1,2,2,3,3), # defines belonging to line
  group = c("A","A","A","A","B","B") # defines color of the point and line
)

fig <- plot_ly(DF, type = "scatter", mode = "lines+markers",
               x = ~x,
               y = ~y,
               split = ~id,
               color = ~group,
               name = ~group,
               legendgroup = ~group) %>%
       layout(showlegend = TRUE) %>%
       style(showlegend = FALSE, traces = 1)

fig
</code>```

Please check my answer here for a more general approach.

Body:
I want to plot multiple points connected by lines in plotly. While there should be exactly one line per id-group (as defined in the dataset), the color of those lines should depend on a different column in the data.

Consider this example data:

 df <- data.frame(
   x = c(1,2,3,4,5,6),
   y = c(0,0,3,1,4,5),
   id= c(1,1,2,2,3,3), # defines belonging to line
   group = c("A","A","A","A","B","B") # defines color of the point and line
 )

if I plot it this way, it kind of works:

 plot_ly(df,type = "scatter", mode = "lines+markers",
         x = ~x,
         y = ~y,
         split = ~id,
         color = ~group)

Unfortunately, the legend is also split along split and color:

I only want it to display the color part of the legend. In this example case the legend would only have two entries. One for "A" and one for "B".

Is there a simple way to do this that I am not seeing here?

Addendum: An id is always linked to one group only. There are no id values, that are shared bewtween multiple different group values

Body:
plotly's color parameter will always create traces based on the provided data (just like split, but with colors mapped).

However, we can combine the separate legend items via legendgroup and display only one of them:

library(plotly)

DF <- data.frame(
  x = c(1,2,3,4,5,6),
  y = c(0,0,3,1,4,5),
  id= c(1,1,2,2,3,3), # defines belonging to line
  group = c("A","A","A","A","B","B") # defines color of the point and line
)

fig <- plot_ly(DF, type = "scatter", mode = "lines+markers",
               x = ~x,
               y = ~y,
               split = ~id,
               color = ~group,
               name = ~group,
               legendgroup = ~group) %>%
       layout(showlegend = TRUE) %>%
       style(showlegend = FALSE, traces = 1)

fig

Please check my answer here for a more general approach.


问:
C# .NET - method to store some very small scale persistent information?
I have an application that will need extremely little persistent storage.  Realistically, we're talking about < 30 integers.  All the application needs is to know those integers on next startup (and the integers do change as it runs).

A database is overkill for this, but I don't particularly want to just use a text file either.

Does C# have any mechanism for persisting small values like this between runs?  I've noticed you can store things in resource files and some other places - I don't know if you can change those in the runtime though.  I'm just learning C# & .NET for a new job, so apologies if this is a silly question!

答:
You can use IMemoryCache and AcroFS library as an additional layer for persistence!

All you need is calling .Persistent() method to obtain the persistent instance of the memory cache.

```<code>_memoryCache
   .Persistent()
   .Set(key, value, TimeSpan.FromMinutes(1));

</code>```

If you don't need to cache you can simply use AcroFS without IMemoryCache :

```<code>var _repository = FileStore.CreateStore();

// store the model with a custpm key
_repository.Store("my-model", MyModel);

// load model
var model = _repository.Load<MyModel>("my-model");

</code>```

Body:
You can use IMemoryCache and AcroFS library as an additional layer for persistence!

All you need is calling .Persistent() method to obtain the persistent instance of the memory cache.

_memoryCache
   .Persistent()
   .Set(key, value, TimeSpan.FromMinutes(1));

If you don't need to cache you can simply use AcroFS without IMemoryCache :

var _repository = FileStore.CreateStore();

// store the model with a custpm key
_repository.Store("my-model", MyModel);

// load model
var model = _repository.Load<MyModel>("my-model");


问:
Android Compose TextField: How to set exact 3 lines
I want to create TextField with exact 3 lines:

I want to see 3 lines even without any text in this TextField, i.e. I need a direct equivalent of EditText.lines in classic xml layout.

My not working code is:

```<code>OutlinedTextField(
            value = currentText,
            onValueChange = { currentText = it },
            label = { Text ("Label") },
            maxLines = 3,
            modifier = Modifier.fillMaxWidth().wrapContentHeight().padding(16.dp),
            singleLine = false
        )
</code>```

Could you help me?

答:
We can show multiline edittext by setting height of OutlinedTextField. Following example is tested.

```<code>                OutlinedTextField(
                    modifier = Modifier
                        .fillMaxWidth().height(120.dp)
                        .padding(start = 15.dp, top = 10.dp, end = 15.dp)
                        .background(Color.White, RoundedCornerShape(5.dp)),
                    shape = RoundedCornerShape(5.dp),
                    value = text,
                    onValueChange = { text = it },
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                    maxLines = 3,
                    textStyle = MaterialTheme.typography.caption
                )
</code>```

Attached image below.

Body:
I want to create TextField with exact 3 lines:

I want to see 3 lines even without any text in this TextField, i.e. I need a direct equivalent of EditText.lines in classic xml layout.

My not working code is:

OutlinedTextField(
            value = currentText,
            onValueChange = { currentText = it },
            label = { Text ("Label") },
            maxLines = 3,
            modifier = Modifier.fillMaxWidth().wrapContentHeight().padding(16.dp),
            singleLine = false
        )

Could you help me?

Body:
We can show multiline edittext by setting height of OutlinedTextField. Following example is tested.

                OutlinedTextField(
                    modifier = Modifier
                        .fillMaxWidth().height(120.dp)
                        .padding(start = 15.dp, top = 10.dp, end = 15.dp)
                        .background(Color.White, RoundedCornerShape(5.dp)),
                    shape = RoundedCornerShape(5.dp),
                    value = text,
                    onValueChange = { text = it },
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                    maxLines = 3,
                    textStyle = MaterialTheme.typography.caption
                )

Attached image below.


问:
All possible combinations of data in a single table in alphabetical order
I'm trying to write a simple SQL query to show all possible combinations of data in a single table. Here's the table:

id
fruit

1
apple

2
orange

3
pear

4
plum

I've only got as fair as pairing all the data using CROSS JOIN: "apple,orange", "apple,pear" etc.

```<code>SELECT t1.fruit, t2.fruit
FROM fruits t1
CROSS JOIN fruits t2
WHERE t1.fruit < t2.fruit
</code>```

Instead I'm looking for all unique combinations in alphabetical order, e.g.

apple

apple,orange

apple,orange,pear

apple,orange,pear,plum

apple,pear

apple,plum

apple,orange,plum

apple,pear,plum

orange

orange,pear

orange,pear,plum

orange,plum

pear

pear,plum

plum

i.e. as long as a combination exists once, it doesn't need to appear again in a different order, e.g. with apple,orange, there is no need for orange,apple

答:
This should work for any table size.

Result here

Note: this requires MySQL 8+.

```<code>-- TABLE

CREATE TABLE IF NOT EXISTS `fruits`
(
    `id`     int(6) NOT NULL,
    `fruit`  char(20)

);
INSERT INTO `fruits` VALUES (1, 'apple');
INSERT INTO `fruits` VALUES (2, 'orange');
INSERT INTO `fruits` VALUES (3, 'pear');
INSERT INTO `fruits` VALUES (4 ,'plum');

-- QUERY

WITH RECURSIVE cte ( combination, curr ) AS (
    SELECT
        CAST(t.fruit AS CHAR(80)),
        t.id
    FROM
        fruits t

    UNION ALL

    SELECT
        CONCAT(c.combination, ', ', CAST( t.fruit AS CHAR(100))),
        t.id
    FROM
        fruits t
    INNER JOIN
        cte c
        ON (c.curr < t.id)
)
SELECT combination FROM cte;
</code>```

Credit:

Code adapted from this answer

Body:
I'm trying to write a simple SQL query to show all possible combinations of data in a single table. Here's the table:

id
fruit

1
apple

2
orange

3
pear

4
plum

I've only got as fair as pairing all the data using CROSS JOIN: "apple,orange", "apple,pear" etc.

SELECT t1.fruit, t2.fruit
FROM fruits t1
CROSS JOIN fruits t2
WHERE t1.fruit < t2.fruit

Instead I'm looking for all unique combinations in alphabetical order, e.g.

apple

apple,orange

apple,orange,pear

apple,orange,pear,plum

apple,pear

apple,plum

apple,orange,plum

apple,pear,plum

orange

orange,pear

orange,pear,plum

orange,plum

pear

pear,plum

plum

i.e. as long as a combination exists once, it doesn't need to appear again in a different order, e.g. with apple,orange, there is no need for orange,apple

Body:
This should work for any table size.

Result here

Note: this requires MySQL 8+.

-- TABLE

CREATE TABLE IF NOT EXISTS `fruits`
(
    `id`     int(6) NOT NULL,
    `fruit`  char(20)

);
INSERT INTO `fruits` VALUES (1, 'apple');
INSERT INTO `fruits` VALUES (2, 'orange');
INSERT INTO `fruits` VALUES (3, 'pear');
INSERT INTO `fruits` VALUES (4 ,'plum');

-- QUERY

WITH RECURSIVE cte ( combination, curr ) AS (
    SELECT
        CAST(t.fruit AS CHAR(80)),
        t.id
    FROM
        fruits t

    UNION ALL

    SELECT
        CONCAT(c.combination, ', ', CAST( t.fruit AS CHAR(100))),
        t.id
    FROM
        fruits t
    INNER JOIN
        cte c
        ON (c.curr < t.id)
)
SELECT combination FROM cte;

Credit:

Code adapted from this answer


问:
How make VueJS understand localized numbers?
Let's figure a simple sum app. two inputs, a and b and a c result.

we have this markup

```<code><div id="app">
<input v-model.number="v1">
<input v-model.number="v2">
{{v3}}
</div>
</code>```

and this Vue script

```<code>var vm = new Vue ({
    el: "#app",
       data: {
        a:0,
        b:0,
    },
    computed: {
     c:function(){
            return this.a + this.b;
        }
    }
})
</code>```

this works great except that I'm working with localized numbers. that means. using comma "," instead of dot "." and dot instead of comma .

entering number with decimal places confuses vue, and it are not able to make a correct sum.

What can I do in order to make VueJS understand localized number input and them make the correct sum?

for instance in pt-BR locale: 1.000,30 + 100,30 = 1.100,60

答:
Using vuex as store my approach on doing this was to use two-way-computed-property with a getter and a setter.

The getter takes the data (in float) out of the store and shows it in the input-field formated with .toLocalString().

The setter takes the input as a local-formatted string and replaces ( .replace() ) the dots with "" and the commas with "."- after doing this string needs to be parsed as float ( parseFloat(string) ) and then the action for updating the store will be dispatched.

Body:
Let's figure a simple sum app. two inputs, a and b and a c result.

we have this markup

<input v-model.number="v1">
<input v-model.number="v2">
{{v3}}

and this Vue script

var vm = new Vue ({
    el: "#app",
       data: {
        a:0,
        b:0,
    },
    computed: {
     c:function(){
            return this.a + this.b;
        }
    }
})

this works great except that I'm working with localized numbers. that means. using comma "," instead of dot "." and dot instead of comma .

entering number with decimal places confuses vue, and it are not able to make a correct sum.

What can I do in order to make VueJS understand localized number input and them make the correct sum?

for instance in pt-BR locale: 1.000,30 + 100,30 = 1.100,60


问:
extracting data from a string in PHP
I am a complete beginner in PHP.
I have several hundred product descriptions, for example here:

Superpremium cat food light chicken 1 kg

Superpremium cat food light chicken 10kg

Superpremium cat food beef 2x10 kg

Superpremium cat food beef 2 x 3,8 kg

Superpremium cat food beef 2 x 2kg

Superpremium cat food beef 42 x 85g

I would need to extract from the product name the name of flavor, quantity and weight like this:

For example:

From this: Superpremium cat food beef 42 x 85g

To this:

Flavor: beef

Number of pieces: 42

Weight: 85

KG/g: g

I tried to use an array, but it doesn't work for me at all.

There's a mess in the numbers. Sometimes 10kg is given, sometimes 10 kg with a gap as you can see in the examples above.

I have a list of name of the products (brands), list of flavors etc. so my idea was to use array and use if the string contains flavor then return "Flavor: beef" etc. I spent hours on looking how to use the functions but as a beginner have no idea how to make it work.

Thanks for help!

```<code><?php
function flavor($product) {

$arr = array('turkey', 'chicken', 'fish', 'salmon', 'rabbit', 'beef', 'cod');
foreach ($arr as $product) {
    return $product;

}
}

?>
</code>```

答:
Probably the best way to parse it, you could use regular expressions.

If you have T-Regx you can do

$pattern = pattern('^(.*?) (?:(\d+) ?x ?)?((?:\d+)(?:,\d+)?) ?(k?g)$', 'm');
$match = $pattern->match('Superpremium cat food beef 2 x 3,8 kg');

$match->first(function (Detail $detail) {
    $text = $detail->get(1);
    $quantity = $detail->group(2)->orReturn(null);
    $amount = $detail->get(3);
    $unit = $detail->get(4);

    var_dump($text, $quantity, $amount, $unit);
});
```

Title: extracting data from a string in PHP

Body:
I am a complete beginner in PHP.
I have several hundred product descriptions, for example here:

Superpremium cat food light chicken 1 kg

Superpremium cat food light chicken 10kg

Superpremium cat food beef 2x10 kg

Superpremium cat food beef 2 x 3,8 kg

Superpremium cat food beef 2 x 2kg

Superpremium cat food beef 42 x 85g

I would need to extract from the product name the name of flavor, quantity and weight like this:

For example:

From this: Superpremium cat food beef 42 x 85g

To this:

Flavor: beef

Number of pieces: 42

Weight: 85

KG/g: g

I tried to use an array, but it doesn't work for me at all.

There's a mess in the numbers. Sometimes 10kg is given, sometimes 10 kg with a gap as you can see in the examples above.

I have a list of name of the products (brands), list of flavors etc. so my idea was to use array and use if the string contains flavor then return "Flavor: beef" etc. I spent hours on looking how to use the functions but as a beginner have no idea how to make it work.

Thanks for help!

<?php
function flavor($product) {

$arr = array('turkey', 'chicken', 'fish', 'salmon', 'rabbit', 'beef', 'cod');
foreach ($arr as $product) {
    return $product;

}
}

?>


问:
Using git underneath a perforce repository - an easy way to notify perforce of changes?
So,
I've been driven nuts enough by Perforce I'm now attempting to use a git repo beneath the covers.

My question is this:

When I'm futzing around with the files via my git repo, is there an easy/automatic way for me to keep track of these in perforce? I've looked into git hooks, and there doesn't seem to be one that when I commit a file to the git repo, it automatically opens the file for edit in perforce, so the perforce server knows about the changes. Let alone anything to do with moving the file around, which git recognizes automatically but perforce needs to be specifically told about.

I currently have perforce configured so that all files are writable, which makes things a lot easier when using things like emacs for editing.

Should I just be looking into git-p4? I had a few people say they were successfully using a git repo under the covers of another version control repo (perforce or otherwise).

答:
Do use git-p4, it's quite easy to use.

To set it up, first you need to enter all your files in P4, then you can do git p4 clone //my/p4/repo.

A good documentation for git-p4 can be found here: http://kb.perforce.com/article/1417/git-p4

ContentLicense: CC BY-SA 2.5


问:
How to install solr 6.x with Homebrew?
I want to install solr 6.6.1 and solr 6.4.1 with homebrew on my Mac.

With brew install solr, by default version 8 is installed.

With brew search solr i can only find solr versions 7.7 & 8. How do i install older versions?

I would like to be able to switch between which version of the service is running with homebrew.

答:
One can Install Solr@6.6 from here:</p>
```<code>brew tap-new $USER/solr
brew extract --version=6.6 solr $USER/solr
brew search /solr/
brew install <user local formula path>
</code>```

Title: How to install solr 6.x with Homebrew?

Body:
One can Install Solr@6.6 from here:

brew tap-new $USER/solr
brew extract --version=6.6 solr $USER/solr
brew search /solr/
brew install <user local formula path>


问:
How to Draw Right Angled Triangle progress I can Fill It percentage wise
I need to draw something like this in the UI , And Unable to draw it in image View, Can anyone help me achieve this kind of design?

答:
Might be too late but i have to create a similar thing recently . Sharing it here, i think it can help.

```<code>class TriangleProgressView : View {
private var progress = 0
private var paint: Paint? = null

constructor(context: Context?) : super(context) {
    init()
}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
    init()
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    init()
}

private fun init() {
    paint = Paint()
    paint!!.style = Paint.Style.FILL
}

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    drawShadow(canvas)
    if (progress == 0) return
    drawProgress(canvas)
}

private fun drawShadow(canvas: Canvas) {
    paint!!.color = Color.GRAY
    val path = Path()
    path.moveTo(0f, measuredHeight.toFloat())
    path.lineTo(measuredWidth.toFloat(), measuredHeight.toFloat())
    path.lineTo(measuredWidth.toFloat(), 0f)
    path.close()
    canvas.drawPath(path, paint!!)
}

private fun drawProgress(canvas: Canvas) {
    paint!!.color = Color.BLUE
    val height = measuredHeight
    val width = measuredWidth
    val progressX = width / 100 * progress
    val progressY = height - height * progressX / width
    val path = Path()
    path.moveTo(0f, height.toFloat())
    path.lineTo(progressX.toFloat(), height.toFloat())
    path.lineTo(progressX.toFloat(), progressY.toFloat())
    path.close()
    canvas.drawPath(path, paint!!)
}

fun setProgress(progress: Int) {
    this.progress = progress
    invalidate()
}
}
</code>```

Now all you gotta do is call setProgress from the Seekbar listener . It should work . All the main Logic is inside drawProgress method . progress calculated with the help of tan of angle because angle stays the same .

Body:
Might be too late but i have to create a similar thing recently . Sharing it here, i think it can help.

class TriangleProgressView : View {
private var progress = 0
private var paint: Paint? = null

constructor(context: Context?) : super(context) {
    init()
}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
    init()
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    init()
}

private fun init() {
    paint = Paint()
    paint!!.style = Paint.Style.FILL
}

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    drawShadow(canvas)
    if (progress == 0) return
    drawProgress(canvas)
}

private fun drawShadow(canvas: Canvas) {
    paint!!.color = Color.GRAY
    val path = Path()
    path.moveTo(0f, measuredHeight.toFloat())
    path.lineTo(measuredWidth.toFloat(), measuredHeight.toFloat())
    path.lineTo(measuredWidth.toFloat(), 0f)
    path.close()
    canvas.drawPath(path, paint!!)
}

private fun drawProgress(canvas: Canvas) {
    paint!!.color = Color.BLUE
    val height = measuredHeight
    val width = measuredWidth
    val progressX = width / 100 * progress
    val progressY = height - height * progressX / width
    val path = Path()
    path.moveTo(0f, height.toFloat())
    path.lineTo(progressX.toFloat(), height.toFloat())
    path.lineTo(progressX.toFloat(), progressY.toFloat())
    path.close()
    canvas.drawPath(path, paint!!)
}

fun setProgress(progress: Int) {
    this.progress = progress
    invalidate()
}
}

Now all you gotta do is call setProgress from the Seekbar listener . It should work . All the main Logic is inside drawProgress method . progress calculated with the help of tan of angle because angle stays the same .


问:
Openshift 4: oc get environment variable with name
Is there a way to get the value of a specific Openshift Service environment variable?

such as:

```<code>oc get <namespace>/servicename env <envname>
</code>```

答:
Found this:</p>
```<code>oc set env dc/<applicaiton-name> --list
</code>```

Body:
Is there a way to get the value of a specific Openshift Service environment variable?

such as:

oc get <namespace>/servicename env <envname>

Body:
Found this:

oc set env dc/<applicaiton-name> --list


问:
Tool for exporting html as pdf
I have a html document which marks up a report. I have a button on this page "Export as pdf". However I am not sure how to export html into a pdf..Are there any tools out there that anyone recommends for such a task..

EDIT: In more detail:

I have the following php:

```<code><?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src = "jQuery.js"></script>
   <script>
   $(document).ready(function(){

   });
  </script>
  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
  </head>
  <body>
  <h1>Entry Report - <?php echo($date); ?></h1>
  <div id = "buttons">
  <a href = "http://dev.speechlink.co.uk">Export as PDF</a>
  </div>
  <h3>Biological Information</h3>
  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("<br/>");
      echo($value['question']." <br/> "."<img src = \"$image\"/>");
      echo("<br/>");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("<br/>");
    $i++;
      }
  ?>
  <h3>Fatigue and Recovery</h3>
  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Illness and Injury</h3>
  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Training Sessions</h3>
  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>General Feedback</h3>
  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       echo("User didn't leave any feedback");
     }
     echo("<br/>");
  ?>
  </body>
</html>
<?php
}
?>
</code>```

This displays the following:

So if I'm using fpdf, what is the best way to export the following as a pdf? Should I write a fpdf function in the same php file or is it best to write a separate php file which creates and displays the pdf (which means I would have to post all relevant data to this file)...

答:
Another much easier way is with HTML2FPDF.
HTML2FPDF is a PHP Class library that uses the FPDF class library to convert HTML files to PDF files. This library consist of three classes namely PDF, HTML2FPDF and FPDF (modified FPDF class). The class PDF extends the class HTML2FPDF that extends the class FPDF.

Now let us see, how to convert a sample html page into a PDF file using HTML2FPDF Library. The html page contains a table that lists a few nations with their corresponding national flags. Below is the code for the conversion.

```<code><?
require('html2fpdf.php');
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen("sample.html","r");
$strContent = fread($fp, filesize("sample.html"));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output("sample.pdf");
echo "PDF file is generated successfully!";
?>
</code>```

First, we need to include the html2fpdf.php file that contains the HTML2FPDF class and an object is created using the constructor HTML2FPDF(). Then a new page is added to the pdf document using the function AddPage(). The html contents are read from the sample.html file using file functions. Then the html contents are written in to the pdf format using WriteHTML() function. To view the html file, click here and to view the generated pdf, click here. The above sample code with the sample html file and images and the html2fpdf class libraries can be downloaded here.

The HTML2FPDF class library will be working best with the XHTML 1.0. Also the class does not support all the features available with HTML. To know the supported HTML tags and other features, Please refer http://html2fpdf.sourceforge.net.

I recommend you to use this since it's much easier and friendly.

Title: Tool for exporting html as pdf

Body:
I have a html document which marks up a report. I have a button on this page "Export as pdf". However I am not sure how to export html into a pdf..Are there any tools out there that anyone recommends for such a task..

EDIT: In more detail:

I have the following php:

<?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>

   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>

Entry Report - <?php echo($date); ?>

  Export as PDF

Biological Information

  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("
");
      echo($value['question']."
 "."");
      echo("
");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("
");
    $i++;
      }
  ?>

Fatigue and Recovery

  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Illness and Injury

  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Training Sessions

  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

General Feedback

  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       echo("User didn't leave any feedback");
     }
     echo("
");
  ?>

<?php
}
?>

This displays the following:

So if I'm using fpdf, what is the best way to export the following as a pdf? Should I write a fpdf function in the same php file or is it best to write a separate php file which creates and displays the pdf (which means I would have to post all relevant data to this file)...

Body:
Another much easier way is with HTML2FPDF.
HTML2FPDF is a PHP Class library that uses the FPDF class library to convert HTML files to PDF files. This library consist of three classes namely PDF, HTML2FPDF and FPDF (modified FPDF class). The class PDF extends the class HTML2FPDF that extends the class FPDF.

Now let us see, how to convert a sample html page into a PDF file using HTML2FPDF Library. The html page contains a table that lists a few nations with their corresponding national flags. Below is the code for the conversion.

<?
require('html2fpdf.php');
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen("sample.html","r");
$strContent = fread($fp, filesize("sample.html"));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output("sample.pdf");
echo "PDF file is generated successfully!";
?>

First, we need to include the html2fpdf.php file that contains the HTML2FPDF class and an object is created using the constructor HTML2FPDF(). Then a new page is added to the pdf document using the function AddPage(). The html contents are read from the sample.html file using file functions. Then the html contents are written in to the pdf format using WriteHTML() function. To view the html file, click here and to view the generated pdf, click here. The above sample code with the sample html file and images and the html2fpdf class libraries can be downloaded here.

The HTML2FPDF class library will be working best with the XHTML 1.0. Also the class does not support all the features available with HTML. To know the supported HTML tags and other features, Please refer http://html2fpdf.sourceforge.net.

I recommend you to use this since it's much easier and friendly.


问:
ERC1155 NFT transfer using Ethers.js
I want to transfer ERC1155 NFT from one contract account to another. Does anyone know how to make it work with ethers.js</p>

答:
As every Ethereum contract

use Type Chain to create contract typings ABI and contract factory in TS

connect contract to Ethers.js provider

perform transactions using Contracts methods.
Probably the response is too generic but the question is generic too.

Title: ERC1155 NFT transfer using Ethers.js


问:
Node and NPM path in OSX
I have a very strange configuration issue.

When logging to machine (SSH session) and executing the following commands using interactive shell, they succeed:

```<code>node --version
npm --v
</code>```

However, when I execute the following through script from remote machine:

```<code>#!/bin/bash

#Script input arguments
user=${1}
server=${2}

#Tell the shell to quote your variables to be eval-safe!
printf -v user_q '%q' "$user"
printf -v server_q '%q' "$server"
#

# Script variables
address="$user_q"@"$server_q"
#

function run {
    ssh "$address" /bin/bash "$@"
}

run << SSHCONNECTION

node --version
npm --v

 exit
SSHCONNECTION
</code>```

I get the following output:

/bin/bash: line 2: node: command not found

/bin/bash: line 3: npm: command not found

I am conscious that the issue may be the in .bash_profile file configuration

```<code>export PATH="/usr/local/bin/npm:/usr/local/bin/node:/usr/local/bin:$PATH"
</code>```

Also, here is result of npm config get prefix:

/usr/local

Can you please suggest what I am doing wrong?

答:
I believe what happened is due to the fact .bash_profile is only executed when bash is invoked for an interactive shell, more info about this here: https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html#Bash-Startup-Files

When invoking and passing the script directly to /bin/bash, it will behave as a non-interactive shell which the default behaviour to not read the .bash_profile.

I would suggest setting you PATH variable in /etc/environment so it will take affect for all users and all manners of scripting.

Title: Node and NPM path in OSX

Body:
I have a very strange configuration issue.

When logging to machine (SSH session) and executing the following commands using interactive shell, they succeed:

node --version
npm --v

However, when I execute the following through script from remote machine:

#!/bin/bash

#Script input arguments
user=${1}
server=${2}

#Tell the shell to quote your variables to be eval-safe!
printf -v user_q '%q' "$user"
printf -v server_q '%q' "$server"
#

# Script variables
address="$user_q"@"$server_q"
#

function run {
    ssh "$address" /bin/bash "$@"
}

run << SSHCONNECTION

node --version
npm --v

 exit
SSHCONNECTION

I get the following output:

/bin/bash: line 2: node: command not found

/bin/bash: line 3: npm: command not found

I am conscious that the issue may be the in .bash_profile file configuration

export PATH="/usr/local/bin/npm:/usr/local/bin/node:/usr/local/bin:$PATH"

Also, here is result of npm config get prefix:

/usr/local

Can you please suggest what I am doing wrong?


问:
Java object graph visitor library
Do you know a good java object graph visitor library?

I want to visit an object and its sub components and perform some actions when some conditions are matched.

Example usage:

on a huge domain object graph, reset
each id to null

on a huge domain object graph, replace each Set with a TreeSet
instance containing the same
elements.

I want a library, not custom code because traversing an Object graph can be tricky. You have to handle collections, arrays, proxies, and so on...
I have think about reuse part of XStream to achieve this, but it doesn't look so easy: Xstream visitor is more oriented on object transformation than object self modification.

答:
I've been looking for the same thing, and found this.

http://code.google.com/p/behaim/

Title: Java object graph visitor library


问:
Deserialized object type get value throw null reference
i have a json response from ajax and i am trying to deserialize it as object type(not a defined model class) and access its properties value. deserializer works fine but when try to get the value i get the null reference error.

```<code>// on break point i can clearly see the object properties and values and its not null
var tankJsonObj = JsonConvert.DeserializeObject<object>(tankJson);

//here from GetValue i get the null refernce error
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();
</code>```

i tried the test data

```<code>var tankJsonObj = new { tankName = "xx" };
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();
</code>```

and it works fine. i cant understand why the object that initiated by deserializer which is not null throwing the error on getting the property value.

答:
JsonConvert.DeserializeObject<object> returns a JObject instance. That class does not have a property called tankName, so tankJsonObj.GetType().GetProperty("tankName") returns null.

When you test using an anonymous type, that type does have a property called tankName.

You don't need reflection to extract values from a JObject:

```<code>JObject tankJsonObj = JsonConvert.DeserializeObject<JObject>(tankJson);
string tankName = tankJsonObj["tankName"]?.ToString();
</code>```

Body:
i have a json response from ajax and i am trying to deserialize it as object type(not a defined model class) and access its properties value. deserializer works fine but when try to get the value i get the null reference error.

// on break point i can clearly see the object properties and values and its not null
var tankJsonObj = JsonConvert.DeserializeObject<object>(tankJson);

//here from GetValue i get the null refernce error
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();

i tried the test data

var tankJsonObj = new { tankName = "xx" };
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();

and it works fine. i cant understand why the object that initiated by deserializer which is not null throwing the error on getting the property value.

Body:
JsonConvert.DeserializeObject<object> returns a JObject instance. That class does not have a property called tankName, so tankJsonObj.GetType().GetProperty("tankName") returns null.

When you test using an anonymous type, that type does have a property called tankName.

You don't need reflection to extract values from a JObject:

JObject tankJsonObj = JsonConvert.DeserializeObject<JObject>(tankJson);
string tankName = tankJsonObj["tankName"]?.ToString();


问:
Material-UI custom theme palette property yielding 'undefined' error in Jest
In short, I'm using Jest, React Testing Library, and Material UI createMuiTheme and everything works except for the tests.  They break only when I add the custom theme from my compound theme from createMuiTheme.

I'm creating a custom theme for my MUI project as follows:

```<code>import { createMuiTheme } from '@material-ui/core/styles';

export const theme = {
  palette: {
    extra: {
      activeButton: '#D4564E',
      black: '#000000',
      darkGrey: '#232323',
      rgbaInvisible: 'rgba(0, 0, 0, 0)',
      success: '#4CAF50',
      white: '#FFFFFF',
    },
  },
};

export default createMuiTheme(theme);
</code>```

My component styles are defined in JSS like this:

```<code>const useStyles = makeStyles((theme) => {
  return {
    ctaCopy: {
      color: theme.extraColors.activeButton,
    },
  };
});
</code>```

The component itself I don't think is important but it looks like this:

```<code><Link className={classes.ctaCopy} href={ctaUrl}>
  {ctaCopy}
</Link>
</code>```

This works.  The component displays properly when rendered, with the expected colors.  However, when I use this component in a Jest test, it fails, saying:

```<code>TypeError: Cannot read property 'activeButton' of undefined
</code>```

Update:

I dug a little further and attempted a few other solutions, including using MuiThemeProvider and ThemeProvider (separately, of course).  In order to do this, I used import to pull in my custom theme, which is hosted in an external library.  As follows:

```<code>import { defaultTheme } from 'my-external-lib';
</code>```

This, again, works on a rendered page.  I went so far as to console.log the defaultTheme and it prints correctly, again, in the rendered page.  However, in the tests, if I console.log(defaultTheme) the result is undefined!!

So perhaps the updated question nuance is, why can't I use import in this way with Jest/React Testing Library?

This may warrant a whole new question being posted.

More of what I've tried so far:

```<code>// This theme created as above
import { ThemeProvider } from '@material-ui/core';
import { defaultTheme } from '@my-external-lib';
import MyComponent from './MyComponent';

const setupComponent = ({
  ctaCopy,
  ctaUrl,
} = {}) => {
  render(
    <ThemeProvider theme={defaultTheme}>
      <MyComponent
        ctaCopy={ctaCopy}
        ctaUrl={ctaUrl}
      />
    </ThemeProvider>,
  );
};

const testCtaCopy = 'test-cta-copy';
const testCtaUrl = 'https://www.test.com';

describe('My component', () => {
  it('should render', () => {
    expect.assertions(1);

    setupComponent({ ctaCopy: testCtaCopy, ctaUrl: testCtaUrl });

    expect(screen.getByText(testCtaCopy)).toBeInTheDocument();
  });
});
</code>```

Why am I getting this error in tests only?

答:
I encountered this today, the solution that fixed for me is this</p>
```<code>const useStyles = makeStyles((theme) => {
  return {
    ctaCopy: {
      color: theme.extraColors?.activeButton,
    },
  };
});
</code>```

Body:
In short, I'm using Jest, React Testing Library, and Material UI createMuiTheme and everything works except for the tests.  They break only when I add the custom theme from my compound theme from createMuiTheme.

I'm creating a custom theme for my MUI project as follows:

import { createMuiTheme } from '@material-ui/core/styles';

export const theme = {
  palette: {
    extra: {
      activeButton: '#D4564E',
      black: '#000000',
      darkGrey: '#232323',
      rgbaInvisible: 'rgba(0, 0, 0, 0)',
      success: '#4CAF50',
      white: '#FFFFFF',
    },
  },
};

export default createMuiTheme(theme);

My component styles are defined in JSS like this:

const useStyles = makeStyles((theme) => {
  return {
    ctaCopy: {
      color: theme.extraColors.activeButton,
    },
  };
});

The component itself I don't think is important but it looks like this:

<Link className={classes.ctaCopy} href={ctaUrl}>
  {ctaCopy}
</Link>

This works.  The component displays properly when rendered, with the expected colors.  However, when I use this component in a Jest test, it fails, saying:

TypeError: Cannot read property 'activeButton' of undefined

Update:

I dug a little further and attempted a few other solutions, including using MuiThemeProvider and ThemeProvider (separately, of course).  In order to do this, I used import to pull in my custom theme, which is hosted in an external library.  As follows:

import { defaultTheme } from 'my-external-lib';

This, again, works on a rendered page.  I went so far as to console.log the defaultTheme and it prints correctly, again, in the rendered page.  However, in the tests, if I console.log(defaultTheme) the result is undefined!!

So perhaps the updated question nuance is, why can't I use import in this way with Jest/React Testing Library?

This may warrant a whole new question being posted.

More of what I've tried so far:

// This theme created as above
import { ThemeProvider } from '@material-ui/core';
import { defaultTheme } from '@my-external-lib';
import MyComponent from './MyComponent';

const setupComponent = ({
  ctaCopy,
  ctaUrl,
} = {}) => {
  render(
    <ThemeProvider theme={defaultTheme}>
      <MyComponent
        ctaCopy={ctaCopy}
        ctaUrl={ctaUrl}
      />
    </ThemeProvider>,
  );
};

const testCtaCopy = 'test-cta-copy';
const testCtaUrl = 'https://www.test.com';

describe('My component', () => {
  it('should render', () => {
    expect.assertions(1);

    setupComponent({ ctaCopy: testCtaCopy, ctaUrl: testCtaUrl });

    expect(screen.getByText(testCtaCopy)).toBeInTheDocument();
  });
});

Why am I getting this error in tests only?

Body:
I encountered this today, the solution that fixed for me is this

const useStyles = makeStyles((theme) => {
  return {
    ctaCopy: {
      color: theme.extraColors?.activeButton,
    },
  };
});


问:
Minimalistic nyc (istanbul) javascript coverage not working for es-modules (ESM)
Trying to figure out why I get no coverage out of nyc whatsovever, I ended up with a file single file ./x.js that only contains

#!/usr/bin/env node
'use strict'
console.log('======= starting tests =======');
```
<p>In <code>package.json</code> I have</p>
<pre class="lang-json prettyprint-override"><code>  ...
  "scripts": {
    "test": "nyc ./x.js",
  }
  ...
</code>```

and when I run npm run test I get the following

console log from the one-liner

a html coverage report as requested in the config (see below), yet the line is not market as covered

despite configuring a cache directory, it stays empty which seems to indicate that on-the-fly instrumentation is not done.

From all the examples on net I assumed that instrumentation is done on the fly and that nyc instrument is rather for special uses cases. Can anyone provide some inside what is going on and what not? Here is (one of the gazillion versions of) the config I tried:

{
  "cache": true,
  "cache-dir": "./kkk",
  "instrument": true,
  "extension": [
    ".ts",
    ".js"
  ],
  "include": [
    "**/x.js"
  ],
  "reporter": [
      "html"
  ],
  "all": true
}
```

I start getting coverage output when not using "type": "module" in my package.json.

Versions:

node: v16.13.2

nyc: 15.1.0

答:
The problem seems to be that nyc in fact cannot load es-modules (ESM) on the fly. A possible solution could have been

```<code>npm i -D @istanbuljs/esm-loader-hook
NODE_OPTIONS='--experimental-loader @istanbuljs/esm-loader-hook' ./node_modules/.bin/nyc ..more options.. ./x.js
</code>```

according to this github repository. Yet, this did not work for me, likely because my node version (16.13.2) is too new, as promised on that site.

The above link further points to c8 as a solution. Some background can be found on the c8 developer's blog. Bottom line: es-modules were difficult to implement for istanbul, so use a new node feature to collect coverage data and "just" convert this to human readable form: c8.

Works for me, given the example file in the question,

```<code>./node_modules/.bin/c8 node ./x.js
</code>```

produces the expected coverage output. Further I noticed that when a .js file is included that was produced by the typescript compiler with "sourceMap": true, the coverage nicely shows the .ts file.

Body:
Trying to figure out why I get no coverage out of nyc whatsovever, I ended up with a file single file ./x.js that only contains

#!/usr/bin/env node
'use strict'
console.log('======= starting tests =======');

In package.json I have

  ...
  "scripts": {
    "test": "nyc ./x.js",
  }
  ...

and when I run npm run test I get the following

console log from the one-liner

a html coverage report as requested in the config (see below), yet the line is not market as covered

despite configuring a cache directory, it stays empty which seems to indicate that on-the-fly instrumentation is not done.

From all the examples on net I assumed that instrumentation is done on the fly and that nyc instrument is rather for special uses cases. Can anyone provide some inside what is going on and what not? Here is (one of the gazillion versions of) the config I tried:

{
  "cache": true,
  "cache-dir": "./kkk",
  "instrument": true,
  "extension": [
    ".ts",
    ".js"
  ],
  "include": [
    "**/x.js"
  ],
  "reporter": [
      "html"
  ],
  "all": true
}

I start getting coverage output when not using "type": "module" in my package.json.

Versions:

node: v16.13.2

nyc: 15.1.0

Body:
The problem seems to be that nyc in fact cannot load es-modules (ESM) on the fly. A possible solution could have been

npm i -D @istanbuljs/esm-loader-hook
NODE_OPTIONS='--experimental-loader @istanbuljs/esm-loader-hook' ./node_modules/.bin/nyc ..more options.. ./x.js

according to this github repository. Yet, this did not work for me, likely because my node version (16.13.2) is too new, as promised on that site.

The above link further points to c8 as a solution. Some background can be found on the c8 developer's blog. Bottom line: es-modules were difficult to implement for istanbul, so use a new node feature to collect coverage data and "just" convert this to human readable form: c8.

Works for me, given the example file in the question,

./node_modules/.bin/c8 node ./x.js

produces the expected coverage output. Further I noticed that when a .js file is included that was produced by the typescript compiler with "sourceMap": true, the coverage nicely shows the .ts file.


问:
Colored hatched bar plot on overlapping / hidden bars with matplotlib
Currently, I create my bar plot like this to compare two results

```<code>plt.figure(figsize=(12,8))
result_df.sym.plot(kind='barh', edgecolor='none')
result_df.non_sym.plot(kind='barh', edgecolor='none',color='orange')
</code>```

This results in this

I want to show that the blue results generally outperform the yellow ones. But for some categories they do not, so they aren't visible at all.
What I now want is something like this:

I quickly added this with powerpoint but of course I want to generate it directly with matplotlib/seaborn/pandas. But I have no idea how. There is the hatched parameter in matplotlib but it does not give the effect I want.

答:
With matplotlib you can get this effect by plotting a third bar with the first dataset using only the hatch:

```<code>df = pd.DataFrame({'A': [1, 2, 3, 4],
                   'B': [4, 3, 2, 1]
                  })

import matplotlib as mpl
mpl.rcParams['hatch.linewidth'] = 10
mpl.rcParams['hatch.color'] = '#1F77B4'
df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].plot(kind='barh', color='none', hatch='/')
</code>```

output:

or

```<code>df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].mask(df['B'].lt(df['A'])).plot(kind='barh', color='none', hatch='/')
</code>```

output:

For thinner hatches:

```<code>import matplotlib as mpl
mpl.rcParams['hatch.linewidth'] = 3
mpl.rcParams['hatch.color'] = '#1F77B4'
df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].mask(df['B'].lt(df['A'])).plot(kind='barh', color='none', hatch='//')
</code>```

output:

Body:
Currently, I create my bar plot like this to compare two results

plt.figure(figsize=(12,8))
result_df.sym.plot(kind='barh', edgecolor='none')
result_df.non_sym.plot(kind='barh', edgecolor='none',color='orange')

This results in this

I want to show that the blue results generally outperform the yellow ones. But for some categories they do not, so they aren't visible at all.
What I now want is something like this:

I quickly added this with powerpoint but of course I want to generate it directly with matplotlib/seaborn/pandas. But I have no idea how. There is the hatched parameter in matplotlib but it does not give the effect I want.

Body:
With matplotlib you can get this effect by plotting a third bar with the first dataset using only the hatch:

df = pd.DataFrame({'A': [1, 2, 3, 4],
                   'B': [4, 3, 2, 1]
                  })

import matplotlib as mpl
mpl.rcParams['hatch.linewidth'] = 10
mpl.rcParams['hatch.color'] = '#1F77B4'
df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].plot(kind='barh', color='none', hatch='/')

output:

or

df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].mask(df['B'].lt(df['A'])).plot(kind='barh', color='none', hatch='/')

output:

For thinner hatches:

import matplotlib as mpl
mpl.rcParams['hatch.linewidth'] = 3
mpl.rcParams['hatch.color'] = '#1F77B4'
df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].mask(df['B'].lt(df['A'])).plot(kind='barh', color='none', hatch='//')

output:


问:
CSS overflow and position
I wish that when I'm with the mouse over the link, that blur will disappear and work properly if I don't add the line class.
When I add the line class, everything breaks down, the links change position on the x-axis and only the Contact link is visible.
How can I add that line for all 3 links without affecting the position and disappearance of the link blur?

And why does that navbar overflow-x occur?
its width in css is 100 vw.
I think it's from the mouseover event, but how can I prevent that overflow-x? Why does the navbar have that width?

const cursor = document.querySelector('.cursor');

const navLinks = document.querySelectorAll('nav ul li a');
const nav = document.querySelector('nav') ;

navLinks.forEach(link =>{
  nav.style.overflow='hidden' ;
  link.addEventListener('mouseover',e=>{
    e.target.classList.add('line');
   e.target.classList.remove('blur') ;

  })}) ;

  navLinks.forEach(link =>{
    link.addEventListener('mouseleave',e=>{

     e.target.classList.add('blur') ;
    })}) ;

nav.addEventListener('mousemove' , function(mouse){
  const x = mouse.pageX +'px';
  const y = mouse.pageY +'px';
  cursor.style.left = x ;
  cursor.style.top = y ;

})  ;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav {
  height:10vh;
  width:100vw;
  box-shadow:5px 0px 10px rgba(0,0,0,1);
  display:flex;
  align-items:center;
  background:gray;
  overflow:hidden;

  cursor:none;

}

.cursor{
  width:3vw;
  height:3vw;
  background:brown;
  border-radius:50%;
  position:absolute;
  pointer-events:none;
  transform:translate(-50%,-50%) ;
}
.logo{
  position:relative;
  width:10vw;
  height:100%;

}

.logo h2{
  position:absolute;
  top:50%;
  font-size:1rem;

}
nav ul {
  display:flex;
  height:100%;
  width:90vw;
  position:relative;

}

nav ul li {
  list-style:none;
  padding-left:15vw;
  position:relative;
  top:50%;

}

nav ul li a{

text-decoration:none;
font-size:1rem;
position:relative;
cursor:none;

}

.blur{
  filter:blur(3px);
}

.section{
  position:relative;
  top:3vh;
  width:100%;

  height:100vh;

}

.section1{
  background:red;
}
.section2{
  background:blue;
}
.section3{
  background:purple;
}

.line{
  width:1px;
  height:100%;
  position:absolute;
  background:black;
  animation:anime 1.5s linear infinite;
}
@keyframes anime {
  0%{
    transform:translateX(0);
  }
  100%{
    transform:translateX(100%);
  }
}</code>```

logo

Home

About

Contact

```

答:
I formatted your code a bit.
The problem was, that your anchor was just 1px wide, that was too small for the event listeners to react.
I changed the line to a pseudo element ::before.

The rest of your code I left untouched.

const cursor = document.querySelector('.cursor');

const navLinks = document.querySelectorAll('nav ul li a');
const nav = document.querySelector('nav');

navLinks.forEach(link => {
  nav.style.overflow = 'hidden';
  link.addEventListener('mouseover', e => {
    e.target.classList.remove('blur');
  })
  link.addEventListener('mouseleave', e => {
    e.target.classList.add('blur');
  });
});

nav.addEventListener('mousemove', function(mouse) {
  const x = mouse.pageX + 'px';
  const y = mouse.pageY + 'px';
  cursor.style.left = x;
  cursor.style.top = y;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav {
  height: 10vh;
  width: 100vw;
  box-shadow: 5px 0px 10px rgba(0, 0, 0, 1);
  display: flex;
  align-items: center;
  background: gray;
  overflow: hidden;
  cursor: none;
}

.cursor {
  width: 3vw;
  height: 3vw;
  background: brown;
  border-radius: 50%;
  position: absolute;
  pointer-events: none;
  transform: translate(-50%, -50%);
}

.logo {
  position: relative;
  width: 10vw;
  height: 100%;
}

.logo h2 {
  position: absolute;
  top: 50%;
  font-size: 1rem;
}

nav ul {
  display: flex;
  height: 100%;
  width: 90vw;
  position: relative;
}

nav ul li {
  list-style: none;
  padding-left: 15vw;
  position: relative;
  top: 50%;
}

nav ul li a {
  text-decoration: none;
  font-size: 1rem;
  position: relative;
  cursor: none;
  height: 100%;
  display: block;
}

.blur {
  filter: blur(3px);
}

.section {
  position: relative;
  top: 3vh;
  width: 100%;
  height: 100vh;
}

.section1 {
  background: red;
}

.section2 {
  background: blue;
}

.section3 {
  background: purple;
}

nav a::before {
  content: " ";
  width: 1px;
  height: 100%;
  position: absolute;
  background: black;
  animation: anime 1.5s linear infinite;
}

@keyframes anime {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(100%);
  }
}</code>```

logo

Home

About

Contact

```

Title: CSS overflow and position

Body:
I wish that when I'm with the mouse over the link, that blur will disappear and work properly if I don't add the line class.
When I add the line class, everything breaks down, the links change position on the x-axis and only the Contact link is visible.
How can I add that line for all 3 links without affecting the position and disappearance of the link blur?

And why does that navbar overflow-x occur?
its width in css is 100 vw.
I think it's from the mouseover event, but how can I prevent that overflow-x? Why does the navbar have that width?

const cursor = document.querySelector('.cursor');

const navLinks = document.querySelectorAll('nav ul li a');
const nav = document.querySelector('nav') ;

navLinks.forEach(link =>{
  nav.style.overflow='hidden' ;
  link.addEventListener('mouseover',e=>{
    e.target.classList.add('line');
   e.target.classList.remove('blur') ;

  })}) ;

  navLinks.forEach(link =>{
    link.addEventListener('mouseleave',e=>{

     e.target.classList.add('blur') ;
    })}) ;

nav.addEventListener('mousemove' , function(mouse){
  const x = mouse.pageX +'px';
  const y = mouse.pageY +'px';
  cursor.style.left = x ;
  cursor.style.top = y ;

})  ;

nav {
  height:10vh;
  width:100vw;
  box-shadow:5px 0px 10px rgba(0,0,0,1);
  display:flex;
  align-items:center;
  background:gray;
  overflow:hidden;

  cursor:none;

}

.cursor{
  width:3vw;
  height:3vw;
  background:brown;
  border-radius:50%;
  position:absolute;
  pointer-events:none;
  transform:translate(-50%,-50%) ;
}
.logo{
  position:relative;
  width:10vw;
  height:100%;

}

.logo h2{
  position:absolute;
  top:50%;
  font-size:1rem;

}
nav ul {
  display:flex;
  height:100%;
  width:90vw;
  position:relative;

}

nav ul li {
  list-style:none;
  padding-left:15vw;
  position:relative;
  top:50%;

}

nav ul li a{

text-decoration:none;
font-size:1rem;
position:relative;
cursor:none;

}

.blur{
  filter:blur(3px);
}

.section{
  position:relative;
  top:3vh;
  width:100%;

  height:100vh;

}

.section1{
  background:red;
}
.section2{
  background:blue;
}
.section3{
  background:purple;
}

.line{
  width:1px;
  height:100%;
  position:absolute;
  background:black;
  animation:anime 1.5s linear infinite;
}
@keyframes anime {
  0%{
    transform:translateX(0);
  }
  100%{
    transform:translateX(100%);
  }
}

logo

Home

About

Contact

Body:
I formatted your code a bit.
The problem was, that your anchor was just 1px wide, that was too small for the event listeners to react.
I changed the line to a pseudo element ::before.

The rest of your code I left untouched.

const cursor = document.querySelector('.cursor');

const navLinks = document.querySelectorAll('nav ul li a');
const nav = document.querySelector('nav');

navLinks.forEach(link => {
  nav.style.overflow = 'hidden';
  link.addEventListener('mouseover', e => {
    e.target.classList.remove('blur');
  })
  link.addEventListener('mouseleave', e => {
    e.target.classList.add('blur');
  });
});

nav.addEventListener('mousemove', function(mouse) {
  const x = mouse.pageX + 'px';
  const y = mouse.pageY + 'px';
  cursor.style.left = x;
  cursor.style.top = y;
});

nav {
  height: 10vh;
  width: 100vw;
  box-shadow: 5px 0px 10px rgba(0, 0, 0, 1);
  display: flex;
  align-items: center;
  background: gray;
  overflow: hidden;
  cursor: none;
}

.cursor {
  width: 3vw;
  height: 3vw;
  background: brown;
  border-radius: 50%;
  position: absolute;
  pointer-events: none;
  transform: translate(-50%, -50%);
}

.logo {
  position: relative;
  width: 10vw;
  height: 100%;
}

.logo h2 {
  position: absolute;
  top: 50%;
  font-size: 1rem;
}

nav ul {
  display: flex;
  height: 100%;
  width: 90vw;
  position: relative;
}

nav ul li {
  list-style: none;
  padding-left: 15vw;
  position: relative;
  top: 50%;
}

nav ul li a {
  text-decoration: none;
  font-size: 1rem;
  position: relative;
  cursor: none;
  height: 100%;
  display: block;
}

.blur {
  filter: blur(3px);
}

.section {
  position: relative;
  top: 3vh;
  width: 100%;
  height: 100vh;
}

.section1 {
  background: red;
}

.section2 {
  background: blue;
}

.section3 {
  background: purple;
}

nav a::before {
  content: " ";
  width: 1px;
  height: 100%;
  position: absolute;
  background: black;
  animation: anime 1.5s linear infinite;
}

@keyframes anime {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(100%);
  }
}

<nav>
  <div class="logo">
    <h2 class="logo">logo</h2>
  </div>
  <div class='cursor'></div>

  <ul>
    <li><a class="blur" href="#">Home</a>
    </li>

    <li><a class="blur" href="#">About</a>
    </li>

    <li><a class="blur" href="#">Contact</a>
    </li>
  </ul>
</nav>
<div class="section section1">
</div>

<div class="section section2">
</div>

<div class="section section3">
</div>


问:
How do I make a video full screen using actionscript in flex desktop application
I am playing a flv video using the videoplayer class of flex. (all the properties of it are being set at runtime)

I want to make the video fullscreen without clicking on the fullscreen button i.e. through programming.

Is it possible. If yes then how can I do this.?

答:
Use the displayState property of the stage.  You can access the stage as a variable on the Application class.  So, conceptually, do this:

```<code>FlexGlobals.topLevelApplication.stage.displayState = StageDisplayState.FULL_SCREEN
</code>```

run this code in an applicationComplete event handler on the main application tag to put your app into full screen mode after it is finished loading.

Body:
Use the displayState property of the stage.  You can access the stage as a variable on the Application class.  So, conceptually, do this:

FlexGlobals.topLevelApplication.stage.displayState = StageDisplayState.FULL_SCREEN

run this code in an applicationComplete event handler on the main application tag to put your app into full screen mode after it is finished loading.


问:
how to run apache NifiModule on Azure IoT edge device?
I deployed apache nifi module on azure iot edge device with following desired properties:

```<code>{
    "certificatefile": "azure-iot-test-only.root.ca.cert.pem",
    "flowversion": "1.1",
    "accountname": "",
    "accountkey": "",
    "containername": ""
}
</code>```

I got following error while running the module:

I placed root ca certificate and flow file on edge device in /config folder.

Can anyone please suggest the solution? It failed to execute following command

```<code>[ERROR] Error loading certificate: Command failed: keytool -import -noprompt -alias iot-edge -file /config/azure-iot-test-only.root.ca.cert.pem -keystore /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts -storepass changeit
</code>```

Thanks..

答:
You need to make sure that the following service have read permissions for the directories holding the certificates and keys:

The private key file should be owned by the aziotks group.

The certificate files should be owned by the aziotcs group

Ref: Configure IoT Edge with the new certificates

Body:
I deployed apache nifi module on azure iot edge device with following desired properties:

{
    "certificatefile": "azure-iot-test-only.root.ca.cert.pem",
    "flowversion": "1.1",
    "accountname": "",
    "accountkey": "",
    "containername": ""
}

I got following error while running the module:

I placed root ca certificate and flow file on edge device in /config folder.

Can anyone please suggest the solution? It failed to execute following command

[ERROR] Error loading certificate: Command failed: keytool -import -noprompt -alias iot-edge -file /config/azure-iot-test-only.root.ca.cert.pem -keystore /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts -storepass changeit

Thanks..


问:
How to send Django model object's details as answer according to the user's choice of InlineKeyboardButton?
I'm new to creating telegram bots with Django. I selected python-telegram-bot library for creating bots with Django.

I've created a Django model, named as category:

```<code>class category(models.Model):
    name = models.CharField(max_length=250)
    category_id = models.IntegerField()

    def __str__(self):
        return self.name
</code>```

and product:

```<code>class product(models.Model):
    product_category = models.ForeignKey(category, on_delete=models.SET_NULL, blank=True, null=True)
    name = models.CharField(max_length=250)
    cost = models.FloatField()
    img = models.ImageField()

    def __str__(self):
        return self.name
</code>```

Successfully created InlineKeyboardButtons and placed id of each product model object to each button, with these functions:

```<code>def product(update: Update, context: CallbackContext):
    query = update.callback_query.data

    product_button_list = []

    for each in product.objects.select_related().filter(product_category_id = query):
        product_button_list.append(InlineKeyboardButton(each.name, callback_data=each.id))
    reply_markup = InlineKeyboardMarkup(build_menu(product_button_list,n_cols=2))
    update.callback_query.message.edit_text("Mahsulotni tanlang!", reply_markup=reply_markup)

def build_menu(buttons,n_cols,header_buttons=None,footer_buttons=None):
  menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
  if header_buttons:
    menu.insert(0, header_buttons)
  if footer_buttons:
    menu.append(footer_buttons)
  return menu
</code>```

When the user selects a button named as the name of the product model object, I am receiving the correct id of the product model object, tested with printing the query:

```<code>def product_info(update: Update, context: CallbackContext):
    query = update.callback_query.data
    print(query)

    obj = product.objects.filter(pk=query)
    print(obj)
</code>```

Question: How to reply Django product model object's fields including its image to the user according to the user's chosen product?

Like:

You have chosen a product:

Image of the product

Name of the product

Cost of the product

答:
Here is the answer, I have successed so far:</p>
```<code>filename = 'path_until_media_folder' + str(obj.img.url)

update.callback_query.bot.send_photo(update.effective_chat.id, photo=open(filename, 'rb'))
</code>```

Body:
I'm new to creating telegram bots with Django. I selected python-telegram-bot library for creating bots with Django.

I've created a Django model, named as category:

class category(models.Model):
    name = models.CharField(max_length=250)
    category_id = models.IntegerField()

    def __str__(self):
        return self.name

and product:

class product(models.Model):
    product_category = models.ForeignKey(category, on_delete=models.SET_NULL, blank=True, null=True)
    name = models.CharField(max_length=250)
    cost = models.FloatField()
    img = models.ImageField()

    def __str__(self):
        return self.name

Successfully created InlineKeyboardButtons and placed id of each product model object to each button, with these functions:

def product(update: Update, context: CallbackContext):
    query = update.callback_query.data

    product_button_list = []

    for each in product.objects.select_related().filter(product_category_id = query):
        product_button_list.append(InlineKeyboardButton(each.name, callback_data=each.id))
    reply_markup = InlineKeyboardMarkup(build_menu(product_button_list,n_cols=2))
    update.callback_query.message.edit_text("Mahsulotni tanlang!", reply_markup=reply_markup)

def build_menu(buttons,n_cols,header_buttons=None,footer_buttons=None):
  menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
  if header_buttons:
    menu.insert(0, header_buttons)
  if footer_buttons:
    menu.append(footer_buttons)
  return menu

When the user selects a button named as the name of the product model object, I am receiving the correct id of the product model object, tested with printing the query:

def product_info(update: Update, context: CallbackContext):
    query = update.callback_query.data
    print(query)

    obj = product.objects.filter(pk=query)
    print(obj)

Question: How to reply Django product model object's fields including its image to the user according to the user's chosen product?

Like:

You have chosen a product:

Image of the product

Name of the product

Cost of the product

Body:
Here is the answer, I have successed so far:

filename = 'path_until_media_folder' + str(obj.img.url)

update.callback_query.bot.send_photo(update.effective_chat.id, photo=open(filename, 'rb'))


问:
WooCommerce Custom Email template "template_base" not working properly
I'm developing a plugin that creates custom email templates.

The email templates will be stored on the plugin itself. However, this is not working properly. This is my Email Class

```<code> class SV_SplitEmail_New_Order extends WC_Email
{

    /**
     * Constructor.
     */
    public function __construct() {

        $this->id              = 'sv_split_new_order';
        $this->title           = __( 'New Order - Split Orders', 'woocommerce' );
        $this->description     = __( 'New order emails are sent to chosen recipient(s) when a new order is received. Compatible with Split and Plain orders. The default "New Order" email should be disabled.', 'woocommerce' );
        $this->customer_email  = false;
        $this->template_base   = SVTHEMING_PATH.'app/Providers/Order_Splitting/templates/';
        $this->template_html   = 'emails/admin-new-split-order.php';
        $this->placeholders    = array(
            '{order_date}'   => '',
            '{order_number}' => '',
        );

        // Triggers for this email.
        add_action( 'woocommerce_order_status_pending_to_processing_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_pending_to_completed_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_pending_to_on-hold_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_failed_to_processing_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_failed_to_completed_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_failed_to_on-hold_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_cancelled_to_processing_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_cancelled_to_completed_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_cancelled_to_on-hold_notification', array( $this, 'trigger' ), 10, 2 );

        // Call parent constructor.
        parent::__construct();

        // Other settings.
        $this->recipient = $this->get_option( 'recipient', get_option( 'admin_email' ) );
    }
</code>```

This shows up correctly on the dashboard.

However, when the emails get sent out, they are blank.

If I put the email template file on the site's theme folder, this works properly.

However, this is not ideal because on deployment / updates of the plugin, I will always have to update the theme's email templates.

I've made sure to define the $this->template_base correctly, and can confirm because the dashboard displays the correct file.

M I missing something?

答:
I'm not sure if you're still having this issue, but I have been up until recently and found the fix (at least for my problem). Hopefully it'll sort this for you, or help someone else out.

In the get_content_html() and get_content_plain() functions, you need to pass in the new template_base path. If you modify your functions (or add them if you haven't got them in your class) like this, it should solve it:

```<code>public function get_content_html() {
            return wc_get_template_html(
                    $this->template_html,
                    array(
                        'order'              => $this->object,
                        'email_heading'      => $this->get_heading(),
                        'additional_content' => $this->get_additional_content(),
                        'sent_to_admin'      => false,
                        'plain_text'         => false,
                        'email'              => $this,
                    ), '', $this->template_base
                );
        }

        public function get_content_plain() {
            return wc_get_template_html(
                    $this->template_plain,
                    array(
                        'order'              => $this->object,
                        'email_heading'      => $this->get_heading(),
                        'additional_content' => $this->get_additional_content(),
                        'sent_to_admin'      => false,
                        'plain_text'         => true,
                        'email'              => $this,
                    ), '', $this->template_base
                );
        }
</code>```

After that it seems to know where to look and my new email class certainly triggered fine.

Body:
I'm developing a plugin that creates custom email templates.

The email templates will be stored on the plugin itself. However, this is not working properly. This is my Email Class

 class SV_SplitEmail_New_Order extends WC_Email
{

    /**
     * Constructor.
     */
    public function __construct() {

        $this->id              = 'sv_split_new_order';
        $this->title           = __( 'New Order - Split Orders', 'woocommerce' );
        $this->description     = __( 'New order emails are sent to chosen recipient(s) when a new order is received. Compatible with Split and Plain orders. The default "New Order" email should be disabled.', 'woocommerce' );
        $this->customer_email  = false;
        $this->template_base   = SVTHEMING_PATH.'app/Providers/Order_Splitting/templates/';
        $this->template_html   = 'emails/admin-new-split-order.php';
        $this->placeholders    = array(
            '{order_date}'   => '',
            '{order_number}' => '',
        );

        // Triggers for this email.
        add_action( 'woocommerce_order_status_pending_to_processing_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_pending_to_completed_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_pending_to_on-hold_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_failed_to_processing_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_failed_to_completed_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_failed_to_on-hold_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_cancelled_to_processing_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_cancelled_to_completed_notification', array( $this, 'trigger' ), 10, 2 );
        add_action( 'woocommerce_order_status_cancelled_to_on-hold_notification', array( $this, 'trigger' ), 10, 2 );

        // Call parent constructor.
        parent::__construct();

        // Other settings.
        $this->recipient = $this->get_option( 'recipient', get_option( 'admin_email' ) );
    }

This shows up correctly on the dashboard.

However, when the emails get sent out, they are blank.

If I put the email template file on the site's theme folder, this works properly.

However, this is not ideal because on deployment / updates of the plugin, I will always have to update the theme's email templates.

I've made sure to define the $this->template_base correctly, and can confirm because the dashboard displays the correct file.

M I missing something?

Body:
I'm not sure if you're still having this issue, but I have been up until recently and found the fix (at least for my problem). Hopefully it'll sort this for you, or help someone else out.

In the get_content_html() and get_content_plain() functions, you need to pass in the new template_base path. If you modify your functions (or add them if you haven't got them in your class) like this, it should solve it:

public function get_content_html() {
            return wc_get_template_html(
                    $this->template_html,
                    array(
                        'order'              => $this->object,
                        'email_heading'      => $this->get_heading(),
                        'additional_content' => $this->get_additional_content(),
                        'sent_to_admin'      => false,
                        'plain_text'         => false,
                        'email'              => $this,
                    ), '', $this->template_base
                );
        }

        public function get_content_plain() {
            return wc_get_template_html(
                    $this->template_plain,
                    array(
                        'order'              => $this->object,
                        'email_heading'      => $this->get_heading(),
                        'additional_content' => $this->get_additional_content(),
                        'sent_to_admin'      => false,
                        'plain_text'         => true,
                        'email'              => $this,
                    ), '', $this->template_base
                );
        }

After that it seems to know where to look and my new email class certainly triggered fine.


问:
Subset groups in a data.table using conditions on two columns
I have a data.table with a high number of groups. I would like to subset whole groups (not just rows) based on the conditions on multiple columns. Consider the following data.table:

```<code>DT <- structure(list(id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L),
                 group = c("A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"),
                 y = c(14, 19, 16, 10, 6, 8, 14, 19, 10, 9, 6, 8),
                 x = c(3, 3, 2, 3, 3, 3, 3, 2, 2, 3, 3, 3)),
            row.names = c(NA, -12L),
            class = c("data.table", "data.frame"))
>DT

    id group  y x
 1:  1     A 14 3
 2:  2     A 19 3
 3:  3     A 16 2
 4:  4     A 10 3
 5:  5     B  6 3
 6:  6     B  8 3
 7:  7     B 14 3
 8:  8     B 19 2
 9:  9     C 10 2
10: 10     C  9 3
11: 11     C  6 3
12: 12     C  8 3
</code>```

I would like to keep groups that have y=6 and x=3 in the same row. So that I would have only class B and C (preferably using data.table package in R):

```<code>    id group  y x
 1:  5     B  6 3
 2:  6     B  8 3
 3:  7     B 14 3
 4:  8     B 19 2
 5:  9     C 10 2
 6: 10     C  9 3
 7: 11     C  6 3
 8: 12     C  8 3
</code>```

All my attempts gave me only those rows containing y=6 and x=3, which I do not want:

```<code>    id group  y x
 1:  5     B  6 3
 2: 11     C  6 3
</code>```

答:
Try dplyr package</p>
```<code>#select groups containing y and x
groups = DT %>% filter(y == 6, x == 3) %>% select(group) %>% unique() %>% unlist() %>% as.vector()

# filter for selected groups
DT %>% filter(group %in% groups)
</code>```

Body:
I have a data.table with a high number of groups. I would like to subset whole groups (not just rows) based on the conditions on multiple columns. Consider the following data.table:

DT <- structure(list(id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L),
                 group = c("A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"),
                 y = c(14, 19, 16, 10, 6, 8, 14, 19, 10, 9, 6, 8),
                 x = c(3, 3, 2, 3, 3, 3, 3, 2, 2, 3, 3, 3)),
            row.names = c(NA, -12L),
            class = c("data.table", "data.frame"))
>DT

    id group  y x
 1:  1     A 14 3
 2:  2     A 19 3
 3:  3     A 16 2
 4:  4     A 10 3
 5:  5     B  6 3
 6:  6     B  8 3
 7:  7     B 14 3
 8:  8     B 19 2
 9:  9     C 10 2
10: 10     C  9 3
11: 11     C  6 3
12: 12     C  8 3

I would like to keep groups that have y=6 and x=3 in the same row. So that I would have only class B and C (preferably using data.table package in R):

    id group  y x
 1:  5     B  6 3
 2:  6     B  8 3
 3:  7     B 14 3
 4:  8     B 19 2
 5:  9     C 10 2
 6: 10     C  9 3
 7: 11     C  6 3
 8: 12     C  8 3

All my attempts gave me only those rows containing y=6 and x=3, which I do not want:

    id group  y x
 1:  5     B  6 3
 2: 11     C  6 3

Body:
Try dplyr package

#select groups containing y and x
groups = DT %>% filter(y == 6, x == 3) %>% select(group) %>% unique() %>% unlist() %>% as.vector()

# filter for selected groups
DT %>% filter(group %in% groups)


问:
Simple string addition in ruby/rails
This is something I wasn't expecting.

I'm using anemone to count links in pages (anemone is a web spider framework for ruby)

Its pretty straightforward, but why won't this work?

```<code>anemone.on_every_page do |page|
    @myLinks =[]
      page.links.each_with_index do |link,index|
        puts "HOWDY PARDNER"
        @tempLink =(link.to_s + ",")
        @myLinks[index] = @tempLink
      end
end
</code>```

The part in question is the addition of link.to_s  +","

The reason I'm doing this addition is that links.to_s comes down as an entire string with no spaces. I'd like to sepsrate them with a , so I can use .split() later.

答:
to split (you mean join?) them later you don't need to add ",":

```<code>@my_links = ["Link 1", "Link 2", "Link 3"]
@my_links.join(", ")
#=> "Link 1, Link 2, Link 3"
@my_links.to_sentence
#=> "Link 1, Link 2, and Link 3"
</code>```

That's all you need, I think.

```<code>anemone.on_every_page do |page|
  @my_links = page.links.join(", ")
end
</code>```

Title: Simple string addition in ruby/rails

Body:
This is something I wasn't expecting.

I'm using anemone to count links in pages (anemone is a web spider framework for ruby)

Its pretty straightforward, but why won't this work?

anemone.on_every_page do |page|
    @myLinks =[]
      page.links.each_with_index do |link,index|
        puts "HOWDY PARDNER"
        @tempLink =(link.to_s + ",")
        @myLinks[index] = @tempLink
      end
end

The part in question is the addition of link.to_s  +","

The reason I'm doing this addition is that links.to_s comes down as an entire string with no spaces. I'd like to sepsrate them with a , so I can use .split() later.

Body:
to split (you mean join?) them later you don't need to add ",":

@my_links = ["Link 1", "Link 2", "Link 3"]
@my_links.join(", ")
#=> "Link 1, Link 2, Link 3"
@my_links.to_sentence
#=> "Link 1, Link 2, and Link 3"

That's all you need, I think.

anemone.on_every_page do |page|
  @my_links = page.links.join(", ")
end


问:
How to check if two [String: Any] are identical?
Is there any way to check if two [String: Any] are identical ?

```<code>let actual: [[String: Any]] = [
    ["id": 12345, "name": "Rahul Katariya"],
    ["id": 12346, "name": "Aar Kay"]
]
var expected: [[String: Any]]!

if actual == expected {
    print("Equal")
}
</code>```

Basically i want Dictionary to conform to Equatable protocol in Swift 3.

答:
With Swift 5.5 you can easily cast it to NSDictionary, as it always succeeds:

```<code>XCTAssertEqual(actual as NSDictionary, expected as NSDictionary)
</code>```

Body:
Is there any way to check if two [String: Any] are identical ?

let actual: [[String: Any]] = [
    ["id": 12345, "name": "Rahul Katariya"],
    ["id": 12346, "name": "Aar Kay"]
]
var expected: [[String: Any]]!

if actual == expected {
    print("Equal")
}

Basically i want Dictionary to conform to Equatable protocol in Swift 3.

Body:
With Swift 5.5 you can easily cast it to NSDictionary, as it always succeeds:

XCTAssertEqual(actual as NSDictionary, expected as NSDictionary)


问:
Error/bug removing table row using jQuery
I'm using a jQuery datatable with an action button setting at the last column. The action buttons are Add and Delete row. The traditional way of removing table row using jQuery is no doubt the remove method. Great its working.

```<code>$(this).closest('tr').remove();
</code>```

Adding new row to datatable has multiple option and my case was straight forward.

```<code>var table = $('#example').DataTable();
table.row.add( [input01,input02,buttons] ).draw( false );

//input01, input02, buttons (Add and Delete) are standard html element
</code>```

Now the issue comes when adding a new row the deleted rows will also appear.

Tried the using empty method but it's only deleting the table cell inside the triggered table row.

答:
This is because when you use $(this).closest('tr').remove();, the row is removed from the DOM but not removed from the DataTable instance. So it will reappear on your next .draw().

To actually remove it from the DOM and the DataTable instance, you should instead use this

```<code>table.row( $(this).closest('tr') ).remove().draw(false);
</code>```

Body:
I'm using a jQuery datatable with an action button setting at the last column. The action buttons are Add and Delete row. The traditional way of removing table row using jQuery is no doubt the remove method. Great its working.

$(this).closest('tr').remove();

Adding new row to datatable has multiple option and my case was straight forward.

var table = $('#example').DataTable();
table.row.add( [input01,input02,buttons] ).draw( false );

//input01, input02, buttons (Add and Delete) are standard html element

Now the issue comes when adding a new row the deleted rows will also appear.

Tried the using empty method but it's only deleting the table cell inside the triggered table row.

Body:
This is because when you use $(this).closest('tr').remove();, the row is removed from the DOM but not removed from the DataTable instance. So it will reappear on your next .draw().

To actually remove it from the DOM and the DataTable instance, you should instead use this

table.row( $(this).closest('tr') ).remove().draw(false);