答:
Apparently did not understand something in SO 8114657 answers.
Here is your working code in accordance with that answer....

.wcppec-checkout-buttons {
    pointer-events: none; /* NEW */

    outline: 10px solid #ffc439;
    outline-offset: -10px
}

#woo_pp_ec_button_cart {
    pointer-events: auto; /* NEW */

    height: 44px
}
#woo_pp_ec_button_cart:hover { /* CHANGED */
    outline: 10px solid #f1bb37;
    outline-offset: -10px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wcppec-checkout-buttons">
    <div id="woo_pp_ec_button_cart"></div>
</div></code>```

Title: Change border from parent div by hovering the child div

Body:
I try to change the color of the border but nothing works out.
Is it even possible with css? I already found this: How to affect other elements when one element is hovered
and also How to style the parent element when hovering a child element?

Some java / jquery solution?

.wcppec-checkout-buttons {
  outline: 10px solid #ffc439;
  outline-offset: -10px;
}

#woo_pp_ec_button_cart {
  height: 44px;
}

#woo_pp_ec_button_cart:hover>.wcppec-checkout-buttons {
  outline: 10px solid #f1bb37;
  outline-offset: -10px;
}

Body:
Apparently did not understand something in SO 8114657 answers.
Here is your working code in accordance with that answer....

.wcppec-checkout-buttons {
    pointer-events: none; /* NEW */

    outline: 10px solid #ffc439;
    outline-offset: -10px
}

#woo_pp_ec_button_cart {
    pointer-events: auto; /* NEW */

    height: 44px
}
#woo_pp_ec_button_cart:hover { /* CHANGED */
    outline: 10px solid #f1bb37;
    outline-offset: -10px
}

<div class="wcppec-checkout-buttons">
    <div id="woo_pp_ec_button_cart"></div>
</div>


来源: stackexchange

问:
Nix add variadic args to a set from a function
Is something like this possible in nix?

```<code>f = {x, y, ...}:
{
    x = x + 1;
    y = y + 2;
    ...;
}
</code>```

where calling f on a set of arguments returns a set:

```<code>f { x = 1; y = 2; }                   -> { x = 2; y = 4; }
f { x = 1; y = 2; z = 5 }             -> { x = 2; y = 4; z = 5; }
f { x = 1; y = 2; z = 5; s = "str"; } -> { x = 2; y = 4; z = 5; s = "str"; }
</code>```

To be clear. The set of ellipsis ... is the variadic argument type and does not mean etcetera used in everyday language. The solution here is to call get { ... } on ellipsis if possible. But I don't know if the language supports this.

答:
This should work:

```<code>f = args@{x, y, ...}: args // { x = x + 2; y = y + 2; }
</code>```

You can read more about it here:

https://nixos.org/nix/manual/#ss-functions

ContentLicense: CC BY-SA 4.0

Body:
Is something like this possible in nix?

f = {x, y, ...}:
{
    x = x + 1;
    y = y + 2;
    ...;
}

where calling f on a set of arguments returns a set:

f { x = 1; y = 2; }                   -> { x = 2; y = 4; }
f { x = 1; y = 2; z = 5 }             -> { x = 2; y = 4; z = 5; }
f { x = 1; y = 2; z = 5; s = "str"; } -> { x = 2; y = 4; z = 5; s = "str"; }

To be clear. The set of ellipsis ... is the variadic argument type and does not mean etcetera used in everyday language. The solution here is to call get { ... } on ellipsis if possible. But I don't know if the language supports this.

Body:
This should work:

f = args@{x, y, ...}: args // { x = x + 2; y = y + 2; }

You can read more about it here:

https://nixos.org/nix/manual/#ss-functions


问:
Flow $ObjMap on type parameter
Flow isn't producing the error I expect in the following.  Is it a bug with Flow (probably) or do I misunderstand something about type parameters?

```<code>function test<A: Object>(
  obj: A,
  mapper: $ObjMap<A, <V>(V) => V => any>
) {
}

test(
  {
    foo: 1,
    bar: '2',
  },
  {
    foo: (x: number) => String(x),
    bar: (x: number) => parseInt(x),
    //       ^^^^^^
    // should error that this is the wrong argument type
  }
)
</code>```

It seems like a bug because the following produces an error, albeit in the wrong place:

```<code>const a = {foo: 1, bar: '2'}
type A = typeof a
type B = $ObjMap<A, <V>(V) => V => any>

const b: B = {
  foo: x => String(x),
  bar: (x: number) => parseInt(x),
}
</code>```

Error:

```<code>3: type B = $ObjMap<A, <V>(V) => V => any>
            ^ Cannot instantiate `$ObjMap` because string [1] is incompatible with number [2] in the first argument.
   References:
   1: const a = {foo: 1, bar: '2'}
                              ^ [1]
   7:   bar: (x: number) => parseInt(x),
                 ^ [2]
</code>```

答:
Okay, I was able to get it to work with

```<code>declare function test<A: Object, M: $ReadOnly<$ObjMap<A, <I, O>(I) => I => O>>>(
  obj: A,
  mapper: M
): $ObjMap<M, <I, O>((I) => O) => O>
</code>```

Not ideal because the output is only assignable to a $ReadOnly shape, but it covers all the type checking I need.

Title: Flow $ObjMap on type parameter

Body:
Flow isn't producing the error I expect in the following.  Is it a bug with Flow (probably) or do I misunderstand something about type parameters?

function test(
  obj: A,
  mapper: $ObjMap<A, <V>(V) => V => any>
) {
}

test(
  {
    foo: 1,
    bar: '2',
  },
  {
    foo: (x: number) => String(x),
    bar: (x: number) => parseInt(x),
    //       ^^^^^^
    // should error that this is the wrong argument type
  }
)

It seems like a bug because the following produces an error, albeit in the wrong place:

const a = {foo: 1, bar: '2'}
type A = typeof a
type B = $ObjMap<A, <V>(V) => V => any>

const b: B = {
  foo: x => String(x),
  bar: (x: number) => parseInt(x),
}

Error:

3: type B = $ObjMap<A, <V>(V) => V => any>
            ^ Cannot instantiate `$ObjMap` because string [1] is incompatible with number [2] in the first argument.
   References:
   1: const a = {foo: 1, bar: '2'}
                              ^ [1]
   7:   bar: (x: number) => parseInt(x),
                 ^ [2]

Body:
Okay, I was able to get it to work with

declare function test<A: Object, M: $ReadOnly<$ObjMap<A, <I, O>(I) => I => O>>>(
  obj: A,
  mapper: M
): $ObjMap<M, <I, O>((I) => O) => O>

Not ideal because the output is only assignable to a $ReadOnly shape, but it covers all the type checking I need.


问:
Global error handling of file_get_contents() PHP
I am occasionally getting errors while using file_get_contents and its used a fair bit in my script. I know I can suppress errors individually with @file_get_contents and that I can set global error messages with

```<code>//error handler function
function customError($errno)
  {
  echo 'Oh No!';
  }

//set error handler
set_error_handler("customError");
</code>```

But how do I specifically set an error handler for all file_get_content's uses?

Thanks

答:
or check the trace and handle error if referer function is file_get_contents</p>

```<code>//error handler function
    function customError($errno)
    {
        $a = debug_backtrace();
        if($a[1]['function'] == 'file_get_contents')
        {
            echo 'Oh No!';
        }
    }

    //set error handler
    set_error_handler("customError");
</code>```

Body:
I am occasionally getting errors while using file_get_contents and its used a fair bit in my script. I know I can suppress errors individually with @file_get_contents and that I can set global error messages with

//error handler function
function customError($errno)
  {
  echo 'Oh No!';
  }

//set error handler
set_error_handler("customError");

But how do I specifically set an error handler for all file_get_content's uses?

Thanks

Body:
or check the trace and handle error if referer function is file_get_contents

//error handler function
    function customError($errno)
    {
        $a = debug_backtrace();
        if($a[1]['function'] == 'file_get_contents')
        {
            echo 'Oh No!';
        }
    }

    //set error handler
    set_error_handler("customError");

ContentLicense: CC BY-SA 3.0


问:
Changing Request Path in .Net Core 3.1
Prior to 3.0, I could change the path of a request (without any form of browser redirection) by just accessing the HttpRequest property of the HttpContext and then changed the value of the Path.

As an example, to display a page for a user who needed to change his/her password (irrespective of the page the user intended to visit), I extended the HttpContext

```<code>public static void ChangeDefaultPassword(this HttpContext context)
=> context.Request.Path = "/Account/ChangePassword";
</code>```

This piece of code takes the user to the action method ChangePassword in the AccountController without executing the action method the user intends to visit.

Then enters dotnet core 3.1.

In 3.1, the extension method changes the path. However, it never executes the action method. It ignores the updated path.

I am aware this is due to the changes in the routing.The endpoint can now be accessed with the extension method HttpContext.GetEndpoint(). There is also an extension method HttpContext.SetEndpoint which seems to be the right way to set a new endpoint. However, there is no sample of how to accomplish this.

The Question

How do I change the request path, without executing the original path?

What I Have Tried

I tried changing the path. It seems routing in dotnet core 3.1 ignores the value of the HttpRequest path value.

I tried redirecting with context.Response.Redirect("/Account/ChangePassword");. This worked but it first executed the original action method requested by the user. This behavior defeated the purpose.

I tried using the extension method HttpContext.SetEndpoint, but there was no example available to work with.

答:
I had a similar reroute issue. In my case, I want to reroute users to a "you don't have permissions" view when an AuthorationHandler fails. I applied the following code, notably (httpContext.Response.Redirect(...)) in (.Net Core 3.1) to route me to a NoPermissions action on a Home Controller.

In the handler class:

```<code> protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, FooBarRequirement requirement) {
var hasAccess = await requirement.CheckAccess(context.User);
if (hasAccess)
context.Succeed(requirement);
else {
var message = "You do not have access to this Foobar function";
AuthorizeHandler.NoPermission(mHttpContextAccessor.HttpContext, context, requirement, message);
 }
}
</code>```

I wrote a static class to handle the redirect, passing in the url expected by the controller and action plus an error message, and the redirect permanent flag set to true:

```<code>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;

