问:
Docker - Replacement for `dockerd` on Mac
I wanted to start the docker daemon with an open TCP address like this: docker daemon -H tcp://0.0.0.0:2375, but the terminal suggested that I use dockerd instead, which is apparently not a program that comes with the Docker Client for mac. Is there a way I can either

A - get some form of dockerd on my mac machine.

B - get around the use of dockerd by some other method.

?

答:
get around the use of dockerd by some other method. (2016)

Note that in 2022, you can go without dockerd/Docker Desktop entirely.

See Batuhan Apaydin's article "A modern toolkit to start working with container images on macOS that meets your needs without requiring a Docker Daemon or even Docker Desktop".

It uses lima+nerdctl

The nerdctl tool is designed as a drop-in replacement for the Docker client

And Lima is a hypervisor that launches Linux virtual machines with automatic file sharing, port forwarding, and containerd.

The name of lima comes from an abbreviation of the first two capital letters of LInux MAchines.

The design of Lima is similar to WSL2, but Lima focuses on macOS as the primary target host.

Lima uses QEMU, which is a generic and open source machine emulator and virtualizer, as a hypervisor under the hood to achieve the virtualization thing.

Lima can also work with other container engines such as Podman and even for non-container applications.

By default, when lima launches a VM, it runs buildkitd and containerd in a rootless way and also downloads necessary client tooling around them such as buildctl, nerdctl.

Everything will be set up for us. So, all that’s left is building, pulling, and running containers

For buildkit, Batuhan proposes developer-guy/buildkit-machine

buildkit-machine allows you to make buildkitd daemon accessible in your macOS environment.

To do so, it uses lima, which is a Linux subsystem for macOS, under the hood.

lima spins up a VM that runs buildkitd daemon in a rootless way which means that sock file of the buildkitd daemon is now be able to accessible from /run/user/<USERID>/buildkit/buildkitd.

So: no more Docker Desktop / dockerd, and use container in a rootless mode!

For more, see Bret Fisher's video "Free Docker Desktop Alternatives: DevOps and Docker Live Show (Ep 156)" (Jan. 2022)


来源: stackexchange

问:
Shuffle a list of numbers, character and symbols
I was in the process of creating a simple program to generate a password with a 'List' consisting of numbers, symbols, and characters. In the process, I wanted to randomize and shuffle them.
I used the random.shuffle method to shuffle the list. My question (Sorry, very new to Python) - why cannot we store the outcome of a shuffle activity into a variable.
Giving an example here.

```<code>mylist = ["apple", "banana", "cherry"]
shufflefinal = random.shuffle(mylist)
</code>```

(Why cannot we store the random.shuffle(mylist) into a variable shufflefinal)
What is the rule here ? I understand how to get the outcome but wanted to understand the difference and the logic on why this cannot be stored and retrieved through a variable .

Your insight would be valuable .

答:
random.shuffle() function modifies the original list. This function returns None so it can't store modified list to shuffllefinal var.</p>
```<code>mylist = ["apple", "banana", "cherry"]
print("Before shuffle: ", mylist)
random.shuffle(mylist)
print("After shuffle: ", mylist)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was in the process of creating a simple program to generate a password with a 'List' consisting of numbers, symbols, and characters. In the process, I wanted to randomize and shuffle them.
I used the random.shuffle method to shuffle the list. My question (Sorry, very new to Python) - why cannot we store the outcome of a shuffle activity into a variable.
Giving an example here.

mylist = ["apple", "banana", "cherry"]
shufflefinal = random.shuffle(mylist)

(Why cannot we store the random.shuffle(mylist) into a variable shufflefinal)
What is the rule here ? I understand how to get the outcome but wanted to understand the difference and the logic on why this cannot be stored and retrieved through a variable .

Your insight would be valuable .

Body:
random.shuffle() function modifies the original list. This function returns None so it can't store modified list to shuffllefinal var.

mylist = ["apple", "banana", "cherry"]
print("Before shuffle: ", mylist)
random.shuffle(mylist)
print("After shuffle: ", mylist)


问:
how do I update price after in axios response using jquery?
I am writing inventory management system where I what the user to select product and I use axios to get the corresponding price of the product

It is a multiple rows where the user click on add product to select the product and the corresponding price displays

The jquery creates a new row of product and also which allows the user to select a product and it uses axios to request for the price from the server.

When the request returns the price from the server it update the price input field.

But it updates the price with 0 instead of the response from axios

$("#add-product").click(function(e) {
  e.preventDefault();
  $("#new-field").clone().appendTo("#wrapper");
});
$("#payment-method").change(function() {
  $(".full-payment").css({
    "display": "block"
  });
})

$("#wrapper").on('change', '.product', function(e) {
  e.preventDefault();
  $(this).closest('.row-field').find('.price').html("loading...")

  let price = 0;
  axios.get("/api/get-price/" + $(this).val())
    .then(function(response) {
      console.log(response.data.price)
      $(this).closest('.row-field').find('.price').html(price);
      $(this).closest('.row-field').find('.price').val(price);

    });

})

$("#wrapper").on('keyup', '.quantity', function() {
  var total = 0;
  let price = $(this).closest(".row-field").find(".price").val();
  console.log("price", price)
  if (isNaN(price)) {
    alert("Allow the rpice to load")
  } else {

    total = parseInt($(this).closest(".row-field").find(".price").val()) * parseInt($(this).val());
    if (isNaN(total)) {
      $(this).closest(".row-field").find(".sub-total").html(0.00);
      return;
    }
    $(this).closest(".row-field").find(".sub-total").html(total);
    console.log("total", total);

    var total = 0,
      val;
    $(".sub-total").each(function() {
      vals = parseInt($(this).text());
      console.log("value ", vals)
      val = isNaN(vals) || $.trim(vals) === "" ? 0 : parseFloat(vals);
      total += val;
    })
    $(".total").html(total);
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6 offset-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item">Dashboard</li>
            <li class="breadcrumb-item active">Add New Sales</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>

  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <!-- left column -->
        <div class="col-md-12">
          <!-- general form elements -->
          <div class="card card-primary">
            <div class="card-header">
              <h3 class="card-title">Add New Sales</h3>
            </div>
            <!-- /.card-header -->

            <!-- form start -->
            <form role="form" action="{{ url('admin/sales/store-sales') }}" method="post">
              @csrf
              <div class="card-body">
                <div class="row">

                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Payment Method</label>
                      <select name="payment_method" id="payment-method" class="form-control">
                        <option value="">Select Payment Method</option>
                        <option value="cash">Cash</option>
                        <option value="bank_transfer">Bank Transfer</option>
                      </select>
                      <!-- @if ($errors->first())
    <span style="font-size: 12px; color: red">{{ $errors->first('payment_method') }}</span>
    @endif -->
                    </div>
                  </div>
                  <div class="col-md-12 right my-3">
                    Add New Product
                  </div>
                  <div id="wrapper" class="col-md-12">
                    <div id="new-field" class="col-md-12 row-field">
                      <div class="row">

                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Product Name</label>
                            <select name="product[]" class="form-control product">
                              <option value="">Select Product Name</option>
                              @foreach ($products as $product)
                              <option value="{{ $product->id }}" name="product[]">
                                {{ $product->name }}</option>
                              @endforeach
                            </select>
                          </div>
                        </div>
                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Quantity</label>
                            <input type="text" name="quantity[]" class="form-control quantity" value="{{ old('quantity') }}" placeholder="Enter Quantity">
                          </div>
                        </div>
                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Unit Price</label>
                            <div class="price form-control">Price</div>
                            <input type="hidden" name="price[]" class="price" />
                          </div>
                        </div>
                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Sub Total</label>
                            <div class="form-control sub-total">0.00</div>
                          </div>
                        </div>
                      </div>
                    </div>

                  </div>
                </div>

                <!-- /.card-body -->
                <div id="new-field" class="row">
                  <div class="col-md-9">
                    Total
                  </div>
                  <div class="col-md-3 total">
                    N
                    <span>0.00</span>

                  </div>
                </div>
              </div>

              <div class="card-footer">
                <button type="submit" class="btn btn-primary float-md-right">Add Sales</button>
              </div>
            </form>
          </div>
          <!-- /.card -->
        </div>
        <!--/.col (left) -->
      </div>
      <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
  </section>
</div></code>```

答:
You have a field and a div with the same class. I would save

```<code>const $priceDiv = $(this).closest('.row-field').find('div.price');
$priceDiv.html("loading")
const $priceInp = $(this).closest('.row-field').find('input.price');

.then(function(response) {
  console.log(response.data.price);
  $priceDiv.html(response.data.price);
  $priceInp.val(response.data.price);
</code>```

Also remember to change more places:

```<code>$(this).closest(".row-field").find(".price").val();
</code>```

Body:
I am writing inventory management system where I what the user to select product and I use axios to get the corresponding price of the product

It is a multiple rows where the user click on add product to select the product and the corresponding price displays

The jquery creates a new row of product and also which allows the user to select a product and it uses axios to request for the price from the server.

When the request returns the price from the server it update the price input field.

But it updates the price with 0 instead of the response from axios

