问:
A typical bracket balanced problem in ocaml
I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

```<code>false = is_balanced")("
false = is_balanced "(a)b)"
true = is_balanced "fo"
true = is_balanced "a(b(c)d)e"
</code>```
```<code>let rec list_car ch = match ch with
  | "" -> []
  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
  in
  left (brk, 0) ;;
</code>```

But I got the following results:

```<code>is_balanced "(((";;
- : bool = true
 is_balanced "()";;
- : bool = false
</code>```

答:
Now I fixed mt code,and it works!Thanks a lot for the tipps</p>
```<code>let rec list_car ch = match ch with
      | "" -> []
      | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    |')'::xs,level ->
    if level >0 then left(xs,pred level) else false
    | '('::xs,level ->left(xs,succ level)
    | _::xs, level -> left (xs, level)
    |[],level ->if level =0 then true else false
  in
  left (brk, 0) ;;
</code>```

Body:
I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

false = is_balanced")("
false = is_balanced "(a)b)"
true = is_balanced "fo"
true = is_balanced "a(b(c)d)e"

let rec list_car ch = match ch with
  | "" -> []
  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
  in
  left (brk, 0) ;;

But I got the following results:

is_balanced "(((";;
- : bool = true
 is_balanced "()";;
- : bool = false

Body:
Now I fixed mt code,and it works!Thanks a lot for the tipps

let rec list_car ch = match ch with
      | "" -> []
      | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    |')'::xs,level ->
    if level >0 then left(xs,pred level) else false
    | '('::xs,level ->left(xs,succ level)
    | _::xs, level -> left (xs, level)
    |[],level ->if level =0 then true else false
  in
  left (brk, 0) ;;


来源: stackexchange

问:
Analysis of algorithms
I am reading algorithm analysis topic. Here is the text snippet from the book

When n doubles, the running time goes up by a factor of 2 for linear
  programs, 4 for quadratic programs, and  8 for cubic programs.
  Programs that run in logarithmic time take only an additive constant
  longer when n doubles,  and programs that run in O(n log n) take
  slightly more than twice as long to run under the same circumstances.

These increases can be hard to spot if the lower-order terms have
  relatively large coefficients and n is not large enough.

My question is what does author mean lower-order terms have relatively large coefficients? Can any one explain with example

Thanks!

答:
Asymptotic notation refers to the bounds of the runtime as n->infinity. So, a function that is O(n log n) may have an actual runtime of .1*n log n + 100000*n.

In this case, the 100000*n term is the "lower-order term". As n->infinity, this term is overpowered by the .1*n log n term.

However, as you can see, for small n, the 100000*n term will dominate the runtime.

ContentLicense: CC BY-SA 3.0

Title: Analysis of algorithms


问:
oracle ELSE case runs regardless
I have a case statement (myCol is a NUMBER):

select case when myCol < 0 then 0 else round(POWER(10,AVG(LOG(10,myCol))),2) end myCol from myTable where id = 123 group by myCol;

But Oracle seems to run the else clause regardless, and the POWER or LOG functions throw ORA-01428: argument '-2.75' is out of range when myCol is negative (-2.75). I would think the else clause would be ignored if myCol < 0 but maybe Oracle is compiling the entire statement before running?

I also tried using decode(sign(myCol)... but that also fails.

How can I handle this?

答:
I'd say that query you posted isn't complete. Why? Because of this:

```<code>SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select case when myCol < 0 then 0
  6              else round(POWER(10,AVG(LOG(10,myCol))),2)
  7         end myCol
  8  from test;
select case when myCol < 0 then 0
                 *
ERROR at line 5:
ORA-00937: not a single-group group function

SQL>
</code>```

But, when you add the group by clause, you get error you mentioned:

```<code>SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select case when myCol < 0 then 0
  6              else round(POWER(10,AVG(LOG(10,myCol))),2)
  7         end myCol
  8  from test
  9  group by mycol;
            else round(POWER(10,AVG(LOG(10,myCol))),2)
                                           *
ERROR at line 6:
ORA-01428: argument '-2.75' is out of range

SQL>
</code>```

What to do? One option is to apply the abs function, because it is GROUP BY that causes your problems - it splits the whole result data set into rows, each mycol on its own, and that's where -2.75 becomes out of range.

```<code>SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select mycol original_value,
  6         case when myCol < 0 then 0
  7              else round(POWER(10,AVG(LOG(10,abs(myCol)))),2)
  8         end myCol                           ---
  9  from test                               -- this
 10  group by mycol;

ORIGINAL_VALUE      MYCOL
-------------- ----------
         -2,75          0
             2          2

SQL>
</code>```

ContentLicense: CC BY-SA 4.0

Title: oracle ELSE case runs regardless

Body:
I'd say that query you posted isn't complete. Why? Because of this:

SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select case when myCol < 0 then 0
  6              else round(POWER(10,AVG(LOG(10,myCol))),2)
  7         end myCol
  8  from test;
select case when myCol < 0 then 0
                 *
ERROR at line 5:
ORA-00937: not a single-group group function

SQL>

But, when you add the group by clause, you get error you mentioned:

SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select case when myCol < 0 then 0
  6              else round(POWER(10,AVG(LOG(10,myCol))),2)
  7         end myCol
  8  from test
  9  group by mycol;
            else round(POWER(10,AVG(LOG(10,myCol))),2)
                                           *
ERROR at line 6:
ORA-01428: argument '-2.75' is out of range

SQL>

What to do? One option is to apply the abs function, because it is GROUP BY that causes your problems - it splits the whole result data set into rows, each mycol on its own, and that's where -2.75 becomes out of range.

SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select mycol original_value,
  6         case when myCol < 0 then 0
  7              else round(POWER(10,AVG(LOG(10,abs(myCol)))),2)
  8         end myCol                           ---
  9  from test                               -- this
 10  group by mycol;

ORIGINAL_VALUE      MYCOL
-------------- ----------
         -2,75          0
             2          2

SQL>


问:
Plot_ly rotate animation in R
I am trying to animate a 3D figure being rotated around an axis and print that as a .gif or video format. Could not find a resource to assist, please point me in the right direction. Any input is appreciated. Example figure below:</p>
```<code>library(plotly)
x <- iris$Sepal.Length
y <- iris$Sepal.Width
z <- iris$Petal.Length
test3d <- plot_ly(type = "scatter3d", mode = "markers",
                  x=x, y=y, z=z)
</code>```

答:
This is taken from my earlier answer here.

We can use the code without shiny and save a standalone HTML file via htmlwidgets::saveWidget:

```<code>library(plotly)
library(htmlwidgets)
library(utils)

N <- 100
x <- rnorm(N, mean = 50, sd = 2.3)
y <- runif(N, min = 0, max = 100)
z <- runif(N, min = 4, max = 70)
luci.frame <- data.frame(x, y, z)

fig <- plot_ly(
  type = "scatter3d",
  mode = "markers",
  data = luci.frame,
  x = ~ x,
  y = ~ y,
  z = ~ z
) %>%
  layout(scene = list(camera = list(
    eye = list(
      x = 1.25,
      y = 1.25,
      z = 1.25
    ),
    center = list(x = 0,
                  y = 0,
                  z = 0)
  ))) %>%
  onRender("
      function(el, x){
  var id = el.getAttribute('id');
  var gd = document.getElementById(id);
  Plotly.update(id).then(attach);
  function attach() {
    var cnt = 0;

    function run() {
      rotate('scene', Math.PI / 180);
      requestAnimationFrame(run);
    }
    run();

    function rotate(id, angle) {
      var eye0 = gd.layout[id].camera.eye
      var rtz = xyz2rtz(eye0);
      rtz.t += angle;

      var eye1 = rtz2xyz(rtz);
      Plotly.relayout(gd, id + '.camera.eye', eye1)
    }

    function xyz2rtz(xyz) {
      return {
        r: Math.sqrt(xyz.x * xyz.x + xyz.y * xyz.y),
        t: Math.atan2(xyz.y, xyz.x),
        z: xyz.z
      };
    }

    function rtz2xyz(rtz) {
      return {
        x: rtz.r * Math.cos(rtz.t),
        y: rtz.r * Math.sin(rtz.t),
        z: rtz.z
      };
    }
  };
}
    ")

htmlwidgets::saveWidget(partial_bundle(fig), file = "rotate_scatter3d.HTML", selfcontained = TRUE)

utils::browseURL("rotate_scatter3d.HTML")
</code>```

Title: Plot_ly rotate animation in R

Body:
I am trying to animate a 3D figure being rotated around an axis and print that as a .gif or video format. Could not find a resource to assist, please point me in the right direction. Any input is appreciated. Example figure below:

library(plotly)
x <- iris$Sepal.Length
y <- iris$Sepal.Width
z <- iris$Petal.Length
test3d <- plot_ly(type = "scatter3d", mode = "markers",
                  x=x, y=y, z=z)

Body:
This is taken from my earlier answer here.

We can use the code without shiny and save a standalone HTML file via htmlwidgets::saveWidget:

library(plotly)
library(htmlwidgets)
library(utils)

N <- 100
x <- rnorm(N, mean = 50, sd = 2.3)
y <- runif(N, min = 0, max = 100)
z <- runif(N, min = 4, max = 70)
luci.frame <- data.frame(x, y, z)

fig <- plot_ly(
  type = "scatter3d",
  mode = "markers",
  data = luci.frame,
  x = ~ x,
  y = ~ y,
  z = ~ z
) %>%
  layout(scene = list(camera = list(
    eye = list(
      x = 1.25,
      y = 1.25,
      z = 1.25
    ),
    center = list(x = 0,
                  y = 0,
                  z = 0)
  ))) %>%
  onRender("
      function(el, x){
  var id = el.getAttribute('id');
  var gd = document.getElementById(id);
  Plotly.update(id).then(attach);
  function attach() {
    var cnt = 0;

    function run() {
      rotate('scene', Math.PI / 180);
      requestAnimationFrame(run);
    }
    run();

    function rotate(id, angle) {
      var eye0 = gd.layout[id].camera.eye
      var rtz = xyz2rtz(eye0);
      rtz.t += angle;

      var eye1 = rtz2xyz(rtz);
      Plotly.relayout(gd, id + '.camera.eye', eye1)
    }

    function xyz2rtz(xyz) {
      return {
        r: Math.sqrt(xyz.x * xyz.x + xyz.y * xyz.y),
        t: Math.atan2(xyz.y, xyz.x),
        z: xyz.z
      };
    }

    function rtz2xyz(rtz) {
      return {
        x: rtz.r * Math.cos(rtz.t),
        y: rtz.r * Math.sin(rtz.t),
        z: rtz.z
      };
    }
  };
}
    ")

htmlwidgets::saveWidget(partial_bundle(fig), file = "rotate_scatter3d.HTML", selfcontained = TRUE)

utils::browseURL("rotate_scatter3d.HTML")


问:
how to locate coredump function with -O2
when the application compiled with -O2 crash, how to locate the function or the code line that make the application crash?</p>

答:
when the application compiled with -O2 crash, how to locate the function or the code line that make the application crash?

In exactly the same way as you would for an application compiled without -O2.

when the application crash on the production environment, it's hard to locate the problem.

Your first step should be to arrange for the production environment to save a core dump somewhere, or at least to print crashing address (often logged in /var/log/messages or the like).

Once you have a core, you can use debugger, e.g. gdb a.out core and then where command will list functions leading to the crash.

If you want file and line info, you need to build a.out with the -g flag (in addition to -O2).

If you don't have a core, but do have the crashing address, then addr2line -fe a.out $address should give you the function name.


问:
How to sort and put together several lines into a longer line?
I am looking for a way to sort and combine objects / segments into one connected segment.
I have a list of objects and I have to arrange them so that the end of one matches the beginning of the other (some of them can be reversed), is there some way to do it, thank you in advance.</p>
```<code>class Line:
def __init__(self, name, start, end):
    self.name = name
    self.startPoint = start
    self.endPoint = end

def __repr__(self):
    return f"<{self.name}{self.startPoint}-{self.endPoint}>"

a = Line("d", (4, 4), (3, 3))
b = Line("b", (2, 2), (3, 3))
c = Line("c", (1, 1), (2, 2))
d = Line("a", (0, 0), (1, 1))
l = [a, b, c, d]

#result
# a.reverse
sorted_l = [d, c, b, a]
</code>```

答:
A simple solution is to use the list.sort() function to sort a collection of objects (using some attribute) in Python.

In your case you can use a lambda function to handle the sorting:

```<code>list_objects = [a, b, c, d]
</code>```

use lambda in sort() method, I have specified class variable name (x.startPoint) for sorting you can use others if you want.

```<code>list_objects.sort(key=lambda x: x.startPoint)
</code>```

result will be as below:

```<code>[<a (0, 0)-(1, 1)>, <c (1, 1)-(2, 2)>, <b (2, 2)-(3, 3)>, <d (4, 4)-(3, 3)>]
</code>```

Body:
I am looking for a way to sort and combine objects / segments into one connected segment.
I have a list of objects and I have to arrange them so that the end of one matches the beginning of the other (some of them can be reversed), is there some way to do it, thank you in advance.

class Line:
def __init__(self, name, start, end):
    self.name = name
    self.startPoint = start
    self.endPoint = end

def __repr__(self):
    return f"<{self.name}{self.startPoint}-{self.endPoint}>"

a = Line("d", (4, 4), (3, 3))
b = Line("b", (2, 2), (3, 3))
c = Line("c", (1, 1), (2, 2))
d = Line("a", (0, 0), (1, 1))
l = [a, b, c, d]

#result
# a.reverse
sorted_l = [d, c, b, a]

Body:
A simple solution is to use the list.sort() function to sort a collection of objects (using some attribute) in Python.

In your case you can use a lambda function to handle the sorting:

list_objects = [a, b, c, d]

use lambda in sort() method, I have specified class variable name (x.startPoint) for sorting you can use others if you want.

list_objects.sort(key=lambda x: x.startPoint)

result will be as below:

[<a (0, 0)-(1, 1)>, <c (1, 1)-(2, 2)>, <b (2, 2)-(3, 3)>, <d (4, 4)-(3, 3)>]


问:
Why im getting this error Warning: Operand of null-aware operation '??' has type 'String' which excludes null. Dart Language
so i was learning about SWITCH and CASE Statements in dart language, in the course he explains the code but he don't get an error while i get one.

the error i get
: Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
String ``userName = name ?? "Guest User";

My Code is

```<code>void learnCondExpr() {
 String name = 'Yamix';

 String userName = name ?? "Guest User";
 print(userName);
}
</code>```

can i get some help please :)

答:
The probem is that name is not-nullable String.
You can declare it as a nullable type by adding a ?.

Like this:

```<code>String? name = 'Yamix';
</code>```

Keep in mind that even if your string is nullable but you assign a value to it, that's going to be constant, and that's the reason why you may be getting a warning when checking it for null:

The left operand can't be null, so the right operand is never executed.
Try removing the operator and the right operand

Body:
so i was learning about SWITCH and CASE Statements in dart language, in the course he explains the code but he don't get an error while i get one.

the error i get
: Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
String ``userName = name ?? "Guest User";

My Code is

void learnCondExpr() {
 String name = 'Yamix';

 String userName = name ?? "Guest User";
 print(userName);
}

can i get some help please :)