namespace Foo.BusinessLogic.Security {
public static class AuthorizeHandler {
    public static void NoPermission(HttpContext httpContext,
AuthorizationHandlerContext context, IAuthorizationRequirement requirement, string
errorMessage) {
        context.Succeed(requirement);
        httpContext.Response.Redirect($"/home/nopermission/?m={errorMessage}", true);
    }
  }
}
</code>```

Finally, the controller and action that handles the view and message

```<code>[AllowAnonymous]
public IActionResult NoPermission(string m) {
 return View("NoPermission", m);
 }
}
</code>```

Title: Changing Request Path in .Net Core 3.1

Body:
Prior to 3.0, I could change the path of a request (without any form of browser redirection) by just accessing the HttpRequest property of the HttpContext and then changed the value of the Path.

As an example, to display a page for a user who needed to change his/her password (irrespective of the page the user intended to visit), I extended the HttpContext

public static void ChangeDefaultPassword(this HttpContext context)
=> context.Request.Path = "/Account/ChangePassword";

This piece of code takes the user to the action method ChangePassword in the AccountController without executing the action method the user intends to visit.

Then enters dotnet core 3.1.

In 3.1, the extension method changes the path. However, it never executes the action method. It ignores the updated path.

I am aware this is due to the changes in the routing.The endpoint can now be accessed with the extension method HttpContext.GetEndpoint(). There is also an extension method HttpContext.SetEndpoint which seems to be the right way to set a new endpoint. However, there is no sample of how to accomplish this.

The Question

How do I change the request path, without executing the original path?

What I Have Tried

I tried changing the path. It seems routing in dotnet core 3.1 ignores the value of the HttpRequest path value.

I tried redirecting with context.Response.Redirect("/Account/ChangePassword");. This worked but it first executed the original action method requested by the user. This behavior defeated the purpose.

I tried using the extension method HttpContext.SetEndpoint, but there was no example available to work with.

Body:
I had a similar reroute issue. In my case, I want to reroute users to a "you don't have permissions" view when an AuthorationHandler fails. I applied the following code, notably (httpContext.Response.Redirect(...)) in (.Net Core 3.1) to route me to a NoPermissions action on a Home Controller.

In the handler class:

 protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, FooBarRequirement requirement) {
var hasAccess = await requirement.CheckAccess(context.User);
if (hasAccess)
context.Succeed(requirement);
else {
var message = "You do not have access to this Foobar function";
AuthorizeHandler.NoPermission(mHttpContextAccessor.HttpContext, context, requirement, message);
 }
}

I wrote a static class to handle the redirect, passing in the url expected by the controller and action plus an error message, and the redirect permanent flag set to true:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;

namespace Foo.BusinessLogic.Security {
public static class AuthorizeHandler {
    public static void NoPermission(HttpContext httpContext,
AuthorizationHandlerContext context, IAuthorizationRequirement requirement, string
errorMessage) {
        context.Succeed(requirement);
        httpContext.Response.Redirect($"/home/nopermission/?m={errorMessage}", true);
    }
  }
}

Finally, the controller and action that handles the view and message

[AllowAnonymous]
public IActionResult NoPermission(string m) {
 return View("NoPermission", m);
 }
}


问:
MakeFile is not glowing like it is Executable
This is the code that i have written in my makefile. For some reason it is not letting me execute the make function. When i type "make findName", i get "make: 'findName' is up to date."</p>

```<code>findName:       findName.cpp
        g++ -g findName.cpp -o findName;

clean:
        /bin/rm -f findName *.o

backup:
        #tar -zcvf bbrown.assignment4_1.tar.gz *.cpp *.h makeFile readme # will make a tar.gz
        tar -cvf bbrown.findName.tar *.cpp *.sh makeFile readme
</code>```

答:
A message like "make: 'target' is up to date." means that make has decided it doesn't need to run any commands, based on the timestamps of files involved. The make program considers files (and phony targets) to have a tree of prerequisites, and commands associated with creating a file will only be run if the file doesn't exist or has an older timestamp than one of its prerequisites. In big projects, this helps avoid completely rebuilding everything which could take a lot of time, when only a few source files have actually changed: make will determine which commands are actually needed. But this does require setting up the Makefile with accurate prerequisites.

Your Makefile specifies that file findName has one prerequisite: findName.cpp. If make successfully creates findName, then you do nothing else but just type make again, you'll see the "up to date" message: this is a feature. If you edit and save findName.cpp and then run make, it should repeat the g++ command.

But suppose you also have some header files you're including from findName.cpp, say findName.h. If you edit and save findName.h and then run make, you'll get "up to date", since make didn't know to findName.h has effects on findName. You would need to add the prerequisite to fix this:

```<code>findName:       findName.cpp findName.h
        g++ -g findName.cpp -o findName
</code>```

There are various ways to automatically deal with header dependencies like that, but they get into more advanced use of make, and/or using other build tools.

Body:
This is the code that i have written in my makefile. For some reason it is not letting me execute the make function. When i type "make findName", i get "make: 'findName' is up to date."

findName:       findName.cpp
        g++ -g findName.cpp -o findName;

clean:
        /bin/rm -f findName *.o

backup:
        #tar -zcvf bbrown.assignment4_1.tar.gz *.cpp *.h makeFile readme # will make a tar.gz
        tar -cvf bbrown.findName.tar *.cpp *.sh makeFile readme

Body:
A message like "make: 'target' is up to date." means that make has decided it doesn't need to run any commands, based on the timestamps of files involved. The make program considers files (and phony targets) to have a tree of prerequisites, and commands associated with creating a file will only be run if the file doesn't exist or has an older timestamp than one of its prerequisites. In big projects, this helps avoid completely rebuilding everything which could take a lot of time, when only a few source files have actually changed: make will determine which commands are actually needed. But this does require setting up the Makefile with accurate prerequisites.

Your Makefile specifies that file findName has one prerequisite: findName.cpp. If make successfully creates findName, then you do nothing else but just type make again, you'll see the "up to date" message: this is a feature. If you edit and save findName.cpp and then run make, it should repeat the g++ command.

But suppose you also have some header files you're including from findName.cpp, say findName.h. If you edit and save findName.h and then run make, you'll get "up to date", since make didn't know to findName.h has effects on findName. You would need to add the prerequisite to fix this:

findName:       findName.cpp findName.h
        g++ -g findName.cpp -o findName

There are various ways to automatically deal with header dependencies like that, but they get into more advanced use of make, and/or using other build tools.


问:
How to do "call by reference" in Java?

How to do "call by reference" in Java?  (Assume that we are using that term in the same way that it has been used in peer-reviewed CS literature since the 1960's; see this Wikipedia page for a simple explanation.)

Since Java doesn't support pointers, how is it possible to call a function by reference in Java like we do in C and C++??

答:
In Java, except for primitives, passing Object to a method/function is always by reference.
See Oli Charlesworth's answer for the example.

For primitive types, you can wrap it using array:
For example:

```<code>public void foo(int[] in){
  in[0] = 2;
}