$("#add-product").click(function(e) {
  e.preventDefault();
  $("#new-field").clone().appendTo("#wrapper");
});
$("#payment-method").change(function() {
  $(".full-payment").css({
    "display": "block"
  });
})

$("#wrapper").on('change', '.product', function(e) {
  e.preventDefault();
  $(this).closest('.row-field').find('.price').html("loading...")

  let price = 0;
  axios.get("/api/get-price/" + $(this).val())
    .then(function(response) {
      console.log(response.data.price)
      $(this).closest('.row-field').find('.price').html(price);
      $(this).closest('.row-field').find('.price').val(price);

    });

})

$("#wrapper").on('keyup', '.quantity', function() {
  var total = 0;
  let price = $(this).closest(".row-field").find(".price").val();
  console.log("price", price)
  if (isNaN(price)) {
    alert("Allow the rpice to load")
  } else {

    total = parseInt($(this).closest(".row-field").find(".price").val()) * parseInt($(this).val());
    if (isNaN(total)) {
      $(this).closest(".row-field").find(".sub-total").html(0.00);
      return;
    }
    $(this).closest(".row-field").find(".sub-total").html(total);
    console.log("total", total);

    var total = 0,
      val;
    $(".sub-total").each(function() {
      vals = parseInt($(this).text());
      console.log("value ", vals)
      val = isNaN(vals) || $.trim(vals) === "" ? 0 : parseFloat(vals);
      total += val;
    })
    $(".total").html(total);
  }
})

Dashboard

Add New Sales

Add New Sales

            <form role="form" action="{{ url('admin/sales/store-sales') }}" method="post">
              @csrf

                      Payment Method
                      <select name="payment_method" id="payment-method" class="form-control">
                        <option value="">Select Payment Method</option>
                        <option value="cash">Cash</option>
                        <option value="bank_transfer">Bank Transfer</option>
                      </select>

                    Add New Product

                            Product Name
                            <select name="product[]" class="form-control product">
                              <option value="">Select Product Name</option>
                              @foreach ($products as $product)
                              <option value="{{ $product->id }}" name="product[]">
                                {{ $product->name }}</option>
                              @endforeach
                            </select>

                            Quantity
                            <input type="text" name="quantity[]" class="form-control quantity" value="{{ old('quantity') }}" placeholder="Enter Quantity">

                            Unit Price

Price

                            <input type="hidden" name="price[]" class="price" />

                            Sub Total

0.00

                    Total

                    N
                    0.00

                <button type="submit" class="btn btn-primary float-md-right">Add Sales</button>

            </form>

Body:
You have a field and a div with the same class. I would save

const $priceDiv = $(this).closest('.row-field').find('div.price');
$priceDiv.html("loading")
const $priceInp = $(this).closest('.row-field').find('input.price');

