问:
SQL - How to group/count items by age and status on every date of a year?
I am trying to build a query from multi-year data set (tickets table) of support tickets, with relevant columns of ticked_id, status, created_on date and closed_on date for each ticket. There is also a generic dates table I can join/query to a list of dates.

I'd like to create a "burn down" chart for this year that displays the number of open tickets that were at least a year old on any given date this year. I have been able to create tables that use a sum(case... statement to group by a date - for example to show how many tickets were created on a given week - but I can't figure out how to group by every day or week this year the number of tickets that were open on that day and at least a year old.

Any help is appreciated.

Example Data:

```<code>ticket_id | status | created_on | closed_on
--------------------------------------------
 1          open     1/5/2019
 2          open     1/26/2019
 3          closed   1/28/2019    2/1/2020
 4          open     6/1/2019
 5          closed   6/5/2019     1/1/2020
</code>```

Example Results I Seek:

```<code>Date (2020)    |     Count of Year+ Aged Tickets
------------------------------------------------
1/1/2020             0
1/2/2020             0
1/3/2020             0
1/4/2020             0
1/5/2020             1
1/6/2020             1
... (skipping dates here but want all dates in results)...
1/25/2020            1
1/26/2020            2
1/27/2020            2
1/28/2020            3
1/29/2020            3
1/30/2020            3
1/31/2020            3
2/1/2020             2
... (skipping dates here but want all dates up to current date in results)...
</code>```

ticket_id 1 reached one year of age on 1/5/2020 and is still open
(remains in count)

ticket_id 2 reached one year of age on 1/26/2020 and is still open (remains in count)

ticket_id 3 reached one year of age on 1/28/2020 and was still open, adding to the count, but was closed on 2/1/2020, reducing the count

ticket_id 4 will only add to the count if it is still open on 6/1/2020, but not if it is closed before then

ticket_id 5 will never appear in the count because it never reached one year of age and is closed

答:
If ticket_id is unique then you can do this to get all ticket at least 1 year old

```<code>select ticket_id, created_on , status where status = 'open' and created_on <= dateadd(year,-1,getdate())
</code>```

if you want to count number of ticket per month then

```<code>select count(ticket_id), month(created_on) , status where status = 'open' and created_on <= dateadd(year,-1,getdate())
group by month(created_on)
</code>```

Body:
I am trying to build a query from multi-year data set (tickets table) of support tickets, with relevant columns of ticked_id, status, created_on date and closed_on date for each ticket. There is also a generic dates table I can join/query to a list of dates.

I'd like to create a "burn down" chart for this year that displays the number of open tickets that were at least a year old on any given date this year. I have been able to create tables that use a sum(case... statement to group by a date - for example to show how many tickets were created on a given week - but I can't figure out how to group by every day or week this year the number of tickets that were open on that day and at least a year old.

Any help is appreciated.

Example Data:

ticket_id | status | created_on | closed_on
--------------------------------------------
 1          open     1/5/2019
 2          open     1/26/2019
 3          closed   1/28/2019    2/1/2020
 4          open     6/1/2019
 5          closed   6/5/2019     1/1/2020

Example Results I Seek:

Date (2020)    |     Count of Year+ Aged Tickets
------------------------------------------------
1/1/2020             0
1/2/2020             0
1/3/2020             0
1/4/2020             0
1/5/2020             1
1/6/2020             1
... (skipping dates here but want all dates in results)...
1/25/2020            1
1/26/2020            2
1/27/2020            2
1/28/2020            3
1/29/2020            3
1/30/2020            3
1/31/2020            3
2/1/2020             2
... (skipping dates here but want all dates up to current date in results)...

ticket_id 1 reached one year of age on 1/5/2020 and is still open
(remains in count)

ticket_id 2 reached one year of age on 1/26/2020 and is still open (remains in count)

ticket_id 3 reached one year of age on 1/28/2020 and was still open, adding to the count, but was closed on 2/1/2020, reducing the count

ticket_id 4 will only add to the count if it is still open on 6/1/2020, but not if it is closed before then

ticket_id 5 will never appear in the count because it never reached one year of age and is closed

Body:
If ticket_id is unique then you can do this to get all ticket at least 1 year old

select ticket_id, created_on , status where status = 'open' and created_on <= dateadd(year,-1,getdate())

if you want to count number of ticket per month then

select count(ticket_id), month(created_on) , status where status = 'open' and created_on <= dateadd(year,-1,getdate())
group by month(created_on)


来源: stackexchange

问:
How to only iterate over one argument of an matrix array if both have the same variable in python?
I am trying to eliminate some non zero entries in a matrix where the 2 adjacent diagonals to the main diagonal are nonzero.

h = np.zeros((n**2,n**2))
for i in np.arange(0, n**2):
    for j in np.arange(0,n**2):
        if(i==j):
            for i in np.arange(0,n**2,n):
                h[i,j-1] = 0

print(h)```

I want it to only eliminate the lower triangle non-zero entries, but it's erasing some entries in the upper triangle. I know this is because on the last if statement with the for loop, it is iterating for both arguments of the array, when I only want it to iterate for the first argument i, but since I set i=j, it runs for both.

The matrix I want to obtain is the following:

Desired matrix

PS: sorry for the extremely bad question format, this is my first question.

答:
```<code>hamiltonian = np.zeros((n**2,n**2))   # store the Hamiltonian
for i in np.arange(0, n**2):
    for j in np.arange(0,n**2):
        if abs(i-j) == 1:
            hamiltonian[i,j] = 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to eliminate some non zero entries in a matrix where the 2 adjacent diagonals to the main diagonal are nonzero.

h = np.zeros((n**2,n**2))
for i in np.arange(0, n**2):
    for j in np.arange(0,n**2):
        if(i==j):
            for i in np.arange(0,n**2,n):
                h[i,j-1] = 0

print(h)

I want it to only eliminate the lower triangle non-zero entries, but it's erasing some entries in the upper triangle. I know this is because on the last if statement with the for loop, it is iterating for both arguments of the array, when I only want it to iterate for the first argument i, but since I set i=j, it runs for both.

The matrix I want to obtain is the following:

Desired matrix

PS: sorry for the extremely bad question format, this is my first question.


问:
Textmate - indent no longer working for shortcut Cmd + ]
Recently the Textmate shortcuts Cmd + [ and Cmd + ] for indent and outdent respectively stopped work.  When I trigger them now I just hear the warning bell.

I realise I can use Alt + Tab and Alt + Shift + Tab but I prefer the other shortcuts.

答:
If you don't have a lot of preferences set...

Move ~/Library/Preferences/com.macromates.textmate.plist to someplace else and restart Textmate with all settings now at their defaults.

If you do have lots of preferences set (check by doing the above and seeing if it feels awful!) do as above and then compare the newly generated preferences file to your original (may require saving as XML with Property List Editor).

ContentLicense: CC BY-SA 3.0


问:
How to select DISTINCT entries in SQLite Flutter with whereArgs?
I want to return Distinct records from a table in SQLITE flutter by giving some condition such as return All the distinct records where ID = x (where x will be taken by the user).

How can I achieve this?

答:
Working with the SQFlite package you can use a query or a rawQuery to perform that, in both cases you need to pass the where arguments as an array, and for the distinct operator you can do it as follows:

```<code>  /// [GET] Get all the data by date using a query
  getData(String date) async {
    final db = await database;
    final response = await db.query(
      "TableExample",
      distinct: true,
      orderBy: 'id',
      where: 'date = ?',
      whereArgs: [date],
    );
    //...
  }

  /// [GET] Get all the data by date using a rawQuery
  getDailyPollResponsesPerRangeDate(String date) async {
    final db = await database;
    final response = await db.rawQuery(
      "SELECT DISTINCT TableExample.id, TableExample.date "
      "FROM TableExample "
      "WHERE TableExample.date == ? "
      "ORDER BY TableExample.date DESC",
      [date],
    );
    //...
  }
</code>```

Body:
Working with the SQFlite package you can use a query or a rawQuery to perform that, in both cases you need to pass the where arguments as an array, and for the distinct operator you can do it as follows:

  /// [GET] Get all the data by date using a query
  getData(String date) async {
    final db = await database;
    final response = await db.query(
      "TableExample",
      distinct: true,
      orderBy: 'id',
      where: 'date = ?',
      whereArgs: [date],
    );
    //...
  }

  /// [GET] Get all the data by date using a rawQuery
  getDailyPollResponsesPerRangeDate(String date) async {
    final db = await database;
    final response = await db.rawQuery(
      "SELECT DISTINCT TableExample.id, TableExample.date "
      "FROM TableExample "
      "WHERE TableExample.date == ? "
      "ORDER BY TableExample.date DESC",
      [date],
    );
    //...
  }


问:
How do I link to another html with a different style? Is it possible to do?
I am working on a home page that links to several of my projects. I am trying to link to another html that has a different style than the home page. The images and text I have for the second html works fine, but it takes on the style of the home page, and not its own design which is different. My question is is it possible to link to another html that has a different style? If so, how do I input this? When I try putting the style for the second html in the home page's folder, it won't let me since there's already another style.css I used for the main home page. I tried changing the name of the second style file and it still does not work. </p>

答:
Yes, it is possible to use different style for diffrent html pages. There are mainly two easy way

Either you use different css files for each html page (Which is not recommended):
Let say for homepage.html you use mystyle.css

```<code><html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
</html>
</code>```

So for other html page you can use secondpage.css

```<code><html>
<head>
<link rel="stylesheet" type="text/css" href="secondpage.css">
</head>
</html>
</code>```

and make sure you specify path correctly

Other way which is recommended is you give diffrent class name for the html attributes, So that you can specify the all styling in single stylesheet. which will reduce your page loding time too.

Lets say this is home.html :

```<code>    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
    </head>
    <body>

    <div class="homepage">
    // Other content here
    </div

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

So in Second html file you can use different class

```<code>    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
    </head>
    <body>

    <div class="secondpage">
    // Other content here
    </div

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

so now yourstylesheet will look like :

```<code>.homepage{
        //your style here
        }
.secondpage{
          // your style here
         }
</code>```

Hope so this helps.

Body:
Yes, it is possible to use different style for diffrent html pages. There are mainly two easy way

Either you use different css files for each html page (Which is not recommended):
Let say for homepage.html you use mystyle.css