int[] byRef = new int[1];
byRef[0] = 1;
foo(byRef);
// ==> byRef[0] == 2.
</code>```

Title: How to do "call by reference" in Java?

Body:
In Java, except for primitives, passing Object to a method/function is always by reference.
See Oli Charlesworth's answer for the example.

For primitive types, you can wrap it using array:
For example:

public void foo(int[] in){
  in[0] = 2;
}

int[] byRef = new int[1];
byRef[0] = 1;
foo(byRef);
// ==> byRef[0] == 2.


问:
Does anyone understand why my Heroku build might be failing?
I'm able to push to Heroku. When I run heroku open, I get application error on the browser page. It suggests that I run heroku logs --tail, which I have done and I get the following in my CLI:

```<code>2020-02-18T13:38:17.617747+00:00 app[api]: Release v2 created by user myemail@gmail.com
2020-02-18T13:38:17.617747+00:00 app[api]: Enable Logplex by user myemail@gmail.com
2020-02-18T13:38:16.539707+00:00 app[api]: Initial release by user myemail@gmail.com
2020-02-18T13:38:16.539707+00:00 app[api]: Release v1 created by user myemail@gmail.com
2020-02-18T13:39:28.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:39:29.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/b161fc9c-34f9-4258-8f6a-c8cf73016f74
2020-02-18T13:40:39.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:40:40.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/6a2ef41e-da40-4b22-9f44-dfc558e3f8c6
2020-02-18T13:41:55.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:41:56.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/7e98abc0-c073-40bd-bdcd-3e3c1960a1d4
2020-02-18T13:42:06.962017+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=event-finder-au.herokuapp.com request_id=447e958f-de6c-40d4-bee4-8d3d61531a72 fwd="86.7.194.99" dyno= connect= service= status=502 bytes= protocol=https
2020-02-18T13:42:07.345863+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/favicon.ico" host=event-finder-au.herokuapp.com request_id=227ffbed-06eb-4120-8e6a-c8ceded83237 fwd="86.7.194.99" dyno= connect= service= status=502 bytes= protocol=https
2020-02-18T13:48:08.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:48:09.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/851460c8-5acc-4547-89b0-723b2cb0070b
2020-02-18T13:48:42.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:48:43.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/bb02d5f6-b034-476f-8855-ad5173bedfa4
2020-02-18T13:51:22.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:51:23.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/7c1b17e9-27b2-4169-9a6b-c33a7593a20d
2020-02-18T13:55:45.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:55:46.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/caf2422c-28bd-4362-9a00-40a1e8a4bef9
2020-02-18T13:56:58.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:56:59.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/44aabc7b-81a4-45c8-95ab-3ba0b0b98cb2
2020-02-18T13:59:22.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:59:24.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/6e917697-398f-46ca-89e7-a127db05608e
2020-02-18T14:00:58.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T14:01:00.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/bf2be350-233f-4320-ab4e-034b13bb6a9d
2020-02-18T14:01:19.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T14:01:20.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/42aba518-a40c-4f50-b4c5-839aecdeeb35
2020-02-18T14:02:44.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T14:03:40.379721+00:00 app[api]: Deploy 2daf4356 by user myemail@gmail.com
2020-02-18T14:03:40.379721+00:00 app[api]: Release v3 created by user myemail@gmail.com
2020-02-18T14:03:40.400674+00:00 app[api]: Scaled to web@1:Free by user myemail@gmail.com
2020-02-18T14:03:45.330569+00:00 heroku[web.1]: Starting process with command `npm start`
2020-02-18T14:03:45.000000+00:00 app[api]: Build succeeded
2020-02-18T14:03:50.190387+00:00 heroku[web.1]: State changed from starting to crashed
2020-02-18T14:03:50.195889+00:00 heroku[web.1]: State changed from crashed to starting
2020-02-18T14:03:50.173709+00:00 heroku[web.1]: Process exited with status 1
2020-02-18T14:03:50.033183+00:00 app[web.1]: npm ERR! missing script: start
2020-02-18T14:03:50.058454+00:00 app[web.1]:
2020-02-18T14:03:50.058836+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-02-18T14:03:50.058991+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-02-18T14_03_50_034Z-debug.log
2020-02-18T14:03:53.954752+00:00 heroku[web.1]: Starting process with command `npm start`
2020-02-18T14:03:56.614988+00:00 heroku[web.1]: State changed from starting to crashed
2020-02-18T14:03:56.600007+00:00 heroku[web.1]: Process exited with status 1
2020-02-18T14:03:56.523382+00:00 app[web.1]: npm ERR! missing script: start
2020-02-18T14:03:56.536675+00:00 app[web.1]:
2020-02-18T14:03:56.537274+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-02-18T14:03:56.537588+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-02-18T14_03_56_524Z-debug.log
2020-02-18T14:03:58.167610+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=event-finder-au.herokuapp.com request_id=6461804e-4804-4ce0-91b0-314ba1d0a0b4 fwd="86.7.194.99" dyno= connect= service= status=503 bytes= protocol=https
2020-02-18T14:03:58.671517+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=event-finder-au.herokuapp.com request_id=0072ed32-b9ad-4205-a3e0-111a4b57eb45 fwd="86.7.194.99" dyno= connect= service= status=503 bytes= protocol=https
2020-02-18T14:05:11.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T14:05:49.857750+00:00 heroku[web.1]: State changed from crashed to starting
2020-02-18T14:05:49.660236+00:00 app[api]: Deploy 6b00eac2 by user myemail@gmail.com
2020-02-18T14:05:49.660236+00:00 app[api]: Release v4 created by user myemail@gmail.com
2020-02-18T14:05:53.023230+00:00 heroku[web.1]: Starting process with command `npm start`
2020-02-18T14:05:55.615774+00:00 heroku[web.1]: State changed from starting to crashed
2020-02-18T14:05:55.540224+00:00 app[web.1]: npm ERR! missing script: start
2020-02-18T14:05:55.549366+00:00 app[web.1]:
2020-02-18T14:05:55.549975+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-02-18T14:05:55.550306+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-02-18T14_05_55_541Z-debug.log
2020-02-18T14:05:55.602183+00:00 heroku[web.1]: Process exited with status 1
2020-02-18T14:05:54.000000+00:00 app[api]: Build succeeded
2020-02-18T14:06:01.546305+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=event-finder-au.herokuapp.com request_id=3bc8dfc5-a6f2-436f-bcf2-9fbb2dc54e5c fwd="86.7.194.99" dyno= connect= service= status=503 bytes= protocol=https
2020-02-18T14:06:01.850676+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=event-finder-au.herokuapp.com request_id=6736e715-66e8-4cc7-9425-6a1f45307230 fwd="86.7.194.99" dyno= connect= service= status=503 bytes= protocol=https
</code>```

I'm a complete novice when it comes to this kind of thing so I have literally no idea what any of this means.

My package.json looks like this if it helps -

```<code>{
  "name": "basic-react-webpack-setup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "webpack-dev-server --mode=development"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.2.3",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.5",
    "css-loader": "^2.1.0",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.1",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^3.9.0"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "bulma": "^0.8.0",
    "child_process": "^1.0.2",
    "cluster": "^0.7.7",
    "file": "^0.2.2",
    "lib": "^4.0.5",
    "loader": "^2.1.1",
    "moment": "^2.24.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-map-gl": "^5.1.3",
    "react-router-dom": "^5.1.2",
    "url": "^0.11.0"
  }
}
</code>```

答:
The important part of that output is this:

```<code>npm ERR! missing script: start
</code>```

Heroku needs to know how to run your application. You can provide a Procfile with the relevant command, e.g.

```<code>web: node server.js
</code>```

or you can add a start script to your package.json, since Heroku runs that by default in the absence of a Procfile for JavaScript projects:

```<code>"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "serve": "webpack-dev-server --mode=development",
  "start" "node server.js"
},
</code>```

Obviously, you'll have to adjust the command depending on how your application works.

Body:
I'm able to push to Heroku. When I run heroku open, I get application error on the browser page. It suggests that I run heroku logs --tail, which I have done and I get the following in my CLI:

2020-02-18T13:38:17.617747+00:00 app[api]: Release v2 created by user myemail@gmail.com
2020-02-18T13:38:17.617747+00:00 app[api]: Enable Logplex by user myemail@gmail.com
2020-02-18T13:38:16.539707+00:00 app[api]: Initial release by user myemail@gmail.com
2020-02-18T13:38:16.539707+00:00 app[api]: Release v1 created by user myemail@gmail.com
2020-02-18T13:39:28.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:39:29.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/b161fc9c-34f9-4258-8f6a-c8cf73016f74
2020-02-18T13:40:39.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:40:40.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/6a2ef41e-da40-4b22-9f44-dfc558e3f8c6
2020-02-18T13:41:55.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:41:56.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/7e98abc0-c073-40bd-bdcd-3e3c1960a1d4
2020-02-18T13:42:06.962017+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=event-finder-au.herokuapp.com request_id=447e958f-de6c-40d4-bee4-8d3d61531a72 fwd="86.7.194.99" dyno= connect= service= status=502 bytes= protocol=https
2020-02-18T13:42:07.345863+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/favicon.ico" host=event-finder-au.herokuapp.com request_id=227ffbed-06eb-4120-8e6a-c8ceded83237 fwd="86.7.194.99" dyno= connect= service= status=502 bytes= protocol=https
2020-02-18T13:48:08.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:48:09.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/851460c8-5acc-4547-89b0-723b2cb0070b
2020-02-18T13:48:42.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:48:43.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/bb02d5f6-b034-476f-8855-ad5173bedfa4
2020-02-18T13:51:22.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:51:23.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/7c1b17e9-27b2-4169-9a6b-c33a7593a20d
2020-02-18T13:55:45.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:55:46.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/caf2422c-28bd-4362-9a00-40a1e8a4bef9
2020-02-18T13:56:58.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:56:59.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/44aabc7b-81a4-45c8-95ab-3ba0b0b98cb2
2020-02-18T13:59:22.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T13:59:24.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/6e917697-398f-46ca-89e7-a127db05608e
2020-02-18T14:00:58.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T14:01:00.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/bf2be350-233f-4320-ab4e-034b13bb6a9d
2020-02-18T14:01:19.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T14:01:20.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/fdcfdeca-6786-4e3a-82b5-3ed6ee7a5517/activity/builds/42aba518-a40c-4f50-b4c5-839aecdeeb35
2020-02-18T14:02:44.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T14:03:40.379721+00:00 app[api]: Deploy 2daf4356 by user myemail@gmail.com
2020-02-18T14:03:40.379721+00:00 app[api]: Release v3 created by user myemail@gmail.com
2020-02-18T14:03:40.400674+00:00 app[api]: Scaled to web@1:Free by user myemail@gmail.com
2020-02-18T14:03:45.330569+00:00 heroku[web.1]: Starting process with command `npm start`
2020-02-18T14:03:45.000000+00:00 app[api]: Build succeeded
2020-02-18T14:03:50.190387+00:00 heroku[web.1]: State changed from starting to crashed
2020-02-18T14:03:50.195889+00:00 heroku[web.1]: State changed from crashed to starting
2020-02-18T14:03:50.173709+00:00 heroku[web.1]: Process exited with status 1
2020-02-18T14:03:50.033183+00:00 app[web.1]: npm ERR! missing script: start
2020-02-18T14:03:50.058454+00:00 app[web.1]:
2020-02-18T14:03:50.058836+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-02-18T14:03:50.058991+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-02-18T14_03_50_034Z-debug.log
2020-02-18T14:03:53.954752+00:00 heroku[web.1]: Starting process with command `npm start`
2020-02-18T14:03:56.614988+00:00 heroku[web.1]: State changed from starting to crashed
2020-02-18T14:03:56.600007+00:00 heroku[web.1]: Process exited with status 1
2020-02-18T14:03:56.523382+00:00 app[web.1]: npm ERR! missing script: start
2020-02-18T14:03:56.536675+00:00 app[web.1]:
2020-02-18T14:03:56.537274+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-02-18T14:03:56.537588+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-02-18T14_03_56_524Z-debug.log
2020-02-18T14:03:58.167610+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=event-finder-au.herokuapp.com request_id=6461804e-4804-4ce0-91b0-314ba1d0a0b4 fwd="86.7.194.99" dyno= connect= service= status=503 bytes= protocol=https
2020-02-18T14:03:58.671517+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=event-finder-au.herokuapp.com request_id=0072ed32-b9ad-4205-a3e0-111a4b57eb45 fwd="86.7.194.99" dyno= connect= service= status=503 bytes= protocol=https
2020-02-18T14:05:11.000000+00:00 app[api]: Build started by user myemail@gmail.com
2020-02-18T14:05:49.857750+00:00 heroku[web.1]: State changed from crashed to starting
2020-02-18T14:05:49.660236+00:00 app[api]: Deploy 6b00eac2 by user myemail@gmail.com
2020-02-18T14:05:49.660236+00:00 app[api]: Release v4 created by user myemail@gmail.com
2020-02-18T14:05:53.023230+00:00 heroku[web.1]: Starting process with command `npm start`
2020-02-18T14:05:55.615774+00:00 heroku[web.1]: State changed from starting to crashed
2020-02-18T14:05:55.540224+00:00 app[web.1]: npm ERR! missing script: start
2020-02-18T14:05:55.549366+00:00 app[web.1]:
2020-02-18T14:05:55.549975+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-02-18T14:05:55.550306+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-02-18T14_05_55_541Z-debug.log
2020-02-18T14:05:55.602183+00:00 heroku[web.1]: Process exited with status 1
2020-02-18T14:05:54.000000+00:00 app[api]: Build succeeded
2020-02-18T14:06:01.546305+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=event-finder-au.herokuapp.com request_id=3bc8dfc5-a6f2-436f-bcf2-9fbb2dc54e5c fwd="86.7.194.99" dyno= connect= service= status=503 bytes= protocol=https
2020-02-18T14:06:01.850676+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=event-finder-au.herokuapp.com request_id=6736e715-66e8-4cc7-9425-6a1f45307230 fwd="86.7.194.99" dyno= connect= service= status=503 bytes= protocol=https

I'm a complete novice when it comes to this kind of thing so I have literally no idea what any of this means.

My package.json looks like this if it helps -

{
  "name": "basic-react-webpack-setup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "webpack-dev-server --mode=development"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.2.3",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.5",
    "css-loader": "^2.1.0",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.1",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^3.9.0"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "bulma": "^0.8.0",
    "child_process": "^1.0.2",
    "cluster": "^0.7.7",
    "file": "^0.2.2",
    "lib": "^4.0.5",
    "loader": "^2.1.1",
    "moment": "^2.24.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-map-gl": "^5.1.3",
    "react-router-dom": "^5.1.2",
    "url": "^0.11.0"
  }
}

Body:
The important part of that output is this:

npm ERR! missing script: start

Heroku needs to know how to run your application. You can provide a Procfile with the relevant command, e.g.

web: node server.js

or you can add a start script to your package.json, since Heroku runs that by default in the absence of a Procfile for JavaScript projects:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "serve": "webpack-dev-server --mode=development",
  "start" "node server.js"
},

Obviously, you'll have to adjust the command depending on how your application works.


问:
SIM800 HTTPS 606 Error
I have been using SSL to connect a SIMCOM SIM800 GSM Module to a Microsoft Azure function endpoint.  This has been working for months and has now stopped working and reports a 606 error code which indicates an "SSL alert message with a level of fatal result and the immediate termination of the connection" according to  SIM800 Series_SSL_Application Note_V1.02

I tried HTTPS connections to various other sites using the SIM800 e.g. google and httpbin and got mixed results: I could connect to some e.g. google but not others e.g. httpbin.  See here for a similar result.

Does anyone know if sites have recently changed SSL cipher or protocol requirements? The SIM800 module (only) supports  SSL2.0, SSL3.0 and TLS1.0.

答: I kept getting a 606 error while trying to 'GET' my AWS API and I could not figure this out. Reconfigured the custom domain mapping to use TLS1.0 instead of TLS1.2 and communication is now flowing through.</p>

Title: SIM800 HTTPS 606 Error


问:
How do I reset the numbers after calculating the Total
How will I clear the total after the first calculation?
I want it to reset if I add a new item after the first calculation. Right now it's adding it to the previous one.
For example, for the first calculation (item1 + item2) = total
if I add another item, it becomes (item1 + item 2) + (item1 + item2 + item3) = total

What I want is for it to reset and calculate the new total with the new item added.

 var count = 0;
    var tax = 0.05;
    var taxFeild = document.getElementById("Tax");
    var checkBoxes = document.getElementById("checkBoxes");
    var checks=document.querySelectorAll('.items');
    var ItemTotal=document.getElementById('ItemTotal');
    var Total=document.getElementById('TotalWithTax');
    var btn = document.getElementById("btn");

function Calculate()
      {

       for(var i =0 ;i< checks.length;i++)
         {
           if(checks[i].checked)
             {
               count+=parseFloat(checks[i].value);
             }
         }
        ItemTotal.textContent += count;
        taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
        Total.textContent += ((tax*count) + count).toFixed(2);
      }

        btn.addEventListener('click',Calculate);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">

</head>
<body>

<h2 class="first-heading">Assignment 1</h2>
<div class="row">
  <div class="column">
      <div id="checkBoxes">
            <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
            <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
            <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
            <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
            <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
            <button id="btn">Calculate</button>
        </div>
  </div>
  <div class="column" >

        <div id="Sums">
                <p id="ItemTotal"> Item Total: </p>
                <p id="Tax"> Tax: </p>
                <p id="TotalWithTax">Total with Tax: </p>
        </div>
  </div>
</div>
<script src="java.js"></script>

</body>
</html></code>```