.then(function(response) {
  console.log(response.data.price);
  $priceDiv.html(response.data.price);
  $priceInp.val(response.data.price);

Also remember to change more places:

$(this).closest(".row-field").find(".price").val();


问:
Make cells negative based upon the value of another
I'm able to colour cells based upon the value of another with the code below, which I found on this forum

```<code>Sub ColorMeElmo()
   Dim i As Long, r1 As Range, r2 As Range

   For i = 2 To 100
      Set r1 = Range("D" & i)
      Set r2 = Range("A" & i & ":C" & i)
      If r1.Value = "Aankoop" Then r2.Interior.Color = vbRed
      If r1.Value = "Verkoop" Then r2.Interior.Color = vbBlue
      If r1.Value = "Dividend" Then r2.Interior.Color = vbYellow
   Next i
End Sub
</code>```

Now I'm trying to make cells negative or possitive based upon the value of r1.
I tried this:

```<code>If r1.Value = "Verkoop" Then r2.Value = r2.Value * (-1)
</code>```

答:
Ibrez’s answer is right. Anyway, I would recommend you write some clearer and more performant code (having 3 conditionals in each loop could be kind of slow if you have a big data sheet).  This is my suggestion:</p>
```<code>Public Sub ColorMeElmo()
   Dim i As Long, r1 As Range, r2 As Range, r3 As Range
   Dim color As Long
   Dim value2 As Integer, value3 As Integer

   For i = 2 To 100
      Set r1 = Range("A" & i)
      Set r2 = Range("B" & i)
      Set r3 = Range("C" & i)

      Select Case r1
          Case "Aankoop"
              color = vbRed
              value2 = r2
              value3 = r3
          Case "Verkoop"
              color = vbBlue
              value2 = -r2
              value3 = -r3
          Case "Dividend"
              color = vbYellow
              value2 = r2
              value3 = r3
          Case Else
              'some unexpected value would be highlighted in grey
              color = RGB(127, 127, 127)
              value2 = r2
              value3 = r3
      End Select

      r2.Interior.color = color
      r2 = value2
      r3.Interior.color = color
      r3 = value3
   Next i
End Sub
</code>```

Body:
I'm able to colour cells based upon the value of another with the code below, which I found on this forum

Sub ColorMeElmo()
   Dim i As Long, r1 As Range, r2 As Range

   For i = 2 To 100
      Set r1 = Range("D" & i)
      Set r2 = Range("A" & i & ":C" & i)
      If r1.Value = "Aankoop" Then r2.Interior.Color = vbRed
      If r1.Value = "Verkoop" Then r2.Interior.Color = vbBlue
      If r1.Value = "Dividend" Then r2.Interior.Color = vbYellow
   Next i
End Sub

Now I'm trying to make cells negative or possitive based upon the value of r1.
I tried this:

If r1.Value = "Verkoop" Then r2.Value = r2.Value * (-1)

Body:
Ibrez’s answer is right. Anyway, I would recommend you write some clearer and more performant code (having 3 conditionals in each loop could be kind of slow if you have a big data sheet).  This is my suggestion:

Public Sub ColorMeElmo()
   Dim i As Long, r1 As Range, r2 As Range, r3 As Range
   Dim color As Long
   Dim value2 As Integer, value3 As Integer

   For i = 2 To 100
      Set r1 = Range("A" & i)
      Set r2 = Range("B" & i)
      Set r3 = Range("C" & i)

      Select Case r1
          Case "Aankoop"
              color = vbRed
              value2 = r2
              value3 = r3
          Case "Verkoop"
              color = vbBlue
              value2 = -r2
              value3 = -r3
          Case "Dividend"
              color = vbYellow
              value2 = r2
              value3 = r3
          Case Else
              'some unexpected value would be highlighted in grey
              color = RGB(127, 127, 127)
              value2 = r2
              value3 = r3
      End Select

      r2.Interior.color = color
      r2 = value2
      r3.Interior.color = color
      r3 = value3
   Next i
End Sub


问:
Exoplayer Next button not clickable when Repeat Mode is REPEAT_MODE_ONE at the last video
I am using exoplayer 2.12 and when i reach the last video in the timeline and player.repeatMode = Player.REPEAT_MODE_ONE then Next button is not clickable . What i want is to make some action at that point of time to make next button clickable.

答:
You can override the below method of the Player interface.

```<code>override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
       super.onMediaItemTransition(mediaItem, reason)
       val currentIndex = currentWindowIndex
       // check if currentIndex is the last item by comparing with
       // exoPlayer.mediaItemCount
}
</code>```

This method is called every time the player is switched to a new item or the playlist is changed. You can set the repeatMode = Player.REPEAT_MODE_ALL if the item is last one in the playlist.

Body:
You can override the below method of the Player interface.

override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
       super.onMediaItemTransition(mediaItem, reason)
       val currentIndex = currentWindowIndex
       // check if currentIndex is the last item by comparing with
       // exoPlayer.mediaItemCount
}

This method is called every time the player is switched to a new item or the playlist is changed. You can set the repeatMode = Player.REPEAT_MODE_ALL if the item is last one in the playlist.


答:
According to the documentation on random.shuffle:

Shuffle the sequence x in place.

This means the list provided as argument is mutated. It follows the same principle as sort, which is also in-place.

If you want to leave the original list unmodified, then create a copy:

```<code>mylist = ["apple", "banana", "cherry"]
shufflefinal = mylist[:]  # Get a shallow copy
random.shuffle(shufflefinal)  # Shuffle the copy
</code>```

The above documentation mentions another way:

To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.

So in your case:

```<code>mylist = ["apple", "banana", "cherry"]
shufflefinal = random.sample(mylist, k=len(mylist))
</code>```

Title: Shuffle a list of numbers, character and symbols

Body:
According to the documentation on random.shuffle:

Shuffle the sequence x in place.

This means the list provided as argument is mutated. It follows the same principle as sort, which is also in-place.

If you want to leave the original list unmodified, then create a copy:

mylist = ["apple", "banana", "cherry"]
shufflefinal = mylist[:]  # Get a shallow copy
random.shuffle(shufflefinal)  # Shuffle the copy

The above documentation mentions another way:

To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.

So in your case:

mylist = ["apple", "banana", "cherry"]
shufflefinal = random.sample(mylist, k=len(mylist))


问:
Python getting input for test cases in competitive coding
How do I take input for T test cases with N values in a list.

Where T is the number of test cases and N is the length of inputs to be taken into a list

```<code>3
3
2 2 2
3
1 2 3
4
2 3 4 5
</code>```

I want to get out the lists to work on them like:

```<code>[2, 2, 2]
[1, 2, 3]
[2, 3, 4, 5]
</code>```

答:
You can take inputs using Python List Comprehension. Input for T test cases with N values in a list. I am using Python 3.x.</p>
```<code>T = int(input())  #Enter the No. of Testcases
input_list = [[j for j in input().split(' ')] for i in range(T)]
</code>```

Body:
How do I take input for T test cases with N values in a list.

Where T is the number of test cases and N is the length of inputs to be taken into a list

3
3
2 2 2
3
1 2 3
4
2 3 4 5

I want to get out the lists to work on them like:

[2, 2, 2]
[1, 2, 3]
[2, 3, 4, 5]

Body:
You can take inputs using Python List Comprehension. Input for T test cases with N values in a list. I am using Python 3.x.

T = int(input())  #Enter the No. of Testcases
input_list = [[j for j in input().split(' ')] for i in range(T)]


问:
Node.js global require
how can i require a module globally so i can use it in different modules without having to require it again?
or do i just have to do that everytime?
is there any best practice for this?

heres an example of what i am talking about.
lets say i have an index.js like this:

```<code>var a = require('a.js'),
utils = require('utils.js');

var str = 'hello this is a test';
str = a.change(str);

utils.return(str);
</code>```

a.js

```<code>var utils = require('utils.js');

exports.change = function(str) {
    str = str.replace('test', 'example');
    utils.return('i changed test to example!');
    return str;
}
</code>```

utils.js

```<code>exports.return = function (msg) {
    console.log(msg);
}
</code>```

you see i have to require('utils.js') twice, but i would rather require it once in the index.js and have it available in the index.js and a.js as utils.
is there any good way to accomplish that?

答:
For people googling this problem in the future you can use the global variable.
Only do this in really specific ocasions (eg: code replicated in every file)

global.mymodule = require("mymodule");
mymodule.abc // works in any file in the same process
```

ContentLicense: CC BY-SA 3.0

Title: Node.js global require

Body:
how can i require a module globally so i can use it in different modules without having to require it again?
or do i just have to do that everytime?
is there any best practice for this?

heres an example of what i am talking about.
lets say i have an index.js like this:

var a = require('a.js'),
utils = require('utils.js');

var str = 'hello this is a test';
str = a.change(str);

utils.return(str);

a.js

var utils = require('utils.js');

exports.change = function(str) {
    str = str.replace('test', 'example');
    utils.return('i changed test to example!');
    return str;
}

utils.js

exports.return = function (msg) {
    console.log(msg);
}

you see i have to require('utils.js') twice, but i would rather require it once in the index.js and have it available in the index.js and a.js as utils.
is there any good way to accomplish that?


问:
jQuery each function, skip a specific element
I'm trying to use the jQuery each function: http://api.jquery.com/each/

I have a list of things, and I want to perform different javascript for different list elements.

Here's  the  html code:

```<code><ul id="list-with-stuff">
    <li class='non-stuff'>foo</li>
    <li>bar</li>
</ul>
</code>```

And here's the javascript:

```<code>jQuery.fn.stuffplaylist = function() {

    return this.each(function() {

        if ($(this).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        }
        else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
};

$(document).ready(function() {
    $("#list-with-stuff").stuffplaylist();
});
</code>```

Check it out on jsfiddle here: http://jsfiddle.net/73gB9/

The problem I am having is not being able to work out how to determine what list element is selected, and thus run different javascript. For example I want to run the "TRUE" alert for the first element in the list, however it only runs the "FALSE" alert in it's current state.

I know it must be possible, however I'm inexperienced with Javascript & jQuery and haven't been able to work out from searching the internet.

With the above code if you make ul have the class 'non-stuff' then it does output the "TRUE" alert message, otherwise the "FALSE" alert pops up.

So if you know the best practice way of doing it then I am keen to hear your answer. Particularly if it helps me along with learning Javascript :-)

Thank you.

答:
```<code>return this.each(function(i, element) {
    if ($(element).hasClass('non-stuff') || !i) { // !i == 0 and 0 is first element
        alert("TRUE. Has non-stuff class");
        return true;
    } else {
        alert("FALSE. Has not got non-stuff class");
        return false;
    };
});
</code>```

Body:
I'm trying to use the jQuery each function: http://api.jquery.com/each/

I have a list of things, and I want to perform different javascript for different list elements.

Here's  the  html code:

foo

bar

And here's the javascript:

jQuery.fn.stuffplaylist = function() {

    return this.each(function() {

        if ($(this).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        }
        else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
};

$(document).ready(function() {
    $("#list-with-stuff").stuffplaylist();
});

Check it out on jsfiddle here: http://jsfiddle.net/73gB9/

The problem I am having is not being able to work out how to determine what list element is selected, and thus run different javascript. For example I want to run the "TRUE" alert for the first element in the list, however it only runs the "FALSE" alert in it's current state.

I know it must be possible, however I'm inexperienced with Javascript & jQuery and haven't been able to work out from searching the internet.

With the above code if you make ul have the class 'non-stuff' then it does output the "TRUE" alert message, otherwise the "FALSE" alert pops up.

So if you know the best practice way of doing it then I am keen to hear your answer. Particularly if it helps me along with learning Javascript :-)

Thank you.


问:
View javascript object model in real time
Are there tools or techniques (other than repeated console.log() calls) to view the javascript object model used in a web page in real time? eg something like:

```<code>    firstUser (User)
    -- userName Joe Bloggs (String)
    -- userEmail joe.bloggs@gmail.com (String)
    -- userSelections (Array)
    ----[1,2,4]

    secondUser (User)
    -- userName John Doe (String)
    -- userEmail jogn.doe@gmail.com (String)
    -- userSelections (Array)
    ----[1,2,3]
</code>```

I know this can be achieved using console.log(firstUser) and console.log(secondUser) but it would be useful to be able to display the entire data model so that I can see variables being altered in real time.

答:
One option is using the watch panel on the right inside the source tab to help you monitor different variables

You could also use the console.table() method (instead of console.log) which displays tabular data as a table.

Body:
Are there tools or techniques (other than repeated console.log() calls) to view the javascript object model used in a web page in real time? eg something like:

    firstUser (User)
    -- userName Joe Bloggs (String)
    -- userEmail joe.bloggs@gmail.com (String)
    -- userSelections (Array)
    ----[1,2,4]

    secondUser (User)
    -- userName John Doe (String)
    -- userEmail jogn.doe@gmail.com (String)
    -- userSelections (Array)
    ----[1,2,3]

I know this can be achieved using console.log(firstUser) and console.log(secondUser) but it would be useful to be able to display the entire data model so that I can see variables being altered in real time.


问:
Oracle - Rank and transform on columns
I got a sample data as below in this cte_orders. Each row is a order and contains the user_id, zone_code and zone_name.

I need to rank the top 3 zone_code for each user_id, and I need the output be on columns.
Like this

```<code>|user_id |  top1_zone  |  top2_zone  |  top3_zone  |
|--------+-------------+-------------+-------------+
|1000    |  5555-ABCD  |  4567-ZMNY  |  7888-IXPO  |
|--------+-------------+-------------+-------------+
|9999    |  3456-JJKL  |  7688-HBGT  |  5555-ABCD  |
|--------+-------------+-------------+-------------+
</code>```

Here's the SQL with the test data and the query that I'm trying.
The problem with this query is the result is given a row for each position of the rank.

```<code>(
    SELECT 1 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 2 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
    SELECT 3 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 4 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 5 as order_id, '1000' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
    SELECT 6 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
    SELECT 7 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
    SELECT 8 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 9 as order_id, '1000' as user_id, '1999' as zone_code, 'LNKJ' as zone_name from dual union all
    SELECT 10 as order_id, '1000' as user_id, '5677' as zone_code, 'OPLH' as zone_name from dual union all
    SELECT 11 as order_id, '1000' as user_id, '7888' as zone_code, 'IXPO' as zone_name from dual union all
    SELECT 12 as order_id, '9999' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
    SELECT 13 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
    SELECT 14 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 15 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
    SELECT 16 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
    SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
    SELECT 18 as order_id, '9999' as user_id, '1566' as zone_code, 'LNOI' as zone_name from dual union all
    SELECT 19 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
    SELECT 20 as order_id, '9999' as user_id, '7654' as zone_code, 'NNJJ' as zone_name from dual union all
    SELECT 21 as order_id, '9999' as user_id, '4433' as zone_code, 'NHJE' as zone_name from dual union all
    SELECT 22 as order_id, '9999' as user_id, '4111' as zone_code, 'ABHJ' as zone_name from dual

)

select
    user_id,
    CASE WHEN rank_zones = 1 then zone_concat end as top1_zone,
    CASE WHEN rank_zones = 2 then zone_concat end as top2_zone,
    CASE WHEN rank_zones = 3 then zone_concat end as top3_zone
    from

(
    select
        user_id,
        zone_code||'-'||zone_name as zone_concat,
        row_number() over (partition by user_id order by count(*) desc) rank_zones
    from cte_orders
    group by
        user_id,
        zone_code||'-'||zone_name

)
where rank_zones <= 3

group by
    user_id,
    CASE WHEN rank_zones = 1 then zone_concat end,
    CASE WHEN rank_zones = 2 then zone_concat end,
    CASE WHEN rank_zones = 3 then zone_concat end
order by user_id;
</code>```

The output that i getting

```<code>|user_id |  top1_zone  |  top2_zone  |  top3_zone  |
|--------+-------------+-------------+-------------+
|1000    |  5555-ABCD  |    (null)   |    (null)   |
|--------+-------------+-------------+-------------+
|1000    |    (null)   |  4567-ZMNY  |    (null)   |
|--------+-------------+-------------+-------------+
|1000    |    (null)   |    (null)   |  7888-IXPO  |
|--------+-------------+-------------+-------------+
|9999    |  3456-JJKL  |    (null)   |    (null)   |
|--------+-------------+-------------+-------------+
|9999    |    (null)   |  7688-HBGT  |    (null)   |
|--------+-------------+-------------+-------------+
|9999    |    (null)   |    (null)   |  5555-ABCD  |
|--------+-------------+-------------+-------------+
</code>```

How can i fix my query to get one row for each user_id without the nulls?

答:
You can use oracle pivot as below:

```<code> with cte_orders as(
     SELECT 1 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 2 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 3 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 4 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 5 as order_id, '1000' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
     SELECT 6 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 7 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 8 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 9 as order_id, '1000' as user_id, '1999' as zone_code, 'LNKJ' as zone_name from dual union all
     SELECT 10 as order_id, '1000' as user_id, '5677' as zone_code, 'OPLH' as zone_name from dual union all
     SELECT 11 as order_id, '1000' as user_id, '7888' as zone_code, 'IXPO' as zone_name from dual union all
     SELECT 12 as order_id, '9999' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
     SELECT 13 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 14 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 15 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 16 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
     SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
     SELECT 18 as order_id, '9999' as user_id, '1566' as zone_code, 'LNOI' as zone_name from dual union all
     SELECT 19 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 20 as order_id, '9999' as user_id, '7654' as zone_code, 'NNJJ' as zone_name from dual union all
     SELECT 21 as order_id, '9999' as user_id, '4433' as zone_code, 'NHJE' as zone_name from dual union all
     SELECT 22 as order_id, '9999' as user_id, '4111' as zone_code, 'ABHJ' as zone_name from dual

 ),
 cte as(select
         user_id,
         zone_code||'-'||zone_name as zone_concat,
         row_number() over (partition by user_id order by count(*) desc ) rank_zones
     from cte_orders
     group by
         user_id,
         zone_code||'-'||zone_name)

 select user_id,"1" top1_zone, "2" top2_zone, "3" top3_zone
 from cte
 PIVOT (
   MAX(ZONE_CONCAT) FOR rank_zones IN (1,2,3)
 )

</code>```

Output:

USER_ID
TOP1_ZONE
TOP2_ZONE
TOP3_ZONE

1000
5555-ABCD
4567-ZMNY
5599-HZTR

9999
3456-JJKL
5555-ABCD
7688-HBGT

db<>fiddle here

Or you can use decode in aggregation with group by:

```<code> with cte_orders as(
     SELECT 1 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 2 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 3 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 4 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 5 as order_id, '1000' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
     SELECT 6 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 7 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 8 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 9 as order_id, '1000' as user_id, '1999' as zone_code, 'LNKJ' as zone_name from dual union all
     SELECT 10 as order_id, '1000' as user_id, '5677' as zone_code, 'OPLH' as zone_name from dual union all
     SELECT 11 as order_id, '1000' as user_id, '7888' as zone_code, 'IXPO' as zone_name from dual union all
     SELECT 12 as order_id, '9999' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
     SELECT 13 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 14 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 15 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 16 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
     SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
     SELECT 18 as order_id, '9999' as user_id, '1566' as zone_code, 'LNOI' as zone_name from dual union all
     SELECT 19 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 20 as order_id, '9999' as user_id, '7654' as zone_code, 'NNJJ' as zone_name from dual union all
     SELECT 21 as order_id, '9999' as user_id, '4433' as zone_code, 'NHJE' as zone_name from dual union all
     SELECT 22 as order_id, '9999' as user_id, '4111' as zone_code, 'ABHJ' as zone_name from dual

 ),
 cte as(select
         user_id,
         zone_code||'-'||zone_name as zone_concat,
         row_number() over (partition by user_id order by count(*) desc ) rank_zones
     from cte_orders
     group by
         user_id,
         zone_code||'-'||zone_name)

 select user_id,
   max(decode(rank_zones,1,ZONE_CONCAT)) top1_zone,
   max(decode(rank_zones,2,ZONE_CONCAT)) top2_zone,
   max(decode(rank_zones,3,ZONE_CONCAT)) top3_zone
 from cte
 group by user_id
</code>```

Output:

USER_ID
TOP1_ZONE
TOP2_ZONE
TOP3_ZONE

1000
5555-ABCD
4567-ZMNY
5599-HZTR

9999
3456-JJKL
5555-ABCD
7688-HBGT

db<>fiddle here

Title: Oracle - Rank and transform on columns

Body:
I got a sample data as below in this cte_orders. Each row is a order and contains the user_id, zone_code and zone_name.

I need to rank the top 3 zone_code for each user_id, and I need the output be on columns.
Like this

|user_id |  top1_zone  |  top2_zone  |  top3_zone  |
|--------+-------------+-------------+-------------+
|1000    |  5555-ABCD  |  4567-ZMNY  |  7888-IXPO  |
|--------+-------------+-------------+-------------+
|9999    |  3456-JJKL  |  7688-HBGT  |  5555-ABCD  |
|--------+-------------+-------------+-------------+

Here's the SQL with the test data and the query that I'm trying.
The problem with this query is the result is given a row for each position of the rank.

(
    SELECT 1 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 2 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
    SELECT 3 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 4 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 5 as order_id, '1000' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
    SELECT 6 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
    SELECT 7 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
    SELECT 8 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 9 as order_id, '1000' as user_id, '1999' as zone_code, 'LNKJ' as zone_name from dual union all
    SELECT 10 as order_id, '1000' as user_id, '5677' as zone_code, 'OPLH' as zone_name from dual union all
    SELECT 11 as order_id, '1000' as user_id, '7888' as zone_code, 'IXPO' as zone_name from dual union all
    SELECT 12 as order_id, '9999' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
    SELECT 13 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
    SELECT 14 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 15 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
    SELECT 16 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
    SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
    SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
    SELECT 18 as order_id, '9999' as user_id, '1566' as zone_code, 'LNOI' as zone_name from dual union all
    SELECT 19 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
    SELECT 20 as order_id, '9999' as user_id, '7654' as zone_code, 'NNJJ' as zone_name from dual union all
    SELECT 21 as order_id, '9999' as user_id, '4433' as zone_code, 'NHJE' as zone_name from dual union all
    SELECT 22 as order_id, '9999' as user_id, '4111' as zone_code, 'ABHJ' as zone_name from dual

)

select
    user_id,
    CASE WHEN rank_zones = 1 then zone_concat end as top1_zone,
    CASE WHEN rank_zones = 2 then zone_concat end as top2_zone,
    CASE WHEN rank_zones = 3 then zone_concat end as top3_zone
    from

(
    select
        user_id,
        zone_code||'-'||zone_name as zone_concat,
        row_number() over (partition by user_id order by count(*) desc) rank_zones
    from cte_orders
    group by
        user_id,
        zone_code||'-'||zone_name

)
where rank_zones <= 3

group by
    user_id,
    CASE WHEN rank_zones = 1 then zone_concat end,
    CASE WHEN rank_zones = 2 then zone_concat end,
    CASE WHEN rank_zones = 3 then zone_concat end
order by user_id;

The output that i getting

|user_id |  top1_zone  |  top2_zone  |  top3_zone  |
|--------+-------------+-------------+-------------+
|1000    |  5555-ABCD  |    (null)   |    (null)   |
|--------+-------------+-------------+-------------+
|1000    |    (null)   |  4567-ZMNY  |    (null)   |
|--------+-------------+-------------+-------------+
|1000    |    (null)   |    (null)   |  7888-IXPO  |
|--------+-------------+-------------+-------------+
|9999    |  3456-JJKL  |    (null)   |    (null)   |
|--------+-------------+-------------+-------------+
|9999    |    (null)   |  7688-HBGT  |    (null)   |
|--------+-------------+-------------+-------------+
|9999    |    (null)   |    (null)   |  5555-ABCD  |
|--------+-------------+-------------+-------------+

How can i fix my query to get one row for each user_id without the nulls?

Body:
You can use oracle pivot as below:

 with cte_orders as(
     SELECT 1 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 2 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 3 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 4 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 5 as order_id, '1000' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
     SELECT 6 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 7 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 8 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 9 as order_id, '1000' as user_id, '1999' as zone_code, 'LNKJ' as zone_name from dual union all
     SELECT 10 as order_id, '1000' as user_id, '5677' as zone_code, 'OPLH' as zone_name from dual union all
     SELECT 11 as order_id, '1000' as user_id, '7888' as zone_code, 'IXPO' as zone_name from dual union all
     SELECT 12 as order_id, '9999' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
     SELECT 13 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 14 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 15 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 16 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
     SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
     SELECT 18 as order_id, '9999' as user_id, '1566' as zone_code, 'LNOI' as zone_name from dual union all
     SELECT 19 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 20 as order_id, '9999' as user_id, '7654' as zone_code, 'NNJJ' as zone_name from dual union all
     SELECT 21 as order_id, '9999' as user_id, '4433' as zone_code, 'NHJE' as zone_name from dual union all
     SELECT 22 as order_id, '9999' as user_id, '4111' as zone_code, 'ABHJ' as zone_name from dual

 ),
 cte as(select
         user_id,
         zone_code||'-'||zone_name as zone_concat,
         row_number() over (partition by user_id order by count(*) desc ) rank_zones
     from cte_orders
     group by
         user_id,
         zone_code||'-'||zone_name)

 select user_id,"1" top1_zone, "2" top2_zone, "3" top3_zone
 from cte
 PIVOT (
   MAX(ZONE_CONCAT) FOR rank_zones IN (1,2,3)
 )

Output:

USER_ID
TOP1_ZONE
TOP2_ZONE
TOP3_ZONE

1000
5555-ABCD
4567-ZMNY
5599-HZTR

9999
3456-JJKL
5555-ABCD
7688-HBGT

db<>fiddle here

Or you can use decode in aggregation with group by:

 with cte_orders as(
     SELECT 1 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 2 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 3 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 4 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 5 as order_id, '1000' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
     SELECT 6 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 7 as order_id, '1000' as user_id, '4567' as zone_code, 'ZMNY' as zone_name from dual union all
     SELECT 8 as order_id, '1000' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 9 as order_id, '1000' as user_id, '1999' as zone_code, 'LNKJ' as zone_name from dual union all
     SELECT 10 as order_id, '1000' as user_id, '5677' as zone_code, 'OPLH' as zone_name from dual union all
     SELECT 11 as order_id, '1000' as user_id, '7888' as zone_code, 'IXPO' as zone_name from dual union all
     SELECT 12 as order_id, '9999' as user_id, '5599' as zone_code, 'HZTR' as zone_name from dual union all
     SELECT 13 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 14 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 15 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 16 as order_id, '9999' as user_id, '5555' as zone_code, 'ABCD' as zone_name from dual union all
     SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
     SELECT 17 as order_id, '9999' as user_id, '7688' as zone_code, 'HBGT' as zone_name from dual union all
     SELECT 18 as order_id, '9999' as user_id, '1566' as zone_code, 'LNOI' as zone_name from dual union all
     SELECT 19 as order_id, '9999' as user_id, '3456' as zone_code, 'JJKL' as zone_name from dual union all
     SELECT 20 as order_id, '9999' as user_id, '7654' as zone_code, 'NNJJ' as zone_name from dual union all
     SELECT 21 as order_id, '9999' as user_id, '4433' as zone_code, 'NHJE' as zone_name from dual union all
     SELECT 22 as order_id, '9999' as user_id, '4111' as zone_code, 'ABHJ' as zone_name from dual

 ),
 cte as(select
         user_id,
         zone_code||'-'||zone_name as zone_concat,
         row_number() over (partition by user_id order by count(*) desc ) rank_zones
     from cte_orders
     group by
         user_id,
         zone_code||'-'||zone_name)

 select user_id,
   max(decode(rank_zones,1,ZONE_CONCAT)) top1_zone,
   max(decode(rank_zones,2,ZONE_CONCAT)) top2_zone,
   max(decode(rank_zones,3,ZONE_CONCAT)) top3_zone
 from cte
 group by user_id

Output:

USER_ID
TOP1_ZONE
TOP2_ZONE
TOP3_ZONE

1000
5555-ABCD
4567-ZMNY
5599-HZTR

9999
3456-JJKL
5555-ABCD
7688-HBGT

db<>fiddle here


问:
Exception: type 'Image' is not a subtype of type 'File?'
I have a function that returns an image, and another variable initialized as null. but when I call the function and update the state of the variable to get the returned image of the function I get this error :

Unhandled Exception: type 'Image' is not a subtype of type 'File?'

```<code>Future ff(String styleImagePath, String originalImagePath) async {
  ImageTransferFacade showtime = ImageTransferFacade();
  showtime.loadModel();
  var style_image =
      await showtime.loadStyleImage('assets/Tableau_Dashboard.jpg');
  var original_image =
      await showtime.loadoriginalImage('assets/Tableau_Dashboard.jpg');

  var output_image = await showtime.transfer(original_image, style_image);
  output_image = Image.memory(output_image);
  return output_image;
}

File? finalsd = null;
// This is where I'll use the 'finalsd' variable , but if I change type to Image instead of File
    child: Card(
                      child: (finalsd == null)
                          ? Image.file(File(_image.path))
                          : Image.file(File(finalsd!
                              .path)))))
</code>```

Error emerges here :

```<code>child: GestureDetector(
                  onTap: () {
                    ff(imageList[index], widget.image.path).then((value) {
                      setState(() {
                        finalsd = value;
</code>```

答:
Your method returns a Future containing the type Image. After resolving the Future in your GestureDetector you are assigning it to a variable of type File. Both types are not related and thus the error is thrown.

```<code>output_image = Image.memory(output_image);
return output_image;
</code>```

This creates and returns an Image and you are assigning it to this variable:

```<code>File? finalsd = null;
</code>```

Dart would probably also warn you about this if you would declare the generic type in the return type of your method:

```<code>Future<Image> ff(String styleImagePath, String originalImagePath) async {
</code>```

Body:
I have a function that returns an image, and another variable initialized as null. but when I call the function and update the state of the variable to get the returned image of the function I get this error :

Unhandled Exception: type 'Image' is not a subtype of type 'File?'

Future ff(String styleImagePath, String originalImagePath) async {
  ImageTransferFacade showtime = ImageTransferFacade();
  showtime.loadModel();
  var style_image =
      await showtime.loadStyleImage('assets/Tableau_Dashboard.jpg');
  var original_image =
      await showtime.loadoriginalImage('assets/Tableau_Dashboard.jpg');

  var output_image = await showtime.transfer(original_image, style_image);
  output_image = Image.memory(output_image);
  return output_image;
}

File? finalsd = null;
// This is where I'll use the 'finalsd' variable , but if I change type to Image instead of File
    child: Card(
                      child: (finalsd == null)
                          ? Image.file(File(_image.path))
                          : Image.file(File(finalsd!
                              .path)))))

Error emerges here :

child: GestureDetector(
                  onTap: () {
                    ff(imageList[index], widget.image.path).then((value) {
                      setState(() {
                        finalsd = value;

Body:
Your method returns a Future containing the type Image. After resolving the Future in your GestureDetector you are assigning it to a variable of type File. Both types are not related and thus the error is thrown.

output_image = Image.memory(output_image);
return output_image;

This creates and returns an Image and you are assigning it to this variable:

File? finalsd = null;

Dart would probably also warn you about this if you would declare the generic type in the return type of your method:

Future<Image> ff(String styleImagePath, String originalImagePath) async {


问:
Mock GoogleAPI request
I am using the google-maps gem.

I am trying to mock/stub api requests unsuccessfully.

```<code>module GoogleMap
  class Route
    attr_accessor :start_location, :end_location

    def initialize(start_location, end_location)
      @start_location = start_location
      @end_location = end_location
    end

    def driving_duration_in_seconds
      route.duration.value
    end

    def driving_distance_in_meters
      route.distance.value
    end

    def driving_distance_hash
      return unless start_location && end_location

      { distance_in_meters: driving_distance_in_meters, duration_in_seconds: driving_duration_in_seconds }
    end

    private

    def coordinates_as_strings(location)
      "#{location.latitude},#{location.longitude}"
    end

    def route
      @route ||= Google::Maps.route(coordinates_as_strings(start_location), coordinates_as_strings(end_location))
    end
  end
end
</code>```

I need to stub:

```<code> WebMock::NetConnectNotAllowedError:
   Real HTTP connections are disabled. Unregistered request: GET https://maps.googleapis.com/maps/api/directions/json?destination=37.19687112,116.43791248&key=<apikey>&language=en&origin=2.15362819,-81.63712649 with headers {'Accept'=>'*/*', 'Date'=>'Sat, 12 Feb 2022 21:35:55 GMT', 'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'}

   You can stub this request with the following snippet:

   stub_request(:get, "https://maps.googleapis.com/maps/api/directions/json?destination=37.19687112,116.43791248&key=<apikey>&language=en&origin=2.15362819,-81.63712649").
     with(
       headers: {
      'Accept'=>'*/*',
      'Date'=>'Sat, 12 Feb 2022 21:35:55 GMT',
      'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'
       }).
     to_return(status: 200, body: "", headers: {})
</code>```

If I try a most basic stub I get an error:

```<code>    stub_request(:any, /maps.googleapis.com/).
    to_return(status: 200, body: '', headers: {})
</code>```
```<code>     Google::Maps::InvalidResponseException:
       unknown error: 783: unexpected token at ''
     # .../gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:64:in `rescue in response'
     # .../gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:60:in `response'
     # .../.rvm/gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:27:in `query'
</code>```

I think it is erroring out because I am not passing a key in. But I don't see why I should have to pass in a valid api key into a webmock.

I also would not have my route defined by anything. And in order to test that route can return route.distance.value etc, I would need to mock with something.

For other tests I was successful in mocking instances, but to test this lib that it actually works, I feel like mocking instance methods and not that an api was actually called is a waste of a test. Maybe this is just a waste of time, and I should assume it works because I am using a gem.

But I was expecting something like this:

```<code>RSpec.describe GoogleMap do
  let(:start_location) { create(:location) }
  let(:end_location) { create(:location) }

  context 'GoogleMaps::Route.new(start_location, end_location)' do
    let(:subject) { GoogleMap::Route.new(start_location, end_location) }

    # I have not been successful in stubbing this with the correct regex

    # stub_request(:get, "https://maps.googleapis.com/maps/api/directions/json?destination=<lat>,<long>key=<key>&language=en&origin=<lat>,<long>").
    # with(
    #   headers: {
    #  'Accept'=>'*/*',
    #  'Date'=>'Thu, 10 Feb 2022 21:09:02 GMT',
    #  'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'
    #   }).
    # to_return(status: 200, body: "", headers: {})
    # stub_request(:get, %r{https:\/\/maps\.googleapis\.com\/maps\/api\/directions\/json\?destination=.+,.+&key=.+&language=en&origin=.+,.+}).
    # stub_request(:any, /maps.googleapis.com/).
    # to_return(status: 200, body: '', headers: {})

    xit 'gives driving distance in seconds'
    xit 'gives driving duration in meters'
  end
end
</code>```

答:
Your WebMock is working fine. Google::Maps::InvalidResponseException is raised after WebMock has replaced the network call. At the point that exception is raised, the Google Maps API client is trying to parse what the network call returned, which is ''.

It's expecting some valid JSON to be returned. If you have your mock return {} is should get past that line. It may well stumble on some other exception later though, as the gem expects a certain schema.

You can dig that out and add in a valid response if you wanted to continue down this path. However, I'd recommend not mocking the network request as that's an implementation detail of a third party piece of code which could change at any time - making your test fail. Instead, I would mock out Google::Maps.route to return what you need it to.

Title: Mock GoogleAPI request

Body:
I am using the google-maps gem.

I am trying to mock/stub api requests unsuccessfully.

module GoogleMap
  class Route
    attr_accessor :start_location, :end_location

    def initialize(start_location, end_location)
      @start_location = start_location
      @end_location = end_location
    end

    def driving_duration_in_seconds
      route.duration.value
    end

    def driving_distance_in_meters
      route.distance.value
    end

    def driving_distance_hash
      return unless start_location && end_location

      { distance_in_meters: driving_distance_in_meters, duration_in_seconds: driving_duration_in_seconds }
    end

    private

    def coordinates_as_strings(location)
      "#{location.latitude},#{location.longitude}"
    end

    def route
      @route ||= Google::Maps.route(coordinates_as_strings(start_location), coordinates_as_strings(end_location))
    end
  end
end

I need to stub:

 WebMock::NetConnectNotAllowedError:
   Real HTTP connections are disabled. Unregistered request: GET https://maps.googleapis.com/maps/api/directions/json?destination=37.19687112,116.43791248&key=<apikey>&language=en&origin=2.15362819,-81.63712649 with headers {'Accept'=>'*/*', 'Date'=>'Sat, 12 Feb 2022 21:35:55 GMT', 'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'}

   You can stub this request with the following snippet:

   stub_request(:get, "https://maps.googleapis.com/maps/api/directions/json?destination=37.19687112,116.43791248&key=<apikey>&language=en&origin=2.15362819,-81.63712649").
     with(
       headers: {
      'Accept'=>'*/*',
      'Date'=>'Sat, 12 Feb 2022 21:35:55 GMT',
      'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'
       }).
     to_return(status: 200, body: "", headers: {})

If I try a most basic stub I get an error:

    stub_request(:any, /maps.googleapis.com/).
    to_return(status: 200, body: '', headers: {})

     Google::Maps::InvalidResponseException:
       unknown error: 783: unexpected token at ''
     # .../gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:64:in `rescue in response'
     # .../gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:60:in `response'
     # .../.rvm/gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:27:in `query'

I think it is erroring out because I am not passing a key in. But I don't see why I should have to pass in a valid api key into a webmock.

I also would not have my route defined by anything. And in order to test that route can return route.distance.value etc, I would need to mock with something.

For other tests I was successful in mocking instances, but to test this lib that it actually works, I feel like mocking instance methods and not that an api was actually called is a waste of a test. Maybe this is just a waste of time, and I should assume it works because I am using a gem.

But I was expecting something like this:

RSpec.describe GoogleMap do
  let(:start_location) { create(:location) }
  let(:end_location) { create(:location) }

  context 'GoogleMaps::Route.new(start_location, end_location)' do
    let(:subject) { GoogleMap::Route.new(start_location, end_location) }

    # I have not been successful in stubbing this with the correct regex

    # stub_request(:get, "https://maps.googleapis.com/maps/api/directions/json?destination=<lat>,<long>key=<key>&language=en&origin=<lat>,<long>").
    # with(
    #   headers: {
    #  'Accept'=>'*/*',
    #  'Date'=>'Thu, 10 Feb 2022 21:09:02 GMT',
    #  'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'
    #   }).
    # to_return(status: 200, body: "", headers: {})
    # stub_request(:get, %r{https:\/\/maps\.googleapis\.com\/maps\/api\/directions\/json\?destination=.+,.+&key=.+&language=en&origin=.+,.+}).
    # stub_request(:any, /maps.googleapis.com/).
    # to_return(status: 200, body: '', headers: {})

    xit 'gives driving distance in seconds'
    xit 'gives driving duration in meters'
  end
end


问:
Add "...Read More" to the end of UILabel
I have a UILabel and in some cases the text is longer then the UILabel itself, so I see the text as "bla bla bla..." I want to add a ...Read More button text at the end of the UILabel..

I've read some posts but they offer solutions that are not good to me, for example: to calculate how many characters will enter the UILabel, but with the font i'm using each character has a different width.

How can I manage to do that?

Thanks in advance!

答:
I couldn't get anything here to work so I'm posting my solution. I had a UILabel that was supposed to be 3 lines and at the end of the text it should read ... Read more. I made a UIFont extension that calculates the height of a string with a particular font and width and then I made a String extension that recursively makes a string smaller until it fits into x lines.

```<code>extension String {
    /**
This method returns a substring of a string that fits in a label with a specific width and number of lines
It has optional suffix so you can add your own ellipsis, like "... Read more"
 - Parameter width: The label width that constrains the text. Make sure to call it after subViews have been laid out
 - Parameter lines: Number of allowed lines in the label
 - Parameter font: The font to use with the label
 - Parameter suffix: Custom string that will be added to the string and will fit within the width/lines constraint
 - Returns: A substring that fits within the constraints given
 */
func textThatFits(width: CGFloat, lines: Int, font: UIFont, suffix: String = "") -> String {
    let lineHeight = font.lineHeight
    let completeString = self + suffix
    let size = font.sizeOfString(completeString, constrainedToWidth: width)
    if size.height > lineHeight * CGFloat(lines) {
        let partialString = self.components(separatedBy: " ").dropLast().joined(separator: " ")
        return partialString.textThatFits(width: width, lines: lines, font: font, suffix: suffix)
    } else {
        return completeString
    }
}
}

extension UIFont {
    /**
 Calculate the height of a string with this font and constrained width
 - Parameter string: String to calculate size for
 - Parameter width: The constrained width for the bounding box when calculating the size
 - Returns: Size of string contained in bounding rect of width and max height
 */
func sizeOfString(_ string: String, constrainedToWidth width: Double) -> CGSize {
    return (string as NSString).boundingRect(
        with: CGSize(width: width, height: .greatestFiniteMagnitude),
        options: [.usesFontLeading, .usesLineFragmentOrigin],
        attributes: [.font: self],
        context: nil).size
}
}
</code>```

Then I had to call it from viewDidLayoutSubviews since my label's width wasn't correct until then. Lastly, I used this like this:

```<code>private func setReadMoreText() {
    let readMoreSuffix = "... Read more"
    let font = // YOUR_FONT
    let fittingString = YOUR_LONG_STRING.textThatFits(width: YOUR_UILABEL.frame.width, lines: NUMBER_OF_LINES, font: font, suffix: readMoreSuffix)
    // This is not needed but I wanted the Read more text to be colored. You could just set your fittingString directly as text.
    let privacyAttrString = NSMutableAttributedString(string: fittingString, attributes: [.font: font])
    privacyAttrString.addAttributes([.foregroundColor: YOUR_COLOR], range: NSRange(location: fittingString.count - readMoreSuffix.count + 4, length: readMoreSuffix.count - 4))
    self.YOUR_UILABEL.text = privacyAttrString
}
</code>```

Body:
I couldn't get anything here to work so I'm posting my solution. I had a UILabel that was supposed to be 3 lines and at the end of the text it should read ... Read more. I made a UIFont extension that calculates the height of a string with a particular font and width and then I made a String extension that recursively makes a string smaller until it fits into x lines.

extension String {
    /**
This method returns a substring of a string that fits in a label with a specific width and number of lines
It has optional suffix so you can add your own ellipsis, like "... Read more"
 - Parameter width: The label width that constrains the text. Make sure to call it after subViews have been laid out
 - Parameter lines: Number of allowed lines in the label
 - Parameter font: The font to use with the label
 - Parameter suffix: Custom string that will be added to the string and will fit within the width/lines constraint
 - Returns: A substring that fits within the constraints given
 */
func textThatFits(width: CGFloat, lines: Int, font: UIFont, suffix: String = "") -> String {
    let lineHeight = font.lineHeight
    let completeString = self + suffix
    let size = font.sizeOfString(completeString, constrainedToWidth: width)
    if size.height > lineHeight * CGFloat(lines) {
        let partialString = self.components(separatedBy: " ").dropLast().joined(separator: " ")
        return partialString.textThatFits(width: width, lines: lines, font: font, suffix: suffix)
    } else {
        return completeString
    }
}
}

extension UIFont {
    /**
 Calculate the height of a string with this font and constrained width
 - Parameter string: String to calculate size for
 - Parameter width: The constrained width for the bounding box when calculating the size
 - Returns: Size of string contained in bounding rect of width and max height
 */
func sizeOfString(_ string: String, constrainedToWidth width: Double) -> CGSize {
    return (string as NSString).boundingRect(
        with: CGSize(width: width, height: .greatestFiniteMagnitude),
        options: [.usesFontLeading, .usesLineFragmentOrigin],
        attributes: [.font: self],
        context: nil).size
}
}

Then I had to call it from viewDidLayoutSubviews since my label's width wasn't correct until then. Lastly, I used this like this:

private func setReadMoreText() {
    let readMoreSuffix = "... Read more"
    let font = // YOUR_FONT
    let fittingString = YOUR_LONG_STRING.textThatFits(width: YOUR_UILABEL.frame.width, lines: NUMBER_OF_LINES, font: font, suffix: readMoreSuffix)
    // This is not needed but I wanted the Read more text to be colored. You could just set your fittingString directly as text.
    let privacyAttrString = NSMutableAttributedString(string: fittingString, attributes: [.font: font])
    privacyAttrString.addAttributes([.foregroundColor: YOUR_COLOR], range: NSRange(location: fittingString.count - readMoreSuffix.count + 4, length: readMoreSuffix.count - 4))
    self.YOUR_UILABEL.text = privacyAttrString
}


问:
PHP send variable value external webpage
I'm currently trying to send the two variable values, $incorrect and $correct from a form.

I have tried to use $_POST[] to create this functionality, yet it doesn't work!

Could anyone help me when creating such a functionality  ?

page1.php

```<code><form action="testresult.php" method="POST">
    <label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
    <input type="text" id="question1_answer" name="question1_answer" required><br><br>

    <label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
    <input type="text" id="question2_answer" name="question2_answer" required><br><br>

    <label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
    <input type="text" id="question3_answer" name="question3_answer" required><br><br>

    <input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />

    <input type="submit" name="submitAnswers" value="Submit">
</form>

<?php
        if(isset($_POST["submitAnswers"])){
            $correct = 0;
            $incorrect = 0;
            $qn1_ans = $_POST['question1_answer'];
            $qn2_ans = $_POST['question2_answer'];
            $qn3_ans = $_POST['question3_answer'];

            if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
            else { $incorrect ++; }

        }
    ?>
</code>```

And on the receiving end
page2.php

```<code><html>
    <head>
    <title>Results</title>
    </head>
    <body>
        <?php
        $correct = $_POST['correct'];
        $incorrect = $_POST['incorrect'];

        echo $correct."test ".$incorrect;
        ?>
    </body>
</html>
</code>```

答:
Where did those variables from from?

In your code you're calling two vars $array_answer and $question_num_array.

None of these two variables are set! Please fix this issue.

Body:
I'm currently trying to send the two variable values, $incorrect and $correct from a form.

I have tried to use $_POST[] to create this functionality, yet it doesn't work!

Could anyone help me when creating such a functionality  ?

page1.php

<form action="testresult.php" method="POST">
    Question 1: <?php echo $array_question[$question_num_array[0]] ?>

    <input type="text" id="question1_answer" name="question1_answer" required>

    Question 2: <?php echo $array_question[$question_num_array[1]] ?>

    <input type="text" id="question2_answer" name="question2_answer" required>

    Question 3: <?php echo $array_question[$question_num_array[2]] ?>

    <input type="text" id="question3_answer" name="question3_answer" required>

    <input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />

    <input type="submit" name="submitAnswers" value="Submit">
</form>

<?php
        if(isset($_POST["submitAnswers"])){
            $correct = 0;
            $incorrect = 0;
            $qn1_ans = $_POST['question1_answer'];
            $qn2_ans = $_POST['question2_answer'];
            $qn3_ans = $_POST['question3_answer'];

            if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
            else { $incorrect ++; }

        }
    ?>

And on the receiving end
page2.php

    <title>Results</title>

        <?php
        $correct = $_POST['correct'];
        $incorrect = $_POST['incorrect'];

        echo $correct."test ".$incorrect;
        ?>


问:
How can I apply reinforcement learning to continuous action spaces?
I'm trying to get an agent to learn the mouse movements necessary to best perform some task in a reinforcement learning setting (i.e. the reward signal is the only feedback for learning).

I'm hoping to use the Q-learning technique, but while I've found a way to extend this method to continuous state spaces, I can't seem to figure out how to accommodate a problem with a continuous action space.

I could just force all mouse movement to be of a certain magnitude and in only a certain number of different directions, but any reasonable way of making the actions discrete would yield a huge action space. Since standard Q-learning requires the agent to evaluate all possible actions, such an approximation doesn't solve the problem in any practical sense.

答:
There are numerous ways to extend reinforcement learning to continuous actions. One way is to use actor-critic methods. Another way is to use policy gradient methods.

A rather extensive explanation of different methods can be found in the following paper, which is available online:
Reinforcement Learning in Continuous State and Action Spaces (by Hado van Hasselt and Marco A. Wiering).


问:
How do I get to tap on a CustomPaint path in Flutter using GestureDetect?
I'm very new to flutter and am trying to figure out how to get a gesture detected on a CustomPaint path. I can click on a host of other things but not on paths for some reason... How do I get this to work? My code thus far is below.

import 'package:flutter/material.dart';

void main() => runApp(MbiraShapes());

class MbiraShapes extends StatefulWidget {
    @override
  _MbiraShapesState createState() => _MbiraShapesState();
}

class _MbiraShapesState extends State<MbiraShapes>{

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Mbira Shapes',
        home: PathExample());
  }
}

class PathExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: KeyPathPainter(),
    );
  }
}

class KeyPathPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint lineDrawer = Paint()
      ..color = Colors.blue
      ..strokeWidth = 8.0;

    Path path = Path()
// Moves to starting point
      ..moveTo(50, 50)
      //draw lines passing through xc, yc to end at x,y
      ..quadraticBezierTo(77, 370, 50, 750)
      ..quadraticBezierTo(100, 775, 150, 750)
      ..quadraticBezierTo(110, 440, 75, 50);
    //close shape from last point
    path.close();
    canvas.drawPath(path, lineDrawer);

    Path path2 = Path()
// Moves to starting point
      ..moveTo(250, 50)
      //draw lines passing through xc, yc to end at x,y
      ..quadraticBezierTo(280, 350, 270, 675)
      ..quadraticBezierTo(290, 750, 350, 750)
      ..quadraticBezierTo(365, 710, 345, 600)
      ..quadraticBezierTo(320, 450, 270, 50);
    //close shape from last point
    path2.close();
    canvas.drawPath(path2, lineDrawer);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}```
</div>
</div>
</p>

<p>I tried the snippet below with GestureDetector but it does not work.
I tried a Listener but get no response for onPointerDown, only for onPointerMove, but I need a tap action, not a move action.  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text("widget.title)"),
      ),

      body: Center(
        child: GestureDetector(
          child: CustomPaint(
            painter: KeyPathPainter(),
            child: Container()),
          onTap: () {
            print("tapped the key");
          },
        ),
      ),
    );
  }</code>```

I just want to tap a key and get a response, it will be a sound in the end but for now, I'm just trying to figure out how to get the onTap to work.

答:
You should have a child of CustomPaint</p>
```<code>   @override
   Widget build(BuildContext context) {
     return CustomPaint(
       painter: YourAwesomePainter(),
       child: Container(), // this line will solve the tap problem
    );
   }
</code>```

Body:
I'm very new to flutter and am trying to figure out how to get a gesture detected on a CustomPaint path. I can click on a host of other things but not on paths for some reason... How do I get this to work? My code thus far is below.

import 'package:flutter/material.dart';

void main() => runApp(MbiraShapes());

class MbiraShapes extends StatefulWidget {
    @override
  _MbiraShapesState createState() => _MbiraShapesState();
}

class _MbiraShapesState extends State<MbiraShapes>{

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Mbira Shapes',
        home: PathExample());
  }
}

class PathExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: KeyPathPainter(),
    );
  }
}

class KeyPathPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint lineDrawer = Paint()
      ..color = Colors.blue
      ..strokeWidth = 8.0;

    Path path = Path()
// Moves to starting point
      ..moveTo(50, 50)
      //draw lines passing through xc, yc to end at x,y
      ..quadraticBezierTo(77, 370, 50, 750)
      ..quadraticBezierTo(100, 775, 150, 750)
      ..quadraticBezierTo(110, 440, 75, 50);
    //close shape from last point
    path.close();
    canvas.drawPath(path, lineDrawer);

    Path path2 = Path()
// Moves to starting point
      ..moveTo(250, 50)
      //draw lines passing through xc, yc to end at x,y
      ..quadraticBezierTo(280, 350, 270, 675)
      ..quadraticBezierTo(290, 750, 350, 750)
      ..quadraticBezierTo(365, 710, 345, 600)
      ..quadraticBezierTo(320, 450, 270, 50);
    //close shape from last point
    path2.close();
    canvas.drawPath(path2, lineDrawer);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

I tried the snippet below with GestureDetector but it does not work.
I tried a Listener but get no response for onPointerDown, only for onPointerMove, but I need a tap action, not a move action.

@override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text("widget.title)"),
      ),

      body: Center(
        child: GestureDetector(
          child: CustomPaint(
            painter: KeyPathPainter(),
            child: Container()),
          onTap: () {
            print("tapped the key");
          },
        ),
      ),
    );
  }

