问:
C# Generic Copy Constructor
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

```<code>interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}
</code>```

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

```<code>public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}
</code>```

Calling the method requires the type:

```<code>someFoo.Clone<T> ...
</code>```

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

```<code>IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;
</code>```

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

答:
So you have everything ok but you want to be able to use the syntax

```<code>someFoo.Clone()
</code>```

instead of

```<code>someFoo.Clone<int>()
</code>```

you want the int to be implied rather than having to put it ther explicitly?

The reason you can't do that in your code example is that IFoo doesn't reference the generic type T that you need in order to create Bar<T>.

I would suggest that you really need another interface: IFoo<T>

If you had that, and your extension method looks like this:

```<code>public static Bar<T> Clone<T>(this IFoo<T> foo)
{
    return new Bar<T>(foo);
}
</code>```

Then you will have no problem using

```<code>IFoo<int> someFoo = new Foo<int>();
Bar<int> someBar = someFoo.Clone();
</code>```

Hope that helps

OwnerDisplayName: blu

ContentLicense: CC BY-SA 2.5

Title: C# Generic Copy Constructor

Body:
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}

Calling the method requires the type:

someFoo.Clone<T> ...

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

LastEditorDisplayName: blu

Body:
So you have everything ok but you want to be able to use the syntax

someFoo.Clone()

instead of

someFoo.Clone<int>()

you want the int to be implied rather than having to put it ther explicitly?

The reason you can't do that in your code example is that IFoo doesn't reference the generic type T that you need in order to create Bar<T>.

I would suggest that you really need another interface: IFoo<T>

If you had that, and your extension method looks like this:

public static Bar<T> Clone<T>(this IFoo<T> foo)
{
    return new Bar<T>(foo);
}

Then you will have no problem using

IFoo<int> someFoo = new Foo<int>();
Bar<int> someBar = someFoo.Clone();

Hope that helps

OwnerDisplayName: Jero


来源: stackexchange

问:
Fortran equivalent to a C++ pure virtual method
In C++, I can define a generic interface by

```<code>class super_class {
public:
    virtual void method()=0;
};

class sub_class : public super_class {
public:
    void method() {
        // Do Something
    }
};

main() {
    super_class *a = new sub_class();
    a->method() // This will call the method defined in the sub_class.
}
</code>```

How do I do the same thing in Fortran? I attempted

```<code>MODULE super_class
TYPE, ABSTRACT :: super_class_type
END TYPE
END MODULE

MODULE sub_class
TYPE, EXTENDS(super_class_type) :: sub_class_type
CONTAINS
   PROCEDURE :: method
END TYPE

INTERFACE subclass_type
    MODULE PROCEDURE construct_subclass_type
END INTERFACE

CONTAINS

FUNCTION construct_subclass_type()
CLASS (subclass_type), POINTER :: construct_subclass_type
ALLOCATE(construct_subclass_type)
END FUNCTION

SUBROUTINE method(this)
CLASS (sub_class), INTENT(in) :: this
!  Do Something
END SUBROUTINE

END MODULE

PROGRAM example
CLASS (super_class_type), POINTER :: a

a=>construct_subclass_type()
CALL a%method()

END PROGRAM
</code>```

but I end up with a compiler error.

```<code>CALL a%method(3)
       1
Error: ‘method’ at (1) is not a member of the ‘super_class_type’ structure
</code>```

I'm not sure how to specify that the super_class expects a method to be overridden by the subclass method.

Tried Using Deferred.

I tried specifying the method as deferred in the super_class

```<code>TYPE, ABSTRACT :: super_class_type
CONTAINS
    PROCEDURE, DEFERRED :: method
END TYPE

ABSTRACT INTERFACE
    SUBROUTINE method(this)
        CLASS (super_class_type), INTENT(inout) :: this
    END SUBROUTINE
END INTERFACE
</code>```

but this brings up a new error

```<code>PROCEDURE, DEFERRED :: method
                  1
Error: Interface must be specified for DEFERRED binding at (1)

CLASS (super_class_type), INTENT(inout) :: this
                       1
Error: Derived type ‘super_class_type’ at (1) is being used before it is defined
</code>```

答:
It is very simple to fix your last code

```<code>TYPE, ABSTRACT :: super_class_type
CONTAINS
    PROCEDURE(method_interface), DEFERRED :: method
END TYPE

ABSTRACT INTERFACE
    SUBROUTINE method_interface(this)
        import
        CLASS (super_class_type), INTENT(inout) :: this
    END SUBROUTINE
END INTERFACE

end
</code>```

You should not confuse the name of the binding and name of the interface. I renamed the interface to make it clear. Note the import statement needed to get the locally defined names into the interface.

ContentLicense: CC BY-SA 4.0

Body:
In C++, I can define a generic interface by

class super_class {
public:
    virtual void method()=0;
};

class sub_class : public super_class {
public:
    void method() {
        // Do Something
    }
};

main() {
    super_class *a = new sub_class();
    a->method() // This will call the method defined in the sub_class.
}

How do I do the same thing in Fortran? I attempted

MODULE super_class
TYPE, ABSTRACT :: super_class_type
END TYPE
END MODULE

MODULE sub_class
TYPE, EXTENDS(super_class_type) :: sub_class_type
CONTAINS
   PROCEDURE :: method
END TYPE

INTERFACE subclass_type
    MODULE PROCEDURE construct_subclass_type
END INTERFACE

CONTAINS

FUNCTION construct_subclass_type()
CLASS (subclass_type), POINTER :: construct_subclass_type
ALLOCATE(construct_subclass_type)
END FUNCTION

SUBROUTINE method(this)
CLASS (sub_class), INTENT(in) :: this
!  Do Something
END SUBROUTINE

END MODULE

PROGRAM example
CLASS (super_class_type), POINTER :: a

a=>construct_subclass_type()
CALL a%method()

END PROGRAM

but I end up with a compiler error.

CALL a%method(3)
       1
Error: ‘method’ at (1) is not a member of the ‘super_class_type’ structure

I'm not sure how to specify that the super_class expects a method to be overridden by the subclass method.

Tried Using Deferred.

I tried specifying the method as deferred in the super_class

TYPE, ABSTRACT :: super_class_type
CONTAINS
    PROCEDURE, DEFERRED :: method
END TYPE

ABSTRACT INTERFACE
    SUBROUTINE method(this)
        CLASS (super_class_type), INTENT(inout) :: this
    END SUBROUTINE
END INTERFACE

but this brings up a new error

PROCEDURE, DEFERRED :: method
                  1
Error: Interface must be specified for DEFERRED binding at (1)

CLASS (super_class_type), INTENT(inout) :: this
                       1
Error: Derived type ‘super_class_type’ at (1) is being used before it is defined

Body:
It is very simple to fix your last code

TYPE, ABSTRACT :: super_class_type
CONTAINS
    PROCEDURE(method_interface), DEFERRED :: method
END TYPE

ABSTRACT INTERFACE
    SUBROUTINE method_interface(this)
        import
        CLASS (super_class_type), INTENT(inout) :: this
    END SUBROUTINE
END INTERFACE

end

You should not confuse the name of the binding and name of the interface. I renamed the interface to make it clear. Note the import statement needed to get the locally defined names into the interface.


问:
Determining/accessing the type of a generic parameter?
I need to refactor a function that hydrates values from localStorage:

```<code>export function hydrateFromLocalStorage<T>(key: string): T {
  try {
    return JSON.parse(localStorage.getItem(key))
  }
  catch (error) {
    return null;
  }
}
</code>```

If the type T is anything other than an object, it doesn't need to be passed through the JSON parser.

I have seen many examples of using ReturnType, but not within the function body. Is it possible to determine T within the function?

答:
Why not just perform regular type check?</p>

```<code>export function hydrateFromLocalStorage<T>(key: string): T {
  try {
    const value = localStorage.getItem(key);
    if (typeof value === object) {
      return JSON.parse(value);
    }
    return value;
  }
  catch (error) {
    return null;
  }
}
</code>```

Body:
I need to refactor a function that hydrates values from localStorage:

export function hydrateFromLocalStorage<T>(key: string): T {
  try {
    return JSON.parse(localStorage.getItem(key))
  }
  catch (error) {
    return null;
  }
}

If the type T is anything other than an object, it doesn't need to be passed through the JSON parser.

I have seen many examples of using ReturnType, but not within the function body. Is it possible to determine T within the function?

Body:
Why not just perform regular type check?

export function hydrateFromLocalStorage<T>(key: string): T {
  try {
    const value = localStorage.getItem(key);
    if (typeof value === object) {
      return JSON.parse(value);
    }
    return value;
  }
  catch (error) {
    return null;
  }
}


问:
Kubectl get status of pod as yaml
I can run kubectl get pod nginx -o=jsonpath={'.status'} to get just the status in json for my pod.

How can I do the same filtering but have the result returned in yaml instead of json?

So I would like to get this kind of output by the command:

```<code>status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2019-05-31T14:58:57Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2019-05-31T14:59:02Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2019-05-31T14:58:57Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://5eb07d9c8c4de3b1ba454616ef7b258d9ce5548a46d4d5521a0ec5bc2d36b716
    image: nginx:1.15.12
    imageID: docker-pullable://nginx@sha256:1d0dfe527f801c596818da756e01fa0e7af4649b15edc3eb245e8da92c8381f8
    lastState: {}
    name: nginx
    ready: true
    restartCount: 0
    state:
      running:
        startedAt: "2019-05-31T14:59:01Z"
</code>```

答:
You cannot do that with kubectl, there is no such output option for it.

However, it should be easy to extract that lines with awk.

```<code>kubectl get pods -o yaml | awk '/^status:/{flag=1}flag'
</code>```

This starts the output at the line status:. In this case that is exactly what yo want.

Title: Kubectl get status of pod as yaml

Body:
I can run kubectl get pod nginx -o=jsonpath={'.status'} to get just the status in json for my pod.

How can I do the same filtering but have the result returned in yaml instead of json?

So I would like to get this kind of output by the command:

status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2019-05-31T14:58:57Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2019-05-31T14:59:02Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2019-05-31T14:58:57Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://5eb07d9c8c4de3b1ba454616ef7b258d9ce5548a46d4d5521a0ec5bc2d36b716
    image: nginx:1.15.12
    imageID: docker-pullable://nginx@sha256:1d0dfe527f801c596818da756e01fa0e7af4649b15edc3eb245e8da92c8381f8
    lastState: {}
    name: nginx
    ready: true
    restartCount: 0
    state:
      running:
        startedAt: "2019-05-31T14:59:01Z"

Body:
You cannot do that with kubectl, there is no such output option for it.

However, it should be easy to extract that lines with awk.

kubectl get pods -o yaml | awk '/^status:/{flag=1}flag'

This starts the output at the line status:. In this case that is exactly what yo want.


问:
NodeJS sample app failing to startup, unable to find 'config'?
I'm learning node and am trying to run a sample app I've pulled from git:

https://github.com/madhums/node-express-mongoose-demo

After following all the instructions, when I run

```<code>npm start
</code>```

I get an error that says

```<code>> nodejs-express-mongoose-demo@4.0.0 start /Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo
> NODE_PATH=./config:./app/controllers NODE_ENV=development ./node_modules/.bin/nodemon server.js

20 Dec 16:45:19 - [nodemon] v1.2.1
20 Dec 16:45:19 - [nodemon] to restart at any time, enter `rs`
20 Dec 16:45:19 - [nodemon] watching: *.*
20 Dec 16:45:19 - [nodemon] starting `node --harmony server.js`
WARNING: No configurations found in configuration directory:
WARNING: /Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo/config
WARNING: See https://www.npmjs.org/package/config for more information.

module.js:340
    throw err;
          ^
Error: Cannot find module 'undefined/config/imager.js'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo/app/models/article.js:10:20)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
20 Dec 16:45:20 - [nodemon] app crashed - waiting for file changes before starting...
</code>```

This occcurs after making sure I have mongodb installed and running, making sure I've installed all dependencies including 'config'. In fact in node shell when I run

```<code>require('config')
</code>```

the result is undefined.

Why is this application failing to start?

答:
I had a similar error.

The problem: I created the config folder in a sub folder within the root directory.

The solution: Moved the config folder to the root directory.

Another possible cause of the error could be due to the absence of the configuration files (e.g. config/default.json, config/production.json, etc.) in the config folder.

ContentLicense: CC BY-SA 3.0

Body:
I'm learning node and am trying to run a sample app I've pulled from git:

https://github.com/madhums/node-express-mongoose-demo

After following all the instructions, when I run

npm start

I get an error that says

> nodejs-express-mongoose-demo@4.0.0 start /Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo
> NODE_PATH=./config:./app/controllers NODE_ENV=development ./node_modules/.bin/nodemon server.js

20 Dec 16:45:19 - [nodemon] v1.2.1
20 Dec 16:45:19 - [nodemon] to restart at any time, enter `rs`
20 Dec 16:45:19 - [nodemon] watching: *.*
20 Dec 16:45:19 - [nodemon] starting `node --harmony server.js`
WARNING: No configurations found in configuration directory:
WARNING: /Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo/config
WARNING: See https://www.npmjs.org/package/config for more information.

module.js:340
    throw err;
          ^
Error: Cannot find module 'undefined/config/imager.js'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo/app/models/article.js:10:20)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
20 Dec 16:45:20 - [nodemon] app crashed - waiting for file changes before starting...

This occcurs after making sure I have mongodb installed and running, making sure I've installed all dependencies including 'config'. In fact in node shell when I run

require('config')

the result is undefined.

Why is this application failing to start?


问:
New to objective-c. I don't understand the magic in writing methods without declaration in SenTestCase
I write my first simple unit tests and don't understand the magic objective c compiler. I can write unit test methods without declaring them in the test class .h file.

my test class remains the same empty shell:

```<code>@interface chronos2Tests : SenTestCase {
@private

}
@end
</code>```

In the .m file, I can write unit test methods, which names started with test. I have thought, that I must declare all member functions in the .h file? Is it possible, to write private member functions in objective c without declaring them in the .h file?

答:
The testXXX methods are are called reflectively by SenTest and that is the reason you do not need a header file to define the methods.

Edit:

Headers main purpose in Objective-C are a hint to the compiler of how an object can be accessed while not exposing implementation details. It also serves as a form of documentation and is therefore optional. OCUnit is open source and what seems to be magic happening in your test case is really just the work of the well documented NSInvocation and Class Categories.

Body:
I write my first simple unit tests and don't understand the magic objective c compiler. I can write unit test methods without declaring them in the test class .h file.

my test class remains the same empty shell:

@interface chronos2Tests : SenTestCase {
@private

}
@end

In the .m file, I can write unit test methods, which names started with test. I have thought, that I must declare all member functions in the .h file? Is it possible, to write private member functions in objective c without declaring them in the .h file?


问:
How to create a django ViewFlow process programmatically
Synopsis

I'm developing a web application to learn Django (python 3.4 & Django 1.6.10). The web app has complex and often updated workflows. I decided to integrate the Django-Viewflow library (https://github.com/viewflow/viewflow/) as it seems to be a very convenient way to handle workflows and not incorporate the workflow logic with the application models.

In this case, I have created a workflow to collect authorship information and copyrights using the Django-Viewflow library. The workflow should be initiated each time an author is added to a book.

My Problem

The documentation offers step by step guidelines to integrate an end-to-end worklfow solution (frontend and backend). My problem is that I'm having hard time to control the workflow programmatically (specifically from the Book model).

Description of the application

I have a Book model (core model) with a many to many relationship to Authors.

myApp/models.py

```<code>class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
</code>```

The workflow components are:

myFlow/models.py

```<code>from viewflow.models import Process

class AuthorInvitation(process)
    consent_confirmed = models.BooleanField(default=False)
    signature = models.CharField(max_length=150)
</code>```

myFlow/flows.py

```<code>from viewflow import flow
from viewflow.base import this, Flow
from viewflow.contrib import celery
from viewflow.views import StartProcessView, ProcessView
from . import models, tasks

class AuthorInvitationFlow(Flow):
    process_cls = models.AuthorInvitation

    start = flow.Start(StartProcessView) \
        .Permission(auto_create=True) \
        .Next(this.notify)

    notify = celery.Job(tasks.send_authorship_request) \
        .Next(this.approve)

    approve = flow.View(ProcessView, fields=["confirmed","signature"]) \
        .Permission(auto_create=True) \
        .Next(this.check_approve)

    check_approve = flow.If(cond=lambda p: p.confirmed) \
        .OnTrue(this.send) \
        .OnFalse(this.end)

    send = celery.Job(tasks.send_authorship) \
        .Next(this.end)

    end = flow.End()
</code>```

Question

How can you control the workflow process programmatically (activate, confirm steps, redo steps, cancel the process....)? I have tried to dig into the code of the library. It seems that the class activate contains the right method but not sure how the whole should be orchestrated.

Thanks in advance!

答:
to start manually:

```<code>from viewflow import flow
from viewflow.base import this, Flow
from .models import CIE
from viewflow import frontend
from django.utils.decorators import method_decorator

@frontend.register
class CIE(Flow):
    process_class = CIE
    start = flow.StartFunction(this.create_flow).Next(this.end)
    end = flow.End()

    @method_decorator(flow.flow_start_func)
    def create_flow(self, activation):
        activation.prepare()
        activation.done()
        return activation
</code>```

after that expose rpc:

```<code>from modernrpc.core import rpc_method
from flow.flows import CIE

    @rpc_method
    def start():
        CIE.start.run()
</code>```

Body:
Synopsis

I'm developing a web application to learn Django (python 3.4 & Django 1.6.10). The web app has complex and often updated workflows. I decided to integrate the Django-Viewflow library (https://github.com/viewflow/viewflow/) as it seems to be a very convenient way to handle workflows and not incorporate the workflow logic with the application models.

In this case, I have created a workflow to collect authorship information and copyrights using the Django-Viewflow library. The workflow should be initiated each time an author is added to a book.

My Problem

The documentation offers step by step guidelines to integrate an end-to-end worklfow solution (frontend and backend). My problem is that I'm having hard time to control the workflow programmatically (specifically from the Book model).

Description of the application

I have a Book model (core model) with a many to many relationship to Authors.

myApp/models.py

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

The workflow components are:

myFlow/models.py

from viewflow.models import Process

class AuthorInvitation(process)
    consent_confirmed = models.BooleanField(default=False)
    signature = models.CharField(max_length=150)

myFlow/flows.py

from viewflow import flow
from viewflow.base import this, Flow
from viewflow.contrib import celery
from viewflow.views import StartProcessView, ProcessView
from . import models, tasks

class AuthorInvitationFlow(Flow):
    process_cls = models.AuthorInvitation

    start = flow.Start(StartProcessView) \
        .Permission(auto_create=True) \
        .Next(this.notify)

    notify = celery.Job(tasks.send_authorship_request) \
        .Next(this.approve)

    approve = flow.View(ProcessView, fields=["confirmed","signature"]) \
        .Permission(auto_create=True) \
        .Next(this.check_approve)

    check_approve = flow.If(cond=lambda p: p.confirmed) \
        .OnTrue(this.send) \
        .OnFalse(this.end)

    send = celery.Job(tasks.send_authorship) \
        .Next(this.end)

    end = flow.End()

Question

How can you control the workflow process programmatically (activate, confirm steps, redo steps, cancel the process....)? I have tried to dig into the code of the library. It seems that the class activate contains the right method but not sure how the whole should be orchestrated.

Thanks in advance!

Body:
to start manually:

from viewflow import flow
from viewflow.base import this, Flow
from .models import CIE
from viewflow import frontend
from django.utils.decorators import method_decorator

@frontend.register
class CIE(Flow):
    process_class = CIE
    start = flow.StartFunction(this.create_flow).Next(this.end)
    end = flow.End()

    @method_decorator(flow.flow_start_func)
    def create_flow(self, activation):
        activation.prepare()
        activation.done()
        return activation

after that expose rpc:

from modernrpc.core import rpc_method
from flow.flows import CIE

    @rpc_method
    def start():
        CIE.start.run()


问:
Max function on date giving multiple records
I have got 3 tables: order, customer and invoice. I need to get the latest invoice number for each customer.

I am using the max function on order date  and then grouping by customer number and invoice number, where order status was confirmed or shipped.