答:
You should:

Declare the count variable inside the Calculate function, so that it starts from 0 every time the button is clicked

Instead of +=ing to the ItemTotal, TotalWithTax, etc fields, create an inner element that you assign to the text to instead. So, for example, instead of

```<code><p id="ItemTotal"> Item Total: </p>
</code>```

use:

```<code><p> Item Total: <span id="ItemTotal"></span></p>
</code>```

This way, whenever the button is clicked, you can simply assign to the ItemTotal, overwriting whatever was there previously.

var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks = document.querySelectorAll('.items');
var ItemTotal = document.getElementById('ItemTotal');
var Total = document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

function Calculate() {
  let count = 0;
  for (var i = 0; i < checks.length; i++) {
    if (checks[i].checked) {
      count += parseFloat(checks[i].value);
    }
  }
  ItemTotal.textContent = count;
  taxFeild.textContent = (parseFloat(tax * count).toFixed(2));
  Total.textContent = ((tax * count) + count).toFixed(2);
}

btn.addEventListener('click', Calculate);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 class="first-heading">Assignment 1</h2>
<div class="row">
  <div class="column">
    <div id="checkBoxes">
      <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
      <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
      <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
      <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
      <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
      <button id="btn">Calculate</button>
    </div>
  </div>
  <div class="column">

    <div id="Sums">
      <p> Item Total: <span id="ItemTotal"></span></p>
      <p> Tax: <span id="Tax"></span></p>
      <p>Total with Tax: <span id="TotalWithTax"></span></p>
    </div>
  </div>
</div></code>```

You might also consider surrounding the inputs with s, to make them more clickable:

var taxRate = 0.05;

var checks = document.querySelectorAll('.items');
var subtotalSpan = document.getElementById('ItemTotal');
var taxSpan = document.getElementById("Tax");
var totalSpan = document.getElementById('TotalWithTax');

function Calculate() {
  let subtotal = 0;
  for (var i = 0; i < checks.length; i++) {
    if (checks[i].checked) {
      subtotal += parseFloat(checks[i].value);
    }
  }
  const tax = taxRate * subtotal;
  const total = tax + subtotal;

  subtotalSpan.textContent = subtotal;
  taxSpan.textContent = tax.toFixed(2);
  totalSpan.textContent = total.toFixed(2);
}

var btn = document.getElementById("btn");
btn.addEventListener('click', Calculate);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#checkBoxes > label {
  cursor: pointer;
}</code>```

Assignment 1

      <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)

      <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)

      <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)

      <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)

      <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)

      <button id="btn">Calculate</button>

 Item Total:

 Tax:

Total with Tax:

```

Body:
How will I clear the total after the first calculation?
I want it to reset if I add a new item after the first calculation. Right now it's adding it to the previous one.
For example, for the first calculation (item1 + item2) = total
if I add another item, it becomes (item1 + item 2) + (item1 + item2 + item3) = total

What I want is for it to reset and calculate the new total with the new item added.

 var count = 0;
    var tax = 0.05;
    var taxFeild = document.getElementById("Tax");
    var checkBoxes = document.getElementById("checkBoxes");
    var checks=document.querySelectorAll('.items');
    var ItemTotal=document.getElementById('ItemTotal');
    var Total=document.getElementById('TotalWithTax');
    var btn = document.getElementById("btn");

function Calculate()
      {

       for(var i =0 ;i< checks.length;i++)
         {
           if(checks[i].checked)
             {
               count+=parseFloat(checks[i].value);
             }
         }
        ItemTotal.textContent += count;
        taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
        Total.textContent += ((tax*count) + count).toFixed(2);
      }

        btn.addEventListener('click',Calculate);

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">

Assignment 1

            <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)

            <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)

            <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)

            <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)

            <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)

            <button id="btn">Calculate</button>

 Item Total:

 Tax:

Total with Tax:

Body:
You should:

Declare the count variable inside the Calculate function, so that it starts from 0 every time the button is clicked

Instead of +=ing to the ItemTotal, TotalWithTax, etc fields, create an inner element that you assign to the text to instead. So, for example, instead of

<p id="ItemTotal"> Item Total: </p>

use:

<p> Item Total: <span id="ItemTotal"></span></p>

This way, whenever the button is clicked, you can simply assign to the ItemTotal, overwriting whatever was there previously.

var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks = document.querySelectorAll('.items');
var ItemTotal = document.getElementById('ItemTotal');
var Total = document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

function Calculate() {
  let count = 0;
  for (var i = 0; i < checks.length; i++) {
    if (checks[i].checked) {
      count += parseFloat(checks[i].value);
    }
  }
  ItemTotal.textContent = count;
  taxFeild.textContent = (parseFloat(tax * count).toFixed(2));
  Total.textContent = ((tax * count) + count).toFixed(2);
}

btn.addEventListener('click', Calculate);

<h2 class="first-heading">Assignment 1</h2>
<div class="row">
  <div class="column">
    <div id="checkBoxes">
      <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
      <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
      <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
      <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
      <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
      <button id="btn">Calculate</button>
    </div>
  </div>
  <div class="column">

    <div id="Sums">
      <p> Item Total: <span id="ItemTotal"></span></p>
      <p> Tax: <span id="Tax"></span></p>
      <p>Total with Tax: <span id="TotalWithTax"></span></p>
    </div>
  </div>
</div>

You might also consider surrounding the inputs with <label>s, to make them more clickable:

var taxRate = 0.05;

var checks = document.querySelectorAll('.items');
var subtotalSpan = document.getElementById('ItemTotal');
var taxSpan = document.getElementById("Tax");
var totalSpan = document.getElementById('TotalWithTax');

function Calculate() {
  let subtotal = 0;
  for (var i = 0; i < checks.length; i++) {
    if (checks[i].checked) {
      subtotal += parseFloat(checks[i].value);
    }
  }
  const tax = taxRate * subtotal;
  const total = tax + subtotal;

  subtotalSpan.textContent = subtotal;
  taxSpan.textContent = tax.toFixed(2);
  totalSpan.textContent = total.toFixed(2);
}

var btn = document.getElementById("btn");
btn.addEventListener('click', Calculate);

#checkBoxes > label {
  cursor: pointer;
}

<h2 class="first-heading">Assignment 1</h2>
<div class="row">
  <div class="column">
    <div id="checkBoxes">
      <label><input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)</label><br>
      <label><input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)</label><br>
      <label><input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)</label><br>
      <label><input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)</label><br>
      <label><input type="checkbox" class="items" value='5.99'> Side salad ($5.99)</label><br>
      <button id="btn">Calculate</button>
    </div>
  </div>
  <div class="column">
    <div id="Sums">
      <p> Item Total: <span id="ItemTotal"></span></p>
      <p> Tax: <span id="Tax"></span></p>
      <p>Total with Tax: <span id="TotalWithTax"></span></p>
    </div>
  </div>
</div>


问:
Python SMTP import
Has anyone had this before?  It's working with all the other scripts I've written.

```<code>import smtplib
</code>```

File "/usr/lib64/python2.4/smtplib.py", line 49, in ?
    from email.base64MIME import encode as encode_base64
ImportError: No module named base64MIME

And it's not called email.py!

答:
Do python -v then import smtplib at the python command-line.

That should show you where it is getting email from.

EDIT:

Please could you post your output from the import email line.

Mine is:

```<code>import email # directory /usr/lib/python2.4/email
# /usr/lib/python2.4/email/__init__.pyc matches /usr/lib/python2.4/email/__init__.py
import email # precompiled from /usr/lib/python2.4/email/__init__.pyc
# /usr/lib/python2.4/email/base64MIME.pyc matches /usr/lib/python2.4/email/base64MIME.py
import email.base64MIME # precompiled from /usr/lib/python2.4/email/base64MIME.pyc
# /usr/lib/python2.4/email/Utils.pyc matches /usr/lib/python2.4/email/Utils.py
import email.Utils # precompiled from /usr/lib/python2.4/email/Utils.pyc
</code>```

Title: Python SMTP import

Body:
Has anyone had this before?  It's working with all the other scripts I've written.

import smtplib

File "/usr/lib64/python2.4/smtplib.py", line 49, in ?
    from email.base64MIME import encode as encode_base64
ImportError: No module named base64MIME

And it's not called email.py!

Body:
Do python -v then import smtplib at the python command-line.

That should show you where it is getting email from.

EDIT:

Please could you post your output from the import email line.

Mine is:

import email # directory /usr/lib/python2.4/email
# /usr/lib/python2.4/email/__init__.pyc matches /usr/lib/python2.4/email/__init__.py
import email # precompiled from /usr/lib/python2.4/email/__init__.pyc
# /usr/lib/python2.4/email/base64MIME.pyc matches /usr/lib/python2.4/email/base64MIME.py
import email.base64MIME # precompiled from /usr/lib/python2.4/email/base64MIME.pyc
# /usr/lib/python2.4/email/Utils.pyc matches /usr/lib/python2.4/email/Utils.py
import email.Utils # precompiled from /usr/lib/python2.4/email/Utils.pyc


问:
What is Python first argument? sys.argv[0] or sys.argv[1]
According to https://www.tutorialspoint.com/python/python_command_line_arguments.htm

first argument is always script name and it is also being counted in number of arguments.

which is sys.argv[0]

However, when I read other tutorial such as

https://www.cyberciti.biz/faq/python-command-line-arguments-argv-example/

it says that first argument is sys.argv[1]

```<code>#!/usr/bin/python
__author__ = 'nixCraft'
import sys total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
# Pharsing args one by one
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[1]))
print ("Second argument: %s" % str(sys.argv[2]))
</code>```

Which one is correct and should be followed?

This is confusing especially to those who just started learning programming and Python.

答: sys.argv[0] is the name of the script.  Technically it is the "first" argument, but is typically of no use to you, unless you don't know the name of the file you're executing.  sys.argv[1], is the name of the first argument after the name of the script, so the first useful argument.

Body:
According to https://www.tutorialspoint.com/python/python_command_line_arguments.htm

first argument is always script name and it is also being counted in number of arguments.

which is sys.argv[0]

However, when I read other tutorial such as

https://www.cyberciti.biz/faq/python-command-line-arguments-argv-example/

it says that first argument is sys.argv[1]

#!/usr/bin/python
__author__ = 'nixCraft'
import sys total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
# Pharsing args one by one
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[1]))
print ("Second argument: %s" % str(sys.argv[2]))

Which one is correct and should be followed?

This is confusing especially to those who just started learning programming and Python.


问:
Exclude a letter in Regex Pattern
I am trying to create a Regex pattern for <String>-<String>. This is my current pattern:

(\w+\-\w+).

The first String is not allowed to be "W". However, it can still contain "W"s if it's more than one letter long.

For example:
W-80 -> invalid
W42-80 -> valid

How can this be achieved?

答:
Just restrict the last char to "any word char except 'W'".

There are a couple of ways to do this:

Negative look-behind (easy to read):

```<code>^\w+(?<!W)-\w+$
</code>```

See live demo.

Negated intersection (trainwreck to read):

```<code>^\w*[\w&&[^W]]-\w+$
</code>```

See live demo.

——

The question has shifted. Here’s a new take:

```<code>^.+(?<!^W)-\w+
</code>```

This allows anything as the first term except just "W".

Title: Exclude a letter in Regex Pattern

Body:
Just restrict the last char to "any word char except 'W'".

There are a couple of ways to do this:

Negative look-behind (easy to read):

^\w+(?<!W)-\w+$

See live demo.

Negated intersection (trainwreck to read):

^\w*[\w&&[^W]]-\w+$

See live demo.

——

The question has shifted. Here’s a new take:

^.+(?<!^W)-\w+

This allows anything as the first term except just "W".


问:
Substring in Calc script Essbase
I am trying to get the First 3 characters from Accounts dimension in Essbase (BSO cube). When i try to execute the below query. I am getting an error "Invalid Object type"</p>

```<code>FIX(
@substring(@NAME("Account"),0,3),
"Jan"
)
ENDFIX
</code>```

答:
What are you trying to obtain?
In the FIX section you should only write the cross-members for the calc

like

```<code>FIX("Jan", "FY20", "Actual")
/*In this section you can include the code*/
@CONCATENATE("Item_",@substring(@NAME("Account"),0,3))
ENDFIX
</code>```

Title: Substring in Calc script Essbase

Body:
I am trying to get the First 3 characters from Accounts dimension in Essbase (BSO cube). When i try to execute the below query. I am getting an error "Invalid Object type"

FIX(
@substring(@NAME("Account"),0,3),
"Jan"
)
ENDFIX

Body:
What are you trying to obtain?
In the FIX section you should only write the cross-members for the calc

like

FIX("Jan", "FY20", "Actual")
/*In this section you can include the code*/
@CONCATENATE("Item_",@substring(@NAME("Account"),0,3))
ENDFIX


问:
How to get rid of degree symbols on the axis text in ggplot?
I have a map that I've created using ggplot. The text on the x and y axis are longitude, and latitude values. When I add my values from my dataframe to the map they have degree symbols next to them but I want to get rid of the degree symbols. I only want the degree symbol in my axis title. My map looks like this.

Below, is the code I used to import the map, and plot my data with. I've specified where these degree symbols are coming from

```<code>canada = map_data("worldHires", "Canada")

ggplot(data = canada) +
  geom_polygon(data = canada, aes(x=long, y = lat, group = group), fill = "grey") +
  coord_sf(xlim=c(-64.5,-62.8), ylim=c(42.7,45), expand = FALSE) +
  labs(x=expression(paste("Longitude ",degree,"W",sep="")),
       y=expression(paste("Latitude ",degree,"N",sep=""))) +

  #Here is where the degree symbols are added
  geom_point(data = mapindividual_dets,
             mapping = aes(x = longitude,
                           y = latitude),
             size = 10)
</code>```

Here is a sample of the dataframe I have that is giving me the issues. I can't put it all on here because it is too large.

```<code>mapindividual_dets = structure(list(location = c("ARB-04", "BIRCHY HEAD", "Boca1",
                                                 "BON-AR-S2", "BON-AR-S2", "BON-W-S5"), month = structure(c(12L,
                                                                                10L, 10L, 8L, 11L, 2L), .Label = c("Jan", "Feb", "Mar", "Apr",
                                                                                "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered",
                                                                                "factor")), year = c(2018, 2018, 2018, 2018, 2018, 2018), animal_id = c("NSTR-007",
                                                                                "NSTR-007", "NSTR-021", "NSTR-007", "NSTR-007", "NSTR-007"),
                                    detection_count = c(3L, 256L, 2L, 4L, 2L, 2L), num_unique_tags = c(1L,
                                                                                1L, 1L, 1L, 1L, 1L), total_res_time_in_seconds = c(0, 1182040,
                                                                                0, 2732221, 0, 0), latitude = c(24.94808, 44.5713, 26.32559,
                                                                                -49.27732, -49.27732, -49.27985), longitude = c(-80.45412,
                                                                                -64.03512, -80.07108, 69.48038, 69.48038, 69.47853)), class = c("grouped_df",
                                                                                "tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), groups = structure(list(
                                                                                location = c("ARB-04", "BIRCHY HEAD", "Boca1", "BON-AR-S2",
                                                                                "BON-AR-S2", "BON-W-S5"), month = structure(c(12L, 10L, 10L,
                                                                                8L, 11L, 2L), .Label = c("Jan", "Feb", "Mar", "Apr", "May",
                                                                                "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered",
                                                                                "factor")), year = c(2018, 2018, 2018, 2018, 2018, 2018),
                                                                                .rows = list(1L, 2L, 3L, 4L, 5L, 6L)), row.names = c(NA,
                                                                                -6L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE))

</code>```

Does anyone know how to get rid of the degree symbols on the axis text?

答:
Supply your own labels. You can use a function. I recommend I, if you want to keep the sign (as e.g. degrees West are coded as negative) or abs if you don't want the sign.

```<code>nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
ggplot(nc) +
    geom_sf(aes(fill = AREA)) +
    scale_x_continuous(label = abs) +
    scale_y_continuous(label = abs)