<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
</html>

So for other html page you can use secondpage.css

<html>
<head>
<link rel="stylesheet" type="text/css" href="secondpage.css">
</head>
</html>

and make sure you specify path correctly

Other way which is recommended is you give diffrent class name for the html attributes, So that you can specify the all styling in single stylesheet. which will reduce your page loding time too.

Lets say this is home.html :

    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
    </head>
    <body>

    <div class="homepage">
    // Other content here
    </div

    </body>
    </html>

So in Second html file you can use different class

    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
    </head>
    <body>

    <div class="secondpage">
    // Other content here
    </div

    </body>
    </html>

so now yourstylesheet will look like :

.homepage{
        //your style here
        }
.secondpage{
          // your style here
         }

Hope so this helps.


问:
How to pass a value from a Jquery submit function to PHP?
I have a jQuery function which I call when I click a button and which submits a form:

```<code>function SubmitFormData() {
        $("#myForm").submit(); // Submit the form
    }
</code>```

and in PHP I would like to check for "if form as been submited AND if value is true". Without using Jquery, just submitting to PHP I do it like this:

```<code>if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['accepted'])){
   ///submit to database
 }
</code>```

is there a way to set this variable: $_POST['accepted']? so I would keep the if statement as it is.

答:
As Jquery being the Javascript framework it is a client-side language and PHP is a server-side language.to pass the data from JS(Jquery) to a PHP file you will need to make an ajax call to the PHP page and post the data.

For more details regarding jquery Click Here.

Body:
I have a jQuery function which I call when I click a button and which submits a form:

function SubmitFormData() {
        $("#myForm").submit(); // Submit the form
    }

and in PHP I would like to check for "if form as been submited AND if value is true". Without using Jquery, just submitting to PHP I do it like this:

if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['accepted'])){
   ///submit to database
 }

is there a way to set this variable: $_POST['accepted']? so I would keep the if statement as it is.


问:
Avoiding `Sync` for shared static variables
I have the following definitions:

```<code>struct MyCustomFactory;

trait Factory {
    fn new<'a>(entity: &'a str) -> Arc<dyn Display + 'a>
    where
        Self: Sized;
}

impl Factory for MyCustomFactory {
    fn new<'a>(entity: &'a str) -> Arc<dyn Display + 'a>
    where
        Self: Sized,
    {
        Arc::new(entity)
    }
}
</code>```

Higher level problem:

I'm trying to create a global static (and immutable) map of strings to structs which implement the Factory trait. The goal is that for any value member of the map, I can treat it like a Factory, call new against it, and in turn will get something back that (in this case) implements the Display trait.

I have the following:

static ITEMS: Lazy<BTreeMap<&'static str, Arc<dyn Factory>>> =
    Lazy::new(|| {
        let mut map = BTreeMap::new();
        let value = Arc::new(MyCustomFactory) as Arc<dyn Factory>;
        map.insert("foo", value);
        map
    });