Body:
The probem is that name is not-nullable String.
You can declare it as a nullable type by adding a ?.

Like this:

String? name = 'Yamix';

Keep in mind that even if your string is nullable but you assign a value to it, that's going to be constant, and that's the reason why you may be getting a warning when checking it for null:

The left operand can't be null, so the right operand is never executed.
Try removing the operator and the right operand


问:
How to get named list of arguments from fmt::format_args
I'm trying to build C++ logging integration for Logz.IO which uses named parameters for string interpolation and I'd like to leverage fmt for argument parsing and formatting. Essentially I'm trying to build function that will allow me to pass named arguments e.g.

```<code>log_fmt("Length: {Length:.2f}", fmt::arg("Length", 125.5f));
</code>```

I followed documentation to build templated function and my own logging function:

```<code>  template <typename S, typename... Args>
  void log_fmt(const S& format, Args&&... args) {
    vlog(level, format,
         fmt::make_args_checked<Args...>(format, args...));
  }

  void vlog(fmt::string_view format, fmt::format_args args) {}
</code>```

Inside my implementation of vlog I would like to convert args to JSON object that will contain all arguments (ideally without formatting part):

```<code>{
    "Length": 125.5
}
</code>```

However it looks like format_args exposes only very basic public interface (only allowing to get. How can I iterate over args and get each argument name and value?

答:
{fmt} doesn't provide an API to iterate over named arguments but you can do it yourself in log_fmt. Each named argument will have the following type:

template <typename Char, typename T> struct named_arg : view {
  const Char* name;
  const T& value;
  named_arg(const Char* n, const T& v) : name(n), value(v) {}
};
```

Body:
I'm trying to build C++ logging integration for Logz.IO which uses named parameters for string interpolation and I'd like to leverage fmt for argument parsing and formatting. Essentially I'm trying to build function that will allow me to pass named arguments e.g.

log_fmt("Length: {Length:.2f}", fmt::arg("Length", 125.5f));

I followed documentation to build templated function and my own logging function:

  template <typename S, typename... Args>
  void log_fmt(const S& format, Args&&... args) {
    vlog(level, format,
         fmt::make_args_checked<Args...>(format, args...));
  }

  void vlog(fmt::string_view format, fmt::format_args args) {}

Inside my implementation of vlog I would like to convert args to JSON object that will contain all arguments (ideally without formatting part):

{
    "Length": 125.5
}

However it looks like format_args exposes only very basic public interface (only allowing to get. How can I iterate over args and get each argument name and value?


问:
How can I filter out in haskell?
I know about the filter function but I'm wondering how I can filter out. For example: filter odd [1,2,3] = [1,3], but I want filter (not(odd)) [1,2,3] = [2] (yes I know there's an even function but this is just an example of it). I don't know if there's a separate function that I don't know about or if there's just something I can add to the argument. Thanks. note: I can't use the GHC.Utils.Misc filterOut.

答:
You were quite close, you can use:

```<code>filter (<strong>not .</strong> odd) [1, 2, 3]</code>```

here we thus construct a function \x -> not (odd x), that will thus retain all elements that are not odd, so even.

Title: How can I filter out in haskell?

Body:
You were quite close, you can use:

filter (not . odd) [1, 2, 3]

here we thus construct a function \x -> not (odd x), that will thus retain all elements that are not odd, so even.


问:
Why does Google ReCaptcha v2 checkbox break after >5min idle time on a mobile device?
I have Google ReCaptcha v2 Checkbox implemented in a ASP.NET Core 3.1 MVC application. It works fine on mobile and desktop - I am able to fill out a form, click Submit, a bootstrap confirmation modal comes up with the captcha, and I can confirm my submission.

However, on my mobile device (I tested Chrome and Brave browsers), if the form page is idle for >5 minutes, and then I fill out the form and pull up the confirmation modal, the captcha sometimes breaks and looks like this:

A gray box with a sad face. It's not a very descriptive error.

I tried both automatic rendering and explicit rendering for the captcha, but the issue persists.

My captcha html, which is inside a bootstrap modal that is initially not shown:

```<code><div id="recaptcha" class="g-recaptcha" data-size="compact" data-sitekey="@ViewData["ReCaptchaKey"]"></div>
</code>```

Code that explicitly renders captcha:

```<code>/**
 * Function gets called when the google recaptcha API loads. This is to ensure element is present in html before
 * initialising captcha.
 * More info: https://stackoverflow.com/a/46388681/12300287
 */
var _captchaTries = 0;
function recaptchaOnload() {
    _captchaTries++;
    if (_captchaTries > 9)
        return;
    if ($('.g-recaptcha').length > 0) {
        grecaptcha.render("recaptcha");
        return;
    }
    window.setTimeout(recaptchaOnload, 1000);
}
</code>```

Script tag for captcha in the head:

```<code><script src="https://www.google.com/recaptcha/api.js?onload=recaptchaOnload&render=explicit"></script>
</code>```

As I said, I tried automatic render with captcha, making the code simpler, but the issue still exists.

EDIT: I'm working on another app with a reCAPTCHA and this still happens, but in this new case it's not when >5mins pass and it's not in a modal. The error seems to be uncommon and hard to recreate. Refreshing the page fixes it. The only pattern I noticed is it tends to appear when I visit the site on my phone after not having visited it in a while.

答:
I still don't know what is the cause of this error but I found a way to handle it.

Above the reCAPTCHA, you can add a button that calls grecaptcha.reset(); method:

```<code><input type="button" onclick="grecaptcha.reset();" value="Reload" />
</code>```

If the reCAPTCHA breaks, clicking the button resets it to working condition.

Body:
I have Google ReCaptcha v2 Checkbox implemented in a ASP.NET Core 3.1 MVC application. It works fine on mobile and desktop - I am able to fill out a form, click Submit, a bootstrap confirmation modal comes up with the captcha, and I can confirm my submission.

However, on my mobile device (I tested Chrome and Brave browsers), if the form page is idle for >5 minutes, and then I fill out the form and pull up the confirmation modal, the captcha sometimes breaks and looks like this:

A gray box with a sad face. It's not a very descriptive error.

I tried both automatic rendering and explicit rendering for the captcha, but the issue persists.

My captcha html, which is inside a bootstrap modal that is initially not shown:

Code that explicitly renders captcha:

/**
 * Function gets called when the google recaptcha API loads. This is to ensure element is present in html before
 * initialising captcha.
 * More info: https://stackoverflow.com/a/46388681/12300287
 */
var _captchaTries = 0;
function recaptchaOnload() {
    _captchaTries++;
    if (_captchaTries > 9)
        return;
    if ($('.g-recaptcha').length > 0) {
        grecaptcha.render("recaptcha");
        return;
    }
    window.setTimeout(recaptchaOnload, 1000);
}

Script tag for captcha in the head:

As I said, I tried automatic render with captcha, making the code simpler, but the issue still exists.

EDIT: I'm working on another app with a reCAPTCHA and this still happens, but in this new case it's not when >5mins pass and it's not in a modal. The error seems to be uncommon and hard to recreate. Refreshing the page fixes it. The only pattern I noticed is it tends to appear when I visit the site on my phone after not having visited it in a while.

Body:
I still don't know what is the cause of this error but I found a way to handle it.

Above the reCAPTCHA, you can add a button that calls grecaptcha.reset(); method:

<input type="button" onclick="grecaptcha.reset();" value="Reload" />

If the reCAPTCHA breaks, clicking the button resets it to working condition.


问:
What's the best and safest practice for releasing outlets?
The iOS documentation says that your view controllers should release (and nil, since that's good practice and actually a must for 2.x compatibility) any retained outlets in -dealloc.

The documentation also says that you should do the same for your outlets in -viewDidUnload if you want to allow them being cleaned up when the view is not visible and a memory warning was issued.

I wonder about two things:

Does this mean that I should duplicate all my outlet releasing code?  Put it all in -dealloc and in -viewDidUnload?  That's a real pain to maintain and really easy to forget!

Am I guaranteed that all my outlets will be re-populated when the view is reloaded after a -viewDidUnload, including my outlets that reference non-view objects in my nib?

The ideal answer answers both questions above and if there is a distinction between which properties should optimally be released in -dealloc VS -viewDidUnload, clarifies this distinction in detail.

答:
Nick answered the part 1 of the question perfectly so I skip to part 2 right away.

You are guaranteed, indeed! When your view gets reloaded from a nib file, everything on that nib file gets reloaded. There is not method to partially load a nib file's contents so if that nib gets reloaded, everything inside will get reloaded, too. But everything loaded from a nib has an autorelease on it. So you have to retain them. If you have Outlets which retains these freshly loaded classes and you connected those Outlets as outlets on nib, you are good to go. On a view controller example controller itself is the file's owner of that nib, view is the root element on nib, view being retained by file's owner outlet "view", all other child elements retained by view itself. If you have multiple root elements or elements that root view does not retain then you have to be sure there is outlets for this elements to retain them if nib loading by system automatically, if you are loading nib by a method then you must be aware all those classes are autoreleased when they arrived to your code.

Simply views are classes too and when a nib file gets loaded, everything inside it gets loaded, not some part of it. It is your responsibility to manage outlets.

ContentLicense: CC BY-SA 2.5


问:
How to writ good test for my ViewModel? (RxSwift)
I wrote some tests for my ViewModel. I use RxSwift in this project. I have never before write unit tests, so i want to ask you about correctness of them. What can I do better next time? It is little difficult for me when I write tests while I use RxSwift. All tests passed, but I don't know if they are "good tests". Thanks for your help.

ViewModel:

```<code>class SettingsViewModel {
private let storage = Storage.shared
private let disposeBag = DisposeBag()
let userSettings = BehaviorRelay<UserSettings>(value: UserSettings(name: "", tags: []))

init() {
    subscribe()
}

private func subscribe() {
    storage.currentUserSettings()
        .subscribe(onNext: { settings in
            if let settings = settings {
                self.userSettings.accept(settings)
            }
        })
        .disposed(by: disposeBag)
}

func saveName(_ name: String) {
    saveSettings(name: name, tags: userSettings.value.tags)
}

func addTag(_ tag: String) {
    let newTags = userSettings.value.tags + [tag]
    saveSettings(name: userSettings.value.name, tags: newTags)
}

func removeTag(_ index: Int) {
    var newTags = userSettings.value.tags
    newTags.remove(at: index)
    saveSettings(name: userSettings.value.name, tags: newTags)
}

private func saveSettings(name: String, tags: [String]) {
    let newSettings = UserSettings(name: name, tags: tags)
    Storage.shared.saveUserSettings(newSettings)
}
</code>```

}

Test class:

```<code>class SettingsViewModelTests: XCTestCase {

func test_userSettingsSaving_includesAddingName() {
    let sut = SettingsViewModel()
    let userSettings = UserSettingsSpy(sut.userSettings)

    sut.saveName("George")
    XCTAssertEqual(userSettings.settings.name, "George")

    sut.saveName("Mike")
    XCTAssertEqual(userSettings.settings.name, "Mike")
}

func test_userSettingsSaving_includesAddingTag() {
    let sut = SettingsViewModel()
    let userSettings = UserSettingsSpy(sut.userSettings)

    sut.addTag("Book")

    var savedTags: [String] = []
    Storage.shared.currentUserSettings()
        .subscribe(onNext: { settings in
            if let tags = settings?.tags {
                savedTags = tags
            }
        })
        .dispose()

    XCTAssertEqual(userSettings.settings.tags, savedTags)
}

func test_userSettingsSaving_includesRemovingTag() {
    let sut = SettingsViewModel()
    let userSettings = UserSettingsSpy(sut.userSettings)

    sut.addTag("TestTagToRemove")
    sut.removeTag(0)

    var savedTags: [String] = []
    Storage.shared.currentUserSettings()
        .subscribe(onNext: { settings in
            if let tags = settings?.tags {
                savedTags = tags
            }
        })
        .dispose()

    XCTAssertEqual(userSettings.settings.tags, savedTags)
}

class UserSettingsSpy {
    private let disposeBag = DisposeBag()
    private(set) var settings = UserSettings(name: "", tags: [])

    init(_ observable: BehaviorRelay<UserSettings>) {
        observable
            .subscribe(onNext: { settings in
                self.settings = settings
            })
            .disposed(by: disposeBag)
    }
}
</code>```

}

答:
An easy way to check the correctness of your tests is to change the system under test and see if your tests flag the error. If they don't, then that is a hole in your tests. For example, the following view model will pass your tests:

```<code>struct Storage {
    static let shared = Storage()
    func currentUserSettings() -> Observable<UserSettings?> { .just(nil) }
}

struct SettingsViewModel {
    let userSettings = BehaviorRelay<UserSettings>(value: UserSettings())

    func saveName(_ value: String) {
        userSettings.accept(UserSettings(name: value, tags: []))
    }

    func addTag(_ value: String) { }

    func removeTag(_ value: Int) { }
}

struct UserSettings {
    var name: String = ""
    var tags: [String] = []
}
</code>```

The code above is obviously missing some important functionality which means your tests are incomplete.

Body:
I wrote some tests for my ViewModel. I use RxSwift in this project. I have never before write unit tests, so i want to ask you about correctness of them. What can I do better next time? It is little difficult for me when I write tests while I use RxSwift. All tests passed, but I don't know if they are "good tests". Thanks for your help.

ViewModel:

class SettingsViewModel {
private let storage = Storage.shared
private let disposeBag = DisposeBag()
let userSettings = BehaviorRelay<UserSettings>(value: UserSettings(name: "", tags: []))

init() {
    subscribe()
}

private func subscribe() {
    storage.currentUserSettings()
        .subscribe(onNext: { settings in
            if let settings = settings {
                self.userSettings.accept(settings)
            }
        })
        .disposed(by: disposeBag)
}

func saveName(_ name: String) {
    saveSettings(name: name, tags: userSettings.value.tags)
}

func addTag(_ tag: String) {
    let newTags = userSettings.value.tags + [tag]
    saveSettings(name: userSettings.value.name, tags: newTags)
}

func removeTag(_ index: Int) {
    var newTags = userSettings.value.tags
    newTags.remove(at: index)
    saveSettings(name: userSettings.value.name, tags: newTags)
}

private func saveSettings(name: String, tags: [String]) {
    let newSettings = UserSettings(name: name, tags: tags)
    Storage.shared.saveUserSettings(newSettings)
}

}

Test class:

class SettingsViewModelTests: XCTestCase {

func test_userSettingsSaving_includesAddingName() {
    let sut = SettingsViewModel()
    let userSettings = UserSettingsSpy(sut.userSettings)

    sut.saveName("George")
    XCTAssertEqual(userSettings.settings.name, "George")

    sut.saveName("Mike")
    XCTAssertEqual(userSettings.settings.name, "Mike")
}

func test_userSettingsSaving_includesAddingTag() {
    let sut = SettingsViewModel()
    let userSettings = UserSettingsSpy(sut.userSettings)

    sut.addTag("Book")

    var savedTags: [String] = []
    Storage.shared.currentUserSettings()
        .subscribe(onNext: { settings in
            if let tags = settings?.tags {
                savedTags = tags
            }
        })
        .dispose()

    XCTAssertEqual(userSettings.settings.tags, savedTags)
}

func test_userSettingsSaving_includesRemovingTag() {
    let sut = SettingsViewModel()
    let userSettings = UserSettingsSpy(sut.userSettings)

    sut.addTag("TestTagToRemove")
    sut.removeTag(0)

    var savedTags: [String] = []
    Storage.shared.currentUserSettings()
        .subscribe(onNext: { settings in
            if let tags = settings?.tags {
                savedTags = tags
            }
        })
        .dispose()

    XCTAssertEqual(userSettings.settings.tags, savedTags)
}

class UserSettingsSpy {
    private let disposeBag = DisposeBag()
    private(set) var settings = UserSettings(name: "", tags: [])

    init(_ observable: BehaviorRelay<UserSettings>) {
        observable
            .subscribe(onNext: { settings in
                self.settings = settings
            })
            .disposed(by: disposeBag)
    }
}

}

Body:
An easy way to check the correctness of your tests is to change the system under test and see if your tests flag the error. If they don't, then that is a hole in your tests. For example, the following view model will pass your tests:

struct Storage {
    static let shared = Storage()
    func currentUserSettings() -> Observable<UserSettings?> { .just(nil) }
}

struct SettingsViewModel {
    let userSettings = BehaviorRelay<UserSettings>(value: UserSettings())

    func saveName(_ value: String) {
        userSettings.accept(UserSettings(name: value, tags: []))
    }

    func addTag(_ value: String) { }

    func removeTag(_ value: Int) { }
}

struct UserSettings {
    var name: String = ""
    var tags: [String] = []
}

The code above is obviously missing some important functionality which means your tests are incomplete.


问:
SQL query using rows from another query
I would like to use the results from one query to perform another query and combine the results into a single table.

The first query obtains a set of devices for a particular device version and date

```<code>SELECT
    dbo.DeviceSession.SerialNumber,
    dbo.DeviceSession.BackupDate
FROM
    dbo.DeviceSession
</code>```

SerialNumber
BackupDate

1
2022-01-24

2
2022-02-08

3
2022-02-10

The second query obtains the number of errors for a particular serial number and backup date.

```<code>SELECT
    ErrorCode, COUNT(*) AS [Count]
FROM
    dbo.DeviceSession FULL OUTER JOIN
    dbo.DeviceSessionErrorLogEntry AS DeviceSessionErrorEntry_1
        ON DeviceSession.Id = DeviceSessionErrorEntry_1.DeviceSessionId
WHERE
    (dbo.DeviceSession.DeviceSerial LIKE '1') AND
    (dbo.DeviceSession.BackupDate LIKE '2022-01-24')
GROUP BY ErrorCode
</code>```

ErrorCode
Count

97
2

150
5

The second query can be combined into a single line by using the "FOR XML PATH('')"

```<code>SELECT
    ErrorCode, COUNT(*) AS [Count]
FROM
    dbo.DeviceSession
FULL OUTER JOIN
    dbo.DeviceSessionErrorLogEntry AS DeviceSessionErrorEntry_1
        ON DeviceSession.Id = DeviceSessionErrorEntry_1.DeviceSessionId
WHERE
    (dbo.DeviceSession.DeviceSerial LIKE '1')
    AND (dbo.DeviceSession.BackupDate LIKE '2022-01-24')
GROUP BY ErrorCode
FOR XML PATH('')
</code>```

XML_FDEWFJEWFOE

<ErrorCode>97</ErrorCode><Count>2</Count><ErrorCode>150</ErrorCode><Count>5</Count>

How would I create a query such that I could obtain a table that lists the total errors for every serial number and backup date from the first query?

Desired output:

SerialNumber
BackupDate
Notes

1
2022-01-24
<ErrorCode>97</ErrorCode><Count>2</Count><ErrorCode>150</ErrorCode><Count>5</Count>

2
2022-02-08
<ErrorCode>97</ErrorCode><Count>5</Count>

3
2022-02-10
<ErrorCode>42</ErrorCode><Count>1</Count>

答:
You can move your error log query into a correlated subquery that references DeviceSession in the outer query. Something like the following:

```<code>DECLARE @DeviceSession TABLE (ID INT, SerialNumber INT, BackupDate DATE)
INSERT @DeviceSession
VALUES
    (101, 1, '2022-01-24'),
    (102, 2, '2022-02-08'),
    (103, 3, '2022-02-10')

DECLARE @DeviceSessionErrorLogEntry TABLE (ID INT, DeviceSessionID INT, ErrorCode INT)
INSERT @DeviceSessionErrorLogEntry
VALUES
    (201, 101, 97),
    (202, 101, 150),
    (203, 101, 150),
    (204, 101, 97),
    (205, 101, 150),
    (206, 102, 97),
    (207, 102, 150),
    (208, 102, 150)

SELECT
    DS.SerialNumber,
    DS.BackupDate,
    Notes = (
        SELECT EL.ErrorCode, COUNT(*) AS [Count]
        FROM @DeviceSessionErrorLogEntry EL
        WHERE DS.Id = EL.DeviceSessionId
        GROUP BY EL.ErrorCode
        ORDER BY EL.ErrorCode
        FOR XML PATH(''), TYPE
    )
FROM @DeviceSession DS
ORDER BY DS.SerialNumber
</code>```

Results:

SerialNumber
BackupDate
Notes

1
2022-01-24
<ErrorCode>97</ErrorCode><Count>2</Count><ErrorCode>150</ErrorCode><Count>3</Count>

2
2022-02-08
<ErrorCode>97</ErrorCode><Count>1</Count><ErrorCode>150</ErrorCode><Count>2</Count>

3
2022-02-10
NULL

The subquery can also be moved to a CROSS APPLY if you would like to separate subquery details from the final select for readability.

If you really need a full outer join (to show error records that have no matching session), the query would need some restructuring with an FULL OUTER JOIN (SELECT DISTINCT DeviceSessionId FROM @DeviceSessionErrorLogEntry EL) IDS ON IDS.DeviceSessionId = DS.Id, and then have the Notes subquery reference those IDs.

Title: SQL query using rows from another query

Body:
I would like to use the results from one query to perform another query and combine the results into a single table.

The first query obtains a set of devices for a particular device version and date

SELECT
    dbo.DeviceSession.SerialNumber,
    dbo.DeviceSession.BackupDate
FROM
    dbo.DeviceSession

SerialNumber
BackupDate

1
2022-01-24

2
2022-02-08

3
2022-02-10

The second query obtains the number of errors for a particular serial number and backup date.

SELECT
    ErrorCode, COUNT(*) AS [Count]
FROM
    dbo.DeviceSession FULL OUTER JOIN
    dbo.DeviceSessionErrorLogEntry AS DeviceSessionErrorEntry_1
        ON DeviceSession.Id = DeviceSessionErrorEntry_1.DeviceSessionId
WHERE
    (dbo.DeviceSession.DeviceSerial LIKE '1') AND
    (dbo.DeviceSession.BackupDate LIKE '2022-01-24')
GROUP BY ErrorCode

ErrorCode
Count

97
2

150
5

The second query can be combined into a single line by using the "FOR XML PATH('')"

SELECT
    ErrorCode, COUNT(*) AS [Count]
FROM
    dbo.DeviceSession
FULL OUTER JOIN
    dbo.DeviceSessionErrorLogEntry AS DeviceSessionErrorEntry_1
        ON DeviceSession.Id = DeviceSessionErrorEntry_1.DeviceSessionId
WHERE
    (dbo.DeviceSession.DeviceSerial LIKE '1')
    AND (dbo.DeviceSession.BackupDate LIKE '2022-01-24')
GROUP BY ErrorCode
FOR XML PATH('')

XML_FDEWFJEWFOE

<ErrorCode>97</ErrorCode><Count>2</Count><ErrorCode>150</ErrorCode><Count>5</Count>

How would I create a query such that I could obtain a table that lists the total errors for every serial number and backup date from the first query?

Desired output:

SerialNumber
BackupDate
Notes

1
2022-01-24
<ErrorCode>97</ErrorCode><Count>2</Count><ErrorCode>150</ErrorCode><Count>5</Count>

2
2022-02-08
<ErrorCode>97</ErrorCode><Count>5</Count>

3
2022-02-10
<ErrorCode>42</ErrorCode><Count>1</Count>

Body:
You can move your error log query into a correlated subquery that references DeviceSession in the outer query. Something like the following:

DECLARE @DeviceSession TABLE (ID INT, SerialNumber INT, BackupDate DATE)
INSERT @DeviceSession
VALUES
    (101, 1, '2022-01-24'),
    (102, 2, '2022-02-08'),
    (103, 3, '2022-02-10')

DECLARE @DeviceSessionErrorLogEntry TABLE (ID INT, DeviceSessionID INT, ErrorCode INT)
INSERT @DeviceSessionErrorLogEntry
VALUES
    (201, 101, 97),
    (202, 101, 150),
    (203, 101, 150),
    (204, 101, 97),
    (205, 101, 150),
    (206, 102, 97),
    (207, 102, 150),
    (208, 102, 150)

SELECT
    DS.SerialNumber,
    DS.BackupDate,
    Notes = (
        SELECT EL.ErrorCode, COUNT(*) AS [Count]
        FROM @DeviceSessionErrorLogEntry EL
        WHERE DS.Id = EL.DeviceSessionId
        GROUP BY EL.ErrorCode
        ORDER BY EL.ErrorCode
        FOR XML PATH(''), TYPE
    )
FROM @DeviceSession DS
ORDER BY DS.SerialNumber

Results:

SerialNumber
BackupDate
Notes

1
2022-01-24
<ErrorCode>97</ErrorCode><Count>2</Count><ErrorCode>150</ErrorCode><Count>3</Count>

2
2022-02-08
<ErrorCode>97</ErrorCode><Count>1</Count><ErrorCode>150</ErrorCode><Count>2</Count>

3
2022-02-10
NULL

The subquery can also be moved to a CROSS APPLY if you would like to separate subquery details from the final select for readability.

If you really need a full outer join (to show error records that have no matching session), the query would need some restructuring with an FULL OUTER JOIN (SELECT DISTINCT DeviceSessionId FROM @DeviceSessionErrorLogEntry EL) IDS ON IDS.DeviceSessionId = DS.Id, and then have the Notes subquery reference those IDs.


问:
Oracle Form Builder / ORA-12154: TNS : could not resolve the connect identifier specified
I'm getting the error message below when trying to connect to database in the Data Block Wizard (in Oracle Form Builder):

ORA-12154: TNS : could not resolve the connect identifier specified

In order to fix that, I set the TNS_ADMIN environment variable to the directory path where the tnsnames.ora file exists. In addition, I have changed the tnsnames.ora file content like so:

```<code>DEV = (DESCRIPTION =(ADDRESS_LIST =
          (ADDRESS = (PROTOCOL = TCP)
          (HOST = localhost)(PORT = 1521)))
          (CONNECT_DATA = (SID = DEV)))
</code>```

However, I still get the same error message.
Any idea how to fix that?

答:
You're trying to base data block on a table that resides in another database, so you're accessing it via a database link. Correct?

If so, create a synonym (that points to that table) in your own schema, and then base data block on that synonym.

Body:
I'm getting the error message below when trying to connect to database in the Data Block Wizard (in Oracle Form Builder):

ORA-12154: TNS : could not resolve the connect identifier specified

In order to fix that, I set the TNS_ADMIN environment variable to the directory path where the tnsnames.ora file exists. In addition, I have changed the tnsnames.ora file content like so:

DEV = (DESCRIPTION =(ADDRESS_LIST =
          (ADDRESS = (PROTOCOL = TCP)
          (HOST = localhost)(PORT = 1521)))
          (CONNECT_DATA = (SID = DEV)))

However, I still get the same error message.
Any idea how to fix that?


问:
ARKit: project a feature point found in the ARPointCloud to image space and check to see if it's contained in a CGRect on screen?
So, I am using ARKit to display feature points in the session. I am able to get the current frame, then its rawFeaturePoints and place geometries in the world space so the user can see them on screen. That is working great.

In the app I then have a quadrant on screen. My objective is to show in screen coordinates feature points that projected would fall inside the 2D quadrant on screen. To do that, I tried this:

get feature points as an array of vector_float3

for each of those points I then get a SCNVector3 setting the Z component to 0 (near plane)

I then call on the ARSCNView:

public func projectPoint(_ point: SCNVector3) -> SCNVector3

This approach does give me 2D points back, but, depending on where the camera is they seem to be way off.

So then, since in ARKit the camera keeps moving around, do I need to take that into account to achieve what I explained?

EDIT:
About flipping the Y of the CGPoint retrieved from the projectPoint call on the camera:

```<code>/**
 Project a 3D point in world coordinate system into 2D viewport space.

 @param point 3D point in world coordinate system.
 @param orientation Viewport orientation.
 @param viewportSize Viewport (or image) size.
 @return 2D point in viewport coordinate system with origin at top-left.
 */
open func projectPoint(_ point: vector_float3, orientation: UIInterfaceOrientation, viewportSize: CGSize) -> CGPoint
</code>```

Remy San mentioned flipping the Y. I tried that and it does seem to work. One difference between what he's doing and what I am doing is that I am not using an SKScene, but I am using SCNScene. Looking at the docs it says:

...The projection of the specified point into a 2D pixel coordinate space
  whose origin is in the upper left corner...

So, what throws me off is that if I don't flip the Y it seems like it's not really working properly. (I'll try to post images to show what I mean). But then if flipping the Y though makes things look better, it goes against the docs. No?

答:
I get you are using the intrinsics matrix for you projection. ARkit technology may also give you some extra information. These are the cameraPoseARFrame, the projectionMatrix and the transformToWorldMap matrices. Are you taking them into consideration when transforming from world coordinates to pixel coordinates?

If anyone has a methodology for applying these matrices to the point cloud coordinates to convert them into screen coordinates, could you contribute to my answer please? I think they may provide more precision and accuracy to the final result.

Thank you!

Body:
So, I am using ARKit to display feature points in the session. I am able to get the current frame, then its rawFeaturePoints and place geometries in the world space so the user can see them on screen. That is working great.

In the app I then have a quadrant on screen. My objective is to show in screen coordinates feature points that projected would fall inside the 2D quadrant on screen. To do that, I tried this:

get feature points as an array of vector_float3

for each of those points I then get a SCNVector3 setting the Z component to 0 (near plane)

I then call on the ARSCNView:

public func projectPoint(_ point: SCNVector3) -> SCNVector3

This approach does give me 2D points back, but, depending on where the camera is they seem to be way off.

So then, since in ARKit the camera keeps moving around, do I need to take that into account to achieve what I explained?

EDIT:
About flipping the Y of the CGPoint retrieved from the projectPoint call on the camera:

/**
 Project a 3D point in world coordinate system into 2D viewport space.

 @param point 3D point in world coordinate system.
 @param orientation Viewport orientation.
 @param viewportSize Viewport (or image) size.
 @return 2D point in viewport coordinate system with origin at top-left.
 */
open func projectPoint(_ point: vector_float3, orientation: UIInterfaceOrientation, viewportSize: CGSize) -> CGPoint

Remy San mentioned flipping the Y. I tried that and it does seem to work. One difference between what he's doing and what I am doing is that I am not using an SKScene, but I am using SCNScene. Looking at the docs it says:

...The projection of the specified point into a 2D pixel coordinate space
  whose origin is in the upper left corner...

So, what throws me off is that if I don't flip the Y it seems like it's not really working properly. (I'll try to post images to show what I mean). But then if flipping the Y though makes things look better, it goes against the docs. No?


问:
How to create an animated line plot with ploty express?
I'm trying to create an animated line plot to illustrate the price increase of 3 different asset classes over time (year), but it doesn't work and I don't know why!

What I've done so far:

get closing price data for each asset

```<code>start = datetime.datetime(2010,7,01)
end = datetime.datetime(2021,7,01)
data = pdr.get_data_yahoo(['BTC-USD', 'GC=F','^GSPC'],startDate,endDate)['Adj Close']
</code>```

transpose columns into rows to avoid a lot of calculations

```<code>data['Date'] = data.index
data['Year'] = data.index.year
dataNew =data.melt(['Date', 'Year'], var_name='Asset')
dataNew = dataNew.rename(columns = {'value': 'Price'})

</code>```

plot

```<code>fig = px.line(dataNew,
             x = 'Date',
             y = 'Price',
             range_y=[0,50000],
             color = 'Asset',
             animation_frame = 'Year')
    st.write(fig)
</code>```

Output:

答:
Short answer:

This is in fact very much possible, and the only additions you'll have to make to a standard px.line() time series using axes of type date plot setup is this:

```<code># input data
dfi = px.data.stocks().head(50)

# new datastructure for animation
df = pd.DataFrame() # container for df with new datastructure
for i in np.arange(start,obs):
    dfa = dfi.head(i).copy()
    dfa['ix']=i
    df = pd.concat([df, dfa])
</code>```

The cool details:

Contrary to what seems to be the most common belief, and contrary to my own comments just a few minutes ago, this is in fact possible to do with px.line and a set of time series as you're describing. As long, as you massage the dataset just a little bit. The only real drawback seems to be that it might not work very well for larger datasets, since the amount of data that the figure structure will contain will be huge. But let's get back to the boring details after the cool stuff. The snippet below and the dataset px.data.stocks() will produce the following figure:

Plot 1 - Animation using the play button:

When the animation has come to an end, you can also subset the lines however you'd like.

Plot 2 - Animation using the slider:

The boring details:

I'll get back to this if the OP or anyone else is interested

Complete code:

```<code>import pandas as pd
import numpy as np
import plotly.express as px

# input data
dfi = px.data.stocks().head(50)
dfi['date'] = pd.to_datetime(dfi['date'])
start = 12
obs = len(dfi)

# new datastructure for animation
df = pd.DataFrame() # container for df with new datastructure
for i in np.arange(start,obs):
    dfa = dfi.head(i).copy()
    dfa['ix']=i
    df = pd.concat([df, dfa])

# plotly figure
fig = px.line(df, x = 'date', y = ['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT'],
              animation_frame='ix',
              # template = 'plotly_dark',
              width=1000, height=600)

# attribute adjusments
fig.layout.updatemenus[0].buttons[0]['args'][1]['frame']['redraw'] = True
fig.show()
</code>```

Body:
I'm trying to create an animated line plot to illustrate the price increase of 3 different asset classes over time (year), but it doesn't work and I don't know why!

What I've done so far:

get closing price data for each asset

start = datetime.datetime(2010,7,01)
end = datetime.datetime(2021,7,01)
data = pdr.get_data_yahoo(['BTC-USD', 'GC=F','^GSPC'],startDate,endDate)['Adj Close']

transpose columns into rows to avoid a lot of calculations

data['Date'] = data.index
data['Year'] = data.index.year
dataNew =data.melt(['Date', 'Year'], var_name='Asset')
dataNew = dataNew.rename(columns = {'value': 'Price'})

plot

fig = px.line(dataNew,
             x = 'Date',
             y = 'Price',
             range_y=[0,50000],
             color = 'Asset',
             animation_frame = 'Year')
    st.write(fig)

Output:

Body:
Short answer:

This is in fact very much possible, and the only additions you'll have to make to a standard px.line() time series using axes of type date plot setup is this:

# input data
dfi = px.data.stocks().head(50)

# new datastructure for animation
df = pd.DataFrame() # container for df with new datastructure
for i in np.arange(start,obs):
    dfa = dfi.head(i).copy()
    dfa['ix']=i
    df = pd.concat([df, dfa])

The cool details:

Contrary to what seems to be the most common belief, and contrary to my own comments just a few minutes ago, this is in fact possible to do with px.line and a set of time series as you're describing. As long, as you massage the dataset just a little bit. The only real drawback seems to be that it might not work very well for larger datasets, since the amount of data that the figure structure will contain will be huge. But let's get back to the boring details after the cool stuff. The snippet below and the dataset px.data.stocks() will produce the following figure:

Plot 1 - Animation using the play button:

When the animation has come to an end, you can also subset the lines however you'd like.

Plot 2 - Animation using the slider:

The boring details:

I'll get back to this if the OP or anyone else is interested

Complete code:

import pandas as pd
import numpy as np
import plotly.express as px

# input data
dfi = px.data.stocks().head(50)
dfi['date'] = pd.to_datetime(dfi['date'])
start = 12
obs = len(dfi)

# new datastructure for animation
df = pd.DataFrame() # container for df with new datastructure
for i in np.arange(start,obs):
    dfa = dfi.head(i).copy()
    dfa['ix']=i
    df = pd.concat([df, dfa])

# plotly figure
fig = px.line(df, x = 'date', y = ['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT'],
              animation_frame='ix',
              # template = 'plotly_dark',
              width=1000, height=600)

# attribute adjusments
fig.layout.updatemenus[0].buttons[0]['args'][1]['frame']['redraw'] = True
fig.show()


问:
How to get the CUDA version?
Is there any quick command or script to check for the version of CUDA installed?

I found the manual of 4.0 under the installation directory but I'm not sure whether it is of the actual installed version or not.

答: If you have multiple CUDA installed, the one loaded in your system is CUDA associated with "nvcc". Therefore, "nvcc --version" shows what you want.</p>

Title: How to get the CUDA version?


问:
AWS + Remmina on Ubuntu - Remmina goes into a loop trying to reconnect
I followed this article to install xrdp on AWS Ubuntu 18 ec2 instance, and everything seemed to work properly for a few days.

However, now, when I try to connect to the EC2 instance using Remmina (from another Ubuntu computer) - Remmina goes into a loop, where it says "Reconnection in Progress.  Attempt 0 (or 1) out of 20."  ... then it goes back to 0, without getting past 2.

Any idea on how to get Remmina to work again?

Troubleshooting steps I tried:

1) Rebooting EC2

2) Rebooting laptop

3) SSHing into EC2 machine (this works just fine)

4) Restarting xrdp on target EC2 instance/reconnecting .  This did not help.

答:
We had this looping behaviour on connection. We eventually discovered that the connection parameters was using the wrong colour depth.

We set Colour depth = High Colour (16bpp), and it worked. It failed when we were using 256 colours (8bpp).

This is one of the configurations on the Basic tab.

I don't really know why this setting caused the looping behaviour, but this worked.


问:
Proper CPython String Concatenation
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

```<code>sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "
</code>```

or should I have set sql_statement to "" and then joined each piece?
Thanks.

答:
Please take a look at the Python performance tips for advice on string concatenation.

Avoid:

```<code>out = "<html>" + head + prologue + query + tail + "</html>"
</code>```

Instead, use

```<code>out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)
</code>```

Title: Proper CPython String Concatenation

Body:
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "

or should I have set sql_statement to "" and then joined each piece?
Thanks.

Body:
Please take a look at the Python performance tips for advice on string concatenation.

Avoid:

out = "<html>" + head + prologue + query + tail + "</html>"

Instead, use

out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)


问:
Can't see Serial.print() outputs in Visual Studio Code from Arduino device (ESP8266)
I can't see any Serial.print() outputs in Visual Studio Code from my Arduino device (an ESP8266 in this case).  I was expecting to see it on the Debug Console.  Do I have something configured incorrectly?

I know my code is working as the LED is flashing but I'm not seeing any output anywhere.

Here's my code:

```<code>#include <Arduino.h>

void setup()
{
    Serial.begin(9600); // EDIT: added this line
    Serial.println("Setup...");
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  Serial.print("On!");
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second

  Serial.print("Off!");
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}
</code>```

I am using this board:
https://www.waveshare.com/wiki/e-Paper_ESP8266_Driver_Board

Here is my platformio.ini file:

```<code>[env:esp12e]
platform = espressif8266
board = esp12e
framework = arduino

; Custom Serial Monitor port
monitor_port = COM4

; Custom Serial Monitor speed (baud rate)
monitor_speed = 9600
</code>```

答: Near the bottom right of the VS Code screen is a little plug icon. Click that to open the serial monitor.</p>

Body:
I can't see any Serial.print() outputs in Visual Studio Code from my Arduino device (an ESP8266 in this case).  I was expecting to see it on the Debug Console.  Do I have something configured incorrectly?

I know my code is working as the LED is flashing but I'm not seeing any output anywhere.

Here's my code:

#include <Arduino.h>

void setup()
{
    Serial.begin(9600); // EDIT: added this line
    Serial.println("Setup...");
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  Serial.print("On!");
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second

  Serial.print("Off!");
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

I am using this board:
https://www.waveshare.com/wiki/e-Paper_ESP8266_Driver_Board

Here is my platformio.ini file:

[env:esp12e]
platform = espressif8266
board = esp12e
framework = arduino

; Custom Serial Monitor port
monitor_port = COM4

; Custom Serial Monitor speed (baud rate)
monitor_speed = 9600


问:
Do I really need X11 for R on Mac?
R version 3.5.2

macOS version 10.14.2 mojave

Whenever installing an R, package I see the following warning:

```<code>Warning message:
In doTryCatch(return(expr), name, parentenv, handler) :
  unable to load shared object '/Library/Frameworks/R.framework/Resources/modules//R_X11.so':
  dlopen(/Library/Frameworks/R.framework/Resources/modules//R_X11.so, 6): Library not loaded: /opt/X11/lib/libSM.6.dylib
  Referenced from: /Library/Frameworks/R.framework/Resources/modules//R_X11.so
  Reason: image not found
</code>```

Everything seems to work fine. ggplot2 plots get drawn,...etc.

Do I really need to install X11 from XQuartz?
Is anything actually broken?

Does it "unlock" anything?

答:
this may work:

brew install --cask xquartz

Title: Do I really need X11 for R on Mac?

Body:
R version 3.5.2

macOS version 10.14.2 mojave

Whenever installing an R, package I see the following warning:

Warning message:
In doTryCatch(return(expr), name, parentenv, handler) :
  unable to load shared object '/Library/Frameworks/R.framework/Resources/modules//R_X11.so':
  dlopen(/Library/Frameworks/R.framework/Resources/modules//R_X11.so, 6): Library not loaded: /opt/X11/lib/libSM.6.dylib
  Referenced from: /Library/Frameworks/R.framework/Resources/modules//R_X11.so
  Reason: image not found

Everything seems to work fine. ggplot2 plots get drawn,...etc.

Do I really need to install X11 from XQuartz?
Is anything actually broken?

Does it "unlock" anything?


问:
Adding a new line in MatDialog Content Angular 7
I am using MatDialog and trying to add a new line in the content definition. Both \n and  are not doing it. Is there another way without having to manually go into the html and change it since it's a reusable component:

```<code>var status: MatDialogRef<GenericDialogComponent> this.dialog.open(GenericDialogComponent,{
     width: '400px',
    data: {title: "Sample Title?", content: "Document " + this.docID + " has been saved. The users email address is provied below:\n\n"+this.email+"</b>"} });
</code>```

HTML

```<code><h1 mat-dialog-title>{{data.title}}</h1>
<div mat-dialog-content>
  <p>{{data.content}}</p>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="Cancel()">Cancel</button>
  <button mat-button (click)="Ok()" cdkFocusInitial>Ok</button>
</div>
</code>```

答:
This worked for me:</p>
```<code>        let warningMessages = ['message1','message2','message3'];

        const config=  {
            panelClass:'msg-dialog-container',
            data: {
                type:WARNNING,
                showConfirm:true,
                message: warningMessages
            }};
</code>```

Body:
I am using MatDialog and trying to add a new line in the content definition. Both \n and  are not doing it. Is there another way without having to manually go into the html and change it since it's a reusable component:

var status: MatDialogRef<GenericDialogComponent> this.dialog.open(GenericDialogComponent,{
     width: '400px',
    data: {title: "Sample Title?", content: "Document " + this.docID + " has been saved. The users email address is provied below:\n\n"+this.email+""} });

HTML

{{data.title}}

{{data.content}}

  <button mat-button (click)="Cancel()">Cancel</button>
  <button mat-button (click)="Ok()" cdkFocusInitial>Ok</button>

Body:
This worked for me:

        let warningMessages = ['message1','message2','message3'];

        const config=  {
            panelClass:'msg-dialog-container',
            data: {
                type:WARNNING,
                showConfirm:true,
                message: warningMessages
            }};


问:
How to prevent rotate on Eyeshot?
My eyeshot project is to show the .dwg file.
But when touch the screen the screen rotate.

I want change rotate event to a pan event at native touch move event. Is this possible?
If is this impossible then I want prevent rotate screen.

答: You can disable rotation using Model.ActiveViewport.Rotate.Enable setting.

Title: How to prevent rotate on Eyeshot?


问:
How can I track down what is causing `go build` to take a long time?
Running it with -v does not really tell me what the problem is. It takes about 20s before printing even a single line.

Running it under strace outputs a lot of noise, and strace does not run on Mac OS.

Removing dependencies to see if they are the problem would be a ridiculous amount of work.

答:
You can use the -x flag to show all commands being executed:

https://godocs.io/cmd/go#hdr-Compile_packages_and_dependencies


问:
Fix image orientation in Jimp
I am using Jimp (https://www.npmjs.com/package/jimp) library to crop the image.

Crop is working fine but I only have an issue with image orientation.

Sometimes, user uploaded rotated images and its result rotated cropped images.

I went through with https://www.npmjs.com/package/jimp documentation but couldn't find anything related to this.

Here are couple of links I went through but didn't helped:

https://justmarkup.com/articles/2019-10-21-image-orientation/

Accessing JPEG EXIF rotation data in JavaScript on the client side

Please help

答:
So, long story short: jimp correctly reads images rotated via exif orientation property and rearranges the pixels as if the exif/orientation property didn't exist, but then also stores the old exif property instead of resetting it to 1 as it should for it to be displayed properly on every device.

The simplest solution I was able to implement was using exif-auto-rotate to rotate the image pixels and reset the exif property on the frontend before uploading the (base64 encoded) image to the backend:

```<code>    import Rotator from 'exif-auto-rotate';

    // ...

    const [file] = e.target.files;

    const image = await Rotator.createRotatedImageAsync(file, "base64")
        .catch(err => {
            if (err === "Image is NOT have a exif code" || err === "Image is NOT JPEG") {
                // just return base64 encoded image if image is not jpeg or contains no exif orientation property
                return toBase64(file)
            }
            // reject if other error
            return Promise.reject(err)
        });
</code>```

If you need to do this on the backend then you are probably better off using jpeg-autorotate with buffers as suggested here:

```<code>const fileIn = fs.readFileSync('input.jpg')
const jo = require('jpeg-autorotate')
const {buffer} = await jo.rotate(fileIn, {quality: 30})
const image = await Jimp.read(buffer)
</code>```

More info on browser-based exif orientation issues:

EXIF Orientation Handling Is a Ghetto

Title: Fix image orientation in Jimp

Body:
So, long story short: jimp correctly reads images rotated via exif orientation property and rearranges the pixels as if the exif/orientation property didn't exist, but then also stores the old exif property instead of resetting it to 1 as it should for it to be displayed properly on every device.

The simplest solution I was able to implement was using exif-auto-rotate to rotate the image pixels and reset the exif property on the frontend before uploading the (base64 encoded) image to the backend:

    import Rotator from 'exif-auto-rotate';

    // ...

    const [file] = e.target.files;

    const image = await Rotator.createRotatedImageAsync(file, "base64")
        .catch(err => {
            if (err === "Image is NOT have a exif code" || err === "Image is NOT JPEG") {
                // just return base64 encoded image if image is not jpeg or contains no exif orientation property
                return toBase64(file)
            }
            // reject if other error
            return Promise.reject(err)
        });

If you need to do this on the backend then you are probably better off using jpeg-autorotate with buffers as suggested here:

const fileIn = fs.readFileSync('input.jpg')
const jo = require('jpeg-autorotate')
const {buffer} = await jo.rotate(fileIn, {quality: 30})
const image = await Jimp.read(buffer)

More info on browser-based exif orientation issues:

EXIF Orientation Handling Is a Ghetto


问:
How to mutate a list of objects in an array as an argument in GraphQL completely
I cannot mutate a list of objects completely, because only the last element of the array will be mutated.

What already works perfectly is, if I put each element ({play_positions_id: ...}) in the array manually like here:

```<code>mutation CreateProfile {
  __typename
  create_profiles_item(data: {status: "draft", play_positions: [{play_positions_id: {id: "1"}}, {play_positions_id: {id: "2"}}]}) {
    id
    status
    play_positions {

      play_positions_id {
        abbreviation
        name
      }
    }
  }
}
</code>```

Output:

```<code>{
  "data": {
    "__typename": "Mutation",
    "create_profiles_item": {
      "id": "1337",
      "status": "draft",
      "play_positions": [
        {
          "play_positions_id": {
            "id": "1",
            "abbreviation": "RWB",
            "name": "Right Wingback"
          }
        },
        {
         "play_positions_id": {
            "id": "2",
            "abbreviation": "CAM",
            "name": "Central Attacking Midfielder"
          }
        }
      ],
    }
  }
}
</code>```

Since you can add many of those elements, I defined a variable/argument like here

```<code>mutation CreateProfile2($cpppi: [create_profiles_play_positions_input]) {
  __typename
  create_profiles_item(data: {status: "draft", play_positions: $cpppi}) {
    id
    status
    play_positions {

      play_positions_id {
        id
        abbreviation
        name
      }
    }
  }
}
</code>```

Variable object for above:

```<code>"cpppi": {
    "play_positions_id": {
      "id": "1"
    },
    "play_positions_id": {
      "id": "2
    }
  }
</code>```

Output:

```<code>{
  "data": {
    "__typename": "Mutation",
    "create_profiles_item": {
      "id": "1338",
      "play_positions": [
        {

          "play_positions_id": {
            "id": "2",
            "abbreviation": "CAM",
            "name": "Central Attacking Midfielder"
          }
        }
      ],
    }
  }
}
</code>```

Schema:

```<code>input create_profiles_input {
  id: ID
  status: String!
  play_positions: [create_profiles_play_positions_input]
}

input create_profiles_play_positions_input {
  id: ID
  play_positions_id: create_play_positions_input
}

input create_play_positions_input {
      id: ID
      abbreviation: String
      name: String
}
</code>```

At the last both snippets, only the last object with the id "2" will be mutated. I need these to use the defined input type from my backend.

答:
I figured it out. I got it wrong with the brackets in the variable. Here the solution:</p>
```<code>"cpppi": [
    {
      "play_positions_id": {
        "id": "1"
      }
    },
    {
      "play_positions_id": {
        "id": "2"
      }
    }
  ]
</code>```

Body:
I cannot mutate a list of objects completely, because only the last element of the array will be mutated.

What already works perfectly is, if I put each element ({play_positions_id: ...}) in the array manually like here:

mutation CreateProfile {
  __typename
  create_profiles_item(data: {status: "draft", play_positions: [{play_positions_id: {id: "1"}}, {play_positions_id: {id: "2"}}]}) {
    id
    status
    play_positions {

      play_positions_id {
        abbreviation
        name
      }
    }
  }
}

Output:

{
  "data": {
    "__typename": "Mutation",
    "create_profiles_item": {
      "id": "1337",
      "status": "draft",
      "play_positions": [
        {
          "play_positions_id": {
            "id": "1",
            "abbreviation": "RWB",
            "name": "Right Wingback"
          }
        },
        {
         "play_positions_id": {
            "id": "2",
            "abbreviation": "CAM",
            "name": "Central Attacking Midfielder"
          }
        }
      ],
    }
  }
}

Since you can add many of those elements, I defined a variable/argument like here

mutation CreateProfile2($cpppi: [create_profiles_play_positions_input]) {
  __typename
  create_profiles_item(data: {status: "draft", play_positions: $cpppi}) {
    id
    status
    play_positions {

      play_positions_id {
        id
        abbreviation
        name
      }
    }
  }
}

Variable object for above:

"cpppi": {
    "play_positions_id": {
      "id": "1"
    },
    "play_positions_id": {
      "id": "2
    }
  }

Output:

{
  "data": {
    "__typename": "Mutation",
    "create_profiles_item": {
      "id": "1338",
      "play_positions": [
        {

          "play_positions_id": {
            "id": "2",
            "abbreviation": "CAM",
            "name": "Central Attacking Midfielder"
          }
        }
      ],
    }
  }
}

Schema:

input create_profiles_input {
  id: ID
  status: String!
  play_positions: [create_profiles_play_positions_input]
}

input create_profiles_play_positions_input {
  id: ID
  play_positions_id: create_play_positions_input
}

input create_play_positions_input {
      id: ID
      abbreviation: String
      name: String
}

At the last both snippets, only the last object with the id "2" will be mutated. I need these to use the defined input type from my backend.

Body:
I figured it out. I got it wrong with the brackets in the variable. Here the solution:

"cpppi": [
    {
      "play_positions_id": {
        "id": "1"
      }
    },
    {
      "play_positions_id": {
        "id": "2"
      }
    }
  ]


问:
Google Sheets script – replace blank spaces
I've got a script that's doing some onEdit formatting on a sheet of mine. All the rest is working well, and I wanted to include a line that deletes spaces from number values I'm importing. That last line is not working.

Any ideas what I'm missing here?

function onEdit(e) {
  var cell = e.range;
  var sh = e.source.getActiveSheet();
  if(sh.getName() === "Trading Journal") {
    cell.setBackground('#fff');
    cell.setFontSize(10)
    cell.setFontFamily()
    cell.replace(/\s/g, "")
}
}```

https://docs.google.com/spreadsheets/d/1rkjO-ITeLdIHq-LLHfHcp6-1j1R0-giS6HGbwYdJ5Ek/edit?usp=sharing

答:
Did a bit of research regarding this, and it seems that .replace() is a string method and therefore may not work with numbers. Reference

But if you only need to remove whitespaces from numbers, here is a simple solution:

```<code>function rSpaces() {
    var ss =  SpreadsheetApp.getActiveSpreadsheet();
    var cell = ss.getActiveCell();
    cell.trimWhitespace();
}
</code>```

You can assign this on an onEdit trigger and check this documentation for any font modifications you want to add.

Body:
I've got a script that's doing some onEdit formatting on a sheet of mine. All the rest is working well, and I wanted to include a line that deletes spaces from number values I'm importing. That last line is not working.

Any ideas what I'm missing here?

function onEdit(e) {
  var cell = e.range;
  var sh = e.source.getActiveSheet();
  if(sh.getName() === "Trading Journal") {
    cell.setBackground('#fff');
    cell.setFontSize(10)
    cell.setFontFamily()
    cell.replace(/\s/g, "")
}
}

https://docs.google.com/spreadsheets/d/1rkjO-ITeLdIHq-LLHfHcp6-1j1R0-giS6HGbwYdJ5Ek/edit?usp=sharing

Body:
Did a bit of research regarding this, and it seems that .replace() is a string method and therefore may not work with numbers. Reference

But if you only need to remove whitespaces from numbers, here is a simple solution:

function rSpaces() {
    var ss =  SpreadsheetApp.getActiveSpreadsheet();
    var cell = ss.getActiveCell();
    cell.trimWhitespace();
}

You can assign this on an onEdit trigger and check this documentation for any font modifications you want to add.


问:
pda to accept the language L={a^n b^m | n<m}
I know how to solve for m<n but I'm struggling to understand the logic for m>n.

In m<n we push all a's in the stack and when we get b we popped out one a, when the input ends with a stack containing m-n a's the machine should enter the final state

How can I do for m>n....

答:
The intial configuration is the same.  But you've got two separate states for reading 'b's:

State B1:  I'm popping 'b's, but the stack hasn't been empty.

If the top of the stack is an 'a' and you read a 'b': stay in that state

If the stack is empty and you read a 'b':  go to state B2

State B2:  I'm popping 'b's, and the stack is empty.

If the top of the stack is empty and you read a 'b', stay in that state

Otherwise fail.

You've read more b's than a's if you're in state B2.


问:
How can I programmatically create a process snapshot on windows/unix?
I am creating a Golang program that creates a process and then should be able to suspend it.

To make it more memory efficient, I would need my program to be able to dump the memory of the process to disk and reload it only when needed.

I cannot find any info here on Stack Overflow and also GitHub is not helping.

Any solution?

答:
Attempting to answer this with the limited info..

To make it more memory efficient, I would need my program to be able to dump the memory of the process to disk and reload it only when needed.

This is generally something handled by your operating system (scheduler, memory management) controlling what processes are currently running / suspended / etc. and what memory needs to be paged in / out. Trying to implement the equivalent is quite complex, error prone, and likely to be less performant. Why do you believe you need to implement this yourself?

If you are building a program and want to have explicit control about whether it should be considered runnable or not, you could create a process which forks (creating two total processes), and have the parent process suspend and resume the child process using signals:

https://man7.org/linux/man-pages/man7/signal.7.html


问:
My shell script for checking leap year is showing error
```<code>#!/bin/bash

echo "Enter the year (YYYY)"
read year

if[ $((year % 4)) -eq 0]
then
  if[ $((year % 100)) -eq 0]
    then
    if[ $((year % 400)) -eq 0]
          then
        echo "its a leap year"
    else
           echo "its not a leap year"
    fi
  else
  echo "Its not a leap year"
  fi
else
 echo "its not a leap year"

fi
</code>```

<p>its showing error on 7th line and also on </p>

```<code>[ $((year % 4)) -eq 0]
</code>```

答:
#!/bin/bash

echo "Enter the year (YYYY)"

read year

if [ $((year%4)) -eq 0 ]

then

if [ $((year%100)) -eq 0 ]

```<code>then

if [ $((year%400)) -eq 0 ]

      then

    echo "its a leap year"

else

       echo "its not a leap year"

fi
</code>```

else

echo "Its a leap year"

fi

else

echo "its not a leap year"

fi

Body:
#!/bin/bash

echo "Enter the year (YYYY)"
read year

if[ $((year % 4)) -eq 0]
then
  if[ $((year % 100)) -eq 0]
    then
    if[ $((year % 400)) -eq 0]
          then
        echo "its a leap year"
    else
           echo "its not a leap year"
    fi
  else
  echo "Its not a leap year"
  fi
else
 echo "its not a leap year"

fi

its showing error on 7th line and also on

[ $((year % 4)) -eq 0]

Body:
#!/bin/bash

echo "Enter the year (YYYY)"

read year

if [ $((year%4)) -eq 0 ]

then

if [ $((year%100)) -eq 0 ]

then

if [ $((year%400)) -eq 0 ]

      then

    echo "its a leap year"

else

       echo "its not a leap year"

fi

else

echo "Its a leap year"

fi

else

echo "its not a leap year"

fi


问:
Tkinter label text is a funtion object instead of text
I've been googling around for over an hour at this point, but I can't figure this out. I want to display the result of the function as the label's text. The problem is that even though the return of the function is for example: 250.2, when I place the label into the tkinter window, it looks more like (numbers)< lambda >, which I think is a function object.

The label:

```<code>self.temperature = ttk.Label(
            self,
            text=lambda:self.displayInfo(0))
</code>```

The function:

```<code>def displayInfo(self, index):
        self.infoList = WeatherInfo.jsonToString(self)

        return self.infoList[index]
</code>```

Thanks in advance.

答:
You are passing a lambda where a string is expected.  If you want the result of the function, then just call the function:

```<code>self.temperature = ttk.Label( self, text=self.displayInfo(0) )
</code>```

Body:
I've been googling around for over an hour at this point, but I can't figure this out. I want to display the result of the function as the label's text. The problem is that even though the return of the function is for example: 250.2, when I place the label into the tkinter window, it looks more like (numbers)< lambda >, which I think is a function object.

The label:

self.temperature = ttk.Label(
            self,
            text=lambda:self.displayInfo(0))

The function:

def displayInfo(self, index):
        self.infoList = WeatherInfo.jsonToString(self)

        return self.infoList[index]

Thanks in advance.

Body:
You are passing a lambda where a string is expected.  If you want the result of the function, then just call the function:

self.temperature = ttk.Label( self, text=self.displayInfo(0) )


问:
Sending and Receiving arrays via Sockets
Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. Hope I explained the problem as clearly as possible. I would appreciate the help!</p>

```<code># Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()
</code>```

答:
eval is doing something completely different than what you think.

To send data over network, you need to serialize it into an array of bytes, then deserialize it back. In Python, serialization of most objects can be done via pickle module:

```<code>if (UDPSock.sendto( pickle.dumps(a), addr)):
</code>```

Deserialization:

```<code>data,addr = UDPSock.recvfrom(buf)
L = pickle.loads(data)
print repr(L) # prints array('i', [1, 3, 2])
</code>```

Body:
Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. Hope I explained the problem as clearly as possible. I would appreciate the help!

# Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()

Body:
eval is doing something completely different than what you think.

To send data over network, you need to serialize it into an array of bytes, then deserialize it back. In Python, serialization of most objects can be done via pickle module:

if (UDPSock.sendto( pickle.dumps(a), addr)):

Deserialization:

data,addr = UDPSock.recvfrom(buf)
L = pickle.loads(data)
print repr(L) # prints array('i', [1, 3, 2])


问:
Hide entire block of text whenever it no longer fits
My text seems to default to hiding particular pieces that don't fit in a div. I would like the whole block to disappear once it no longer fits.

Is there any way to do this?

Here is a sample app of what I currently have:

const App = () => {

  return (

 If you don't fit you need to be hidden. If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.

  )
}

ReactDOM.render(
    <App />,
    document.getElementById('app')
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  border: 1px solid red;
  height: 150px;
  width: 150px;
  overflow: hidden;

}</code>```

```

答:
TL;DR: working example here.

I don't think there is a css way to do this, but since you're using React, you can take advantage of refs and compute the element size.

1. Get a reference to the element

Note that you cannot use a standard useRef hook (as far as I know), because changes to these don't trigger a re-render so React won't know when your container overflows.
Instead, you can use a callback ref and store it in the state.

```<code>const [textRef, setTextRef] = useState(null);

...

<div ref={(newRef) => setTextRef(newRef)} className="container">
  ...
</div>
</code>```

2. Check if it overflows

Now that you have a reference to the element, you can compute whether it overflows or not by comparing scrollHeight and offsetHeight properties.

```<code>const overflows = textRef.scrollHeight > textRef.offsetHeight;
</code>```

3. Store info in state

You have to do this dynamically when the element changes, so place this in an useEffect hook with the textRef as a dependency. Then store the "overflows" property in the state to use it later.

```<code>const [overflows, setOverflows] = useState(false);

useEffect(() => {
  if (textRef) {
    const overflows = textRef.scrollHeight > textRef.offsetHeight;
    setOverflows(overflows);
  }
}, [textRef]);
</code>```

4. Render conditionally

Now that you know whether an element overflows and you have that info in the state, you can simply conditionally render the element.

```<code><div ref={(newRef) => setTextRef(newRef)} className="container">
  {!overflows && <p className="text">If you don't fit you need to be hidden...</p>}
</div>
</code>```

Check out this working example where you can see that one element is shown because it has less text and fits, whereas the other is hidden because it overflows.

Body:
My text seems to default to hiding particular pieces that don't fit in a div. I would like the whole block to disappear once it no longer fits.

Is there any way to do this?

Here is a sample app of what I currently have:

const App = () => {

  return (

 If you don't fit you need to be hidden. If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.

  )
}

ReactDOM.render(
    <App />,
    document.getElementById('app')
);

.container {
  border: 1px solid red;
  height: 150px;
  width: 150px;
  overflow: hidden;

}

Body:
TL;DR: working example here.

I don't think there is a css way to do this, but since you're using React, you can take advantage of refs and compute the element size.

1. Get a reference to the element

Note that you cannot use a standard useRef hook (as far as I know), because changes to these don't trigger a re-render so React won't know when your container overflows.
Instead, you can use a callback ref and store it in the state.

const [textRef, setTextRef] = useState(null);

...

<div ref={(newRef) => setTextRef(newRef)} className="container">
  ...
</div>

2. Check if it overflows

Now that you have a reference to the element, you can compute whether it overflows or not by comparing scrollHeight and offsetHeight properties.

const overflows = textRef.scrollHeight > textRef.offsetHeight;

3. Store info in state

You have to do this dynamically when the element changes, so place this in an useEffect hook with the textRef as a dependency. Then store the "overflows" property in the state to use it later.

const [overflows, setOverflows] = useState(false);

useEffect(() => {
  if (textRef) {
    const overflows = textRef.scrollHeight > textRef.offsetHeight;
    setOverflows(overflows);
  }
}, [textRef]);

4. Render conditionally

Now that you know whether an element overflows and you have that info in the state, you can simply conditionally render the element.

<div ref={(newRef) => setTextRef(newRef)} className="container">
  {!overflows && <p className="text">If you don't fit you need to be hidden...</p>}
</div>

Check out this working example where you can see that one element is shown because it has less text and fits, whereas the other is hidden because it overflows.


问:
SQL view performance
I am using views for query convenience. The view is a join between three tables, using INNER JOIN and OUTER RIGHT joins. The overall result set from the view could be 500,000 records. I then perform other queries off of this view, similar to:

```<code>SELECT colA, colB, colC FROM vwMyView WHERE colD = 'ABC'
</code>```

This query might return only 30 or so results. How will this be for performance? Internally in the SQL engine will the view always be executed, then the WHERE clause applied after, or is SQL Server smart enough to apply the WHERE clause first so that the JOIN operations are only done on a subset of records?

If I'm only returning 30 records to the middle tier, do I need to worry too much that the SQL Server had to trawl through 500,000 records to get to those 30 records? I have indexes applied on all important columns on the base tables.

Using MS SQL Server, view is not materialized

答:
Performance of queries on large datasets typically need clever application of indices. In your case a simple index on colD probably will do the trick. Depending on the data different types of indeces might need scrutiny. Hash tables, btrees etc all behave differently depending on the data. So there is no one solution that rules them all here. Otherwise optimization is better left to the query optimizer in your RDBMS. The developers there spend quite some time optimizing and critical segments probably are in low-level fast moving code.
On another node clever cleaning of the data might be considered as well. And if aggregation is required datawarehousing with clever dimensions and pre aggregated values. Storage is cheap these days, computing time maybe not so.</p>

Title: SQL view performance

Body:
I am using views for query convenience. The view is a join between three tables, using INNER JOIN and OUTER RIGHT joins. The overall result set from the view could be 500,000 records. I then perform other queries off of this view, similar to:

SELECT colA, colB, colC FROM vwMyView WHERE colD = 'ABC'

This query might return only 30 or so results. How will this be for performance? Internally in the SQL engine will the view always be executed, then the WHERE clause applied after, or is SQL Server smart enough to apply the WHERE clause first so that the JOIN operations are only done on a subset of records?

If I'm only returning 30 records to the middle tier, do I need to worry too much that the SQL Server had to trawl through 500,000 records to get to those 30 records? I have indexes applied on all important columns on the base tables.

Using MS SQL Server, view is not materialized


问:
Flutter remove all routes
I want to develop a logout button that will send me to the log in route and remove all other routes from the Navigator. The documentation doesn't seem to explain how to make a RoutePredicate or have any sort of removeAll function.

答:
use popUntil like following

Navigator.popUntil(context, (route) => route.isFirst);

Title: Flutter remove all routes


问:
Python/Selenium: Click on button element without ID attribute
Hi I want to click on this button but I don't know how to find it, it has no explicit NAME or ID, also, what is the code to simulate a mouse click?

This is the HTML:

```<code><button class="aOOlW  bIiDR  " tabindex="0">Accept All</button>
</code>```

This is the part of the code:

```<code>auth = driver.find_element(By.CLASS_NAME, 'aOOlW  bIiDR  ')
auth.send_mouse(Keys.LEFT)
</code>```

As you can see send_mouse(Keys.LEFT) doesn't work.

答:
There is no such method as send_mouse(Keys.LEFT)

To click() on the element with text as Accept All you can use either of the following locator strategies:

Using css_selector:

```<code>driver.find_element(By.CSS_SELECTOR, "button[tabindex='0']").click()
</code>```

Using xpath:

```<code>driver.find_element(By.XPATH, "//button[text()='Accept All']").click()
</code>```

Body:
Hi I want to click on this button but I don't know how to find it, it has no explicit NAME or ID, also, what is the code to simulate a mouse click?

This is the HTML:

<button class="aOOlW  bIiDR  " tabindex="0">Accept All</button>

This is the part of the code:

auth = driver.find_element(By.CLASS_NAME, 'aOOlW  bIiDR  ')
auth.send_mouse(Keys.LEFT)

As you can see send_mouse(Keys.LEFT) doesn't work.

Body:
There is no such method as send_mouse(Keys.LEFT)

To click() on the element with text as Accept All you can use either of the following locator strategies:

Using css_selector:

driver.find_element(By.CSS_SELECTOR, "button[tabindex='0']").click()

Using xpath:

driver.find_element(By.XPATH, "//button[text()='Accept All']").click()


问:
Is there a scripting tool for Mac?
Is there a tool for Mac OS like Windows VBScript?

I want to write some script which generates folders automatically and copy & paste files according to input.

答:
It's called AppleScript...

BUT

python is also another option that comes packed with OSX that has filesystem tools, and probably most popularly, OSX's terminal is bash, so most bash shell scripts will also work with OSX.

Title: Is there a scripting tool for Mac?


问:
Where is my jar in Elastic Beanstalk EC2
I'm new to Elastic Beanstalk, but not to AWS.
I just spawn new EBS with sample java app (Java SE) and managed to make it run.
Since I'm used to create EC2 instance manually, I login into my EC2 but couldn't find where my sample jar app is deployed. My question is: where is my JAR deployed within EC2, in which directory?

Best regards,
Bromo

答:
FWIW with my AMI "runnable jar" it's in

/var/app/current

How to figure this out:
ssh to box, run ps -ef | grep java then sudo ls /proc/<pid>| grep cwd shows a symlink to its current working directory, and it's ps output showed it was running a local jar file relative to that dir.


问:
ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0
After upgrading to Django 4.0, I get the following error when running python manage.py runserver

```<code>  ...
  File "/path/to/myproject/myproject/urls.py", line 16, in <module>
    from django.conf.urls import url
ImportError: cannot import name 'url' from 'django.conf.urls' (/path/to/my/venv/lib/python3.9/site-packages/django/conf/urls/__init__.py)
</code>```

My urls.py is as follows:

```<code>from django.conf.urls

from myapp.views import home

urlpatterns = [
    url(r'^$', home, name="home"),
    url(r'^myapp/', include('myapp.urls'),
]
</code>```

答:
I think a quick fix to this problem is to do followings;

You can easily replace

```<code>from django.conf.urls import url
</code>```

to this:

```<code>from django.urls import re_path as url
</code>```

And keep the rest of code to be same as before.
(Thanks @Alasdair)

Body:
After upgrading to Django 4.0, I get the following error when running python manage.py runserver

  ...
  File "/path/to/myproject/myproject/urls.py", line 16, in <module>
    from django.conf.urls import url
ImportError: cannot import name 'url' from 'django.conf.urls' (/path/to/my/venv/lib/python3.9/site-packages/django/conf/urls/__init__.py)

My urls.py is as follows:

from django.conf.urls

from myapp.views import home

urlpatterns = [
    url(r'^$', home, name="home"),
    url(r'^myapp/', include('myapp.urls'),
]

Body:
I think a quick fix to this problem is to do followings;

You can easily replace

from django.conf.urls import url

to this:

from django.urls import re_path as url

And keep the rest of code to be same as before.
(Thanks @Alasdair)