</code>```

Body:
I have a map that I've created using ggplot. The text on the x and y axis are longitude, and latitude values. When I add my values from my dataframe to the map they have degree symbols next to them but I want to get rid of the degree symbols. I only want the degree symbol in my axis title. My map looks like this.

Below, is the code I used to import the map, and plot my data with. I've specified where these degree symbols are coming from

canada = map_data("worldHires", "Canada")

ggplot(data = canada) +
  geom_polygon(data = canada, aes(x=long, y = lat, group = group), fill = "grey") +
  coord_sf(xlim=c(-64.5,-62.8), ylim=c(42.7,45), expand = FALSE) +
  labs(x=expression(paste("Longitude ",degree,"W",sep="")),
       y=expression(paste("Latitude ",degree,"N",sep=""))) +

  #Here is where the degree symbols are added
  geom_point(data = mapindividual_dets,
             mapping = aes(x = longitude,
                           y = latitude),
             size = 10)

Here is a sample of the dataframe I have that is giving me the issues. I can't put it all on here because it is too large.

mapindividual_dets = structure(list(location = c("ARB-04", "BIRCHY HEAD", "Boca1",
                                                 "BON-AR-S2", "BON-AR-S2", "BON-W-S5"), month = structure(c(12L,
                                                                                10L, 10L, 8L, 11L, 2L), .Label = c("Jan", "Feb", "Mar", "Apr",
                                                                                "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered",
                                                                                "factor")), year = c(2018, 2018, 2018, 2018, 2018, 2018), animal_id = c("NSTR-007",
                                                                                "NSTR-007", "NSTR-021", "NSTR-007", "NSTR-007", "NSTR-007"),
                                    detection_count = c(3L, 256L, 2L, 4L, 2L, 2L), num_unique_tags = c(1L,
                                                                                1L, 1L, 1L, 1L, 1L), total_res_time_in_seconds = c(0, 1182040,
                                                                                0, 2732221, 0, 0), latitude = c(24.94808, 44.5713, 26.32559,
                                                                                -49.27732, -49.27732, -49.27985), longitude = c(-80.45412,
                                                                                -64.03512, -80.07108, 69.48038, 69.48038, 69.47853)), class = c("grouped_df",
                                                                                "tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), groups = structure(list(
                                                                                location = c("ARB-04", "BIRCHY HEAD", "Boca1", "BON-AR-S2",
                                                                                "BON-AR-S2", "BON-W-S5"), month = structure(c(12L, 10L, 10L,
                                                                                8L, 11L, 2L), .Label = c("Jan", "Feb", "Mar", "Apr", "May",
                                                                                "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered",
                                                                                "factor")), year = c(2018, 2018, 2018, 2018, 2018, 2018),
                                                                                .rows = list(1L, 2L, 3L, 4L, 5L, 6L)), row.names = c(NA,
                                                                                -6L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE))

Does anyone know how to get rid of the degree symbols on the axis text?

Body:
Supply your own labels. You can use a function. I recommend I, if you want to keep the sign (as e.g. degrees West are coded as negative) or abs if you don't want the sign.

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
ggplot(nc) +
    geom_sf(aes(fill = AREA)) +
    scale_x_continuous(label = abs) +
    scale_y_continuous(label = abs)


问:
How to count achievements by genre from an array of game objects?
Sorry if something similar has been asked before, but I couldn't think of a way to phrase my question to find a result!

If I have an array of game objects...

```<code>const games = [{title: 'Halo 3', genre: 'FPS', achievements: 7}, {title: 'Fallout 3', genre: 'RPG', achievements: 6}, {title: 'Far Cry 3', genre: 'FPS', achievements: 12}]
</code>```

How do I get the following result, which adds together achievements by genre?

```<code>{ FPS: 19, RPG: 6}
</code>```

Here's what I have so far, which isn't quite right:

```<code>const achievementsByGenreTally = (games, dataKey = 'genre') => {
return games
  .reduce((acc, game) => {
    if (game[dataKey]) {
      acc[game[dataKey]] = game.achievements }
    return acc
    }, {})
</code>```

};

Any help would be greatly appreciated! Thank you :)

答:
Your solution is almost right, but you need to sum all achievements values instead of just assigning them to objects' properties (Also, you need to handle case when the property is missing, because if you try to sum any number with undefined you will get NaN).

```<code>const achievementsByGenreTally = (games, dataKey = 'genre') => {
    return games
        .reduce((acc, game) => {
            if (game[dataKey]) {
                acc[game[dataKey]] = (acc[game[dataKey]] || 0) + game.achievements
            }
            return acc
        }, {})
};
</code>```

Body:
Sorry if something similar has been asked before, but I couldn't think of a way to phrase my question to find a result!

If I have an array of game objects...

const games = [{title: 'Halo 3', genre: 'FPS', achievements: 7}, {title: 'Fallout 3', genre: 'RPG', achievements: 6}, {title: 'Far Cry 3', genre: 'FPS', achievements: 12}]

How do I get the following result, which adds together achievements by genre?

{ FPS: 19, RPG: 6}

Here's what I have so far, which isn't quite right:

const achievementsByGenreTally = (games, dataKey = 'genre') => {
return games
  .reduce((acc, game) => {
    if (game[dataKey]) {
      acc[game[dataKey]] = game.achievements }
    return acc
    }, {})

};

Any help would be greatly appreciated! Thank you :)

Body:
Your solution is almost right, but you need to sum all achievements values instead of just assigning them to objects' properties (Also, you need to handle case when the property is missing, because if you try to sum any number with undefined you will get NaN).

const achievementsByGenreTally = (games, dataKey = 'genre') => {
    return games
        .reduce((acc, game) => {
            if (game[dataKey]) {
                acc[game[dataKey]] = (acc[game[dataKey]] || 0) + game.achievements
            }
            return acc
        }, {})
};


问:
Command inside package.json - what does file > another file mean?
not sure what the "generate" line does inside package.json (I am referring to "generate": "node ./server/generate.js > ./server/database.json",) of an angular project or where to find out more about this, any references or tips please? I am ready to delete the question if you guys think it's lacking in details.

```<code> "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",r
        "lint": "ng lint",
        "e2e": "ng e2e",
        "generate": "node ./server/generate.js > ./server/database.json",
        "server": "json-server --watch ./server/database.json"
      },
</code>```

So basically generate.js builds an object named database, initialised as: var database = { products: []}; (this is just before adding fake data to the "products" subtype); whereas, database.json just contains this:

```<code>{
    "products": []
}
</code>```

What does this node ./ (a path) / file >  (path to json) do? What do you need > for?

What if I add the code to populate database with fake data inside of a .ts class instead of a js file?

And can I directly type a command like this "node ./server/generate.js > ./server/database.json" from the terminal instead of "npm run generate"?

答:
Let's dissect the script inside the quotes:

node ./server/generate.js > ./server/database.json

node

The command to run (javascript interpreter).

./server/generate.js

The script to give the interpreter as parameter, i.e. the program to be executed.

>

Redirect the standard output from the command to a file.

./server/database.json

The file to write the output to.

If you want to do the same with typescript, replace node with ts-node and generate.js with your script file. Basically you can run any command inside the quotes, that's the whole idea of the scripts section.

Body:
not sure what the "generate" line does inside package.json (I am referring to "generate": "node ./server/generate.js > ./server/database.json",) of an angular project or where to find out more about this, any references or tips please? I am ready to delete the question if you guys think it's lacking in details.

 "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",r
        "lint": "ng lint",
        "e2e": "ng e2e",
        "generate": "node ./server/generate.js > ./server/database.json",
        "server": "json-server --watch ./server/database.json"
      },

So basically generate.js builds an object named database, initialised as: var database = { products: []}; (this is just before adding fake data to the "products" subtype); whereas, database.json just contains this:

{
    "products": []
}

What does this node ./ (a path) / file >  (path to json) do? What do you need > for?

What if I add the code to populate database with fake data inside of a .ts class instead of a js file?

And can I directly type a command like this "node ./server/generate.js > ./server/database.json" from the terminal instead of "npm run generate"?


问:
Can't resolve all parameters for Class: (?) although it has been provided
I'm currently writing some test cases for services which are using ngxs for state management. I can't seem to figure out what's wrong with the code below:

```<code>// auth.service.ts
@Injectable({
    providedIn: 'root'
})
export class AuthService {
    @Select(SessionState) session$;
    constructor(private http: HttpClient, private store: Store) {
    }
}

// session.state.ts
export interface SessionStateModel {
    user: User | null;
    token: string | null;
    state: 'authenticated' | 'guest' | 'invalid.credentials' | 'error' | 'pending';
    response?: HttpErrorResponse | string | any;
}

export const defaultSessionState: SessionStateModel = {
    user: null,
    token: null,
    state: 'guest',
    response: null
};

@State<SessionStateModel>({
    name: 'session',
    defaults: defaultSessionState
})
export class SessionState {
    constructor(private auth: AuthService) {
    }
}

// session.state.spec.ts
describe('should handle login, logout and errors properly', () => {
    let store: Store;
    let backend: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                NgxsModule.forRoot([SessionState])
            ],
            providers: [
                AuthService
            ]
        });

        backend = TestBed.get(HttpTestingController);
        store = TestBed.get(Store);
    });

    afterEach(() => {
        // After every test, assert that there are no more pending requests.
        backend.verify();
    });

    it('should handle successful login', () => {
        // oversimplified...
        expect(true).toBe(true);
    });
});
</code>```

When I run this with ng test, karma returns the following exception:
Error: Can't resolve all parameters for SessionState: (?).

This doesn't make any sense to me because I'm already providing what's necessary for the SessionState (which is the AuthService) in the TestBed.configureTestingModule. I can't seem to figure out what am I missing here?

答:
At the time of this answer, ngxs does not work with Ivy if a state class has injected dependencies (but see edit below). You can turn off Ivy by setting the following compiler option in tsconfig.json:

```<code>{
  "angularCompilerOptions": {
    "enableIvy": false
  }
}
</code>```

Edit: Ngxs provides a migration guide for Ivy. Following this guide, you need to add the @Injectable decorator in addition to your @State decorator:

```<code>@State<SessionStateModel>({
    name: 'session',
    defaults: defaultSessionState
})
@Injectable()
export class SessionState {
    constructor(private auth: AuthService) {
    }
}
</code>```

Body:
I'm currently writing some test cases for services which are using ngxs for state management. I can't seem to figure out what's wrong with the code below:

// auth.service.ts
@Injectable({
    providedIn: 'root'
})
export class AuthService {
    @Select(SessionState) session$;
    constructor(private http: HttpClient, private store: Store) {
    }
}

// session.state.ts
export interface SessionStateModel {
    user: User | null;
    token: string | null;
    state: 'authenticated' | 'guest' | 'invalid.credentials' | 'error' | 'pending';
    response?: HttpErrorResponse | string | any;
}

export const defaultSessionState: SessionStateModel = {
    user: null,
    token: null,
    state: 'guest',
    response: null
};

@State<SessionStateModel>({
    name: 'session',
    defaults: defaultSessionState
})
export class SessionState {
    constructor(private auth: AuthService) {
    }
}

// session.state.spec.ts
describe('should handle login, logout and errors properly', () => {
    let store: Store;
    let backend: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                NgxsModule.forRoot([SessionState])
            ],
            providers: [
                AuthService
            ]
        });

        backend = TestBed.get(HttpTestingController);
        store = TestBed.get(Store);
    });

    afterEach(() => {
        // After every test, assert that there are no more pending requests.
        backend.verify();
    });

    it('should handle successful login', () => {
        // oversimplified...
        expect(true).toBe(true);
    });
});

When I run this with ng test, karma returns the following exception:
Error: Can't resolve all parameters for SessionState: (?).

This doesn't make any sense to me because I'm already providing what's necessary for the SessionState (which is the AuthService) in the TestBed.configureTestingModule. I can't seem to figure out what am I missing here?

Body:
At the time of this answer, ngxs does not work with Ivy if a state class has injected dependencies (but see edit below). You can turn off Ivy by setting the following compiler option in tsconfig.json:

{
  "angularCompilerOptions": {
    "enableIvy": false
  }
}

Edit: Ngxs provides a migration guide for Ivy. Following this guide, you need to add the @Injectable decorator in addition to your @State decorator:

@State<SessionStateModel>({
    name: 'session',
    defaults: defaultSessionState
})
@Injectable()
export class SessionState {
    constructor(private auth: AuthService) {
    }
}


问:
Retain all columns in original data table when applying a function that returns a data table with multiple columns
Say I have a data table.

# Load package
library(data.table)

# Dummy data table
dt <- data.table(foo = letters[1:10],
                 bar = LETTERS[11:20],
                 val = 100:109)
```