```<code>  select max(o.order_date), c.customer_number, i.invoice_number
  from orders o , invoices i , customer c
  where o.order_oid = i.order_oid
  and c.customer_oid = i.customer_oid
  and o.status_oid in (  4,6)
  group by c.customer_number, i.invoice_number;
</code>```

I am getting duplicate records like:

```<code> Date       cust_num    invc#
 1/22/2018   479         I128
 4/23/2018   479         I287
 5/18/2018   479         I433
</code>```

It should have returned me only last record. What am I doing wrong?

答:
You can use row_number() window analytic function

```<code>select order_date, customer_number, invoice_number
  from
 (
  select o.order_date, c.customer_number, i.invoice_number,
         row_number() over (partition by c.customer_number order by o.order_date desc) as rn
    from orders o
    join invoices i on o.order_oid = i.order_oid
    join customer c on c.customer_oid = i.customer_oid
   where o.status_oid in (4,6)
  )
 where rn = 1;
</code>```

P.S. : Of course, proper to give up old-style comma seperated join for the queries

Body:
I have got 3 tables: order, customer and invoice. I need to get the latest invoice number for each customer.

I am using the max function on order date  and then grouping by customer number and invoice number, where order status was confirmed or shipped.

  select max(o.order_date), c.customer_number, i.invoice_number
  from orders o , invoices i , customer c
  where o.order_oid = i.order_oid
  and c.customer_oid = i.customer_oid
  and o.status_oid in (  4,6)
  group by c.customer_number, i.invoice_number;

I am getting duplicate records like:

 Date       cust_num    invc#
 1/22/2018   479         I128
 4/23/2018   479         I287
 5/18/2018   479         I433

It should have returned me only last record. What am I doing wrong?

Body:
You can use row_number() window analytic function

select order_date, customer_number, invoice_number
  from
 (
  select o.order_date, c.customer_number, i.invoice_number,
         row_number() over (partition by c.customer_number order by o.order_date desc) as rn
    from orders o
    join invoices i on o.order_oid = i.order_oid
    join customer c on c.customer_oid = i.customer_oid
   where o.status_oid in (4,6)
  )
 where rn = 1;

P.S. : Of course, proper to give up old-style comma seperated join for the queries


问:
Name depends on the number of characters
How to write a conditional statement acting as follows:

If "% name%" has 1 character, name: 00 "% name%"

If "% name%" has 2, name: 0 "% name%"

If "% name%" has 3 , name: "% name%"

```<code>    action.SetDynamicParameter("FileName", ((((((("%version%" + "_")  _

                + String.Join(", ", array2))  _

                + "_")  _

                + "%name%")  _

                + ".jpg"))
</code>```

I will be grateful for your help.

答:
Check the return of the Function for Nothing or check the length of the string before passing it to the Function.</p>

```<code>Private Function GetPaddedName(OriginalName As String) As String
    Dim PaddedString As String = ""
    Select Case OriginalName.Length
        Case 1
            PaddedString = "00" & OriginalName & ".jpg"
        Case 2
            PaddedString = "0" & OriginalName & ".jpg"
        Case 3
            PaddedString = OriginalName & ".jpg"
        Case Else
            PaddedString = Nothing
    End Select
    Return PaddedString
End Function
</code>```

Body:
How to write a conditional statement acting as follows:

If "% name%" has 1 character, name: 00 "% name%"

If "% name%" has 2, name: 0 "% name%"

If "% name%" has 3 , name: "% name%"

    action.SetDynamicParameter("FileName", ((((((("%version%" + "_")  _

                + String.Join(", ", array2))  _

                + "_")  _

                + "%name%")  _

                + ".jpg"))

I will be grateful for your help.

Body:
Check the return of the Function for Nothing or check the length of the string before passing it to the Function.

Private Function GetPaddedName(OriginalName As String) As String
    Dim PaddedString As String = ""
    Select Case OriginalName.Length
        Case 1
            PaddedString = "00" & OriginalName & ".jpg"
        Case 2
            PaddedString = "0" & OriginalName & ".jpg"
        Case 3
            PaddedString = OriginalName & ".jpg"
        Case Else
            PaddedString = Nothing
    End Select
    Return PaddedString
End Function


问:
Java Optionals: Return value or do something and continue the loop
In a loop I have code similar to this

```<code>    for (Id id : ids) {
        Item item = itemRepo.findbyId(id);

        if(item == null) {
            Log.error("No item by id");
            continue;
        }

        // bla bla bla
    }
</code>```

What is the best way to rewrite this using Optionals ?

I tried to rewrite and wanted to use ifPresentOrElse to make code shorter but for the method ifPresentOrElse() is written

When we have an Optional instance, often we want to execute a specific action on the underlying value of it. On the other hand, if the Optional is empty we want to log it or track that fact by incrementing some metric.

Hence, I just can not return value if it is there.
Any suggestions?.

Thank you.

UPDATE: I'm sorry, forgot to mention that I need solution with optional as repository function getById has changed and it returns Optional as result.

答:
```<code>for (Id id : ids) {
    Optional<Item> item = Optional.ofNullable(itemRepo.findbyId(id));

    item.ifPresentOrElse(()->System.out.println(item.get()), this::logNoItem());

}
</code>```

Body:
In a loop I have code similar to this

    for (Id id : ids) {
        Item item = itemRepo.findbyId(id);

        if(item == null) {
            Log.error("No item by id");
            continue;
        }

        // bla bla bla
    }

What is the best way to rewrite this using Optionals ?

I tried to rewrite and wanted to use ifPresentOrElse to make code shorter but for the method ifPresentOrElse() is written

When we have an Optional instance, often we want to execute a specific action on the underlying value of it. On the other hand, if the Optional is empty we want to log it or track that fact by incrementing some metric.

Hence, I just can not return value if it is there.
Any suggestions?.

Thank you.

UPDATE: I'm sorry, forgot to mention that I need solution with optional as repository function getById has changed and it returns Optional as result.


问:
@RefreshScope stops @Scheduled task
I have a monitoring app wherein I am running a fixedRate task. This is pulling in a config parameter configured with Consul. I want to pull in updated configuration, so I added @RefreshScope. But as soon as I update the config value on Consul, the fixedRate task stops running.

```<code>@Service
@RefreshScope
public class MonitorService {

    @Autowired
    private AppConfig appConfig;

    @PostConstruct
    public void postConstRun() {
        System.out.println(appConfig.getMonitorConfig());
    }

    @Scheduled(fixedRate = 1000)
    public void scheduledMonitorScan() {
        System.out.println("MonitorConfig:" + appConfig.getMonitorConfig());
    }
}
</code>```

AppConfig class just has a single String parameter:

```<code>@Configuration
@Getter
@Setter
public class AppConfig {

    @Value("${monitor-config:default value}")
    private String monitorConfig;
}
</code>```

As soon as I update the value in consul, the scheduled task just stops running (display in sheduledMonitorScan method) stop showing up.

答:
Here's how we've solved this issue.

```<code>/**
 * Listener of Spring's lifecycle to revive Scheduler beans, when spring's
 * scope is refreshed.
 * <p>
 * Spring is able to restart beans, when we change their properties. Such a
 * beans marked with RefreshScope annotation. To make it work, spring creates
 * <b>lazy</b> proxies and push them instead of real object. The issue with
 * scope refresh is that right after refresh in order for such a lazy proxy
 * to be actually instantiated again someone has to call for any method of it.
 * <p>
 * It creates a tricky case with Schedulers, because there is no bean, which
 * directly call anything on any Scheduler. Scheduler lifecycle is to start
 * few threads upon instantiation and schedule tasks. No other bean needs
 * anything from them.
 * <p>
 * To overcome this, we had to create artificial method on Schedulers and call
 * them, when there is a scope refresh event. This actually instantiates.
 */
@RequiredArgsConstructor
public class RefreshScopeListener implements ApplicationListener<RefreshScopeRefreshedEvent> {
    private final List<RefreshScheduler> refreshSchedulers;

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
        refreshSchedulers.forEach(RefreshScheduler::materializeAfterRefresh);
    }
}
</code>```

So, we've defined an interface, which does nothing in particular, but allows us to call for a refreshed job.

```<code>public interface RefreshScheduler {
    /**
     * Used after refresh context for scheduler bean initialization
     */
    default void materializeAfterRefresh() {
    }
}
</code>```

And here is actual job, whose parameter from.properties can be refreshed.

```<code>public class AJob implements RefreshScheduler {
    @Scheduled(cron = "${from.properties}")
    public void aTask() {
        // do something useful
    }
}
</code>```

UPDATED:
Of course AJob bean must be marked with @RefreshScope in @Configuration

```<code>@Configuration
@EnableScheduling
public class SchedulingConfiguration {
    @Bean
    @RefreshScope
    public AJob aJob() {
        return new AJob();
    }
}
</code>```

Title: @RefreshScope stops @Scheduled task

Body:
I have a monitoring app wherein I am running a fixedRate task. This is pulling in a config parameter configured with Consul. I want to pull in updated configuration, so I added @RefreshScope. But as soon as I update the config value on Consul, the fixedRate task stops running.

@Service
@RefreshScope
public class MonitorService {

    @Autowired
    private AppConfig appConfig;

    @PostConstruct
    public void postConstRun() {
        System.out.println(appConfig.getMonitorConfig());
    }

    @Scheduled(fixedRate = 1000)
    public void scheduledMonitorScan() {
        System.out.println("MonitorConfig:" + appConfig.getMonitorConfig());
    }
}

AppConfig class just has a single String parameter:

@Configuration
@Getter
@Setter
public class AppConfig {

    @Value("${monitor-config:default value}")
    private String monitorConfig;
}

As soon as I update the value in consul, the scheduled task just stops running (display in sheduledMonitorScan method) stop showing up.

Body:
Here's how we've solved this issue.

/**
 * Listener of Spring's lifecycle to revive Scheduler beans, when spring's
 * scope is refreshed.
 * <p>
 * Spring is able to restart beans, when we change their properties. Such a
 * beans marked with RefreshScope annotation. To make it work, spring creates
 * <b>lazy</b> proxies and push them instead of real object. The issue with
 * scope refresh is that right after refresh in order for such a lazy proxy
 * to be actually instantiated again someone has to call for any method of it.
 * <p>
 * It creates a tricky case with Schedulers, because there is no bean, which
 * directly call anything on any Scheduler. Scheduler lifecycle is to start
 * few threads upon instantiation and schedule tasks. No other bean needs
 * anything from them.
 * <p>
 * To overcome this, we had to create artificial method on Schedulers and call
 * them, when there is a scope refresh event. This actually instantiates.
 */
@RequiredArgsConstructor
public class RefreshScopeListener implements ApplicationListener<RefreshScopeRefreshedEvent> {
    private final List<RefreshScheduler> refreshSchedulers;

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
        refreshSchedulers.forEach(RefreshScheduler::materializeAfterRefresh);
    }
}

So, we've defined an interface, which does nothing in particular, but allows us to call for a refreshed job.

public interface RefreshScheduler {
    /**
     * Used after refresh context for scheduler bean initialization
     */
    default void materializeAfterRefresh() {
    }
}

And here is actual job, whose parameter from.properties can be refreshed.

public class AJob implements RefreshScheduler {
    @Scheduled(cron = "${from.properties}")
    public void aTask() {
        // do something useful
    }
}

UPDATED:
Of course AJob bean must be marked with @RefreshScope in @Configuration

@Configuration
@EnableScheduling
public class SchedulingConfiguration {
    @Bean
    @RefreshScope
    public AJob aJob() {
        return new AJob();
    }
}


问:
Calculate total right and left turn
Lines made by four Line2D method with random x2,y2 position. Every Line "end point" is "origin of" Next Line.  Only first line x1,y1 position have fixed. I have already tried some coordinate based calculations, also tried using angle and degree based.

答:
These boolean methods may help you solve your problem.
They assume that you start at point a, go to point b, and then turn to point c and that your y-axis is reversed (points down).

```<code>boolean isRightTurn(Point a, Point b, Point c) {
  return a.x * (b.y - c.y) + b.x * (c.y - a.y) +  c.x * (a.y - b.y) > 0;
}

boolean isLeftTurn(Point a, Point b, Point c) {
  return a.x * (b.y - c.y) + b.x * (c.y - a.y) +  c.x * (a.y - b.y) < 0;
}
</code>```

To get the number of right, or left turns you would have to check at every turn, whether it is left, or right, and count them.

Title: Calculate total right and left turn

Body:
These boolean methods may help you solve your problem.
They assume that you start at point a, go to point b, and then turn to point c and that your y-axis is reversed (points down).

boolean isRightTurn(Point a, Point b, Point c) {
  return a.x * (b.y - c.y) + b.x * (c.y - a.y) +  c.x * (a.y - b.y) > 0;
}

boolean isLeftTurn(Point a, Point b, Point c) {
  return a.x * (b.y - c.y) + b.x * (c.y - a.y) +  c.x * (a.y - b.y) < 0;
}

To get the number of right, or left turns you would have to check at every turn, whether it is left, or right, and count them.


问:
Application Insights tiles (table) are not automatically refreshed on Azure Dashboard
I've created a simple query using Kusto language in Application Insights. This query has been pinned to Azure Dashboard.

I've noticed that there is no any automatic update applied for the table, moreover refresh button on the tile work only first time when you click on it.

Here is the query pinned to Azure Dashboard:

```<code>traces
| order by timestamp desc nulls last
| take 10
</code>```

Based on information specified here I expected that table should be refreshed every 5 minutes. But seems that the table is never refreshed.

Is there are automatic refresh exist for AI queries on Azure Dashboard? Actually I didn't find any mentioning about automatic refresh apart provided above link.

答:
Metrics refresh depends on time range with minimum of five minutes. Logs refresh at one minute.

Related documentation reference

Regarding the refresh button on the tile, thanks for sharing the feedback on that. We have reached out to concerned team to look further into it. Will keep you updated on it.

Body:
I've created a simple query using Kusto language in Application Insights. This query has been pinned to Azure Dashboard.

I've noticed that there is no any automatic update applied for the table, moreover refresh button on the tile work only first time when you click on it.

Here is the query pinned to Azure Dashboard:

traces
| order by timestamp desc nulls last
| take 10

Based on information specified here I expected that table should be refreshed every 5 minutes. But seems that the table is never refreshed.

Is there are automatic refresh exist for AI queries on Azure Dashboard? Actually I didn't find any mentioning about automatic refresh apart provided above link.


问:
React Native StatusBar translucent not setting to true when app is resumed on android
Mostly it works perfectly, but sometimes when you minimise the app and you try to resume the app, it starts over again and the StatusBar won't be translucent (i.e the StatusBar will be shown). Thanks

i was thinking maybe the issue if from android onResume function.

答:
I had a similar problem, it was because it was opening a new instance each time i opened the app, could you try to add this line to your activity in src/main/AndroidManifest.xml:</p>

```<code> <activity
       android:name=".MainActivity"
       ...
       android:launchMode="singleInstance"> <-- This
</code>```

Body:
I had a similar problem, it was because it was opening a new instance each time i opened the app, could you try to add this line to your activity in src/main/AndroidManifest.xml:

 <activity
       android:name=".MainActivity"
       ...
       android:launchMode="singleInstance"> <-- This


问:
AWS heartbeat service using API Gateway / Lambda / DynamoDB
I'm using a local windows application and I want to be able to know when this application is offline (not later than one minute delay).

I was thinking to create an api gateway called HeartbeatControllerAPI and this api will call a lambda which in turns will set the last heartbeat of the app inside dynamodb table called "Heartbeats" looks like that:

Machine Name | Last Heartbeat

A                  2:00 AM

B                  2:10 AM

C                  2:05 AM

Therefore if I have 3 machines as following:

Machine 1 - with the app installed.

Machine 2 - with the app installed.

Machine 3 - with the app installed.

Then I though that each minute all the machine will do the work as I described above and then I will be able to know which machine is offline / online.

Is this method is right? I'm worried (from billing and overload perspective) what happened if I had 1 millions machines like these whereas on each minute all of them will access the api gateway and update the dynamodb table

答:
Typically a heartbeat is the other way around, where in your case you would do something like have the Lambda triggered by a CloudWatch event (cron event, triggered every X minutes), and that Lambda would call your machines and confirm that they are up and running. This way, your machines are left to do their task, and your heartbeat function (the Lambda) will confirm they are working every X minutes.

This would also mean you only need a single Lambda for a lot of machines (depending on performance, can increase the amount of Lambdas if you reach something like 50 machines maybe).

So if you follow this approach, your Lambda will get triggered by CloudWatch cron event, check if the machines are running and then for each machine if they are running will update the table with the status, and if they aren't, you could maybe send a message to an SNS topic (and subscribe yourself to that topic) so that you can be notified of a machine being down (this is also something that is a lot more complicated if the machine is the one calling, because if it's down then you have to scan the table for the last updated time, it can get costly and inefficient).