```

<p>The compiler complains with:</p>

<pre class="lang-none prettyprint-override"><code>77 | / static ITEMS: Lazy<BTreeMap<&'static str, Arc<dyn Factory>>> =
78 | |     Lazy::new(|| {
79 | |         let map = BTreeMap::new();
80 | |         let value = Arc::new(MyCustomFactory) as Arc<dyn Factory>;
...  |
88 | |     });
   | |_______^ `(dyn Factory + 'static)` cannot be shared between threads safely
   |
   = help: the trait `std::marker::Sync` is not implemented for `(dyn Factory + 'static)`
   = note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Arc<(dyn Factory + 'static)>`
   = note: required because of the requirements on the impl of `std::marker::Send` for `alloc::collections::btree::node::Root<&'static str, std::sync::Arc<(dyn Factory + 'static)>>`
   = note: required because it appears within the type `std::collections::BTreeMap<&'static str, std::sync::Arc<(dyn Factory + 'static)>>`
   = note: required because of the requirements on the impl of `std::marker::Sync` for `once_cell::imp::OnceCell<std::collections::BTreeMap<&'static str, std::sync::Arc<(dyn Factory + 'static)>>>`
   = note: required because it appears within the type `once_cell::sync::OnceCell<std::collections::BTreeMap<&'static str, std::sync::Arc<(dyn Factory + 'static)>>>`
   = note: required because of the requirements on the impl of `std::marker::Sync` for `once_cell::sync::Lazy<std::collections::BTreeMap<&'static str, std::sync::Arc<(dyn Factory + 'static)>>>`
   = note: shared static variables must have a type that implements `Sync`
</code>```

Things I have tried:

Implement Sync against the trait: Declaring the trait to have trait Factory : Sync, (meaning all items which implement the trait, must implement Sync) and/or defining:

   |
66 | unsafe impl Sync for dyn Factory {}
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't implement cross-crate trait with a default impl for non-struct/enum type
```

Wrapping Arc<dyn Factory>: I've tried using Mutex / RefCell / OnceCell and others, all resulting in the same error. It seems like there should be a way to treat the underlying MyCustomFactory as a Singleton that can be locked around. It's fine (and expected) that's there's only once instance of this struct globally.

答:
You were close with adding Sync. If you look closely you'll see that the error then recommends adding Send:

= help: the trait `std::marker::Send` is not implemented for `(dyn Factory + 'static)`
```

<p>Add both <code>Send</code> and <code>Sync</code> and it compiles. You can do:</p>

```trait Factory: Send + Sync {
    ...
}
```

<p>Or, my preference, require them specifically in the static map, since that's where they're needed:</p>

```static ITEMS: Lazy<BTreeMap<&'static str, Arc<dyn Factory + Send + Sync>>> =
    Lazy::new(|| {
        let mut map = BTreeMap::new();
        let value = Arc::new(MyCustomFactory) as Arc<dyn Factory + Send + Sync>;
        map.insert("foo", value);
        map
    });
```

<p>You could also reduce duplication by letting it infer the second <code>Arc</code>:</p>

```let value = Arc::new(MyCustomFactory) as Arc<_>;
```

Body:
I have the following definitions:

struct MyCustomFactory;

trait Factory {
    fn new<'a>(entity: &'a str) -> Arc<dyn Display + 'a>
    where
        Self: Sized;
}

impl Factory for MyCustomFactory {
    fn new<'a>(entity: &'a str) -> Arc<dyn Display + 'a>
    where
        Self: Sized,
    {
        Arc::new(entity)
    }
}

Higher level problem:

I'm trying to create a global static (and immutable) map of strings to structs which implement the Factory trait. The goal is that for any value member of the map, I can treat it like a Factory, call new against it, and in turn will get something back that (in this case) implements the Display trait.

I have the following:

static ITEMS: Lazy<BTreeMap<&'static str, Arc<dyn Factory>>> =
    Lazy::new(|| {
        let mut map = BTreeMap::new();
        let value = Arc::new(MyCustomFactory) as Arc<dyn Factory>;
        map.insert("foo", value);
        map
    });

The compiler complains with:

77 | / static ITEMS: Lazy<BTreeMap<&'static str, Arc<dyn Factory>>> =
78 | |     Lazy::new(|| {
79 | |         let map = BTreeMap::new();
80 | |         let value = Arc::new(MyCustomFactory) as Arc<dyn Factory>;
...  |
88 | |     });
   | |_______^ `(dyn Factory + 'static)` cannot be shared between threads safely
   |
   = help: the trait `std::marker::Sync` is not implemented for `(dyn Factory + 'static)`
   = note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Arc<(dyn Factory + 'static)>`
   = note: required because of the requirements on the impl of `std::marker::Send` for `alloc::collections::btree::node::Root<&'static str, std::sync::Arc<(dyn Factory + 'static)>>`
   = note: required because it appears within the type `std::collections::BTreeMap<&'static str, std::sync::Arc<(dyn Factory + 'static)>>`
   = note: required because of the requirements on the impl of `std::marker::Sync` for `once_cell::imp::OnceCell<std::collections::BTreeMap<&'static str, std::sync::Arc<(dyn Factory + 'static)>>>`
   = note: required because it appears within the type `once_cell::sync::OnceCell<std::collections::BTreeMap<&'static str, std::sync::Arc<(dyn Factory + 'static)>>>`
   = note: required because of the requirements on the impl of `std::marker::Sync` for `once_cell::sync::Lazy<std::collections::BTreeMap<&'static str, std::sync::Arc<(dyn Factory + 'static)>>>`
   = note: shared static variables must have a type that implements `Sync`

Things I have tried:

Implement Sync against the trait: Declaring the trait to have trait Factory : Sync, (meaning all items which implement the trait, must implement Sync) and/or defining:

   |
66 | unsafe impl Sync for dyn Factory {}
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't implement cross-crate trait with a default impl for non-struct/enum type

Wrapping Arc<dyn Factory>: I've tried using Mutex / RefCell / OnceCell and others, all resulting in the same error. It seems like there should be a way to treat the underlying MyCustomFactory as a Singleton that can be locked around. It's fine (and expected) that's there's only once instance of this struct globally.

Body:
You were close with adding Sync. If you look closely you'll see that the error then recommends adding Send:

= help: the trait `std::marker::Send` is not implemented for `(dyn Factory + 'static)`

Add both Send and Sync and it compiles. You can do:

trait Factory: Send + Sync {
    ...
}

Or, my preference, require them specifically in the static map, since that's where they're needed:

static ITEMS: Lazy<BTreeMap<&'static str, Arc<dyn Factory + Send + Sync>>> =
    Lazy::new(|| {
        let mut map = BTreeMap::new();
        let value = Arc::new(MyCustomFactory) as Arc<dyn Factory + Send + Sync>;
        map.insert("foo", value);
        map
    });

You could also reduce duplication by letting it infer the second Arc:

let value = Arc::new(MyCustomFactory) as Arc<_>;


问:
Raise Events in .NET on the main UI thread
I'm developing a class library in .NET that other developers will consume eventually. This library makes use of a few worker threads, and those threads fire status events that will cause some UI controls to be updated in the WinForms / WPF application.

Normally, for every update, you would need to check the .InvokeRequired property on WinForms or equivalent WPF property and invoke this on the main UI thread for updating. This can get old quickly, and something doesn't feel right about making the end developer do this, so...

Is there any way that my library can fire/invoke the events/delegates from the main UI thread?

In particular...

Should I automatically "detect" the "main" thread to use?

If not, should I require the end developer to call some (pseudo) UseThisThreadForEvents() method when the application starts so I can grab the target thread from that call?

答:
I liked Mike Bouk's answer (+1) so much, I incorporated it into my codebase.  I am concerned that his DynamicInvoke call will throw a runtime exception if the Delegate it invokes is not an EventHandler delegate, due to mismatched parameters.  And since you're in a background thread, I assume you may want to call the UI method asynchronously and that you are not concerned with whether it ever finishes.

My version below can only be used with EventHandler delegates and will ignore other delegates in its invocation list.  Since EventHandler delegates return nothing, we don't need the result.  This allows me to call EndInvoke after the asynchronous process completes by passing the EventHandler in the BeginInvoke call.  The call will return this EventHandler in IAsyncResult.AsyncState by way of the AsynchronousCallback, at which point EventHandler.EndInvoke is called.

```<code>/// <summary>
/// Safely raises any EventHandler event asynchronously.
/// </summary>
/// <param name="sender">The object raising the event (usually this).</param>
/// <param name="e">The EventArgs for this event.</param>
public static void Raise(this MulticastDelegate thisEvent, object sender,
    EventArgs e)
{
  EventHandler uiMethod;
  ISynchronizeInvoke target;
  AsyncCallback callback = new AsyncCallback(EndAsynchronousEvent);

  foreach (Delegate d in thisEvent.GetInvocationList())
  {
    uiMethod = d as EventHandler;
    if (uiMethod != null)
    {
      target = d.Target as ISynchronizeInvoke;
      if (target != null) target.BeginInvoke(uiMethod, new[] { sender, e });
      else uiMethod.BeginInvoke(sender, e, callback, uiMethod);
    }
  }
}

private static void EndAsynchronousEvent(IAsyncResult result)
{
  ((EventHandler)result.AsyncState).EndInvoke(result);
}
</code>```

And the usage:

```<code>MyEventHandlerEvent.Raise(this, MyEventArgs);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I liked Mike Bouk's answer (+1) so much, I incorporated it into my codebase.  I am concerned that his DynamicInvoke call will throw a runtime exception if the Delegate it invokes is not an EventHandler delegate, due to mismatched parameters.  And since you're in a background thread, I assume you may want to call the UI method asynchronously and that you are not concerned with whether it ever finishes.

My version below can only be used with EventHandler delegates and will ignore other delegates in its invocation list.  Since EventHandler delegates return nothing, we don't need the result.  This allows me to call EndInvoke after the asynchronous process completes by passing the EventHandler in the BeginInvoke call.  The call will return this EventHandler in IAsyncResult.AsyncState by way of the AsynchronousCallback, at which point EventHandler.EndInvoke is called.

/// <summary>
/// Safely raises any EventHandler event asynchronously.
/// </summary>
/// <param name="sender">The object raising the event (usually this).</param>
/// <param name="e">The EventArgs for this event.</param>
public static void Raise(this MulticastDelegate thisEvent, object sender,
    EventArgs e)
{
  EventHandler uiMethod;
  ISynchronizeInvoke target;
  AsyncCallback callback = new AsyncCallback(EndAsynchronousEvent);

  foreach (Delegate d in thisEvent.GetInvocationList())
  {
    uiMethod = d as EventHandler;
    if (uiMethod != null)
    {
      target = d.Target as ISynchronizeInvoke;
      if (target != null) target.BeginInvoke(uiMethod, new[] { sender, e });
      else uiMethod.BeginInvoke(sender, e, callback, uiMethod);
    }
  }
}

private static void EndAsynchronousEvent(IAsyncResult result)
{
  ((EventHandler)result.AsyncState).EndInvoke(result);
}

And the usage:

MyEventHandlerEvent.Raise(this, MyEventArgs);


问:
Using Splunk Dashboard how to create a filter for each column of a table
I have a table that I saved as a report and created a dashboard that displays the table.
I want to add inputs for each field on the table to be able to filter the table data.
This is the table

I added a text box as the first input

How do I link the text box that has a token called purchCostReferenceToken to the purchCostReference column on the table?

答:
Strictly speaking, the input and the table are not related.  The input controls the search and the table is one way to represent the results of the search.

To control the search, use the input token in it.  Use dollar signs to denote the token.  For example,

```<code>index=foo purchCostReference=$purchCostReferenceToken$ | ...
</code>```

You will need a default value for the token to make this work when no input is provided.  Usually, that value is *.

Body:
Strictly speaking, the input and the table are not related.  The input controls the search and the table is one way to represent the results of the search.

To control the search, use the input token in it.  Use dollar signs to denote the token.  For example,

index=foo purchCostReference=$purchCostReferenceToken$ | ...

You will need a default value for the token to make this work when no input is provided.  Usually, that value is *.


问:
Recursive java function to repeat the beginning and end of the word "computing"
 I can not use global variables, helper methods or any loops

 Not interested in answer, but guidance would be great.

Currently console is printing:

compcompcompcomputingtingtingting

but it needs to be:

computing

compcomputingting

compcompcomputingtingting

compcompcompcomputingtingting

```<code>public static String madComputing(int n) {
    if (n < 0)
        return "Must be postive integer";// printing to present error instead getting error in console
    if (n > 1000)// avoid overflow
        return "Cannot be greater than 1000";

    if (n > 0) {
        //System.out.print("computing");
        return "comp" + madComputing(n - 1) + "ting" ;
    } else
        return "u";
}
</code>```

答:
You can add an extra parameter as the accumulator and give the initial param as "computing".
Call it as madComputing(4, "computing") for your example case.

It looks very bad code wise but it still does the job:

```<code>public static String madComputing(int n, String acc) {
  if (n < 0) {
      return "Must be postive integer";
  }
  if (n > 1000) {
      return "Cannot be greater than 1000";
  }
  if (n > 0) {
      System.out.println(acc);
      acc = "comp" + acc + "ting";
      return madComputing(n - 1, acc);
  } else {
    return "";
  }
}
</code>```

Or if you can not add an accumulator:

```<code>public static String madComputing(int n) {
  if (n < 0) {
      return "Must be postive integer";
  }
  if (n > 1000) {
      return "Cannot be greater than 1000";
  }
  if (n >= 0) {
      String value = "comp" + (n == 0 ? "u" : madComputing(n - 1))+ "ting";
      System.out.println(value);
      return value;
  }
  return null;
}
</code>```

Body:
 I can not use global variables, helper methods or any loops

 Not interested in answer, but guidance would be great.

Currently console is printing:

compcompcompcomputingtingtingting

but it needs to be:

computing

compcomputingting

compcompcomputingtingting

compcompcompcomputingtingting

public static String madComputing(int n) {
    if (n < 0)
        return "Must be postive integer";// printing to present error instead getting error in console
    if (n > 1000)// avoid overflow
        return "Cannot be greater than 1000";

    if (n > 0) {
        //System.out.print("computing");
        return "comp" + madComputing(n - 1) + "ting" ;
    } else
        return "u";
}

Body:
You can add an extra parameter as the accumulator and give the initial param as "computing".
Call it as madComputing(4, "computing") for your example case.

It looks very bad code wise but it still does the job:

public static String madComputing(int n, String acc) {
  if (n < 0) {
      return "Must be postive integer";
  }
  if (n > 1000) {
      return "Cannot be greater than 1000";
  }
  if (n > 0) {
      System.out.println(acc);
      acc = "comp" + acc + "ting";
      return madComputing(n - 1, acc);
  } else {
    return "";
  }
}

Or if you can not add an accumulator:

public static String madComputing(int n) {
  if (n < 0) {
      return "Must be postive integer";
  }
  if (n > 1000) {
      return "Cannot be greater than 1000";
  }
  if (n >= 0) {
      String value = "comp" + (n == 0 ? "u" : madComputing(n - 1))+ "ting";
      System.out.println(value);
      return value;
  }
  return null;
}


问:
SwiftUI or UIKit for animation?
I am starting to implement some animations to my app. As I started up with SwiftUI and had no experience on using UIKit, is the animation in SwiftUI enough for making customized animations? Or, should I try to learn UIKit and wrap it inside of SwiftUI View to achieve some more advanced animation?</p>

答:
I think SwiftUI is pretty much enough to use available animations, if that s not enough for you, you can check amazing custom animations made by SwiftUI LAB.

PART 1 -- PART 2 -- PART3

It includes more than 20 diffrent animations, source code is available.

Title: SwiftUI or UIKit for animation?


问:
Angular 5 AOT compilation failed
I have an Angular 5 app that works without problems when I run it in test mode, that is, when I run the application locally using the ng serve command. However, when I deploy the application in production mode, that is, through the command ng build --prod, the application exports without problems, but when I use the application in a productive environment, this problem appears: (these are images from the browsers console from google and safari)

Google Chrome Console:

Safari Console:

However, if I now export the application using the following command ng build --prod --aot false the application works without any problem.

Next I am going to show the component involved in the commented error:

user-online-quote.component.html

```<code><app-navbar [loggedIn]=loggedIn></app-navbar>
<app-dynamic-form [answers$]="answers$"></app-dynamic-form>
</code>```

user-online-quote.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { DynamicFormService } from '../_services/dynamic-form.service';
import { RadioQuestion }  from '../shared/_shared/answer-radio';
import { Observable } from "rxjs/Rx";
import { AuthService } from '../_services/auth.service';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-user-online-quote',
  templateUrl: './user-online-quote.component.html',
  styleUrls: ['./user-online-quote.component.css'],
  providers:  [DynamicFormService, AuthService]
})
export class UserOnlineQuoteComponent implements OnInit {
  totalPage:number;
  actualPage:number;
  percentageCompletion:number;
  currentQuestion:string;
  selectedOption:string;
  imageSource:string;
  loggedIn:boolean;
  formId:string;
  //public answers: any[];

  //Signo $ porque es un observable
  public answers$: Observable<any[]>;

  constructor(private service: DynamicFormService, private authService: AuthService,
    private activatedRoute: ActivatedRoute) {

   }

  ngOnInit() {
    this.loggedIn=this.authService.isLoggedIn();
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      this.formId=params['form'];
      this.answers$=this.service.getAnswers(this.formId);
    });
    //this.answers=this.service.getAnswers("CAR00PR");
    this.totalPage=4;
    this.actualPage=1;
    this.calculateAdvancePercentage();
    this.currentQuestion="¿Pregunta de prueba?";
  }

  calculateAdvancePercentage(){
    this.percentageCompletion=(this.actualPage/this.totalPage)*100;
  }

  next(){
    this.actualPage=(this.actualPage+1);
    this.calculateAdvancePercentage();
  }

  back(){
    this.actualPage=(this.actualPage-1);
    this.calculateAdvancePercentage();
  }

}
</code>```

dinamic-form.component.html

```<code><div class="space"></div>
<ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '0px', fullScreenBackdrop:true }"></ngx-loading>
<div *ngIf="submitted===false" class="container">
  <div class="row">
  <div class="col-lg-2">
    <div class="mx-2"></div>
  </div>
  <div class="col-lg-8">
    <div>
      <p>{{currentQuestion.description}}</p>
    </div>
    <div class="progress">
      <div class="progress-bar" role="progressbar" [style.width]="percentageCompletion + '%'" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
    </div>
      <hr>
      <div>
        <form [formGroup]="form">
          <div *ngFor="let answer of answers$ | async">
            <div [ngSwitch]="answer.controlType">
              <div *ngSwitchCase="'radio'">
                <div class="radios checkbox-group">
                  <div [hidden]="!(currentQuestion.id===answer.parent)" class="col-lg-12">
                    <input [formControlName]="answer.controlName" [id]="answer.id" type="radio" [value]="answer.label" (click)="next(null,answer.child)">
                      <label [for]="answer.id" class="button-label">
                        {{answer.label}}
                      </label>
                  </div>
                </div>
              </div>
              <div *ngSwitchCase="'radio_textbox'">
                <div class="radios checkbox-group">
                  <div [hidden]="!(currentQuestion.id===answer.parent)" class="col-lg-12">
                    <input [formControlName]="answer.controlName" [id]="answer.id" type="radio" (click)="showTextbox ? showTextbox = false : showTextbox = true;">
                      <label [for]="answer.id" class="button-label">
                        {{answer.label}}
                      </label>
                  </div>
                </div>
                  <div [hidden]="!(currentQuestion.id===answer.parent)" class="input-group mb-3 col-lg-12">
                    <input [hidden]="!showTextbox" type="text" class="form-control" [placeholder]="answer.placeholder" [formControlName]="answer.controlName" [id]="answer.id">
                      <div class="input-group-append">
                        <button [hidden]="!showTextbox" class="btn btn-outline-secondary" type="button" (click)="next(null,answer.child)">Siguiente</button>
                      </div>
                  </div>
              </div>
              <div *ngSwitchCase="'file'">
                <div [hidden]="!(currentQuestion.id===answer.parent)" class="col-lg-12">
                    <div class="form-group">
                        <label [for]="answer.id">{{answer.label}}</label>
                        <div class="custom-file">
                            <input [formControlName]="answer.controlName" type="file" class="custom-file-input" [id]="answer.id" lang="es" (change)="onFileChange($event)" #fileInput>
                            <label class="custom-file-label" for="customFileLang">{{fileName}}</label>
                        </div>
                        <div *ngIf="answer.required===true">
                          <small *ngIf="form.get(answer.controlName).status=='INVALID'" class="form-text text-muted-error">Debes tener una imagen de referencia para poder continuar</small>
                        </div>
                    </div>
                  <div class="my-4"></div>
                </div>
              </div>
              <div *ngSwitchCase="'file_next'">
                <div [hidden]="!(currentQuestion.id===answer.parent)" class="col-lg-12">
                    <div class="form-group">
                        <label [for]="answer.id">{{answer.label}}</label>
                        <div class="custom-file">
                            <input [formControlName]="answer.controlName" type="file" class="custom-file-input" [id]="answer.id" lang="es" (change)="onFileChange($event)" #fileInput>
                            <label class="custom-file-label" for="customFileLang">{{fileName}}</label>
                        </div>
                        <div *ngIf="answer.required===true">
                          <small *ngIf="form.get(answer.controlName).status=='INVALID'" class="form-text text-muted-error">Debes tener una imagen de referencia para poder continuar</small>
                        </div>
                    </div>
                    <div class="my-4"></div>
                    <div class="text-center">
                      <button
                        (click)='next(answer.validations,answer.next)'
                        class="btn btn-outline-secondary">
                        Siguiente
                      </button>
                    </div>
                </div>
              </div>
              <div *ngSwitchCase="'textbox'" [hidden]="!(currentQuestion.id===answer.parent)" class="col-md-6 mb-3">
                <label [for]="answer.id">{{answer.label}}</label>
                <input [formControlName]="answer.controlName" type="text" class="form-control" [id]="answer.id" [placeholder]="answer.placeholder">
                <div *ngIf="answer.required===true">
                  <small *ngIf="form.get(answer.controlName).status=='INVALID'" class="form-text text-muted-error">Este campo es obligatorio</small>
                </div>
              </div>
              <div *ngSwitchCase="'textbox_next'" [hidden]="!(currentQuestion.id===answer.parent)">
                <div class="col-md-6 mb-3">
                  <label [for]="answer.id">{{answer.label}}</label>
                  <input [formControlName]="answer.controlName" type="text" class="form-control" [id]="answer.id" [placeholder]="answer.placeholder">
                  <div *ngIf="answer.required===true">
                    <small *ngIf="form.get(answer.controlName).status=='INVALID'" class="form-text text-muted-error">Este campo es obligatorio</small>
                  </div>
                </div>
                <div class="my-4"></div>
                <div class="text-center">
                  <button
                    (click)='next(answer.validations,answer.next)'
                    class="btn btn-outline-secondary">
                    Siguiente
                  </button>
                </div>
              </div>
              <div *ngSwitchCase="'textarea'">
                <div class="form-group col-lg-12" [hidden]="!(currentQuestion.id===answer.parent)">
                  <label for="description">{{answer.label}}</label>
                  <textarea [formControlName]="answer.controlName" class="form-control" id="description" rows="3"></textarea>
                </div>
                <div class="my-4"></div>
              </div>
            </div>
          </div>

        </form>

      </div>

      <div class="my-4"></div>
      <div class="text-center">
        <button
          (click)='back()'
          class="btn btn btn-outline-secondary">
            Atrás
        </button>
        <button
          [hidden]="currentQuestion.last==true"
          (click)='cancel()'
          class="btn btn btn-outline-secondary">
            Cancelar
        </button>
        <button
          [hidden]="currentQuestion.last==false"
          [disabled]="form.invalid"
          type="submit"
          class="btn btn-outline-success"
          (click)="onSubmit()">
            Enviar Solicitud
        </button>
      </div>
  </div>
  <div class="col-lg-2">
      <div class="mx-2"></div>
  </div>
</div>
</div>
<div *ngIf="submitted==true" class="container">
  <div class="space">
      <div class="container">
          <div class="row">
              <div class="col-lg-1"></div>
              <div class="col-lg-10 justify">
                <p>Tu solicitud se ha enviado correctamente, debes esperar un máximo de 2 días para que el experto elabore una cotización
                  de acuerdo a tus requerimientos.
                </p>
                <div class="d-flex justify-content-center">
                  <a [routerLink]="['/dashboard_usuario/negociaciones/en_proceso']">Ver negociación</a>
                </div>
              </div>
              <div class="col-lg-1"></div>
          </div>
      </div>
  </div>
</div>
</code>```

dinamic-form.component.ts

```<code>import { Component, Input, OnInit, ChangeDetectorRef }  from '@angular/core';
import { FormGroup }                 from '@angular/forms';
import { AnswerBase }              from '../shared/_shared/answer-base';
import { AnswerControlService }    from '../_services/answer-control.service';
import { DynamicFormService } from '../_services/dynamic-form.service';
import { Question } from '../_models/question';
import { Observable } from "rxjs/Rx"
import { Router, ActivatedRoute, Params } from '@angular/router';
import { QuoteDto } from "../_dtos/quoteDto";
import { HttpClient, HttpResponse } from '@angular/common/http';
import {Location} from '@angular/common';

@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  styleUrls: ['./dynamic-form.component.css'],
  providers: [ AnswerControlService ]
})
export class DynamicFormComponent implements OnInit {
  @Input() answers$: Observable<AnswerBase<any>[]>;
  form: FormGroup;
  payLoad = '';
  questionsList : Map<string, Question>;
  totalPage:number;
  actualPage:number;
  percentageCompletion:number;
  currentQuestion:Question;
  previousQuestion:Question;
  backwardQuestions:Array<string>;
  loading:boolean;
  fileName:string;
  photo:File;
  image:any;
  nextDisable:boolean;
  userId:string;
  providerId:string;
  formId:string;
  submitted:boolean;

  constructor(private qcs: AnswerControlService,
    private dynamicFormervice: DynamicFormService,
    private activatedRoute: ActivatedRoute,
    private location:Location,
    private router:Router) {  }

  ngOnInit() {
    this.loading=true;
    this.submitted=false;
    this.fileName="Seleccionar un archivo";
    this.nextDisable=true;
    this.backwardQuestions= new Array();
    this.currentQuestion=new Question('','',false);
    this.form= new FormGroup({});
    this.questionsList= new Map<string, Question>();
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      this.userId=params['user'];
      this.providerId=params['provider'];
      this.formId=params['form'];
        this.dynamicFormervice.getTotalPages(this.formId).subscribe(total => {
          this.totalPage=total;
          this.actualPage=1;
          this.calculateAdvancePercentage();
            this.dynamicFormervice.getQuestions(this.formId).subscribe(items =>{
              items.map(item =>{
                this.questionsList.set(item.id,item);
              });
            this.dynamicFormervice.getInitialQuestionId(this.formId).subscribe(id =>{
              this.currentQuestion=this.questionsList.get(id);
              this.previousQuestion=this.currentQuestion;
              this.loading=false;
            });
          });
        });
    });
    this.answers$.subscribe(a=>{
      this.form = this.qcs.toFormGroup(a);
    });
  }

  onSubmit() {
    this.loading=true;
    this.payLoad=JSON.stringify(this.form.value);
    let quote:QuoteDto = new QuoteDto();
    quote.requirements= this.payLoad;
    this.dynamicFormervice.createQuote(quote,this.userId,this.providerId).subscribe((resp:HttpResponse<String>)=>{
      this.dynamicFormervice.uploadQuotationImage(this.photo,resp.body.substring(resp.body.indexOf(':')+1,resp.body.lastIndexOf('"'))).
      subscribe(resp => {
        this.submitted=true;
        this.loading=false;
      });
    });
  }

  calculateAdvancePercentage(){
    this.percentageCompletion=(this.actualPage/this.totalPage)*100;
  }

  next(validatios:string, childId:string){
    if(validatios!=null){
      let controlRestrictions:string[]=validatios.split(',');
      let validCount=0;
      for (let cr of controlRestrictions) {
        if(this.form.get(cr).status=='VALID'){
          validCount++;
        }
     }
     if(validCount==controlRestrictions.length){
       this.nextDisable=false;
       this.backwardQuestions.push(this.currentQuestion.id);
       this.currentQuestion=this.questionsList.get(childId);
       if(this.currentQuestion.last==true){
        this.percentageCompletion=100;
       }else{
        this.actualPage=(this.actualPage+1);
        this.calculateAdvancePercentage();
       }
     }
    }else{
      this.backwardQuestions.push(this.currentQuestion.id);
      this.currentQuestion=this.questionsList.get(childId);
      if(this.currentQuestion.last==true){
        this.percentageCompletion=100;
      }else{
       this.actualPage=(this.actualPage+1);
       this.calculateAdvancePercentage();
      }
    }
  }

  back(){
    if(this.actualPage==1){
      this.location.back();
    }
    else{
      let questionId:string = this.backwardQuestions.pop();
      this.currentQuestion=this.questionsList.get(questionId);
      this.actualPage=(this.actualPage-1);
      this.calculateAdvancePercentage();
    }
  }

  cancel(){
    this.navegateToProfessionForm();
  }

  navegateToProfessionForm(){
    switch (this.formId) {
      case 'ALB00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '1' } });
        break;
      case 'CAR00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '2' } });
        break;
      case 'DIS00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '3' } });
        break;
      case 'ELE00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '4' } });
        break;
      case 'CLI00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '5' } });
        break;
      case 'FUM00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '6' } });
        break;
      case 'MAQ00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '7' } });
        break;
      case 'PIN00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '8' } });
        break;
      case 'PLO00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '9' } });
        break;
      case 'JAR00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '10' } });
        break;
      case 'SOL00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '11' } });
        break;
      case 'TAP00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '12' } });
        break;
      default:
  }
  }

  onFileChange(event) {
    this.loading=true;
    if(event.target.files && event.target.files.length > 0) {
    let image:File = event.target.files[0];
    let reader=new FileReader();
    reader.readAsDataURL(image);
      reader.onload = (event:any) => {
        let base64=event.target.result
        let filename=image.name;
        let type=image.type;
        this.reduceQuality(base64,filename,type,(file)=>{
          this.photo = file;
          this.fileName=this.photo.name;
          this.loading=false;
        });
      }
    }
    else{
      this.loading=false;
    }
  }

  getBase64(file,callback) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function() {
      let result = reader.result;
      callback(result);
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    };
 }

  reduceQuality(base64Image,filename,extension,callback){
    let canvas = document.createElement('canvas');
    let ctx=canvas.getContext("2d");
    var image = new Image();
   image.onload = ()=>{
    var width = image.width,
            height = image.height,
        canvas = document.createElement('canvas'),
            ctx = canvas.getContext("2d");

    // set proper canvas dimensions before transform & export
        canvas.width = width;
      canvas.height = height;

        // draw image
    ctx.drawImage(image, 0, 0);

    let url:string = '';
    if(extension=='image/jpeg'){
      url = canvas.toDataURL('image/jpeg', 0.1);
    }
    else{
      url = canvas.toDataURL();
    }
    let file:File=this.dataURLtoFile(url,filename);
    callback(file);
  };
    image.src = base64Image;
  }
  dataURLtoFile(dataurl, filename) {
    let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

}
</code>```

package.json

```<code>{
  "name": "front-end",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "angular2-text-mask": "^8.0.4",
    "angularfire2": "^5.0.0-rc.6",
    "bootstrap": "^4.1.0",
    "core-js": "^2.4.1",
    "firebase": "^4.12.1",
    "jquery": "^3.3.1",
    "moment": "^2.20.1",
    "mydatepicker": "^2.6.3",
    "ngx-loading": "^1.0.14",
    "offcanvas-bootstrap": "^2.5.2",
    "popper.js": "^1.14.3",
    "rxjs": "^5.5.6",
    "zone.js": "0.10.3"
  },
  "devDependencies": {
    "@angular/cli": "1.6.5",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}
</code>```

angular-cli.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "front-end"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles-app-loading.scss",
        "styles.css",
        "../node_modules/font-awesome/css/font-awesome.css"
      ],
      "scripts": ["../node_modules/jquery/dist/jquery.slim.min.js",
        "../node_modules/popper.js/dist/umd/popper.min.js",
        "../node_modules/bootstrap/dist/js/bootstrap.min.js",
        "../node_modules/offcanvas-bootstrap/dist/js/bootstrap.offcanvas.min.js"],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }

}
</code>```

The question is why my app only works properly when I don't use AOT feature? Why is this so strange?

What should I do to solve this problem and I can use the AOT feature, since I do not want my application to be penalized in performance? Any ideas?

Important: Before separating the application by modules, the application worked well in production. The described problem appeared after separating my application by modules, however this problematic component is part of the main module.

答:
The error can be related to the specific rxjs version.

See https://github.com/telerik/kendo-angular/issues/1230

Seems like it is the same error with rxjs Observable.merge.apply() that appears only in aot builds.

Title: Angular 5 AOT compilation failed

Body:
I have an Angular 5 app that works without problems when I run it in test mode, that is, when I run the application locally using the ng serve command. However, when I deploy the application in production mode, that is, through the command ng build --prod, the application exports without problems, but when I use the application in a productive environment, this problem appears: (these are images from the browsers console from google and safari)

Google Chrome Console:

Safari Console:

However, if I now export the application using the following command ng build --prod --aot false the application works without any problem.

Next I am going to show the component involved in the commented error:

user-online-quote.component.html

<app-navbar [loggedIn]=loggedIn></app-navbar>
<app-dynamic-form [answers$]="answers$"></app-dynamic-form>

user-online-quote.component.ts

import { Component, OnInit } from '@angular/core';
import { DynamicFormService } from '../_services/dynamic-form.service';
import { RadioQuestion }  from '../shared/_shared/answer-radio';
import { Observable } from "rxjs/Rx";
import { AuthService } from '../_services/auth.service';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-user-online-quote',
  templateUrl: './user-online-quote.component.html',
  styleUrls: ['./user-online-quote.component.css'],
  providers:  [DynamicFormService, AuthService]
})
export class UserOnlineQuoteComponent implements OnInit {
  totalPage:number;
  actualPage:number;
  percentageCompletion:number;
  currentQuestion:string;
  selectedOption:string;
  imageSource:string;
  loggedIn:boolean;
  formId:string;
  //public answers: any[];

  //Signo $ porque es un observable
  public answers$: Observable<any[]>;

  constructor(private service: DynamicFormService, private authService: AuthService,
    private activatedRoute: ActivatedRoute) {

   }

  ngOnInit() {
    this.loggedIn=this.authService.isLoggedIn();
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      this.formId=params['form'];
      this.answers$=this.service.getAnswers(this.formId);
    });
    //this.answers=this.service.getAnswers("CAR00PR");
    this.totalPage=4;
    this.actualPage=1;
    this.calculateAdvancePercentage();
    this.currentQuestion="¿Pregunta de prueba?";
  }

  calculateAdvancePercentage(){
    this.percentageCompletion=(this.actualPage/this.totalPage)*100;
  }

  next(){
    this.actualPage=(this.actualPage+1);
    this.calculateAdvancePercentage();
  }

  back(){
    this.actualPage=(this.actualPage-1);
    this.calculateAdvancePercentage();
  }

}

dinamic-form.component.html

<ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '0px', fullScreenBackdrop:true }"></ngx-loading>

{{currentQuestion.description}}

        <form [formGroup]="form">

                    <input [formControlName]="answer.controlName" [id]="answer.id" type="radio" [value]="answer.label" (click)="next(null,answer.child)">

                        {{answer.label}}

                    <input [formControlName]="answer.controlName" [id]="answer.id" type="radio" (click)="showTextbox ? showTextbox = false : showTextbox = true;">

                        {{answer.label}}

                    <input [hidden]="!showTextbox" type="text" class="form-control" [placeholder]="answer.placeholder" [formControlName]="answer.controlName" [id]="answer.id">

                        <button [hidden]="!showTextbox" class="btn btn-outline-secondary" type="button" (click)="next(null,answer.child)">Siguiente</button>

                        {{answer.label}}

                            <input [formControlName]="answer.controlName" type="file" class="custom-file-input" [id]="answer.id" lang="es" (change)="onFileChange($event)" #fileInput>
                            {{fileName}}

                          Debes tener una imagen de referencia para poder continuar

                        {{answer.label}}

                            <input [formControlName]="answer.controlName" type="file" class="custom-file-input" [id]="answer.id" lang="es" (change)="onFileChange($event)" #fileInput>
                            {{fileName}}

                          Debes tener una imagen de referencia para poder continuar

                      <button
                        (click)='next(answer.validations,answer.next)'
                        class="btn btn-outline-secondary">
                        Siguiente
                      </button>

                {{answer.label}}
                <input [formControlName]="answer.controlName" type="text" class="form-control" [id]="answer.id" [placeholder]="answer.placeholder">

                  Este campo es obligatorio

                  {{answer.label}}
                  <input [formControlName]="answer.controlName" type="text" class="form-control" [id]="answer.id" [placeholder]="answer.placeholder">

                    Este campo es obligatorio

                  <button
                    (click)='next(answer.validations,answer.next)'
                    class="btn btn-outline-secondary">
                    Siguiente
                  </button>

                  {{answer.label}}
                  <textarea [formControlName]="answer.controlName" class="form-control" id="description" rows="3"></textarea>

        </form>

        <button
          (click)='back()'
          class="btn btn btn-outline-secondary">
            Atrás
        </button>
        <button
          [hidden]="currentQuestion.last==true"
          (click)='cancel()'
          class="btn btn btn-outline-secondary">
            Cancelar
        </button>
        <button
          [hidden]="currentQuestion.last==false"
          [disabled]="form.invalid"
          type="submit"
          class="btn btn-outline-success"
          (click)="onSubmit()">
            Enviar Solicitud
        </button>

Tu solicitud se ha enviado correctamente, debes esperar un máximo de 2 días para que el experto elabore una cotización
                  de acuerdo a tus requerimientos.

                  Ver negociación

dinamic-form.component.ts

import { Component, Input, OnInit, ChangeDetectorRef }  from '@angular/core';
import { FormGroup }                 from '@angular/forms';
import { AnswerBase }              from '../shared/_shared/answer-base';
import { AnswerControlService }    from '../_services/answer-control.service';
import { DynamicFormService } from '../_services/dynamic-form.service';
import { Question } from '../_models/question';
import { Observable } from "rxjs/Rx"
import { Router, ActivatedRoute, Params } from '@angular/router';
import { QuoteDto } from "../_dtos/quoteDto";
import { HttpClient, HttpResponse } from '@angular/common/http';
import {Location} from '@angular/common';

@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  styleUrls: ['./dynamic-form.component.css'],
  providers: [ AnswerControlService ]
})
export class DynamicFormComponent implements OnInit {
  @Input() answers$: Observable<AnswerBase<any>[]>;
  form: FormGroup;
  payLoad = '';
  questionsList : Map<string, Question>;
  totalPage:number;
  actualPage:number;
  percentageCompletion:number;
  currentQuestion:Question;
  previousQuestion:Question;
  backwardQuestions:Array<string>;
  loading:boolean;
  fileName:string;
  photo:File;
  image:any;
  nextDisable:boolean;
  userId:string;
  providerId:string;
  formId:string;
  submitted:boolean;

  constructor(private qcs: AnswerControlService,
    private dynamicFormervice: DynamicFormService,
    private activatedRoute: ActivatedRoute,
    private location:Location,
    private router:Router) {  }

  ngOnInit() {
    this.loading=true;
    this.submitted=false;
    this.fileName="Seleccionar un archivo";
    this.nextDisable=true;
    this.backwardQuestions= new Array();
    this.currentQuestion=new Question('','',false);
    this.form= new FormGroup({});
    this.questionsList= new Map<string, Question>();
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      this.userId=params['user'];
      this.providerId=params['provider'];
      this.formId=params['form'];
        this.dynamicFormervice.getTotalPages(this.formId).subscribe(total => {
          this.totalPage=total;
          this.actualPage=1;
          this.calculateAdvancePercentage();
            this.dynamicFormervice.getQuestions(this.formId).subscribe(items =>{
              items.map(item =>{
                this.questionsList.set(item.id,item);
              });
            this.dynamicFormervice.getInitialQuestionId(this.formId).subscribe(id =>{
              this.currentQuestion=this.questionsList.get(id);
              this.previousQuestion=this.currentQuestion;
              this.loading=false;
            });
          });
        });
    });
    this.answers$.subscribe(a=>{
      this.form = this.qcs.toFormGroup(a);
    });
  }

  onSubmit() {
    this.loading=true;
    this.payLoad=JSON.stringify(this.form.value);
    let quote:QuoteDto = new QuoteDto();
    quote.requirements= this.payLoad;
    this.dynamicFormervice.createQuote(quote,this.userId,this.providerId).subscribe((resp:HttpResponse<String>)=>{
      this.dynamicFormervice.uploadQuotationImage(this.photo,resp.body.substring(resp.body.indexOf(':')+1,resp.body.lastIndexOf('"'))).
      subscribe(resp => {
        this.submitted=true;
        this.loading=false;
      });
    });
  }

  calculateAdvancePercentage(){
    this.percentageCompletion=(this.actualPage/this.totalPage)*100;
  }

  next(validatios:string, childId:string){
    if(validatios!=null){
      let controlRestrictions:string[]=validatios.split(',');
      let validCount=0;
      for (let cr of controlRestrictions) {
        if(this.form.get(cr).status=='VALID'){
          validCount++;
        }
     }
     if(validCount==controlRestrictions.length){
       this.nextDisable=false;
       this.backwardQuestions.push(this.currentQuestion.id);
       this.currentQuestion=this.questionsList.get(childId);
       if(this.currentQuestion.last==true){
        this.percentageCompletion=100;
       }else{
        this.actualPage=(this.actualPage+1);
        this.calculateAdvancePercentage();
       }
     }
    }else{
      this.backwardQuestions.push(this.currentQuestion.id);
      this.currentQuestion=this.questionsList.get(childId);
      if(this.currentQuestion.last==true){
        this.percentageCompletion=100;
      }else{
       this.actualPage=(this.actualPage+1);
       this.calculateAdvancePercentage();
      }
    }
  }

  back(){
    if(this.actualPage==1){
      this.location.back();
    }
    else{
      let questionId:string = this.backwardQuestions.pop();
      this.currentQuestion=this.questionsList.get(questionId);
      this.actualPage=(this.actualPage-1);
      this.calculateAdvancePercentage();
    }
  }

  cancel(){
    this.navegateToProfessionForm();
  }

  navegateToProfessionForm(){
    switch (this.formId) {
      case 'ALB00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '1' } });
        break;
      case 'CAR00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '2' } });
        break;
      case 'DIS00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '3' } });
        break;
      case 'ELE00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '4' } });
        break;
      case 'CLI00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '5' } });
        break;
      case 'FUM00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '6' } });
        break;
      case 'MAQ00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '7' } });
        break;
      case 'PIN00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '8' } });
        break;
      case 'PLO00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '9' } });
        break;
      case 'JAR00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '10' } });
        break;
      case 'SOL00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '11' } });
        break;
      case 'TAP00PR':
        this.router.navigate(['/expertos'], { queryParams: { profession: '12' } });
        break;
      default:
  }
  }

  onFileChange(event) {
    this.loading=true;
    if(event.target.files && event.target.files.length > 0) {
    let image:File = event.target.files[0];
    let reader=new FileReader();
    reader.readAsDataURL(image);
      reader.onload = (event:any) => {
        let base64=event.target.result
        let filename=image.name;
        let type=image.type;
        this.reduceQuality(base64,filename,type,(file)=>{
          this.photo = file;
          this.fileName=this.photo.name;
          this.loading=false;
        });
      }
    }
    else{
      this.loading=false;
    }
  }

  getBase64(file,callback) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function() {
      let result = reader.result;
      callback(result);
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    };
 }

  reduceQuality(base64Image,filename,extension,callback){
    let canvas = document.createElement('canvas');
    let ctx=canvas.getContext("2d");
    var image = new Image();
   image.onload = ()=>{
    var width = image.width,
            height = image.height,
        canvas = document.createElement('canvas'),
            ctx = canvas.getContext("2d");

    // set proper canvas dimensions before transform & export
        canvas.width = width;
      canvas.height = height;

        // draw image
    ctx.drawImage(image, 0, 0);

    let url:string = '';
    if(extension=='image/jpeg'){
      url = canvas.toDataURL('image/jpeg', 0.1);
    }
    else{
      url = canvas.toDataURL();
    }
    let file:File=this.dataURLtoFile(url,filename);
    callback(file);
  };
    image.src = base64Image;
  }
  dataURLtoFile(dataurl, filename) {
    let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

}

package.json

{
  "name": "front-end",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "angular2-text-mask": "^8.0.4",
    "angularfire2": "^5.0.0-rc.6",
    "bootstrap": "^4.1.0",
    "core-js": "^2.4.1",
    "firebase": "^4.12.1",
    "jquery": "^3.3.1",
    "moment": "^2.20.1",
    "mydatepicker": "^2.6.3",
    "ngx-loading": "^1.0.14",
    "offcanvas-bootstrap": "^2.5.2",
    "popper.js": "^1.14.3",
    "rxjs": "^5.5.6",
    "zone.js": "0.10.3"
  },
  "devDependencies": {
    "@angular/cli": "1.6.5",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}

angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "front-end"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles-app-loading.scss",
        "styles.css",
        "../node_modules/font-awesome/css/font-awesome.css"
      ],
      "scripts": ["../node_modules/jquery/dist/jquery.slim.min.js",
        "../node_modules/popper.js/dist/umd/popper.min.js",
        "../node_modules/bootstrap/dist/js/bootstrap.min.js",
        "../node_modules/offcanvas-bootstrap/dist/js/bootstrap.offcanvas.min.js"],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }

}

The question is why my app only works properly when I don't use AOT feature? Why is this so strange?

What should I do to solve this problem and I can use the AOT feature, since I do not want my application to be penalized in performance? Any ideas?

Important: Before separating the application by modules, the application worked well in production. The described problem appeared after separating my application by modules, however this problematic component is part of the main module.


问:
Moved an div item on the page
I would like to move an item from my shop page. I moved it with google inspector tool, but i don't have any idea to move it like that in my real site.

Any ideas?
Thanks a lot

enter image description here
enter image description here

答:
When you modify your code with google inspector, it is only to test it and see how it looks, but the changes are not saved.

If you want to save your changes, you need to open the files of your website (HTML, CSS...) directly into a code editor. Some great text editors are Sublime, Visual Studio Code or Atom.

Once you have opened your files inside your code editor, you can edit your code and save it. In your case, it seems that you would want to select the full
...
, cut it and then paste it a few lines below.

I hope this helps. Let me know if you have more questions.

Title: Moved an div item on the page

Body:
When you modify your code with google inspector, it is only to test it and see how it looks, but the changes are not saved.

If you want to save your changes, you need to open the files of your website (HTML, CSS...) directly into a code editor. Some great text editors are Sublime, Visual Studio Code or Atom.

Once you have opened your files inside your code editor, you can edit your code and save it. In your case, it seems that you would want to select the full <div>...</div>, cut it and then paste it a few lines below.

I hope this helps. Let me know if you have more questions.


问:
get initial value of status when extending magento product _beforeSave() function
I'm extending the Mage_Catalog_Model_Product to perform a stock check whenever the product is saved, and if a product is in stock, it will not allow you to disable it.

This works fine, but I want to change the functionality. I want to disallow the ability to disable when the product is in stock ONLY if the product wasn't already disabled. Is it possible to get the initial status value of the product, before the edit was made, from within the _beforeSave() function?

答:
You should be able to load the product from the database again in _beforeSave(), to check the original value. Something like this:

```<code>$originalProduct = Mage::getModel('catalog/product')->load($this->getId());
</code>```

You should be able to get the product's status that is still in the database this way, before the save() overwrites it. Hopefully. I have not tested this. :)

Body:
You should be able to load the product from the database again in _beforeSave(), to check the original value. Something like this:

$originalProduct = Mage::getModel('catalog/product')->load($this->getId());

You should be able to get the product's status that is still in the database this way, before the save() overwrites it. Hopefully. I have not tested this. :)


问:
What's the difference between react-navigation-drawer versus @react-navigation/drawer
I am new to React Native and its my first post in Stackoverflow so my apologies if I did anything wrong.

I m trying to follow the online tutorials to install package react-native-drawer.
However, the official doc asked to install @react-native/drawer.
What's the difference between the two and when should I use what?

答: okay I think I have figured it out. The two are just different versions of react navigation. /stack is v5 and -stack is v4. </p>


问:
asp.net core 2.1 odata use different name of entity in the route
I have a long name of of entity in my code EmployeTraining which used as entity in OData and with same name for the controller.

```<code>Startup.cs

 app.UseMvc(routeBuilder=>
        {
            routeBuilder.Expand().Select().Count().OrderBy().Filter().MaxTop(null);
            routeBuilder.MapODataServiceRoute("EmployeTraining", "odata/v1", EdmModelBuilder.GetEdmModelEmploye());

        });

EdmModelBuilder.cs

public static IEdmModel GetEdmModelEmployes()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EntitySet<EmployeTraining>("EmployeTraining");
        return builder.GetEdmModel();
    }