<p>I'd like to run a function on a column of this data table that returns a data table with multiple columns. Let's say it looks like this:</p>

<pre class="lang-r prettyprint-override"><code># Function that returns data table
f <- function(x){
  data.table(stuff = paste0(x, "_stuff"),
             things = paste0("things_", x))
}
</code>```

If I run it on foo from the data table, it returns this:

# Returns only columns from function
dt[, f(foo)]
#>       stuff   things
#>  1: a_stuff things_a
#>  2: b_stuff things_b
#>  3: c_stuff things_c
#>  4: d_stuff things_d
#>  5: e_stuff things_e
#>  6: f_stuff things_f
#>  7: g_stuff things_g
#>  8: h_stuff things_h
#>  9: i_stuff things_i
#> 10: j_stuff things_j
```

<p>Great! Now, I'd like the returned data table to be appended to my original data table. If I wanted to append it to just a few columns from the original data table, I could just name the columns I want to retain like so:  </p>

<pre class="lang-r prettyprint-override"><code># Returns named column and columns from function
dt[, .(foo, f(foo))]
#>     foo   stuff   things
#>  1:   a a_stuff things_a
#>  2:   b b_stuff things_b
#>  3:   c c_stuff things_c
#>  4:   d d_stuff things_d
#>  5:   e e_stuff things_e
#>  6:   f f_stuff things_f
#>  7:   g g_stuff things_g
#>  8:   h h_stuff things_h
#>  9:   i i_stuff things_i
#> 10:   j j_stuff things_j
</code>```

But, I want to keep all columns without having to name them individually. One way would be to use by:

# Retains all columns
dt[, f(foo), by = names(dt)]
#>     foo bar val   stuff   things
#>  1:   a   K 100 a_stuff things_a
#>  2:   b   L 101 b_stuff things_b
#>  3:   c   M 102 c_stuff things_c
#>  4:   d   N 103 d_stuff things_d
#>  5:   e   O 104 e_stuff things_e
#>  6:   f   P 105 f_stuff things_f
#>  7:   g   Q 106 g_stuff things_g
#>  8:   h   R 107 h_stuff things_h
#>  9:   i   S 108 i_stuff things_i
#> 10:   j   T 109 j_stuff things_j
```

Created on 2020-02-18 by the reprex package (v0.3.0)

This gives me the desired result for this test case, but clearly this only makes sense if rows are unique.

I've tried to use something like dt[, .(names(dt), f(foo))], but this doesn't work as names returns a vector of strings which is then added as a column.

The obvious solution is to use := like so: dt[, c("One", "Two") := f(foo)]. This gives the desired result but I have to name the added columns myself, whereas I'd like to retain the column names returned by the function.

Another solution might be cbind(dt, dt[, foo(f)]), but this seems cludgy.

What is the correct way to achieve this result?

答:
Some suggestions:

1) Modify data.table in the function:

```<code>f2 <- function(dt){
    cols <- c("stuff", "things")
    dt[, (cols) := lapply(paste0("_", cols), function(x) paste0(foo, x))]
}
f2(dt)
</code>```

2) using NSE:

```<code>eval(substitute(dt[, (LHS) := RHS], list(RHS={a <- dt[, f(foo)]}, LHS=names(a))))
</code>```

3) Or assign result to a variable and then update by reference similar to what Gainz mentioned in the comments

```<code>a <- dt[, f(foo)]
dt[, names(a) := a]
</code>```

I prefer option (3).

Body:
Say I have a data table.

# Load package
library(data.table)

# Dummy data table
dt <- data.table(foo = letters[1:10],
                 bar = LETTERS[11:20],
                 val = 100:109)

I'd like to run a function on a column of this data table that returns a data table with multiple columns. Let's say it looks like this:

# Function that returns data table
f <- function(x){
  data.table(stuff = paste0(x, "_stuff"),
             things = paste0("things_", x))
}

If I run it on foo from the data table, it returns this:

# Returns only columns from function
dt[, f(foo)]
#>       stuff   things
#>  1: a_stuff things_a
#>  2: b_stuff things_b
#>  3: c_stuff things_c
#>  4: d_stuff things_d
#>  5: e_stuff things_e
#>  6: f_stuff things_f
#>  7: g_stuff things_g
#>  8: h_stuff things_h
#>  9: i_stuff things_i
#> 10: j_stuff things_j

Great! Now, I'd like the returned data table to be appended to my original data table. If I wanted to append it to just a few columns from the original data table, I could just name the columns I want to retain like so:

# Returns named column and columns from function
dt[, .(foo, f(foo))]
#>     foo   stuff   things
#>  1:   a a_stuff things_a
#>  2:   b b_stuff things_b
#>  3:   c c_stuff things_c
#>  4:   d d_stuff things_d
#>  5:   e e_stuff things_e
#>  6:   f f_stuff things_f
#>  7:   g g_stuff things_g
#>  8:   h h_stuff things_h
#>  9:   i i_stuff things_i
#> 10:   j j_stuff things_j

But, I want to keep all columns without having to name them individually. One way would be to use by:

# Retains all columns
dt[, f(foo), by = names(dt)]
#>     foo bar val   stuff   things
#>  1:   a   K 100 a_stuff things_a
#>  2:   b   L 101 b_stuff things_b
#>  3:   c   M 102 c_stuff things_c
#>  4:   d   N 103 d_stuff things_d
#>  5:   e   O 104 e_stuff things_e
#>  6:   f   P 105 f_stuff things_f
#>  7:   g   Q 106 g_stuff things_g
#>  8:   h   R 107 h_stuff things_h
#>  9:   i   S 108 i_stuff things_i
#> 10:   j   T 109 j_stuff things_j

Created on 2020-02-18 by the reprex package (v0.3.0)

This gives me the desired result for this test case, but clearly this only makes sense if rows are unique.

I've tried to use something like dt[, .(names(dt), f(foo))], but this doesn't work as names returns a vector of strings which is then added as a column.

The obvious solution is to use := like so: dt[, c("One", "Two") := f(foo)]. This gives the desired result but I have to name the added columns myself, whereas I'd like to retain the column names returned by the function.

Another solution might be cbind(dt, dt[, foo(f)]), but this seems cludgy.

What is the correct way to achieve this result?

Body:
Some suggestions:

1) Modify data.table in the function:

f2 <- function(dt){
    cols <- c("stuff", "things")
    dt[, (cols) := lapply(paste0("_", cols), function(x) paste0(foo, x))]
}
f2(dt)

2) using NSE:

eval(substitute(dt[, (LHS) := RHS], list(RHS={a <- dt[, f(foo)]}, LHS=names(a))))

3) Or assign result to a variable and then update by reference similar to what Gainz mentioned in the comments

a <- dt[, f(foo)]
dt[, names(a) := a]

I prefer option (3).


问:
GC.GetTotalMemory(false) and Process.WorkingSet
After running my .net process for a long time, I see there's a big difference between the memory GC is aware of and the process working set.

The values I'm monitoring are GC.GetTotalMemory(false) and Process.WorkingSet.

If I check in the "task manager" (or using a SysInternals tool) the value of WorkingSet (Process) and what's shown in "task manager" don't match, but they're somehow close (let's say, 100mb in task manager, 130 in WorkingSet), but what's shocking for me is that GC.GetTotalMemory(false) is like 40Mb or so.

I've run several times through profilers (my favorite is ants memory profiler from redgate), and there it is easy to check that there's a value called "free memory" which is normally the difference between what GC "sees" and what the OS sees (ok, plus loaded DLLs and so on).

A couple of questions:

Is there a way to programmatically monitor this "GC free memory". Yes, I could use the profiler, but in a long running process is not that easy.

If your process runs for a long time, allocates a lot of memory and then frees it (and allocation means thousands or millions of objects, not as simple as a big allocation and free), the problem is that it will never "shrink" to a low value, despite of the fact that GC values are low and correct. Is there a way to fix this? It could be that something is broken on my process but it has been profiled several times over the years and it doesn't seem to be a leak.

Thanks