问:
collective.xdv and multiple theme files
I am having different theme HTML files for different site sections. There are some major layout differences depending if the page is the front page, or a certain subsection.

As far as I see the default behavior is just to have one HTML file:

http://pypi.python.org/pypi/collective.xdv#usage

What would be the best strategy to use multiple theme files, slight rule variations and collective.xdv?

Plone 4.1b.

答:
We usually just utilize plain xdv and use the rules.xml (or whatever you want to call it) file to setup the theme templates leaving the corresponding properties in the collective.xdv controlpanel empty. Nesting rules gives you quite some fexibility when asigning different templates:

```<code><?xml version="1.0" encoding="UTF-8"?>
<rules xmlns="http://namespaces.plone.org/xdv"
   xmlns:css="http://namespaces.plone.org/xdv+css"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<theme css:if-content="body.section-front-page" href="frontpage.html" />
<theme css:if-path="/section/subsection/somefolder" href="somefolder.html" />
...
<rules css:if-content="#visual-portal-wrapper">
    <!-- The default theme -->
    <theme href="theme.html" />
    <rules css:if-content="body.section-somefolder">
        <!-- Secific rules for somefolder go here -->
        ...
    </rules>
</rules>
</code>```

Title: collective.xdv and multiple theme files

Body:
We usually just utilize plain xdv and use the rules.xml (or whatever you want to call it) file to setup the theme templates leaving the corresponding properties in the collective.xdv controlpanel empty. Nesting rules gives you quite some fexibility when asigning different templates:

<?xml version="1.0" encoding="UTF-8"?>
<rules xmlns="http://namespaces.plone.org/xdv"
   xmlns:css="http://namespaces.plone.org/xdv+css"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<theme css:if-content="body.section-front-page" href="frontpage.html" />
<theme css:if-path="/section/subsection/somefolder" href="somefolder.html" />
...
<rules css:if-content="#visual-portal-wrapper">
    <!-- The default theme -->
    <theme href="theme.html" />
    <rules css:if-content="body.section-somefolder">
        <!-- Secific rules for somefolder go here -->
        ...
    </rules>
</rules>


问:
approch for homework: Does an array A with two numbers X & Y exist so that X+Y=Z - Use Hashing and time complexity should be O(n)
My task is in the title. </p>

<p>I guess a good start could be to use a hash function that seperates all number >Z from all numbers smaller Z. That would take O(n) time. But afterwards I would need to sort all Elements

答:
Given
To paraphrase the question: given an array a with n numeric elements and a number Z find whether there are to elements a[x], a[y] such that a[x]+[y]=Z.

Approach:
To do it in O(n) you could add each element to the array to a hash-set. - O(n).

Then another loop to check if Z-a[i] exists in the set another O(n)
total O(n).

You can even combine the insertion and the check and do a few optimizations but it will still be O(n)

Body:
My task is in the title.

I guess a good start could be to use a hash function that seperates all number >Z from all numbers smaller Z. That would take O(n) time. But afterwards I would need to sort all Elements


问:
Example for when use of a constant yields smaller code than a #define
In his book "Effective C++ 3rd Ed." Scott Meyer writes the following two lines of code

```<code>#define ASPECT_RATIO 1.653
</code>```

and

```<code>const double AspectRatio = 1.653;
</code>```

and explains

"...use of the constant may yield smaller code than using a #define. That’s because the pre-processor’s  blind  substitution  of  the  macro  name ASPECT_RATIO  with 1.653  could  result  in  multiple  copies  of  1.653  in  your  object code, while the use of the constant AspectRatio should never result in more than one copy."