EmployeTrainingControllers.cs

public class EmployeTrainingController : ODataController
{
    internal IEmployeService ServiceEmploye { get; set; }

    public EmployesController(IEmployeService serviceEmploye)
    {

        ServiceEmploye = serviceEmploye;
    }

    //// GET api/employes
    [HttpGet]
    [MyCustomQueryable()]
    public IQueryable<EmployeTraining> Get()
    {

        return ServiceEmploye.GetListeEmployes();
    }
}
</code>```

To call my service it works only through this URL: https://{server}/odata/v1/rh/employetraining

but I need to  use this https://{server}/odata/v1/rh/employe-training
any help please.

答:
The Reason why is working using https://{server}/odata/v1/rh/employetraining is because is the Get method of the EmployeTrainingController Controller.

You should be able to change that behaibour if you modify the [HttpGet] on the Get method to [HttpGet("employe-training")]

Body:
I have a long name of of entity in my code EmployeTraining which used as entity in OData and with same name for the controller.

Startup.cs

 app.UseMvc(routeBuilder=>
        {
            routeBuilder.Expand().Select().Count().OrderBy().Filter().MaxTop(null);
            routeBuilder.MapODataServiceRoute("EmployeTraining", "odata/v1", EdmModelBuilder.GetEdmModelEmploye());

        });

EdmModelBuilder.cs

public static IEdmModel GetEdmModelEmployes()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EntitySet<EmployeTraining>("EmployeTraining");
        return builder.GetEdmModel();
    }

EmployeTrainingControllers.cs

public class EmployeTrainingController : ODataController
{
    internal IEmployeService ServiceEmploye { get; set; }

    public EmployesController(IEmployeService serviceEmploye)
    {

        ServiceEmploye = serviceEmploye;
    }

    //// GET api/employes
    [HttpGet]
    [MyCustomQueryable()]
    public IQueryable<EmployeTraining> Get()
    {

        return ServiceEmploye.GetListeEmployes();
    }
}

To call my service it works only through this URL: https://{server}/odata/v1/rh/employetraining

but I need to  use this https://{server}/odata/v1/rh/employe-training
any help please.


问:
Akka Stream Parallelism
I've been trying to parallelize a stream in Akka Stream, according to the documentation[1], but for some reason I don't get the expected result.

I followed the steps outlined in the documentation, and I don't think I missed anything. Yet, the computations of my stream all happen one after the other in sequence.

What am I missing here?

[1] https://doc.akka.io/docs/akka/current/stream/stream-parallelism.html

```<code>import akka.actor.ActorSystem
import akka.stream.FlowShape
import akka.stream.scaladsl.{Balance, Flow, GraphDSL, Merge, Source}