答:
Just to resurrect an ancient thread, if you want to monitor "GC free memory", you can periodically make a call to GC.GetTotalMemory(false) and store the value. Dump it to disk or a database or something. Alternatively you can use a library like prometheus-net(https://github.com/prometheus-net/)  which will export this and a whole bunch of metrics for you.

As for your second question, there is a way to force your application to shrink, but it's not dot net native, it's windows only, and it's NOT recommended:

```<code>[DllImport("psapi.dll")]
static extern int EmptyWorkingSet(IntPtr hwProc);

static void MinimizeFootprint()
{
    EmptyWorkingSet(Process.GetCurrentProcess().Handle);
}
</code>```

From what little I know I think the OS will take care of this if the server is under memory pressure, and it's more efficient for your app, and for the server in general, if the memory remains allocated to your process. This is because there's a good chance it will need it again in the future, so there's no point in cleaning it up when it will just have to allocate it again, especially when your server has enough memory.

ContentLicense: CC BY-SA 2.5

Body:
Just to resurrect an ancient thread, if you want to monitor "GC free memory", you can periodically make a call to GC.GetTotalMemory(false) and store the value. Dump it to disk or a database or something. Alternatively you can use a library like prometheus-net(https://github.com/prometheus-net/)  which will export this and a whole bunch of metrics for you.

As for your second question, there is a way to force your application to shrink, but it's not dot net native, it's windows only, and it's NOT recommended:

[DllImport("psapi.dll")]
static extern int EmptyWorkingSet(IntPtr hwProc);

static void MinimizeFootprint()
{
    EmptyWorkingSet(Process.GetCurrentProcess().Handle);
}

From what little I know I think the OS will take care of this if the server is under memory pressure, and it's more efficient for your app, and for the server in general, if the memory remains allocated to your process. This is because there's a good chance it will need it again in the future, so there's no point in cleaning it up when it will just have to allocate it again, especially when your server has enough memory.


问:
Concatenation of 2 values from same column using oracle SQL
I'm trying to concatenate the values of a column.

For EX:

```<code>select case when month=1 then month_name1
when month =12 then month_name2 END
from Calendar
where month in (1,12)
</code>```

results:

```<code>Jan
Dec
</code>```

Target results:

```<code>Jan - Dec
</code>```

tried different ways but couldn't get it. looks very simple but hard luck.
Thanks in advance.

答:
Try this query using listagg

```<code>select listagg(case when month=1 then month_name1
               when month =12 then month_name2 END, ' - ')
         within group (order by month)
from Calendar
where month in (1,12)
</code>```

Body:
I'm trying to concatenate the values of a column.

For EX:

select case when month=1 then month_name1
when month =12 then month_name2 END
from Calendar
where month in (1,12)

results:

Jan
Dec

Target results:

Jan - Dec

tried different ways but couldn't get it. looks very simple but hard luck.
Thanks in advance.

Body:
Try this query using listagg

select listagg(case when month=1 then month_name1
               when month =12 then month_name2 END, ' - ')
         within group (order by month)
from Calendar
where month in (1,12)


问:
How can I match an ImageView height to its parent that is wrap_content? (RecyclerView Item)
I have a RecyclerView item with a LinearLayout. The LinearLayout's height is set to wrap_content. Inside that LinearLayout, I would like to have an ImageView with a triangle shape that matches the height of the LinearLayout to get something like this:

With a fixed height for LinearLayout, I can just set it in XML:

```<code> <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"/>
</code>```

To get the same result with a variable height, I've tried to set the ImageView height and width to 0 and then adjust them programmaticaly inside onBindViewHolder:

```<code>holder.mLinearLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int layoutHeight = holder.mLinearLayout.getMeasuredHeight();

holder.mImageView.getLayoutParams().height = layoutHeight;
holder.mImageView.getLayoutParams().width = layoutHeight;

holder.mImageView.requestLayout();
</code>```

It looks like the resizing of the ImageView works but it doesn't show the image. What am I doing wrong here?

答:
My mistake was that I accidentally removed the image source from my XML. The above code shows an image now but it still does not work properly.

To get the right height, you have to replace the measure arguments:

```<code>holder.mLinearLayout.measure(
                View.MeasureSpec.makeMeasureSpec(Resources.getSystem().getDisplayMetrics().widthPixels, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );
</code>```

I'm not sure if that's the best solution but it works.

Body:
I have a RecyclerView item with a LinearLayout. The LinearLayout's height is set to wrap_content. Inside that LinearLayout, I would like to have an ImageView with a triangle shape that matches the height of the LinearLayout to get something like this:

With a fixed height for LinearLayout, I can just set it in XML:

 <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"/>

To get the same result with a variable height, I've tried to set the ImageView height and width to 0 and then adjust them programmaticaly inside onBindViewHolder:

holder.mLinearLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int layoutHeight = holder.mLinearLayout.getMeasuredHeight();

holder.mImageView.getLayoutParams().height = layoutHeight;
holder.mImageView.getLayoutParams().width = layoutHeight;

holder.mImageView.requestLayout();

It looks like the resizing of the ImageView works but it doesn't show the image. What am I doing wrong here?

Body:
My mistake was that I accidentally removed the image source from my XML. The above code shows an image now but it still does not work properly.

To get the right height, you have to replace the measure arguments:

holder.mLinearLayout.measure(
                View.MeasureSpec.makeMeasureSpec(Resources.getSystem().getDisplayMetrics().widthPixels, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );

I'm not sure if that's the best solution but it works.


问:
appending/prepending to userdata passed to cloudformation?
I have some userdata scripts which are currently used by standalone EC2 instances.
I'd like to be able to use these with cloudformation and include calls to the 'cfn-' helper scripts to signal the cloudformation stack of the progress.
Essentially, I'd like to be able to prepend some data to the userdata script, and append some data to it.
To do so I planned to take the existing script and use sed to remove the leading shebang/script line, and pass that slightly modified script into cloudformation as a parameter.  This script needs to be base64 encoded before being passed as a parameter.  I base64 encode and then split based on a 4096 byte size (the parameter size limit).  My cloudformation template has 4 'userdata' parameter fields that I can pass data into.
This currently works in existing scripts:

```<code>"UserData" : { "Fn::Join" : [ "", [ { "Ref" : "UserData" }, { "Ref" : "UserData2" }, { "Ref" : "UserData3" }, { "Ref" : "UserData4" }]]},
</code>```

Note: I don't have to use the base64 intrinsic function here as the individual parameters are already base64 encoded.

I've been trying this, but I'm getting an error (show further down):

```<code>        "UserData" : {
      "Fn::Join": [
        "", [
          { "Fn::Base64":
            { "Fn::Join": [
              "", [
                "#!/bin/bash\n",
                {"Fn::Join": ["", ["AWS_REGION=",{ "Ref" : "AWS::Region" },"\n"]]},
                {"Fn::Join": ["", ["STACKNAME=",{ "Ref" : "AWS::StackName" },"\n"]]},
                "LAUNCHCONFIG=LaunchConfig\n",
                "# # Signalling cloudformation\n",
                {"Fn::Join": ["", ["/opt/aws/bin/cfn-init -v --stack ",{ "Ref" : "AWS::StackName" }," --resource LaunchConfig --region ",{ "Ref" : "AWS::Region" },"\n"]]},
              ]
            ]}
          },
          { "Ref" : "UserData" },
          { "Ref" : "UserData2" },
          { "Ref" : "UserData3" },
          { "Ref" : "UserData4" },
          { "Fn::Base64":
            { "Fn::Join": [
              "", [
                {"Fn::Join": ["", ["/opt/aws/bin/cfn-signal -e $? --stack ",{ "Ref" : "AWS::StackName" }," --resource AutoScalingGroup --region ",{ "Ref" : "AWS::Region" },"\n"]]},
              ]
            ]}
          }
        ]
      ]
    },
</code>```

The error received is:

UserData does not appear to be base64 encoded (Service: AmazonAutoScaling; Status Code: 400; Error Code: ValidationError

I want to avoid the situation where I need to know the appropriate parameters ahead of time - and thus generating a new userdata script including that detail which could be passed as a parameter - as I would like to avoid generating a custom userdata file specifically to use with cloudformation.

I've passed in empty values for the four 'userdata' parameters, so it appears that the leading and trailing elements in the join are not being base64 encoded.
I appreciate any insight into this, or how I might accomplish what I have described.

答:
If I understand, you are passing in userdata that has already been base64 encoded. I think that is incorrect with your setup. The value of the userdata param should not be pre-encoded. It should be plain text. Cloudformation does the encoding. It needs to be encoded as delivered to the EC2 instance, but not in the configuration. You should be joining plain text.

Else, remove the Fn::Base64 block from your script. That may resolve it. Though that is just a straight up guess.

Body:
I have some userdata scripts which are currently used by standalone EC2 instances.
I'd like to be able to use these with cloudformation and include calls to the 'cfn-' helper scripts to signal the cloudformation stack of the progress.
Essentially, I'd like to be able to prepend some data to the userdata script, and append some data to it.
To do so I planned to take the existing script and use sed to remove the leading shebang/script line, and pass that slightly modified script into cloudformation as a parameter.  This script needs to be base64 encoded before being passed as a parameter.  I base64 encode and then split based on a 4096 byte size (the parameter size limit).  My cloudformation template has 4 'userdata' parameter fields that I can pass data into.
This currently works in existing scripts:

"UserData" : { "Fn::Join" : [ "", [ { "Ref" : "UserData" }, { "Ref" : "UserData2" }, { "Ref" : "UserData3" }, { "Ref" : "UserData4" }]]},

Note: I don't have to use the base64 intrinsic function here as the individual parameters are already base64 encoded.

I've been trying this, but I'm getting an error (show further down):

        "UserData" : {
      "Fn::Join": [
        "", [
          { "Fn::Base64":
            { "Fn::Join": [
              "", [
                "#!/bin/bash\n",
                {"Fn::Join": ["", ["AWS_REGION=",{ "Ref" : "AWS::Region" },"\n"]]},
                {"Fn::Join": ["", ["STACKNAME=",{ "Ref" : "AWS::StackName" },"\n"]]},
                "LAUNCHCONFIG=LaunchConfig\n",
                "# # Signalling cloudformation\n",
                {"Fn::Join": ["", ["/opt/aws/bin/cfn-init -v --stack ",{ "Ref" : "AWS::StackName" }," --resource LaunchConfig --region ",{ "Ref" : "AWS::Region" },"\n"]]},
              ]
            ]}
          },
          { "Ref" : "UserData" },
          { "Ref" : "UserData2" },
          { "Ref" : "UserData3" },
          { "Ref" : "UserData4" },
          { "Fn::Base64":
            { "Fn::Join": [
              "", [
                {"Fn::Join": ["", ["/opt/aws/bin/cfn-signal -e $? --stack ",{ "Ref" : "AWS::StackName" }," --resource AutoScalingGroup --region ",{ "Ref" : "AWS::Region" },"\n"]]},
              ]
            ]}
          }
        ]
      ]
    },

The error received is:

UserData does not appear to be base64 encoded (Service: AmazonAutoScaling; Status Code: 400; Error Code: ValidationError

I want to avoid the situation where I need to know the appropriate parameters ahead of time - and thus generating a new userdata script including that detail which could be passed as a parameter - as I would like to avoid generating a custom userdata file specifically to use with cloudformation.

I've passed in empty values for the four 'userdata' parameters, so it appears that the leading and trailing elements in the join are not being base64 encoded.
I appreciate any insight into this, or how I might accomplish what I have described.