I just want to tap a key and get a response, it will be a sound in the end but for now, I'm just trying to figure out how to get the onTap to work.

Body:
You should have a child of CustomPaint

   @override
   Widget build(BuildContext context) {
     return CustomPaint(
       painter: YourAwesomePainter(),
       child: Container(), // this line will solve the tap problem
    );
   }


问:
How to subtract 2 columns in WHERE condition with Laravel Eloquent
```<code>Trjual_h::where('Kd_Pelanggan', '=', $get)
        ->where('Nilai_Faktur', '-', 'Nilai_Bayar', '>=', '0')
        ->select('Nilai_Faktur', 'Tgl_Faktur', 'Lama_Piutang', 'No_Faktur', 'Nilai_Bayar')
        ->get();
</code>```

I need something like

Select Nilai_Faktur, Tgl_Faktur, Lama_Piutang, No_Faktur, Nilai_Bayar
where (Kd_Pelanggan = XXX11) AND (Nilai_Faktur - Nilai_Bayar > 0)
```

But it kept ignoring the two conditions when I run the query, and displaying all available data in my table. Already tried using DB::raw() but it keeps giving me an error.

答:
simply, you can use query builder</p>
```<code>$clients_due_amount = Client::select(DB::raw('SUM(amount - paid) as due_amount'))->first();
</code>```

Body:
Trjual_h::where('Kd_Pelanggan', '=', $get)
        ->where('Nilai_Faktur', '-', 'Nilai_Bayar', '>=', '0')
        ->select('Nilai_Faktur', 'Tgl_Faktur', 'Lama_Piutang', 'No_Faktur', 'Nilai_Bayar')
        ->get();

I need something like

Select Nilai_Faktur, Tgl_Faktur, Lama_Piutang, No_Faktur, Nilai_Bayar
where (Kd_Pelanggan = XXX11) AND (Nilai_Faktur - Nilai_Bayar > 0)

But it kept ignoring the two conditions when I run the query, and displaying all available data in my table. Already tried using DB::raw() but it keeps giving me an error.

Body:
simply, you can use query builder

$clients_due_amount = Client::select(DB::raw('SUM(amount - paid) as due_amount'))->first();


问:
jpa doesn't update data in db when entity changes?
More precisely, it does this within the method, but at the end of the method, these changes are not saved. I cannot make it @Transaction. it is multi-threaded and adds dependent entities.
How can this be fixed?</p>

答:
Inside a method, an entity that is fetched from repository, is in managed JPA state. This means that changes been done at this entity when the method finishes will be persisted in Database automatically. For this to happen though it is neccessary that the method is inside a Transaction. So this method or some other method that has called this method must have @Transactional in order for a transaction to be around the method.

If you don't want to have on this method or some other method that calls this method the @Transactional then your only chance of achieving what you want is to manually store the entity before your method ends. You should at this point do yourRepository.save(yourUpdatedEntity);


问:
Reversing Sencha Touch 2 Scrollbar
I am implementing a sencha touch app on the desktop and I am looking to “reverse” the direction of the scrollbar. Has anyone implemented this?</p>

答:
There is no out of the box solution.

How to start

You can take a look at

```<code>// panel p is the scrollable panel
const scrollbar = p.getScrollable().getIndicators().y.barElement