object ScalaParallell extends App {

  implicit val system = ActorSystem("QuickStart")

  def longRunningComputation(x: Int): Int = {
    println(s"Computing 1 ${x}")
    Thread.sleep(10000)
    println(s"Computation 1 ${x} done")
    x
  }
  def longRunningComputation2(x: Int): Int = {
    println(s"Computing 2 ${x}")
    Thread.sleep(10000)
    println(s"Computation 2 ${x} done")
    x
  }

  val processor: Flow[Int, Int, NotUsed] =
    Flow.fromGraph(GraphDSL.create() { implicit b =>
      import GraphDSL.Implicits._

      // prepare graph elements
      val balance = b.add(Balance[Int](2))
      val merge = b.add(Merge[Int](2))
      val f = Flow[Int].map(longRunningComputation)
      val f2 = Flow[Int].map(longRunningComputation2)

      // connect the graph
      balance.out(0) ~> f.async ~> merge.in(0)
      balance.out(1) ~> f2.async ~> merge.in(1)

      // expose ports
      FlowShape(balance.in, merge.out)
    })

  // Wire it all up.
  val xs = List(1,2,3)
  val source: Source[Int, NotUsed] = Source(xs)
  source.via(processor).runForeach(println)

  Thread.sleep(5000)
}

</code>```

Example output

```<code>Computing 2 1
Computation 2 1 done
Computing 2 2
1
Computation 2 2 done
Computing 2 3
2
Computation 2 3 done
3