Is this still true for current compilers? I played a little bit around with multiple uses of constants but got the same size for both variants with a current g++. Maybe someone could show me a working example?

Thanks.

答:
...while the use of the constant AspectRatio should never result in more than one copy

More than one copy depends on many things, especially processor instruction and compiler optimization setting.  When optimizing for speed, more than one copy may lead to faster execution.  This kind of blanket statement <s>shouldn't be made</s> can't be justified or supported.

Preprocessing

The contents of a #define macro are handled by the preprocessing phase of compilation.  The contents of the macro are inserted before the compilation (translation) begins.  With a simple example:

```<code>#include <iostream>
#define THREE (3)
const int FOUR = 4;
int main()
{
    int value = THREE;
    std::cout << "Value is: " << value << "\n";
    return 0;
}
</code>```

After preprocessing, the compiler sees:

```<code>// contents of iostream header
const int FOUR = 4;
int main()
{
    int value = 3;
    std::cout << "Value is: " << value << "\n";
    return 0;
}
</code>```

The #define macro is no different than pasting the number directly into the code.

Since the number is pasted directly into the code, the compiler deduces the type of the constant (signed vs. unsigned, integer vs. floating point), then emit code to assign the number to the variable.

Identifiers / Symbols

When the compiler encounters the statement:

```<code>  const int FOUR = 4;
</code>```