scrollbar.dom.style.transform = "rotate(180deg)"
</code>```

You will have to set the transform origin, but this should help you jumpstart the problem.

Title: Reversing Sencha Touch 2 Scrollbar

Body:
There is no out of the box solution.

How to start

You can take a look at

// panel p is the scrollable panel
const scrollbar = p.getScrollable().getIndicators().y.barElement

scrollbar.dom.style.transform = "rotate(180deg)"

You will have to set the transform origin, but this should help you jumpstart the problem.


问:
Should constructor call init or vice versa?
In a case where I want to allow initializing a class directly in the construction, as well as allowing an empty instance (either default-constructed or that has had some kind of close() method called on it) to be initialized, is there any reason to prefer either of these two options for avoiding code duplication?

init/open calls constructor:

```<code>struct S {
  S(params...) : initlist... {
    ... init code ...
  }
  void init(params...) {
    *this = S(params...);
  }
  ...
};
</code>```

Constructor calls init/open:

```<code>struct S {
  S(params...) {
    init(params...);
  }
  void init(params...) {
    ... init code ...
  }
  ...
};
</code>```

Think for example a class representing a file, that can have the path passed to the constructor or  call an open() method later.

答:
I would argue neither. Except in rare instances where you want a two step construction process, I'd argue against having an "init" method at all.

Your first option "init calls constructor" actually uses an assignment or move operator for the initializing process. But it hides the fact that is does so. Why?

Wouldn't this be better, instead of introducing another method:

```<code>   S obj;   // create default instance
   obj = S(params...);   // init instance with assignment/move operator