</code>```

I would expect to see two computations happening at the same time. For example:

```<code>Computing 1 1
Computing 1 2
Computation 1 2 done
Computing 1 3
Computation 1 1 done
Computing 2 4
1
2
..
</code>```

答: Try removing the Thread.sleep inside longRunningComputation and longRunningComputation2 and set xs to something much longer for example 1 to 100, then you'll able to observe the parallel processing. Not sure why but the blocking Thread.sleep is definitely considered anti-pattern in akka

Title: Akka Stream Parallelism

Body:
I've been trying to parallelize a stream in Akka Stream, according to the documentation[1], but for some reason I don't get the expected result.

I followed the steps outlined in the documentation, and I don't think I missed anything. Yet, the computations of my stream all happen one after the other in sequence.

What am I missing here?

[1] https://doc.akka.io/docs/akka/current/stream/stream-parallelism.html

import akka.actor.ActorSystem
import akka.stream.FlowShape
import akka.stream.scaladsl.{Balance, Flow, GraphDSL, Merge, Source}

object ScalaParallell extends App {

  implicit val system = ActorSystem("QuickStart")

  def longRunningComputation(x: Int): Int = {
    println(s"Computing 1 ${x}")
    Thread.sleep(10000)
    println(s"Computation 1 ${x} done")
    x
  }
  def longRunningComputation2(x: Int): Int = {
    println(s"Computing 2 ${x}")
    Thread.sleep(10000)
    println(s"Computation 2 ${x} done")
    x
  }

  val processor: Flow[Int, Int, NotUsed] =
    Flow.fromGraph(GraphDSL.create() { implicit b =>
      import GraphDSL.Implicits._

      // prepare graph elements
      val balance = b.add(Balance[Int](2))
      val merge = b.add(Merge[Int](2))
      val f = Flow[Int].map(longRunningComputation)
      val f2 = Flow[Int].map(longRunningComputation2)

      // connect the graph
      balance.out(0) ~> f.async ~> merge.in(0)
      balance.out(1) ~> f2.async ~> merge.in(1)

      // expose ports
      FlowShape(balance.in, merge.out)
    })

  // Wire it all up.
  val xs = List(1,2,3)
  val source: Source[Int, NotUsed] = Source(xs)
  source.via(processor).runForeach(println)

  Thread.sleep(5000)
}

Example output

Computing 2 1
Computation 2 1 done
Computing 2 2
1
Computation 2 2 done
Computing 2 3
2
Computation 2 3 done
3

I would expect to see two computations happening at the same time. For example:

Computing 1 1
Computing 1 2
Computation 1 2 done
Computing 1 3
Computation 1 1 done
Computing 2 4
1
2
..


问:
Configure SQS Dead letter Queue to raise a cloud watch alarm on receiving a message
I was working with Dead letter Queue in Amazon SQS. I want that whenever a new message is received by the queue it should raise a CloudWatch alarm. The problem is I configured an alarm on the metric: number_of_messages_sent of the queue but this metric don't work as expected in case of Dead letter Queues as mentioned in the Amazon SQS Dead-Letter Queues - Amazon Simple Queue Service documentation.

Now some suggestions on this were use number_of_messages_visible but I am not sure how to configure this in an alarm. So if i set that the value of this metric>0 then this is not same as getting a new message in the queue. If an old message is there then the metric value will always be >0. I can do some kind of mathematical expression to get the delta in this metric for some defined period (let's say a minute) but I am looking for some better solution.

答:
I struggled with the same problem and the answer for me was to use NumberOfMessagesSent instead. Then I could set my criteria for new messages that came in during my configured period of time. Here is what worked for me in CloudFormation.

Note that individual alarms do not occur if the alarm stays in an alarm state from constant failure. You can setup another alarm to catch those. ie: Alarm when 100 errors occur in 1 hour using the same method.

Updated: Because the metrics for NumberOfMessagesReceived and NumberOfMessagesSent are dependent on how the message is queued, I have devised a new solutions for our needs using the metric ApproximateNumberOfMessagesDelayed after adding a delay to the dlq settings. If you are adding the messages to the queue manually then NumberOfMessagesReceived will work. Otherwise use ApproximateNumberOfMessagesDelayed after setting up a delay.

```<code>MyDeadLetterQueue:
    Type: AWS::SQS::Queue
    Properties:
      MessageRetentionPeriod: 1209600  # 14 days
      DelaySeconds: 60 #for alarms