the compiler creates the symbol "FOUR" places it into a symbol table with the associated value of 4.  (There may be other attributes associated with the symbol, but let's keep it simple for illustrative purposes).

When the compiler encounters a statement like:

```<code>value = FOUR;
</code>```

The compiler encounters the symbol "FOUR", looks it up in the symbol table, retrieves the value and continues processing, similar to processing the statement value = 4;.

Implementation

The processor instructions emitted for either case depend on the processor and the optimization level of the compiler (and maybe the complexity of the compiler).

Immediate Mode

Processors have accessing or fetching modes.  For simplicity, we are concerned with immediate or direct access mode and indirect mode.  Immediate mode is where the instruction has field for the value.  Let's call it MOVE (as in move a constant into a register):

```<code>+--------------------------------------+    +-------+
|         LOAD operation/instruction   |    |       |
+--------------------+-----------------+    |       |
+ Instruction Number | Register Number |    | Value |
+--------------------+-----------------+    +-------+
</code>```

The MOVE instruction comprises of two fields:  instruction code and the value to load into the register.  The MOVE instruction has two fields, always.  Note:  The value field may be incorporated into the instruction unit (word).

In this case, the compiler would insert the number into the value field of the instruction.  No extra space consumed, no extra instructions emitted.

Indirect Mode

With indirect mode, the processor loads the register via pointer (address).  The processor takes an addition step of dereferencing the pointer to fetch the value.

```<code>+--------------------------------------+    +---------+
|         LOAD operation/instruction   |    | Pointer |
+--------------------+-----------------+    |    to   |
+ Instruction Number | Register Number |    |  Value  |
+--------------------+-----------------+    +---------+
</code>```

Immediate vs. Indirect

Some processors may have a limited range for the immediate value (for example 8-bits) and anything larger (such as int or double), would require indirect access (an addition word for the pointer/address).  Compilers, in lazy mode, could simplify operations and always use indirect mode; immediate mode would be used for higher optimization levels.

When optimizing for space, compilers may save room by using indirect mode for common constants (e.g. PI).  Using a constant variable (instead of a macro) would make this task easier.  However, a compiler may also do this with the value anyway (when it encounters 3.14159... it could store it in a table for later usage).

Summary

The performance and size of using #define macro or const variables depends on the compiler's capabilities, optimization levels and the processor instructions.  A blanket claim that a macro is better or worse than the constant variable for space or execution speed, cannot be justified.  Too many dependencies of compiler and processor.

Common coding guidelines suggest using constant variables, as they have a type and prevent defects based on mismatched types (the compiler can issue warnings or errors).

Body:
In his book "Effective C++ 3rd Ed." Scott Meyer writes the following two lines of code

#define ASPECT_RATIO 1.653

and

const double AspectRatio = 1.653;

and explains

"...use of the constant may yield smaller code than using a #define. That’s because the pre-processor’s  blind  substitution  of  the  macro  name ASPECT_RATIO  with 1.653  could  result  in  multiple  copies  of  1.653  in  your  object code, while the use of the constant AspectRatio should never result in more than one copy."

Is this still true for current compilers? I played a little bit around with multiple uses of constants but got the same size for both variants with a current g++. Maybe someone could show me a working example?

Thanks.

Body:
...while the use of the constant AspectRatio should never result in more than one copy

More than one copy depends on many things, especially processor instruction and compiler optimization setting.  When optimizing for speed, more than one copy may lead to faster execution.  This kind of blanket statement <s>shouldn't be made</s> can't be justified or supported.

Preprocessing

The contents of a #define macro are handled by the preprocessing phase of compilation.  The contents of the macro are inserted before the compilation (translation) begins.  With a simple example:

#include <iostream>
#define THREE (3)
const int FOUR = 4;
int main()
{
    int value = THREE;
    std::cout << "Value is: " << value << "\n";
    return 0;
}

After preprocessing, the compiler sees:

// contents of iostream header
const int FOUR = 4;
int main()
{
    int value = 3;
    std::cout << "Value is: " << value << "\n";
    return 0;
}

The #define macro is no different than pasting the number directly into the code.

Since the number is pasted directly into the code, the compiler deduces the type of the constant (signed vs. unsigned, integer vs. floating point), then emit code to assign the number to the variable.

Identifiers / Symbols

When the compiler encounters the statement:

  const int FOUR = 4;

the compiler creates the symbol "FOUR" places it into a symbol table with the associated value of 4.  (There may be other attributes associated with the symbol, but let's keep it simple for illustrative purposes).

When the compiler encounters a statement like:

value = FOUR;

The compiler encounters the symbol "FOUR", looks it up in the symbol table, retrieves the value and continues processing, similar to processing the statement value = 4;.

Implementation

The processor instructions emitted for either case depend on the processor and the optimization level of the compiler (and maybe the complexity of the compiler).

Immediate Mode

Processors have accessing or fetching modes.  For simplicity, we are concerned with immediate or direct access mode and indirect mode.  Immediate mode is where the instruction has field for the value.  Let's call it MOVE (as in move a constant into a register):

+--------------------------------------+    +-------+
|         LOAD operation/instruction   |    |       |
+--------------------+-----------------+    |       |
+ Instruction Number | Register Number |    | Value |
+--------------------+-----------------+    +-------+

The MOVE instruction comprises of two fields:  instruction code and the value to load into the register.  The MOVE instruction has two fields, always.  Note:  The value field may be incorporated into the instruction unit (word).

In this case, the compiler would insert the number into the value field of the instruction.  No extra space consumed, no extra instructions emitted.

Indirect Mode

With indirect mode, the processor loads the register via pointer (address).  The processor takes an addition step of dereferencing the pointer to fetch the value.

+--------------------------------------+    +---------+
|         LOAD operation/instruction   |    | Pointer |
+--------------------+-----------------+    |    to   |
+ Instruction Number | Register Number |    |  Value  |
+--------------------+-----------------+    +---------+

Immediate vs. Indirect

Some processors may have a limited range for the immediate value (for example 8-bits) and anything larger (such as int or double), would require indirect access (an addition word for the pointer/address).  Compilers, in lazy mode, could simplify operations and always use indirect mode; immediate mode would be used for higher optimization levels.

When optimizing for space, compilers may save room by using indirect mode for common constants (e.g. PI).  Using a constant variable (instead of a macro) would make this task easier.  However, a compiler may also do this with the value anyway (when it encounters 3.14159... it could store it in a table for later usage).

Summary

The performance and size of using #define macro or const variables depends on the compiler's capabilities, optimization levels and the processor instructions.  A blanket claim that a macro is better or worse than the constant variable for space or execution speed, cannot be justified.  Too many dependencies of compiler and processor.

Common coding guidelines suggest using constant variables, as they have a type and prevent defects based on mismatched types (the compiler can issue warnings or errors).


问:
Google Analytics Reporting API service account issues
I've been trying to get data from GA using a service account, however, my issue is that it keeps saying;

Error: User does not have sufficient permissions for this profile.

I have enabled GA reporting API and given access to GA account using the email of the service account. In addition, it was granted "read and analyze" permissions on the account.

Tried this method on a personal account, and everything worked fine, however, when working on a client project, the issue comes back.

What could I be missing?

答:
This was interesting to figure out.

I've used Account ID against one Google Analytics Account and that worked.

For the one I have been having an issue with, I needed to use the View ID.


问:
For loop iterates less times than I expected in Python
I would expect the following loop to iterate six times, instead it iterates three with python3. I don't understand this behavior.
I understand that the list changes as I delete elements but I don't get how that affects the for loop condition.
Why is the loop iterating less than six times?</p>

```<code>a = [1, 2, 3, 4, 5, 6]
for elem in a:
        del a[0]
        print(a)
</code>```

答:
Iterating over and deleting elements from a list at the same time is tricky. One way to manage it is to traverse the list in reverse:

```<code>a = [1, 2, 3, 4, 5, 6]
for elem in reversed(a):
    print(a)
    del a[0]
print(a)
</code>```

It'll print:

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

Body:
I would expect the following loop to iterate six times, instead it iterates three with python3. I don't understand this behavior.
I understand that the list changes as I delete elements but I don't get how that affects the for loop condition.
Why is the loop iterating less than six times?

a = [1, 2, 3, 4, 5, 6]
for elem in a:
        del a[0]
        print(a)

Body:
Iterating over and deleting elements from a list at the same time is tricky. One way to manage it is to traverse the list in reverse:

a = [1, 2, 3, 4, 5, 6]
for elem in reversed(a):
    print(a)
    del a[0]
print(a)

It'll print:

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


问:
Creating function to get means based on column levels
I'm trying to create a function that gives me the means based on another column's levels. I know that R has plenty of functions that do this same thing, but since I'm planning to use the boot package, as I could see I need to provide a function to be used (this package appears not to have pre defined functions such as "FUN=mean"). Sorry for such a basic question!

I searched on pages about the basics of function creation in R but couldn't find what I want. Here an example what I want using iris dataset and tapply:

```<code>data(iris)
with(iris, tapply(Sepal.Length, Species, mean))
</code>```

So, I want a function that gives me the means (Sepal.Length) of each level (Species) of a X data.table (in this case, iris).

```<code>setosa versicolor  virginica
 5.006    5.936      6.588
</code>```

答:
Another option with tidyverse

```<code>f1 <- function(data, grpCol, valueCol) {
        grpCol <- enquo(grpCol)
        valueCol <- enquo(valueCol)
        data %>%
            group_by(!! grpCol) %>%
            summarise(Mean = mean(!! valueCol))
 }

f1(iris, Species, Sepal.Length)
# A tibble: 3 x 2
#  Species     Mean
#  <fct>      <dbl>
#1 setosa      5.01
#2 versicolor  5.94
#3 virginica   6.59
</code>```

Body:
I'm trying to create a function that gives me the means based on another column's levels. I know that R has plenty of functions that do this same thing, but since I'm planning to use the boot package, as I could see I need to provide a function to be used (this package appears not to have pre defined functions such as "FUN=mean"). Sorry for such a basic question!

I searched on pages about the basics of function creation in R but couldn't find what I want. Here an example what I want using iris dataset and tapply:

data(iris)
with(iris, tapply(Sepal.Length, Species, mean))

So, I want a function that gives me the means (Sepal.Length) of each level (Species) of a X data.table (in this case, iris).

setosa versicolor  virginica
 5.006    5.936      6.588

Body:
Another option with tidyverse

f1 <- function(data, grpCol, valueCol) {
        grpCol <- enquo(grpCol)
        valueCol <- enquo(valueCol)
        data %>%
            group_by(!! grpCol) %>%
            summarise(Mean = mean(!! valueCol))
 }

f1(iris, Species, Sepal.Length)
# A tibble: 3 x 2
#  Species     Mean
#  <fct>      <dbl>
#1 setosa      5.01
#2 versicolor  5.94
#3 virginica   6.59


问:
Moment.js - How to access 'moment' function from a moment object?
Let's say I've got a moment object, created by calling moment().

How can I access the original moment function from this object ?

The challenge here is in a case where I cannot import or access moment directly. For instance, in a pure function, receiving nothing else than a moment object as parameter.

Good to know:

I tried the constructor but this is not the function:

moment().constructor !== moment ♂

答:
Have you tried passing the function as parameter?

const moment = require("moment");

const somePureFunc = (moment, date) => {
  return moment(date);
}

console.log(somePureFunc(moment, new Date());
```


问:
Show Loading Spinner with Axios and React (possible Redux)
My objective is show a loading spinner when a http request is called. I want to do this globally, It means, when any component call some api, is automatic to show teh spinner, preferably, with no aditional code to control the spinner.

I'm using react and axios. I know about the axios' interceptors.

My actual strucuture:

<Component App>
    <Component A />
    <Component B />
    <Loading Component>
</Component App>
```

<p>I don't know is It possible in react, but I Tried to make a general class to implement a base informations about the service, for example, baseUrl and the http interceptor. So, when a need to call a API service, I create a specialized class using the general class and concentred all api methods from that concept there, and, then, use the base class to call the axios method get,post,etc. So, the interceptor appears and show the spinner before the request and hide after the request.</p>

<p>The idea is a component call the specialized class to call a API and show the spinner until the request is running.</p>

<p>I think to use redux to make the state be global, but I don't know if It possible to implement in a class (API Class Base and Specialized API Class)</p>

<p>My questions:
- Is It possible use this architeture?
- If yes, how to implement and use redux with this?
- IIs that right to use class or is better use a component to implement a base service class and the specialized class?</p>

<p>App component:</p>

<pre class="lang-php prettyprint-override"><code>class App extends Component {

  constructor(props) {
      super(props);

      this.state = {
          rows: []
      };
  }

  componentDidMount() {
var service = new specializedService();

     var response =

 specializedService.someAPIMethod(1).then((res) => {
           this.setState({
               rows: res.data
           });
     });
}

render() {
return (
        <div className="App">
                <Component A rows={this.state.rows} />
                <Component B rows={this.state.rows}/>
                <Loading />
        </div>
    );
  }
</code>```

specializedService:

```<code>import serviceBase from "./serviceBase";

class specializedService {

    someAPIMethod(id) {
        return serviceBase.get('someMethod/' + id);
    };

}
</code>```

serviceBase:

```<code>import axios from "axios";

const serviceBase = () => {

    const api = axios.create({
        baseURL: 'https://xxxxx.xxxxx.com/xxxxxx/'
    });

    api.interceptors.request.use(async (config) => {
        try{
            // In this moment, show the spinner
            // showLoading();
        }
        catch(e)
        {
            alert('Error request' + e);
        }

        return config;
    });

    api.interceptors.response.use(async (config) => {
        try {
            // In this moment, hide the spinner
            // hideLoading();
        }
        catch(e)
        {
            alert('Error response' + e);
        }

        return config;
    });

    return api;
};

export default serviceBase;
</code>```

I made a simple sample to illustrate the situation, but I don't connect the redux
https://repl.it/@DiegoFerreira1/LoadingSpinnerApp

答: You can try use react context and share method which will change visibility of your Loading component.

Body:
My objective is show a loading spinner when a http request is called. I want to do this globally, It means, when any component call some api, is automatic to show teh spinner, preferably, with no aditional code to control the spinner.

I'm using react and axios. I know about the axios' interceptors.

My actual strucuture:

<Component App>
    <Component A />
    <Component B />
    <Loading Component>
</Component App>

I don't know is It possible in react, but I Tried to make a general class to implement a base informations about the service, for example, baseUrl and the http interceptor. So, when a need to call a API service, I create a specialized class using the general class and concentred all api methods from that concept there, and, then, use the base class to call the axios method get,post,etc. So, the interceptor appears and show the spinner before the request and hide after the request.

The idea is a component call the specialized class to call a API and show the spinner until the request is running.

I think to use redux to make the state be global, but I don't know if It possible to implement in a class (API Class Base and Specialized API Class)

My questions:
- Is It possible use this architeture?
- If yes, how to implement and use redux with this?
- IIs that right to use class or is better use a component to implement a base service class and the specialized class?

App component:

class App extends Component {

  constructor(props) {
      super(props);

      this.state = {
          rows: []
      };
  }

  componentDidMount() {
var service = new specializedService();

     var response =

 specializedService.someAPIMethod(1).then((res) => {
           this.setState({
               rows: res.data
           });
     });
}

render() {
return (

                <Component A rows={this.state.rows} />
                <Component B rows={this.state.rows}/>
                <Loading />

    );
  }

specializedService:

import serviceBase from "./serviceBase";

class specializedService {

    someAPIMethod(id) {
        return serviceBase.get('someMethod/' + id);
    };

}

serviceBase:

import axios from "axios";

const serviceBase = () => {

    const api = axios.create({
        baseURL: 'https://xxxxx.xxxxx.com/xxxxxx/'
    });

    api.interceptors.request.use(async (config) => {
        try{
            // In this moment, show the spinner
            // showLoading();
        }
        catch(e)
        {
            alert('Error request' + e);
        }

        return config;
    });

    api.interceptors.response.use(async (config) => {
        try {
            // In this moment, hide the spinner
            // hideLoading();
        }
        catch(e)
        {
            alert('Error response' + e);
        }

        return config;
    });

    return api;
};

export default serviceBase;

I made a simple sample to illustrate the situation, but I don't connect the redux
https://repl.it/@DiegoFerreira1/LoadingSpinnerApp


问:
How to programmatically transfer a lot of data between tables?
i have two tables where in the first one i have 14 millions and in the second one i have 1.5 million of data.

So i wonder how could i transfer this data to another table to be normalized ?
And how do i convert some type to another, for example: i have a field called 'year' but its type is varchar, but i want it an integer instead, how do i do that ?

I thought about do this using JDBC in a loop while from java, but i think this is not effeciently.

```<code>// 1.5 million of data
CREATE TABLE dbo.directorsmovies
    (
    movieid    INT NULL,
    directorid INT NULL,
    dname      VARCHAR (500) NULL,
    addition   VARCHAR (1000) NULL
    )

//14 million of data
CREATE TABLE dbo.movies
    (
    movieid      VARCHAR (20) NULL,
    title        VARCHAR (400) NULL,
    mvyear       VARCHAR (100) NULL,
    actorid      VARCHAR (20) NULL,
    actorname    VARCHAR (250) NULL,
    sex          CHAR (1) NULL,
    as_character VARCHAR (1500) NULL,
    languages    VARCHAR (1500) NULL,
    genres       VARCHAR (100) NULL
    )
</code>```

And this is my new tables:

```<code>DROP TABLE actor
CREATE TABLE actor (
    id INT PRIMARY KEY IDENTITY,
    name VARCHAR(200) NOT NULL,
    sex VARCHAR(1) NOT NULL
)

DROP TABLE actor_character
CREATE TABLE actor_character(
    id INT PRIMARY KEY IDENTITY,
    character VARCHAR(100)
)

DROP TABLE director
CREATE TABLE director(
    id INT PRIMARY KEY IDENTITY,
    name VARCHAR(200) NOT NULL,
    addition VARCHAR(150)
)

DROP TABLE movie
CREATE TABLE movie(
    id INT PRIMARY KEY IDENTITY,
    title VARCHAR(200) NOT NULL,
    year INT
)

DROP TABLE language
CREATE TABLE language(
    id INT PRIMARY KEY IDENTITY,
    language VARCHAR (100) NOT NULL
)

DROP TABLE genre
CREATE TABLE genre(
    id INT PRIMARY KEY IDENTITY,
    genre VARCHAR(100) NOT NULL
)

DROP TABLE director_movie
CREATE TABLE director_movie(
    idDirector INT,
    idMovie INT,
    CONSTRAINT fk_director_movie_1 FOREIGN KEY (idDirector) REFERENCES director(id),
    CONSTRAINT fk_director_movie_2 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT pk_director_movie PRIMARY KEY(idDirector,idMovie)
)

DROP TABLE genre_movie
CREATE TABLE genre_movie(
    idGenre INT,
    idMovie INT,
    CONSTRAINT fk_genre_movie_1 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT fk_genre_movie_2 FOREIGN KEY (idGenre) REFERENCES genre(id),
    CONSTRAINT pk_genre_movie PRIMARY KEY (idMovie, idGenre)
)

DROP TABLE language_movie
CREATE TABLE language_movie(
    idLanguage INT,
    idMovie INT,
    CONSTRAINT fk_language_movie_1 FOREIGN KEY (idLanguage) REFERENCES language(id),
    CONSTRAINT fk_language_movie_2 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT pk_language_movie PRIMARY KEY (idLanguage, idMovie)
)

DROP TABLE movie_actor
CREATE TABLE movie_actor(
    idMovie INT,
    idActor INT,
    CONSTRAINT fk_movie_actor_1 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT fk_movie_actor_2 FOREIGN KEY (idActor) REFERENCES actor(id),
    CONSTRAINT pk_movie_actor PRIMARY KEY (idMovie,idActor)
)
</code>```

UPDATE:
I'm using SQL Server 2008.
Sorry guys i forgot to mention that are different databases :

The not normalized is call disciplinedb and the my normalized call imdb.

Best regards,
Valter Henrique.

答:
If both tables are in the same database, then the most efficient transfer is to do it all within the database, preferably by sending a SQL statement to be executed there.

Any movement of data from the d/b server to somewhere else and then back to the d/b server is to be avoided unless there is a reason it can only be transformed off-server.  If the destination is different server, then this is much less of an issue.

Body:
i have two tables where in the first one i have 14 millions and in the second one i have 1.5 million of data.

So i wonder how could i transfer this data to another table to be normalized ?
And how do i convert some type to another, for example: i have a field called 'year' but its type is varchar, but i want it an integer instead, how do i do that ?

I thought about do this using JDBC in a loop while from java, but i think this is not effeciently.

// 1.5 million of data
CREATE TABLE dbo.directorsmovies
    (
    movieid    INT NULL,
    directorid INT NULL,
    dname      VARCHAR (500) NULL,
    addition   VARCHAR (1000) NULL
    )

//14 million of data
CREATE TABLE dbo.movies
    (
    movieid      VARCHAR (20) NULL,
    title        VARCHAR (400) NULL,
    mvyear       VARCHAR (100) NULL,
    actorid      VARCHAR (20) NULL,
    actorname    VARCHAR (250) NULL,
    sex          CHAR (1) NULL,
    as_character VARCHAR (1500) NULL,
    languages    VARCHAR (1500) NULL,
    genres       VARCHAR (100) NULL
    )

And this is my new tables:

DROP TABLE actor
CREATE TABLE actor (
    id INT PRIMARY KEY IDENTITY,
    name VARCHAR(200) NOT NULL,
    sex VARCHAR(1) NOT NULL
)

DROP TABLE actor_character
CREATE TABLE actor_character(
    id INT PRIMARY KEY IDENTITY,
    character VARCHAR(100)
)

DROP TABLE director
CREATE TABLE director(
    id INT PRIMARY KEY IDENTITY,
    name VARCHAR(200) NOT NULL,
    addition VARCHAR(150)
)

DROP TABLE movie
CREATE TABLE movie(
    id INT PRIMARY KEY IDENTITY,
    title VARCHAR(200) NOT NULL,
    year INT
)

DROP TABLE language
CREATE TABLE language(
    id INT PRIMARY KEY IDENTITY,
    language VARCHAR (100) NOT NULL
)

DROP TABLE genre
CREATE TABLE genre(
    id INT PRIMARY KEY IDENTITY,
    genre VARCHAR(100) NOT NULL
)

DROP TABLE director_movie
CREATE TABLE director_movie(
    idDirector INT,
    idMovie INT,
    CONSTRAINT fk_director_movie_1 FOREIGN KEY (idDirector) REFERENCES director(id),
    CONSTRAINT fk_director_movie_2 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT pk_director_movie PRIMARY KEY(idDirector,idMovie)
)

DROP TABLE genre_movie
CREATE TABLE genre_movie(
    idGenre INT,
    idMovie INT,
    CONSTRAINT fk_genre_movie_1 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT fk_genre_movie_2 FOREIGN KEY (idGenre) REFERENCES genre(id),
    CONSTRAINT pk_genre_movie PRIMARY KEY (idMovie, idGenre)
)

DROP TABLE language_movie
CREATE TABLE language_movie(
    idLanguage INT,
    idMovie INT,
    CONSTRAINT fk_language_movie_1 FOREIGN KEY (idLanguage) REFERENCES language(id),
    CONSTRAINT fk_language_movie_2 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT pk_language_movie PRIMARY KEY (idLanguage, idMovie)
)

DROP TABLE movie_actor
CREATE TABLE movie_actor(
    idMovie INT,
    idActor INT,
    CONSTRAINT fk_movie_actor_1 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT fk_movie_actor_2 FOREIGN KEY (idActor) REFERENCES actor(id),
    CONSTRAINT pk_movie_actor PRIMARY KEY (idMovie,idActor)
)

UPDATE:
I'm using SQL Server 2008.
Sorry guys i forgot to mention that are different databases :

The not normalized is call disciplinedb and the my normalized call imdb.

Best regards,
Valter Henrique.


问:
No redirection after successful angular form validation
Today, I encountered a problem with angular routing after successful validation of Angular reactive form. All I want to achieve is validate passwords fields in my form and in case success redirect toward another component ('/customers') or in case that passwords are not the same we should do nothing and give a chance to the user to retype proper passwords again.

RegistrationComponent.ts

```<code>
@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {

  registerForm: FormGroup;
  submitted = false;
  email$: Observable<string>;

  constructor(private formBuilder: FormBuilder, private customerService: CustomerService, private router: Router) {
  }

  ngOnInit() {

    this.registerForm = this.formBuilder.group({
      username: ['', Validators.required],
      email: ['', Validators.required],
      name: ['', Validators.required],
      surname: ['', Validators.required],
      phoneNumber: ['', Validators.required],
      nip: ['', Validators.required],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required],
    }, {
      validator: MustMatch('password', 'confirmPassword')
    });
  }

  get form() {
    return this.registerForm.controls;
  }

  onSubmit() {
    this.submitted = true;

    const registeredCustomer: RegistrationForm = {

      username: this.registerForm.controls.username.value,
      email: this.registerForm.controls.email.value,
      name: this.registerForm.controls.name.value,
      surname: this.registerForm.controls.surname.value,
      phoneNumber: this.registerForm.controls.phoneNumber.value,
      password: this.registerForm.controls.password.value,
      confirmPassword: this.registerForm.controls.confirmPassword.value,

    };

    this.email$ = this.customerService
    .register(registeredCustomer)
    .pipe(map(customer => customer.email));

    if (this.registerForm.invalid) {
      return;
    } else {
      setTimeout(() => this.router.navigate((['/customers'])), 5000);
    }

    alert('User successfully registered' + JSON.stringify(this.registerForm.value));

  }

}

</code>```

RegistrationComponent.html

```<code><div class="jumbotron">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-md-3">
        <h3>Fill in the form below to complete the registration process </h3>
        <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
          <div class="form-group">
            <label>Username</label>
            <input type="text" formControlName="username" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.username.errors }" />
            <div *ngIf="submitted && form.username.errors" class="invalid-feedback">
              <div *ngIf="form.username.errors.required">Username is required</div>
            </div>
          </div>
          <div class="form-group">
            <label>Name</label>
            <input type="text" formControlName="name" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.name.errors }" />
            <div *ngIf="submitted && form.name.errors" class="invalid-feedback">
              <div *ngIf="form.name.errors.required">Customer name is required</div>
            </div>
          </div>
          <div class="form-group">
            <label>Surname</label>
            <input type="text" formControlName="surname" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.surname.errors }" />
            <div *ngIf="submitted && form.surname.errors" class="invalid-feedback">
              <div *ngIf="form.surname.errors.required">Customer surname is required</div>
            </div>
          </div>
          <div class="form-group">
            <label>Phone Number</label>
            <input type="text" formControlName="phoneNumber" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.phoneNumber.errors }" />
            <div *ngIf="submitted && form.phoneNumber.errors" class="invalid-feedback">
              <div *ngIf="form.phoneNumber.errors.required">Phone number is required</div>
            </div>
          </div>
          <div class="form-group">
            <label>Email</label>
            <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.email.errors }" />
            <div *ngIf="submitted && form.email.errors" class="invalid-feedback">
              <div *ngIf="form.email.errors.required">Email is required</div>
              <div *ngIf="form.email.errors.email">Email must be a valid email address</div>
            </div>
          </div>
          <div class="form-group">
            <label>Password</label>
            <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.password.errors }" />
            <div *ngIf="submitted && form.password.errors" class="invalid-feedback">
              <div *ngIf="form.password.errors.required">Password is required</div>
              <div *ngIf="form.password.errors.minlength">Password must be at least 6 characters</div>
            </div>
          </div>
          <div class="form-group">
            <label>Confirm Password</label>
            <input type="password" formControlName="confirmPassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.confirmPassword.errors }" />
            <div *ngIf="submitted && form.confirmPassword.errors" class="invalid-feedback">
              <div *ngIf="form.confirmPassword.errors.required">Confirm Password is required</div>
              <div *ngIf="form.confirmPassword.errors.mustMatch">Passwords must match</div>
            </div>
          </div>
          <div class="form-group">
            <button class="btn btn-primary">Register</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