// or after a close()
   obj.close();
   obj = S(params...);
</code>```

Your second option is something seen a lot in older C++ code, pre C++14 (11 perhaps), where delegating constructors had not been created. Usually with classes that had more than one constructor.

```<code>   S(int one, param two, special three)
   {
      init(one, two);
      // and do something with three
      someThree = three;
   }
   s()
   {
      init(10, param::none);
   }
</code>```

Here init would be used for some basic, common initialization and specific initialization could be added after that.

But with delegating constructors, init could easily be replaced by a specific 'base' constructor and the other constructors would simply use it.

```<code>   S(int one, param two)
   {
      myOne = one; ... // other default 'init' stuf
   }
   S(int one, param two, special three)
      :S(one, two)   // call "init", delegate to the "init" constructor
   {
      // and do something with three
      someThree = three;
   }
</code>```

}

My argument here is that init is a constructor and should be written as such and not as "init". Or, to put it the other way round, once you have constructed an object, there is no need for another "init".

A constructor should fully initialize an object.

Anything done to the object after that is not initialization.

You could have a reset, if you want specific parameters to be reset. But that's not really an "init".

Body:
In a case where I want to allow initializing a class directly in the construction, as well as allowing an empty instance (either default-constructed or that has had some kind of close() method called on it) to be initialized, is there any reason to prefer either of these two options for avoiding code duplication?

init/open calls constructor:

struct S {
  S(params...) : initlist... {
    ... init code ...
  }
  void init(params...) {
    *this = S(params...);
  }
  ...
};

Constructor calls init/open:

struct S {
  S(params...) {
    init(params...);
  }
  void init(params...) {
    ... init code ...
  }
  ...
};

Think for example a class representing a file, that can have the path passed to the constructor or  call an open() method later.

Body:
I would argue neither. Except in rare instances where you want a two step construction process, I'd argue against having an "init" method at all.

Your first option "init calls constructor" actually uses an assignment or move operator for the initializing process. But it hides the fact that is does so. Why?

Wouldn't this be better, instead of introducing another method:

   S obj;   // create default instance
   obj = S(params...);   // init instance with assignment/move operator

// or after a close()
   obj.close();
   obj = S(params...);

Your second option is something seen a lot in older C++ code, pre C++14 (11 perhaps), where delegating constructors had not been created. Usually with classes that had more than one constructor.

   S(int one, param two, special three)
   {
      init(one, two);
      // and do something with three
      someThree = three;
   }
   s()
   {
      init(10, param::none);
   }

Here init would be used for some basic, common initialization and specific initialization could be added after that.

But with delegating constructors, init could easily be replaced by a specific 'base' constructor and the other constructors would simply use it.

   S(int one, param two)
   {
      myOne = one; ... // other default 'init' stuf
   }
   S(int one, param two, special three)
      :S(one, two)   // call "init", delegate to the "init" constructor
   {
      // and do something with three
      someThree = three;
   }

}

My argument here is that init is a constructor and should be written as such and not as "init". Or, to put it the other way round, once you have constructed an object, there is no need for another "init".

A constructor should fully initialize an object.

Anything done to the object after that is not initialization.

You could have a reset, if you want specific parameters to be reset. But that's not really an "init".