DLQthresholdAlarm:
 Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: "Alarm dlq messages when we have 1 or more failed messages in 10 minutes"
      Namespace: "AWS/SQS"
      MetricName: "ApproximateNumberOfMessagesDelayed"
      Dimensions:
        - Name: "QueueName"
          Value:
            Fn::GetAtt:
              - "MyDeadLetterQueue"
              - "QueueName"
      Statistic: "Sum"
      Period: 300
      DatapointsToAlarm: 1
      EvaluationPeriods: 2
      Threshold: 1
      ComparisonOperator: "GreaterThanOrEqualToThreshold"
      AlarmActions:
        - !Ref MyAlarmTopic
</code>```

Body:
I struggled with the same problem and the answer for me was to use NumberOfMessagesSent instead. Then I could set my criteria for new messages that came in during my configured period of time. Here is what worked for me in CloudFormation.

Note that individual alarms do not occur if the alarm stays in an alarm state from constant failure. You can setup another alarm to catch those. ie: Alarm when 100 errors occur in 1 hour using the same method.

Updated: Because the metrics for NumberOfMessagesReceived and NumberOfMessagesSent are dependent on how the message is queued, I have devised a new solutions for our needs using the metric ApproximateNumberOfMessagesDelayed after adding a delay to the dlq settings. If you are adding the messages to the queue manually then NumberOfMessagesReceived will work. Otherwise use ApproximateNumberOfMessagesDelayed after setting up a delay.

MyDeadLetterQueue:
    Type: AWS::SQS::Queue
    Properties:
      MessageRetentionPeriod: 1209600  # 14 days
      DelaySeconds: 60 #for alarms

DLQthresholdAlarm:
 Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: "Alarm dlq messages when we have 1 or more failed messages in 10 minutes"
      Namespace: "AWS/SQS"
      MetricName: "ApproximateNumberOfMessagesDelayed"
      Dimensions:
        - Name: "QueueName"
          Value:
            Fn::GetAtt:
              - "MyDeadLetterQueue"
              - "QueueName"
      Statistic: "Sum"
      Period: 300
      DatapointsToAlarm: 1
      EvaluationPeriods: 2
      Threshold: 1
      ComparisonOperator: "GreaterThanOrEqualToThreshold"
      AlarmActions:
        - !Ref MyAlarmTopic


问:
How can I call a high order function again in the code?

const x = { a:1 };

(function q({a}){
  console.log(a);
  return a;
})(x); // unable to execute

console.log(q(x))
```