</code>```

I was based on this tutorial: Registration tutorial

but after small modification, my current solution is not working properly.

I was trying to replace this

```<code>    setTimeout(() => this.router.navigate((['/customers'])), 5000);
</code>```

infront of:

```<code>    if (this.registerForm.invalid) {
      return;
    }
</code>```

and checking if boolean value submitted = false but it didn't yield the desired result.

Thank you in advance for all your help.

Edit: Stackblitz link for application.

component

stackblitz editor

答:
To activate the routing you must inject the routing module in the app.module.ts (i.e root module).
Also define the path for the route in your routing module file as :

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
    {path: 'customers' , component: CustomersComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

Aslo don't forgrt to include <router-outlet></router-outlet> tag because its where the child view will be loaded after the routing is successfull.

Body:
Today, I encountered a problem with angular routing after successful validation of Angular reactive form. All I want to achieve is validate passwords fields in my form and in case success redirect toward another component ('/customers') or in case that passwords are not the same we should do nothing and give a chance to the user to retype proper passwords again.

RegistrationComponent.ts

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {

  registerForm: FormGroup;
  submitted = false;
  email$: Observable<string>;

  constructor(private formBuilder: FormBuilder, private customerService: CustomerService, private router: Router) {
  }

  ngOnInit() {

    this.registerForm = this.formBuilder.group({
      username: ['', Validators.required],
      email: ['', Validators.required],
      name: ['', Validators.required],
      surname: ['', Validators.required],
      phoneNumber: ['', Validators.required],
      nip: ['', Validators.required],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required],
    }, {
      validator: MustMatch('password', 'confirmPassword')
    });
  }

  get form() {
    return this.registerForm.controls;
  }

  onSubmit() {
    this.submitted = true;

    const registeredCustomer: RegistrationForm = {

      username: this.registerForm.controls.username.value,
      email: this.registerForm.controls.email.value,
      name: this.registerForm.controls.name.value,
      surname: this.registerForm.controls.surname.value,
      phoneNumber: this.registerForm.controls.phoneNumber.value,
      password: this.registerForm.controls.password.value,
      confirmPassword: this.registerForm.controls.confirmPassword.value,

    };

    this.email$ = this.customerService
    .register(registeredCustomer)
    .pipe(map(customer => customer.email));

    if (this.registerForm.invalid) {
      return;
    } else {
      setTimeout(() => this.router.navigate((['/customers'])), 5000);
    }

    alert('User successfully registered' + JSON.stringify(this.registerForm.value));

  }

}

RegistrationComponent.html

Fill in the form below to complete the registration process

        <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">

            Username
            <input type="text" formControlName="username" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.username.errors }" />

Username is required

            Name
            <input type="text" formControlName="name" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.name.errors }" />

Customer name is required

            Surname
            <input type="text" formControlName="surname" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.surname.errors }" />

Customer surname is required

            Phone Number
            <input type="text" formControlName="phoneNumber" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.phoneNumber.errors }" />

Phone number is required

            Email
            <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.email.errors }" />

Email is required

Email must be a valid email address

            Password
            <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.password.errors }" />

Password is required

Password must be at least 6 characters

            Confirm Password
            <input type="password" formControlName="confirmPassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && form.confirmPassword.errors }" />

Confirm Password is required

Passwords must match

            <button class="btn btn-primary">Register</button>

        </form>

I was based on this tutorial: Registration tutorial

but after small modification, my current solution is not working properly.

I was trying to replace this

    setTimeout(() => this.router.navigate((['/customers'])), 5000);

infront of:

    if (this.registerForm.invalid) {
      return;
    }

and checking if boolean value submitted = false but it didn't yield the desired result.

Thank you in advance for all your help.

Edit: Stackblitz link for application.

component

stackblitz editor

Body:
To activate the routing you must inject the routing module in the app.module.ts (i.e root module).
Also define the path for the route in your routing module file as :

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
    {path: 'customers' , component: CustomersComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Aslo don't forgrt to include <router-outlet></router-outlet> tag because its where the child view will be loaded after the routing is successfull.


答:
A good use case for using Optional is to write neat code by avoiding unnecessary null checks.
So here in your code there is one place where Optional can be used -

```<code>for (Id id : ids) {
    Item item = itemRepo.findbyId(id);

    Item item_notNull = Optional.ofNullable(item).orElse(<deafult instance of Item>);
    // now do anything with item_notNull, it'll never be null
    // bla bla bla
}
</code>```

The limitation of the above code is you are not getting the notification if Item is null. If you want that you can use the below code

```<code>for (Id id : ids) {
    Optional<Item> item = Optional.ofNullable(Repo.findbyId(id));

    if (item.isPresent()) {
            System.out.println("No item by id");
            continue;
        }else{
            //do something
        }

    // bla bla bla
}
</code>```

Title: Java Optionals: Return value or do something and continue the loop

Body:
In a loop I have code similar to this

    for (Id id : ids) {
        Item item = itemRepo.findbyId(id);

        if(item == null) {
            Log.error("No item by id");
            continue;
        }

        // bla bla bla
    }

What is the best way to rewrite this using Optionals ?

I tried to rewrite and wanted to use ifPresentOrElse to make code shorter but for the method ifPresentOrElse() is written

When we have an Optional instance, often we want to execute a specific action on the underlying value of it. On the other hand, if the Optional is empty we want to log it or track that fact by incrementing some metric.

Hence, I just can not return value if it is there.
Any suggestions?.

Thank you.

UPDATE: I'm sorry, forgot to mention that I need solution with optional as repository function getById has changed and it returns Optional as result.

Body:
A good use case for using Optional is to write neat code by avoiding unnecessary null checks.
So here in your code there is one place where Optional can be used -

for (Id id : ids) {
    Item item = itemRepo.findbyId(id);

    Item item_notNull = Optional.ofNullable(item).orElse(<deafult instance of Item>);
    // now do anything with item_notNull, it'll never be null
    // bla bla bla
}

The limitation of the above code is you are not getting the notification if Item is null. If you want that you can use the below code

for (Id id : ids) {
    Optional<Item> item = Optional.ofNullable(Repo.findbyId(id));

    if (item.isPresent()) {
            System.out.println("No item by id");
            continue;
        }else{
            //do something
        }

    // bla bla bla
}


问:
Angular 6 using ViewChild
How can I have 2 buttons with the same function that will toggle but both are in different component?

and here is how the m_quick_sidebar_toggle is being called

```<code>import { Directive, ElementRef, OnDestroy, AfterViewInit } from '@angular/core';
import { $ } from 'protractor';

   @Directive({
       selector: '[mQuickSidebarOffcanvas]'
      })
   export class QuickSidebarOffcanvasDirective
    implements AfterViewInit, OnDestroy {
       constructor(private el: ElementRef) {}

ngAfterViewInit(): void {
    const offcanvas = new mOffcanvas(this.el.nativeElement, {
        overlay: true,
        baseClass: 'm-quick-sidebar',
        closeBy: 'm_quick_sidebar_close',
        toggleBy: 'm_quick_sidebar_toggle'
    });
}
ngOnDestroy(): void {}
</code>```

}

答:
In the first common ancestor component of these two component use @ViewChild to get a reference to the buttons, then using rxjs merge do:

```<code>...
@ViewChild('firstButton') firstButton : ElementRef;
@ViewChild('secondButton') secondButton : ElementRef;
...
ngAfterViewInit(): void {
    merge(
        fromEvent(firstButton.nativeElement,'click'),
        fromEvent(secondButton.nativeElement,'click')
    ).subscribe( () => toggleFunction() )
}
</code>```

I assumed toggleFunction is part of the ancestor component but even if it's not you can do another @ViewChild to get the component that provides toggle functionality then do:

```<code>elementThatProvidesToggle.toggle()
</code>```

Title: Angular 6 using ViewChild

Body:
How can I have 2 buttons with the same function that will toggle but both are in different component?

and here is how the m_quick_sidebar_toggle is being called

import { Directive, ElementRef, OnDestroy, AfterViewInit } from '@angular/core';
import { $ } from 'protractor';

   @Directive({
       selector: '[mQuickSidebarOffcanvas]'
      })
   export class QuickSidebarOffcanvasDirective
    implements AfterViewInit, OnDestroy {
       constructor(private el: ElementRef) {}

ngAfterViewInit(): void {
    const offcanvas = new mOffcanvas(this.el.nativeElement, {
        overlay: true,
        baseClass: 'm-quick-sidebar',
        closeBy: 'm_quick_sidebar_close',
        toggleBy: 'm_quick_sidebar_toggle'
    });
}
ngOnDestroy(): void {}

}

Body:
In the first common ancestor component of these two component use @ViewChild to get a reference to the buttons, then using rxjs merge do:

...
@ViewChild('firstButton') firstButton : ElementRef;
@ViewChild('secondButton') secondButton : ElementRef;
...
ngAfterViewInit(): void {
    merge(
        fromEvent(firstButton.nativeElement,'click'),
        fromEvent(secondButton.nativeElement,'click')
    ).subscribe( () => toggleFunction() )
}

I assumed toggleFunction is part of the ancestor component but even if it's not you can do another @ViewChild to get the component that provides toggle functionality then do:

elementThatProvidesToggle.toggle()


问:
Configure LogLevel of Azure Function using environment variables
As per the Azure documentation, Functions V2 uses the .NET Core logging filter hierarchy for configuration.

In the following example, an instance of ILogger is injected into the Run method of the function.

```<code>[FunctionName("MyFunction")]
public static void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger logger, ExecutionContext executionContext)
{
    logger.LogInformation("I don't want to see this in production!"));
}
</code>```

When inspecting the ILogger object, each LoggerInformation element has MinLevel of null which seems to log all levels.

In production, I only want to log at the Error level. I would like to be able to configure this using an environment variable but I cannot find any documentation which explains how to achieve this. I have tried adding the following environment variable to no effect:

```<code>"logging__logLevel__Default: "Error"
</code>```

答:
Looking at the code (1, 2, 3) for azure functions runtime, this appears to be possible. You have to set it as

export AzureFunctionsJobHost__logging__logLevel__default=Error
```

<p>This works for other <code>host.json</code> settings too</p>

<pre class="lang-sh prettyprint-override"><code>export AzureFunctionsJobHost__extensions__http__routePrefix=just-another-prefix
</code>```

Body:
As per the Azure documentation, Functions V2 uses the .NET Core logging filter hierarchy for configuration.

In the following example, an instance of ILogger is injected into the Run method of the function.

[FunctionName("MyFunction")]
public static void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger logger, ExecutionContext executionContext)
{
    logger.LogInformation("I don't want to see this in production!"));
}

When inspecting the ILogger object, each LoggerInformation element has MinLevel of null which seems to log all levels.

In production, I only want to log at the Error level. I would like to be able to configure this using an environment variable but I cannot find any documentation which explains how to achieve this. I have tried adding the following environment variable to no effect:

"logging__logLevel__Default: "Error"

Body:
Looking at the code (1, 2, 3) for azure functions runtime, this appears to be possible. You have to set it as

export AzureFunctionsJobHost__logging__logLevel__default=Error

This works for other host.json settings too

export AzureFunctionsJobHost__extensions__http__routePrefix=just-another-prefix