I am unable to execute line 6. Why? In line 3 console is working if I remove line 6:

Error: q is not defined

答:
```<code>const x = { a:1 };
// This IIFE isn't assigned to a variable in global. No reference to the object
(function q({a}){
  console.log(a);
  return a;
})(x); // unable to execute
</code>```

    console.log(q(x))

This works, but you cannot call it again since a was returned back into q and q is not a function:

```<code>const x = { a:1 };
// This IIFE isn't assigned to a variable in global. No reference to the object
const q = (function ({a}){
  console.log(a);
  return a;
})(x); // unable to execute

 console.log(q) // => 1
</code>```

Body:
const x = { a:1 };

(function q({a}){
  console.log(a);
  return a;
})(x); // unable to execute

console.log(q(x))

I am unable to execute line 6. Why? In line 3 console is working if I remove line 6:

Error: q is not defined

Body:
const x = { a:1 };
// This IIFE isn't assigned to a variable in global. No reference to the object
(function q({a}){
  console.log(a);
  return a;
})(x); // unable to execute

    console.log(q(x))

This works, but you cannot call it again since a was returned back into q and q is not a function:

const x = { a:1 };
// This IIFE isn't assigned to a variable in global. No reference to the object
const q = (function ({a}){
  console.log(a);
  return a;
})(x); // unable to execute

 console.log(q) // => 1


问:
Upload file form for website, seems to work but no file in directory?
This is the code.. any ideas? Directory exists and has 777 permissions...</p>

```<code><html>
<head>

 </head>
<body>
<div style="width:340px; border: 2px solid #fff;">
<br> <center>

<p>We only accept files with a .jpg, .gif or .jpeg extension</p>
<?php
  //Define some variables
      $dir = "http://www.mywebsite.com/media/uploads/"; //B?n nên thay ð?i ðý?ng d?n cho phù h?p
    //Ki?u file, Gif, jpeg, zip ::b?n có th? s?a ð?i n?u thích
      $types = array("image/gif","image/pjpeg","image/pjpg","application/x-zip-compressed");

//Check to determine if the submit button has been pressed
    if(isset($_POST['submit'])){

//Shorten Variables
     $tmp_name = $_FILES['upload']['tmp_name'];
     $new_name = $_FILES['upload']['name'];

//Check MIME Type
    if (in_array($_FILES['upload']['type'], $types)){

         //Move file from tmp dir to new location

        move_uploaded_file($tmp_name,$dir . $new_name);

        echo "<strong>{$_FILES['upload']['name']} was uploaded sucessfully, we will be touch!</strong>";

    }else{

    //Print Error Message

     echo "<small>File <strong><em>{$_FILES['upload']['name']}</em></strong> was not uploaded</small><br />";

    //Debug
   $name =  $_FILES['upload']['name'];
   $type =    $_FILES['upload']['type'];
   $size =    $_FILES['upload']['size'];
   $tmp =     $_FILES['upload']['name'];

   echo "Name: $name<br/ >Type: $type<br />Size: $size<br />Tmp: $tmp";

    }

    }

else{

    echo '';

}
        ?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

      <fieldset>

          <div style="padding-left: 90px;"><input type="file" name="upload" />  </div>

</fieldset>
<br>
<input type="submit" name="submit" value="Upload File" />  </center>
</form></div></body></html>
</code>```

答:
is this the path to the folder with the images? if the scripts are located on your localhost you need to change the path, you said it has 777 permissions so im guessing your using linux hosting.

```<code>$dir = "http://www.mywebsite.com/media/uploads/";
</code>```

guessing that /media/ is located in your root folder try

```<code>$dir = "./media/uploads/";
</code>```

Body:
This is the code.. any ideas? Directory exists and has 777 permissions...

We only accept files with a .jpg, .gif or .jpeg extension

<?php
  //Define some variables
      $dir = "http://www.mywebsite.com/media/uploads/"; //B?n nên thay ð?i ðý?ng d?n cho phù h?p
    //Ki?u file, Gif, jpeg, zip ::b?n có th? s?a ð?i n?u thích
      $types = array("image/gif","image/pjpeg","image/pjpg","application/x-zip-compressed");

//Check to determine if the submit button has been pressed
    if(isset($_POST['submit'])){

//Shorten Variables
     $tmp_name = $_FILES['upload']['tmp_name'];
     $new_name = $_FILES['upload']['name'];

//Check MIME Type
    if (in_array($_FILES['upload']['type'], $types)){

         //Move file from tmp dir to new location

        move_uploaded_file($tmp_name,$dir . $new_name);

        echo "{$_FILES['upload']['name']} was uploaded sucessfully, we will be touch!";

    }else{

    //Print Error Message

     echo "File {$_FILES['upload']['name']} was not uploaded
";

    //Debug
   $name =  $_FILES['upload']['name'];
   $type =    $_FILES['upload']['type'];
   $size =    $_FILES['upload']['size'];
   $tmp =     $_FILES['upload']['name'];

   echo "Name: $name
Type: $type
Size: $size
Tmp: $tmp";

    }

    }

else{

    echo '';

}
        ?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

      <fieldset>

<input type="file" name="upload" />

</fieldset>

<input type="submit" name="submit" value="Upload File" />
</form>

Body:
is this the path to the folder with the images? if the scripts are located on your localhost you need to change the path, you said it has 777 permissions so im guessing your using linux hosting.

$dir = "http://www.mywebsite.com/media/uploads/";

guessing that /media/ is located in your root folder try

$dir = "./media/uploads/";


答:
I'll try to explain this to you rather than give you the quick answer. It looks like you have the base cases all correct and your issue can be fixed with a few small tweaks:

I think the primary problem with your code is that you're not printing / creating a new output at every recursive call - your recursive calls are simply appending to the same string each time. You can tell you need to print something at each recursive call because your ideal output doesn't just show the final string but also the increments in between.

So in each recursive call, you'll print your result so far, and then pass that intermediate result to the next recursive call. This means your method needs to take a parameter (or 2) which will be the result so far (accumulator)

Now the question is, what does the intermediate result look like? This will be the the thing that changes between each output, which is the 'comp's before 'u' and the 'tings' after. So you can pass an a 'before' and 'after' string parameters (which will be empty strings on the first call) that hold the string of 'comp's and 'ting's so far.

Then on each call, you just need to add a 'comp' to the before string, a 'ting' to the after string, print the whole thing with a 'u' in the middle (before + 'u' + after) and then pass the new before and after strings to the recursive call

Edit after further clarification: doing it without an accumulator:

If you need to accomplish this without an accumulator, it's a little more complex:

The base case needs to be "computing" instead of "u"

For the non-base case, first make the recursive call (i.e. call the method with n-1) and store it as a string (say recc_result)

Split the recursive result by newline \n and get the last line out of it. This can be done using recc_result.split() and then taking the last element of the array. Call this last_line

Finally, return the recc_result + '\n' + 'comp' + last_line + 'ting'

Explanation:

The change of base case is because you want to print "computing" when n=1 and not just "u".

And the way to thing about the rest is that on each stage, you're taking the last line from the result so far and adding a 'comp' to the front and a 'ting' to the end, then attaching this to the result.

So the base case is 'computing'. Then for n=2, we get the recursive result for n-1 (which is 1) which will give us 'computing'. The last line from this result is the only line (i.e. 'computing'). Then we add a 'comp' and a 'ting' and attach it to the whole result giving us "computing\ncompcomputingting".

For n=3, the recc_result is "computing\ncompcomputingting" from which we take the last line ("compcomputingting") and then add a comp and ting making "compcompcomputingtingting" and attach it to the whole result giving "computing\ncompcomputingting\ncompcompcomputingtingting"

Note: \n = newline

Title: Recursive java function to repeat the beginning and end of the word "computing"