问:
remove words based on first letter using stringr
I want to remove all words that start with "a" in a string.

Input:

```<code>string <- "This is a sentence about nothing."
</code>```

My attempt:

```<code>stringr::str_remove_all(string,"a*\\b")
</code>```

output I got:

```<code>[1] "This is  sentence about nothing."
</code>```

output I want:

```<code>[1] "This is sentence nothing."
</code>```

I am not sure how to detect based on one letter but perform action(e.g., remove, replace) on the whole word. Any input is appreciated!

答:
The a*\b pattern matches zero or more a chars followed with end of string or a word char. It does not match a word unless it is an a word.

You can use

stringr::str_remove_all(string,"\\ba\\w*")
stringr::str_replace_all(string,"\\ba\\w*", "")
gsub("\\ba\\w*", "", string, perl=TRUE) ## ASCII only letters/digits
```
<p>where <code>\ba\w*</code> matches a word boundary, <code>a</code>, and then zero or more word chars.</p>
<p>If you also want to remove any whitespaces before the word, add <code>\s*</code> at the start:</p>
<pre class="lang-r prettyprint-override"><code>stringr::str_remove_all(string,"\\s*\\ba\\w*")
stringr::str_replace_all(string,"\\s*\\ba\\w*", "")
gsub("\\s*\\ba\\w*", "", string, perl=TRUE) ## ASCII only letters/digits/whitespaces
</code>```

If you need to make sure you only remove natural langugage words consisting only of letters, then you can replace \w with \p{L}:

stringr::str_remove_all(string,"\\s*\\ba\\p{L}*")
stringr::str_replace_all(string,"\\s*\\ba\\p{L}*", "")
gsub("(*UCP)\\s*\\ba\\p{L}*", "", string, perl=TRUE) ## any Uncicode letters/digits/whitespaces
```

Body:
I want to remove all words that start with "a" in a string.

Input:

string <- "This is a sentence about nothing."

My attempt:

stringr::str_remove_all(string,"a*\\b")

output I got:

[1] "This is  sentence about nothing."

output I want:

[1] "This is sentence nothing."

I am not sure how to detect based on one letter but perform action(e.g., remove, replace) on the whole word. Any input is appreciated!

Body:
The a*\b pattern matches zero or more a chars followed with end of string or a word char. It does not match a word unless it is an a word.

You can use

stringr::str_remove_all(string,"\\ba\\w*")
stringr::str_replace_all(string,"\\ba\\w*", "")
gsub("\\ba\\w*", "", string, perl=TRUE) ## ASCII only letters/digits

where \ba\w* matches a word boundary, a, and then zero or more word chars.

If you also want to remove any whitespaces before the word, add \s* at the start:

stringr::str_remove_all(string,"\\s*\\ba\\w*")
stringr::str_replace_all(string,"\\s*\\ba\\w*", "")
gsub("\\s*\\ba\\w*", "", string, perl=TRUE) ## ASCII only letters/digits/whitespaces

If you need to make sure you only remove natural langugage words consisting only of letters, then you can replace \w with \p{L}:

stringr::str_remove_all(string,"\\s*\\ba\\p{L}*")
stringr::str_replace_all(string,"\\s*\\ba\\p{L}*", "")
gsub("(*UCP)\\s*\\ba\\p{L}*", "", string, perl=TRUE) ## any Uncicode letters/digits/whitespaces


来源: stackexchange

问:
EXC_BAD_ACCESS at searchbar when there are 2 Words?
The problem is when I write a Letter like "Pasar" the error not showing, but when I press space the error like exc_bad_access showing, why can it be? any one can't tell me about exc_bad_access..

I'am using xcode 4.2 and build at iPhone 5.0 Simulator.

答:
Try using NSZombies. In your project info, set NSZombieEnabled to YES.
Read this to enable NSZombie in your project.

Its just a memory management problem. You'll be releasing something earlier and then using it or you'll be using some variable which doesnt have memory allocated to it. NSZombie will tell you where the app got crashed.

ContentLicense: CC BY-SA 3.0


问:
Add New locale support in MONO .net framework
I am new to MONO, I want to add new locale(Maori) support in MONO.

I am getting below exception:

```<code>CultureNotSupportedExceptionSystem.ArgumentException: Value does not fall within the expected range.
        at System.Globalization.CultureTableRecord..ctor(String cultureName, Boolean useUserOverride)
        at System.Globalization.CultureTableRecord.GetCultureTableRecord(String name, Boolean useUserOverride)
        at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
        at System.Globalization.CultureInfo..ctor(String name)
        at SmartDeviceProject2.Program.Main(String[] args)
</code>```

Here test code:

```<code>namespace SmartDeviceProject2 {
    public class Program {
        public static void Main(string[] args) {
            CultureInfo cultureInfo = null;
            //string culname = "eu-ES"; //basque
            //string culname = "bg-BG"; //bulgarian - Culture found in CEOS
            string culname = "mi-NZ";   //maori
            //int culcode = 0x481;
            try {
                cultureInfo = new CultureInfo(culname);
            } catch (System.PlatformNotSupportedException e) {
                Console.WriteLine("PlatformNotSupportedException:{0}",e.ToString());
            } catch (System.ArgumentException e) {
                Console.WriteLine("CultureNotSupportedException{0}", e.ToString());
            }

            if (cultureInfo != null) {
                Console.WriteLine("Culture is found {0}", culname);
            } else {
                Console.WriteLine("Culture NOT found {0}", culname);
            }
        }
    }
}
</code>```

Can anyone help me to added this Maori locale support in MONO?

答:
I had the same problem when moving a program from Windows to linux.  In our case it was the PNG culture that was missing.  Could not find any way to easily add it to the OS like in Windows, so just modified an existing culture in the program.
For us, all we wanted was just same as Australian culture, but with a different currency symbol (Kina rather than Dollars).

Not sure if this is any help, but here is the code we use.

```<code>public static void Main (string[] args)
    {
        try
        {
            System.Globalization.CultureInfo cultureInfo = new CultureInfo("en-AU");
            cultureInfo.NumberFormat.CurrencySymbol = "K";
            Thread.CurrentThread.CurrentCulture = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            Application.Init ();

            cultureInfo = Thread.CurrentThread.CurrentCulture;
            Console.WriteLine ("Main-:");
            Console.WriteLine ("{0,-33}{1,-25}", "DisplayName", cultureInfo.DisplayName);
            Console.WriteLine ("{0,-33}{1,-25}", "CurrencySymbol", cultureInfo.NumberFormat.CurrencySymbol);

            MainWindow win = new MainWindow (args);
            win.Destroyed += new EventHandler(OnDestroyedEvent);
            win.Show ();
            Application.Run ();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Main exception: " + ex.Message);
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to MONO, I want to add new locale(Maori) support in MONO.

I am getting below exception:

CultureNotSupportedExceptionSystem.ArgumentException: Value does not fall within the expected range.
        at System.Globalization.CultureTableRecord..ctor(String cultureName, Boolean useUserOverride)
        at System.Globalization.CultureTableRecord.GetCultureTableRecord(String name, Boolean useUserOverride)
        at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
        at System.Globalization.CultureInfo..ctor(String name)
        at SmartDeviceProject2.Program.Main(String[] args)

Here test code:

namespace SmartDeviceProject2 {
    public class Program {
        public static void Main(string[] args) {
            CultureInfo cultureInfo = null;
            //string culname = "eu-ES"; //basque
            //string culname = "bg-BG"; //bulgarian - Culture found in CEOS
            string culname = "mi-NZ";   //maori
            //int culcode = 0x481;
            try {
                cultureInfo = new CultureInfo(culname);
            } catch (System.PlatformNotSupportedException e) {
                Console.WriteLine("PlatformNotSupportedException:{0}",e.ToString());
            } catch (System.ArgumentException e) {
                Console.WriteLine("CultureNotSupportedException{0}", e.ToString());
            }

            if (cultureInfo != null) {
                Console.WriteLine("Culture is found {0}", culname);
            } else {
                Console.WriteLine("Culture NOT found {0}", culname);
            }
        }
    }
}

Can anyone help me to added this Maori locale support in MONO?

Body:
I had the same problem when moving a program from Windows to linux.  In our case it was the PNG culture that was missing.  Could not find any way to easily add it to the OS like in Windows, so just modified an existing culture in the program.
For us, all we wanted was just same as Australian culture, but with a different currency symbol (Kina rather than Dollars).

Not sure if this is any help, but here is the code we use.

public static void Main (string[] args)
    {
        try
        {
            System.Globalization.CultureInfo cultureInfo = new CultureInfo("en-AU");
            cultureInfo.NumberFormat.CurrencySymbol = "K";
            Thread.CurrentThread.CurrentCulture = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            Application.Init ();

            cultureInfo = Thread.CurrentThread.CurrentCulture;
            Console.WriteLine ("Main-:");
            Console.WriteLine ("{0,-33}{1,-25}", "DisplayName", cultureInfo.DisplayName);
            Console.WriteLine ("{0,-33}{1,-25}", "CurrencySymbol", cultureInfo.NumberFormat.CurrencySymbol);

            MainWindow win = new MainWindow (args);
            win.Destroyed += new EventHandler(OnDestroyedEvent);
            win.Show ();
            Application.Run ();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Main exception: " + ex.Message);
        }
    }


问:
Updating an array element identified by other fields in the object using jq

Goal

I'd like to add a proxy-url field to the currently active clusters entry of my kubeconfig file. The "active" cluster is identified by the "active" context, which is itself identified by a top-level key current-context. Simplified, the JSON object looks something like:

{
  "clusters":[
    {
      "name":"cluster1",
      "field":"field1"
    },
    {
      "name":"cluster2",
      "field":"field2"
    }
  ],
  "contexts":[
    {
      "name":"context1",
      "context": {
        "cluster":"cluster1"
      }
    },
    {
      "name":"context2",
      "context": {
        "cluster":"cluster2"
      }
    }
  ],
  "current-context": "context1"
}
```
<p>And I'd like to update the <code>clusters</code> entry for <code>cluster1</code> from:</p>
<pre class="lang-json prettyprint-override"><code>{
  "name":"cluster1",
  "field":"field1"
}
</code>```

to

{
  "name":"cluster1",
  "field":"field1",
  "proxy-url":"my-url"
}
```
<h1>First attempt</h1>
<pre class="lang-sh prettyprint-override"><code>jq '. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o.clusters[] | select(.name == $context.context.cluster)
  | .proxy_id |= "my-url"'
</code>```

gives me

{
  "name": "cluster1",
  "field": "field1",
  "proxy_id": "my-url"
}
```
<p>-- great! But I need the rest of the object too.</p>
<h1>Parentheses almost work</h1>
<p>With parentheses, I can get the whole object back & add a "proxy-url" field to the active <em>context</em>, but I can't take it one step further to update the active <em>cluster</em>. This filter:</p>
<pre class="lang-sh prettyprint-override"><code>jq '(. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name)
  | ."proxy-url")
  |= "my-url"'
</code>```

works mint:

{
  "clusters": [...],  // omitted for brevity, unchanged
  "contexts": [
    {
      "name": "context1",
      "context": {
        "cluster": "cluster1"
      },
      "proxy-url": "my-url"  // tada!
    },
    {...}  // omitted for brevity, unchanged
  ],
  "current-context": "context1"
}
```
<p>Trying to take it one step further (to update the <code>cluster</code> identified by that <code>context</code>, instead):</p>
<pre class="lang-sh prettyprint-override"><code>jq '(. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o.clusters[] | select(.name == $context.context.cluster)
  | ."proxy-url")
  |= "my-url"'
</code>```

gives me the following error:

jq: error (at <stdin>:26): Invalid path expression near attempt to access element "clusters" of {"clusters":[{"name":"clus...
exit status 5
```
<p>How can I use the <code>$context.context.cluster</code> result to update the relevant <code>clusters</code> entry? I don't understand why this approach works for adding something to <code>contexts</code> but not to <code>clusters</code>.</p>
<h1>Dirty solution</h1>
<p>I can kludge together a new <code>clusters</code> entry & merge that with the top-level object:</p>
<pre class="lang-sh prettyprint-override"><code>jq '. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o + {"clusters": [($o.clusters[] | select(.name == $context.context.cluster)."proxy-url" |= "my-url")]}
</code>```

but this feels a bit fragile.

答:
This solution retrieves the active cluster using an INDEX construction, then just sets the new field directly without modifying the context:

jq '
  INDEX(.contexts[]; .name)[."current-context"].context.cluster as $cluster
  | (.clusters[] | select(.name == $cluster))."proxy-url" = "my-url"
'
```
<pre class="lang-json prettyprint-override"><code>{
  "clusters": [
    {
      "name": "cluster1",
      "field": "field1",
      "proxy-url": "my-url"
    },
    {
      "name": "cluster2",
      "field": "field2"
    }
  ],
  "contexts": [
    {
      "name": "context1",
      "context": {
        "cluster": "cluster1"
      }
    },
    {
      "name": "context2",
      "context": {
        "cluster": "cluster2"
      }
    }
  ],
  "current-context": "context1"
}
</code>```

Demo

Body:
Goal

I'd like to add a proxy-url field to the currently active clusters entry of my kubeconfig file. The "active" cluster is identified by the "active" context, which is itself identified by a top-level key current-context. Simplified, the JSON object looks something like:

{
  "clusters":[
    {
      "name":"cluster1",
      "field":"field1"
    },
    {
      "name":"cluster2",
      "field":"field2"
    }
  ],
  "contexts":[
    {
      "name":"context1",
      "context": {
        "cluster":"cluster1"
      }
    },
    {
      "name":"context2",
      "context": {
        "cluster":"cluster2"
      }
    }
  ],
  "current-context": "context1"
}

And I'd like to update the clusters entry for cluster1 from:

{
  "name":"cluster1",
  "field":"field1"
}

to

{
  "name":"cluster1",
  "field":"field1",
  "proxy-url":"my-url"
}

First attempt

jq '. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o.clusters[] | select(.name == $context.context.cluster)
  | .proxy_id |= "my-url"'

gives me

{
  "name": "cluster1",
  "field": "field1",
  "proxy_id": "my-url"
}

-- great! But I need the rest of the object too.

Parentheses almost work

With parentheses, I can get the whole object back & add a "proxy-url" field to the active context, but I can't take it one step further to update the active cluster. This filter:

jq '(. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name)
  | ."proxy-url")
  |= "my-url"'

works mint:

{
  "clusters": [...],  // omitted for brevity, unchanged
  "contexts": [
    {
      "name": "context1",
      "context": {
        "cluster": "cluster1"
      },
      "proxy-url": "my-url"  // tada!
    },
    {...}  // omitted for brevity, unchanged
  ],
  "current-context": "context1"
}

Trying to take it one step further (to update the cluster identified by that context, instead):

jq '(. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o.clusters[] | select(.name == $context.context.cluster)
  | ."proxy-url")
  |= "my-url"'

gives me the following error:

jq: error (at <stdin>:26): Invalid path expression near attempt to access element "clusters" of {"clusters":[{"name":"clus...
exit status 5

How can I use the $context.context.cluster result to update the relevant clusters entry? I don't understand why this approach works for adding something to contexts but not to clusters.

Dirty solution

I can kludge together a new clusters entry & merge that with the top-level object:

jq '. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o + {"clusters": [($o.clusters[] | select(.name == $context.context.cluster)."proxy-url" |= "my-url")]}

but this feels a bit fragile.

Body:
This solution retrieves the active cluster using an INDEX construction, then just sets the new field directly without modifying the context:

jq '
  INDEX(.contexts[]; .name)[."current-context"].context.cluster as $cluster
  | (.clusters[] | select(.name == $cluster))."proxy-url" = "my-url"
'

{
  "clusters": [
    {
      "name": "cluster1",
      "field": "field1",
      "proxy-url": "my-url"
    },
    {
      "name": "cluster2",
      "field": "field2"
    }
  ],
  "contexts": [
    {
      "name": "context1",
      "context": {
        "cluster": "cluster1"
      }
    },
    {
      "name": "context2",
      "context": {
        "cluster": "cluster2"
      }
    }
  ],
  "current-context": "context1"
}

Demo


问:
how to fix duplicate Displayed records in table in ASP.NET Core MVC?
I'm trying to display records to View but it shows duplicate records. I try to debug in the Controller, the records are correctly retrieved from the database no prob The problem is in the Views.</p>

```<code><tbody>
                @if (Model == null)
                {
                    <tr>
                        <td colspan="7" class="text-center">No Model Data</td>
                    </tr>
                }
                else
                {
                    @foreach (var list in Model)
                    {
                        <tr>
                        <td>@Html.DisplayFor(Model => list.EmployeeID)</td>
                        <td>@Html.DisplayFor(Model => list.EmployeeName)</td>
                        <td>@Html.DisplayFor(Model => list.Address)</td>
                        <td>@Html.DisplayFor(Model => list.Email)</td>
                        <td>@Html.DisplayFor(Model => list.ContactNo)</td>
                        <td>@Html.DisplayFor(Model => list.Gender)</td>
                        <td>@Html.DisplayFor(Model => list.Birthday)</td>
                        <td>@Html.DisplayFor(Model => list.Status)</td>
                        <td>@Html.DisplayFor(Model => list.Position)</td>
                        <td>@Html.DisplayFor(Model => list.Department)</td>
                        <td>
                            <button class="btn-default" asp-action="Update" asp-route-id="@list.EmployeeID">Edit</button>
                        </td>
                        <td>
                            <form asp-action="Delete" method="post" asp-route-id="@list.EmployeeID">
                                <button class="btn-danger">Delete</button>
                            </form>
                        </td>
                        </tr>
                    }
                }
                </tbody>
</code>```

答:
I experienced what I believe was a similar issue.

I believe the cause of the problem is how Visual Studio was reading the definition of the SQL Server view -- specifically the combination of columns that were identified as "Entity Keys".  I think Visual Studio simply finds all columns that are NOT NULL and sets them as Entity Keys.

In my case, I had a fairly complex SQL Server view (with multiple CTEs, a CROSS APPLY join, an EXCEPT sub-query, a UNION, and a couple LEFT OUTER JOINS).  This complex SQL Server view does return accurate data.  However, in the SQL Server view definition, some columns were defined as NULL when (logically) they will never actually be NULL.  I had to force the SQL Server view column definitions to be NOT NULL.  I had to use the SQL IsNull function.  For example: SELECT ISNULL(col1,'') AS col1...

I then dropped and re-added the SQL Server view to the Visual Studio entity framework model and verified the proper columns were marked as entity keys.

This fixed my problem.

Body:
I'm trying to display records to View but it shows duplicate records. I try to debug in the Controller, the records are correctly retrieved from the database no prob The problem is in the Views.

                @if (Model == null)
                {

                        No Model Data

                }
                else
                {
                    @foreach (var list in Model)
                    {

                        @Html.DisplayFor(Model => list.EmployeeID)
                        @Html.DisplayFor(Model => list.EmployeeName)
                        @Html.DisplayFor(Model => list.Address)
                        @Html.DisplayFor(Model => list.Email)
                        @Html.DisplayFor(Model => list.ContactNo)
                        @Html.DisplayFor(Model => list.Gender)
                        @Html.DisplayFor(Model => list.Birthday)
                        @Html.DisplayFor(Model => list.Status)
                        @Html.DisplayFor(Model => list.Position)
                        @Html.DisplayFor(Model => list.Department)

                            <button class="btn-default" asp-action="Update" asp-route-id="@list.EmployeeID">Edit</button>

                            <form asp-action="Delete" method="post" asp-route-id="@list.EmployeeID">
                                <button class="btn-danger">Delete</button>
                            </form>

                    }
                }


问:
How to delete a row in 2 tables which has the same id. How to use join
DELETE FROM tbl_usergroups,'tbl_group' WHERE (tbl_usergroups.tbl_group_GroupID='tbl_group.GroupID') AND(tbl_usergroups.tbl_group_GroupID=27)

GroupID is a foreign key to tbl_usergroups

答:
If you set the foreign key constraint to cascade on delete, the row in tbl_usergroups should automatically be deleted.

Failing that, you'd have to delete that entry first, and then delete the row in tbl_group once it is no longer referenced by a foreign key.


问:
when condition fails in ansible
I have a simple playbook that loads data to different instances based on the DEPLOY_TO environment variable that is entered from jenkins which has the value dev and test. By comparing the {{ lookup('env','DEPLOY_TO') }}  variable with dev or test using when condition

```<code>- name: load loadBase files into target mysql dev
  shell: mysql -h {{ lookup('env','db_host_dev') }} -u {{ lookup('env','db_user_dev') }} --password={{ lookup('env','db_root_password_dev') }} {{ lookup('env','db_name') }} < /tmp/{{ item | basename }}
  with_items: "{{ data.loadBase }}"
  no_log: false
  when: "{{ lookup('env','DEPLOY_TO') }} == dev"

- name: load loadBase files into target mysql test
  shell: mysql -h {{ lookup('env','db_host_test') }} -u {{ lookup('env','db_user_test') }} --password={{ lookup('env','db_root_password_test') }} {{ lookup('env','db_name') }} < /tmp/{{ item | basename }}
  with_items: "{{ data.loadBase }}"
  no_log: false
  when: "{{ lookup('env','DEPLOY_TO') }} == test"
</code>```

But when running the pipeline to DEPLOY_TO either dev or test, it fails with the following error

```<code>18:34:15  [WARNING]: conditional statements should not include jinja2 templating
18:34:15  delimiters such as {{ }} or {% %}. Found: {{ lookup('env','DEPLOY_TO') }} ==
18:34:15  dev
18:34:15  fatal: [10.0.1.78]: FAILED! => {
18:34:15      "msg": "The conditional check '{{ lookup('env','DEPLOY_TO') }} == dev' failed. The error was: error while evaluating conditional ({{ lookup('env','DEPLOY_TO') }} == dev): 'dev' is undefined\n\nThe error appears to be in '/home/deploy/jenkins/workspace/infrastructure/deploy.yml': line 77, column 11, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n        - name: load loadBase files into target mysql dev\n          ^ here\n"
</code>```

May I please know what am I doing wrong?

答:
You have two problems, both called out in the error messages. The first is:

```<code>conditional statements should not include jinja2 templating
</code>```

The value of a when condition is already evaluated in an implicit template context; you don't need (and shouldn't add) {{...}} markers around (or anywhere inside) the expression. That gets you:

```<code>  when: "lookup('env','DEPLOY_TO') == dev"
</code>```

That gets you to the second error:

```<code>The error was: error while evaluating conditional ({{ lookup('env','DEPLOY_TO') }} == dev): 'dev' is undefined
</code>```

You're comparing the result of the lookup to a variable named dev. If you meant to compare it to a literal string, you need to quote it (just like in the arguments to lookup):

```<code>  when: "lookup('env','DEPLOY_TO') == 'dev'"
</code>```

Title: when condition fails in ansible

Body:
I have a simple playbook that loads data to different instances based on the DEPLOY_TO environment variable that is entered from jenkins which has the value dev and test. By comparing the {{ lookup('env','DEPLOY_TO') }}  variable with dev or test using when condition

- name: load loadBase files into target mysql dev
  shell: mysql -h {{ lookup('env','db_host_dev') }} -u {{ lookup('env','db_user_dev') }} --password={{ lookup('env','db_root_password_dev') }} {{ lookup('env','db_name') }} < /tmp/{{ item | basename }}
  with_items: "{{ data.loadBase }}"
  no_log: false
  when: "{{ lookup('env','DEPLOY_TO') }} == dev"

- name: load loadBase files into target mysql test
  shell: mysql -h {{ lookup('env','db_host_test') }} -u {{ lookup('env','db_user_test') }} --password={{ lookup('env','db_root_password_test') }} {{ lookup('env','db_name') }} < /tmp/{{ item | basename }}
  with_items: "{{ data.loadBase }}"
  no_log: false
  when: "{{ lookup('env','DEPLOY_TO') }} == test"

But when running the pipeline to DEPLOY_TO either dev or test, it fails with the following error

18:34:15  [WARNING]: conditional statements should not include jinja2 templating
18:34:15  delimiters such as {{ }} or {% %}. Found: {{ lookup('env','DEPLOY_TO') }} ==
18:34:15  dev
18:34:15  fatal: [10.0.1.78]: FAILED! => {
18:34:15      "msg": "The conditional check '{{ lookup('env','DEPLOY_TO') }} == dev' failed. The error was: error while evaluating conditional ({{ lookup('env','DEPLOY_TO') }} == dev): 'dev' is undefined\n\nThe error appears to be in '/home/deploy/jenkins/workspace/infrastructure/deploy.yml': line 77, column 11, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n        - name: load loadBase files into target mysql dev\n          ^ here\n"

May I please know what am I doing wrong?

Body:
You have two problems, both called out in the error messages. The first is:

conditional statements should not include jinja2 templating

The value of a when condition is already evaluated in an implicit template context; you don't need (and shouldn't add) {{...}} markers around (or anywhere inside) the expression. That gets you:

  when: "lookup('env','DEPLOY_TO') == dev"

That gets you to the second error:

The error was: error while evaluating conditional ({{ lookup('env','DEPLOY_TO') }} == dev): 'dev' is undefined

You're comparing the result of the lookup to a variable named dev. If you meant to compare it to a literal string, you need to quote it (just like in the arguments to lookup):

  when: "lookup('env','DEPLOY_TO') == 'dev'"


问:
RNA to Protein simulation program's TypeErorr?
Here's what I'm doing:

```<code>
def dna_complement(dna):
  coup = ""
  for letter in dna:
    if letter == "C":
      coup += "G"
    if letter == "G":
      coup += "C"
    if letter == "A":
      coup += "T"
    if letter == "T":
      coup += "A"
  return coup

def convert_to_rna(dna):
  coup2 = ""
  for letter in dna:
    if letter == "C":
      coup2 += "G"
    if letter == "G":
      coup2 += "C"
    if letter == "A":
      coup2 += "U"
    if letter == "T":
      coup2 += "A"
  return coup2

def translate(rna):
  amino_acid = ""
  for len in rna:
    if range(0, len(rna), 3) == "UUU" :
      amino_acid = CODON_TABLE.get("UUU")
    if range(0, len(rna), 3) == "UUC" :
      amino_acid = CODON_TABLE.get("UUC")
    if range(0, len(rna), 3) == "UUA" :
      amino_acid = CODON_TABLE.get("UUA")

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

""" the rna is "UUCUCUACGGUAACAGGGGGCCGGAGGACGACGACGAGAAUCGCCCCGGUGUAGCCGGUGGCGACGGGACGGGGACCUCCCACCGGGGUGGCCGGCAAUGUCGCUCGUAUG" # This is already converted from DNA to RNA so there's no worry about the original RNA
"""

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC"

def main():
  print("\nWelcome to the DNA program: The Code of Life.")
  print("\nSample DNA strand:\n")
  print("Regular DNA:")
  print_bases(dna)
  print("DNA after complement: ")
  dna2 = dna_complement(dna)
  print_bases(dna2)
  print("DNA after RNA convertion: ")
  rna = convert_to_rna(dna)
  print_bases(rna)
  print("The result of translation: ")
  amino_acid = translate(rna)
  print(amino_acid)
</code>```

As in the image above. (Thanks to a user called Random Davis telling me to correct my mistake on the description, now I have everything I'm having right now in display which might be a little better)

When I tried to run this the Type Error telling me that str object is not callable, can someone help me with this?

More information: Sorry for not saying this earlier, I was trying to get the conversion like UUU <-> Phe, UUA <-> Leu, and AUU <-> Ile. And stop the protein from generating once it detected UAA, UAG, UGA.

答:
I would first rewrite your

```<code>range(0, len(rna), 3)
</code>```

Do you want to get 3 by 3 from your input? For example, if your input is "ABCDE", first you want "ABC", then you want "BCD", etc. Is that correct?

If so, I would do it like this:

```<code>p = rna[i:i+3]
</code>```

where rna is your input string.

Also, what do you want to do if you found UUU, UUC or UUA? What if you find all of them?

I hope you find this helpful.

```<code>def translate(rna):
  amino_acid = []
  for i in range(len(rna) - 2):
    p = rna[i:i+3]
    if p == "UUU" :
      amino_acid.append(CODON_TABLE["UUU"])
    if p == "UUC" :
      amino_acid.append(CODON_TABLE["UUC"])
    if p == "UUA" :
      amino_acid.append(CODON_TABLE["UUA"])

  return amino_acid

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

rna = "UUCUCUACGGUAACAGGGGGCCGGAGGACGACGACGAGAAUCGCCCCGGUGUAGCCGGUGGCGACGGGACGGGGACCUCCCACCGGGGUGGCCGGCAAUGUCGCUCGUAUG" # This is already converted from DNA to RNA so there's no worry about the original RNA

translate(rna)
</code>```

Notice that I am iterating over the input and ignoring the last two characters, that's the reason why we iterate till range(len(rna)-2).

Body:
Here's what I'm doing:

def dna_complement(dna):
  coup = ""
  for letter in dna:
    if letter == "C":
      coup += "G"
    if letter == "G":
      coup += "C"
    if letter == "A":
      coup += "T"
    if letter == "T":
      coup += "A"
  return coup

def convert_to_rna(dna):
  coup2 = ""
  for letter in dna:
    if letter == "C":
      coup2 += "G"
    if letter == "G":
      coup2 += "C"
    if letter == "A":
      coup2 += "U"
    if letter == "T":
      coup2 += "A"
  return coup2

def translate(rna):
  amino_acid = ""
  for len in rna:
    if range(0, len(rna), 3) == "UUU" :
      amino_acid = CODON_TABLE.get("UUU")
    if range(0, len(rna), 3) == "UUC" :
      amino_acid = CODON_TABLE.get("UUC")
    if range(0, len(rna), 3) == "UUA" :
      amino_acid = CODON_TABLE.get("UUA")

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

""" the rna is "UUCUCUACGGUAACAGGGGGCCGGAGGACGACGACGAGAAUCGCCCCGGUGUAGCCGGUGGCGACGGGACGGGGACCUCCCACCGGGGUGGCCGGCAAUGUCGCUCGUAUG" # This is already converted from DNA to RNA so there's no worry about the original RNA
"""

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC"

def main():
  print("\nWelcome to the DNA program: The Code of Life.")
  print("\nSample DNA strand:\n")
  print("Regular DNA:")
  print_bases(dna)
  print("DNA after complement: ")
  dna2 = dna_complement(dna)
  print_bases(dna2)
  print("DNA after RNA convertion: ")
  rna = convert_to_rna(dna)
  print_bases(rna)
  print("The result of translation: ")
  amino_acid = translate(rna)
  print(amino_acid)

As in the image above. (Thanks to a user called Random Davis telling me to correct my mistake on the description, now I have everything I'm having right now in display which might be a little better)

When I tried to run this the Type Error telling me that str object is not callable, can someone help me with this?

More information: Sorry for not saying this earlier, I was trying to get the conversion like UUU <-> Phe, UUA <-> Leu, and AUU <-> Ile. And stop the protein from generating once it detected UAA, UAG, UGA.

Body:
I would first rewrite your

range(0, len(rna), 3)

Do you want to get 3 by 3 from your input? For example, if your input is "ABCDE", first you want "ABC", then you want "BCD", etc. Is that correct?

If so, I would do it like this:

p = rna[i:i+3]

where rna is your input string.

Also, what do you want to do if you found UUU, UUC or UUA? What if you find all of them?

I hope you find this helpful.

def translate(rna):
  amino_acid = []
  for i in range(len(rna) - 2):
    p = rna[i:i+3]
    if p == "UUU" :
      amino_acid.append(CODON_TABLE["UUU"])
    if p == "UUC" :
      amino_acid.append(CODON_TABLE["UUC"])
    if p == "UUA" :
      amino_acid.append(CODON_TABLE["UUA"])

  return amino_acid

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

rna = "UUCUCUACGGUAACAGGGGGCCGGAGGACGACGACGAGAAUCGCCCCGGUGUAGCCGGUGGCGACGGGACGGGGACCUCCCACCGGGGUGGCCGGCAAUGUCGCUCGUAUG" # This is already converted from DNA to RNA so there's no worry about the original RNA

translate(rna)

Notice that I am iterating over the input and ignoring the last two characters, that's the reason why we iterate till range(len(rna)-2).


问:
Create and restore snapshot in Xcode 13 just like Android Studio with Android Emulator
I use Android Studio and Xcode to develop Android and iOS apps respectively.

When I use Android Studio, I can use an option to create a snapshot on android emulator. This way I can restore the snapshot and continue the development using the same data that stored in Sqlite database and SharedPreferences.

I use Xcode and want to replicate the behavior do the same process on the iOS simulator because I want to retain data in UserDefaults and the Sqlite database.

I see some options to do that in a very old version of Xcode, but can't find it in the Xcode 13 version.

Is it possible to create and restore a snapshot on Xcode 13 and iOS Simulator just like in Android Studio with Android Emulator ?

If is not possible, there is any other way or workaround to do something similar ?

答:
I found a workaround since I can't find a way to use snapshot with Xcode and
iOS Simulator.

I use the following code in my app:

```<code>print("home directory: \(NSHomeDirectory())" )
</code>```

This code shows where the iOS simulator folder of the app is located

With that information, I can find the database.sqlite file. I can copy and backup the file or edit the info inside direct in the database.sqlite file.

This way I can use the app and restore the database.sqlite when I want to.

After I edit some info in this file, I just need to remember to run the app again using Ctrl+R.

The same is valid with the file that contains the UserDefaults data stored by the app. This file is located inside
HomeDirectory/Library/Preferences/<app_bundle_id>.plist

You can edit and backup the file if you want, but if you modify the file, remember to run the app again with Xcode.

Body:
I found a workaround since I can't find a way to use snapshot with Xcode and
iOS Simulator.

I use the following code in my app:

print("home directory: \(NSHomeDirectory())" )

This code shows where the iOS simulator folder of the app is located

With that information, I can find the database.sqlite file. I can copy and backup the file or edit the info inside direct in the database.sqlite file.

This way I can use the app and restore the database.sqlite when I want to.

After I edit some info in this file, I just need to remember to run the app again using Ctrl+R.

The same is valid with the file that contains the UserDefaults data stored by the app. This file is located inside
HomeDirectory/Library/Preferences/<app_bundle_id>.plist

You can edit and backup the file if you want, but if you modify the file, remember to run the app again with Xcode.


问:
Conditional Formatting Cells in a Column Only Containing Letters F-Z Excluding RR
How could I highlight cells using conditional formatting if I want to only highlight cells containing letters F-Z? The formula would also need to exclude RR.

For example, if a cell in that column contains RR or any letter from A to E, I don't want to highlight it. But, if it contains any letter from F all the way to Z, I want it automatically highlighted.

Tried using regexmatch, but it's not working.

答:
use:

```<code>=REGEXMATCH(A2, "[F-Z]")*(REGEXMATCH(A2, "RR")=FALSE)
</code>```

Body:
use:

=REGEXMATCH(A2, "[F-Z]")*(REGEXMATCH(A2, "RR")=FALSE)


问:
CURL Request to Laravel API Returns NULL Values
I'm attempting to send an array of objects as part of a JSON request with curl.  The request must use json_encode in order to be sent by curl. However I am running into an issue on the Laravel API that is receiving it. Any attempt to get an object from the Request Laravel object returns null i.e.:

```<code>$request->order_number;
$request->items;
</code>```

This is the case for normal fields and the array of objects I am also sending.  The curl appears as:

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Accept: application/json'
));
</code>```

What is the mistake I am making?

EDIT:

To provide more specific information, here is the json_encode var dumped (some omissions):

string(694) "{"order_number":"11111","items":"[{"id":"1005","name":"UpRight 011238-004 Washer, Split Lock","sku":"","quantity":1,"price":0.01}]"}"

答:
The solution ended up being rather convoluted:

```<code>public function postOrderInformation(Request $data) {
        $request = json_decode(json_encode(json_decode($data->getContent(), true)));
}
</code>```

This created a useable object from which the data could be extracted from the laravel Requets object.  If anyone has a more elegant/less ugly solution, please post it.

Body:
I'm attempting to send an array of objects as part of a JSON request with curl.  The request must use json_encode in order to be sent by curl. However I am running into an issue on the Laravel API that is receiving it. Any attempt to get an object from the Request Laravel object returns null i.e.:

$request->order_number;
$request->items;

This is the case for normal fields and the array of objects I am also sending.  The curl appears as:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Accept: application/json'
));

What is the mistake I am making?

EDIT:

To provide more specific information, here is the json_encode var dumped (some omissions):

string(694) "{"order_number":"11111","items":"[{"id":"1005","name":"UpRight 011238-004 Washer, Split Lock","sku":"","quantity":1,"price":0.01}]"}"

Body:
The solution ended up being rather convoluted:

public function postOrderInformation(Request $data) {
        $request = json_decode(json_encode(json_decode($data->getContent(), true)));
}

This created a useable object from which the data could be extracted from the laravel Requets object.  If anyone has a more elegant/less ugly solution, please post it.


问:
How to remove MapBox logo from bottom left corner?
I'm embeding a MapBox map in my html page via mapbox.js script like so:

```<code>L.mapbox.accessToken = 'pk.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxx';
var map = L.mapbox.map('map', 'xxxxx.xxxxxxxx', {
    zoomControl: false
});
</code>```

This produces a map like this:
http://s4.postimg.org/58m4aeb8d/mapbox.png

How do I remove "Mapbox" logo in the bottom left corner?

答:
The Mapbox logo is a small image containing the stylized word "Mapbox". It typically resides on the bottom left corner of a map. While you may move the logo to a different corner of the map, we require the Mapbox logo to appear on our maps so that Mapbox and its maps get proper credit.

https://docs.mapbox.com/help/getting-started/attribution/

Body:
I'm embeding a MapBox map in my html page via mapbox.js script like so:

L.mapbox.accessToken = 'pk.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxx';
var map = L.mapbox.map('map', 'xxxxx.xxxxxxxx', {
    zoomControl: false
});

This produces a map like this:
http://s4.postimg.org/58m4aeb8d/mapbox.png

How do I remove "Mapbox" logo in the bottom left corner?


问:
How to define the the height of the csv table in reStructuredText?
I'm using this code to create a table from csv for my documentation in readthedocs:

```<code>.. csv-table:: Markram et al. Model & Network configuration file
   :file: ../config_files/Markram_config_file.csv
   :header-rows: 1
</code>```

The CSV is large and has a lot of rows and columns. For columns, everything is fine since it just fits a few columns in the page and the others can be accessed by scrolling to the right in the table.
However, all of the rows are placed in the the page and I cannot specify a particular "length" or "height" for the csv table.
I tried to specify the height by :height: 100px but it's not defined for the tables. Is there anyway to specify that? Here's a sample of what I'm using in the table.

答:
I added a file _static/css/custom.css with the following contents (inspired by https://stackoverflow.com/a/4457290/3362993):

table.docutils {
    display: block;
    height: <your_height>px;
    overflow-y: scroll;
    width: <your_width>%
  }
```
<p>and added the following line to <code>conf.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>html_css_files = [
    "css/custom.css",
]
</code>```

I found that the trailing list-comma was necessary for the css file to be recognized :shrug:

Body:
I'm using this code to create a table from csv for my documentation in readthedocs:

.. csv-table:: Markram et al. Model & Network configuration file
   :file: ../config_files/Markram_config_file.csv
   :header-rows: 1

The CSV is large and has a lot of rows and columns. For columns, everything is fine since it just fits a few columns in the page and the others can be accessed by scrolling to the right in the table.
However, all of the rows are placed in the the page and I cannot specify a particular "length" or "height" for the csv table.
I tried to specify the height by :height: 100px but it's not defined for the tables. Is there anyway to specify that? Here's a sample of what I'm using in the table.

Body:
I added a file _static/css/custom.css with the following contents (inspired by https://stackoverflow.com/a/4457290/3362993):

table.docutils {
    display: block;
    height: <your_height>px;
    overflow-y: scroll;
    width: <your_width>%
  }

and added the following line to conf.py:

html_css_files = [
    "css/custom.css",
]

I found that the trailing list-comma was necessary for the css file to be recognized :shrug:


问:
Are these 2 Java exam questions incorrect?
I recently did an exam related to Java that had 2 questions that in my opinion were wrong. I was hoping some of you could help me out.

The questions are:

1)

```<code>public class Cell {
    public Cell(){
    }
    public char content; //The character in this cell.
    public Cell next;  // Pointer to the cell to the right of this one.
    public Cell prev;  // Pointer to the cell to the left of this one.
}

// The following method is supposed to move one node to the right in a
// doubly linked list of Cells but it contains a flaw.
// The global variable 'currentCell' is a pointer to a Cell in the list.

public void moveRight(){
    if (currentCell.next == null){
        Cell newCell = new Cell();
        newCell.content = '';
        newCell.next = null;
        newCell.prev = currentCell;
        currentCell.next = newCell;
        currentCell = currentCell.next;
     }
 }
</code>```

True or False: If 'currentCell' is at the head of the list this moveRight()
method will perform its duties correctly.

For me, this question is False, as the moveRight method will not do anything because currentCell.next is NOT null when the pointer is at the head of the list. Its duties (move to the right) will not be successful.
I would like to know what the community thinks, because according to the exam this should be True?

2.

True or False: An interface contains method declarations as well as implementations.

I believe this should be True. As stated by Oracle (2021), “An interface declaration can contain method signatures, default methods, static methods, and constant definitions. The only methods that have implementations are default and static methods.”

Yet, the exam stated that the correct answer is False.

I hope someone could clarify this further for me.

Thank you!

答:
The problem with the method is not about the != null check: that will be true when currentCell is the last element of the list, and in that case there will be nothing to move (it cannot be moved right).

2.

The question should technically be True for newer versions of Java (after 2014 default methods implementation in Java 8), but (personally) I think the question was more about the essence of interfaces, that are used typically to abstract away from implementations, providing just method declarations.

Body:
I recently did an exam related to Java that had 2 questions that in my opinion were wrong. I was hoping some of you could help me out.

The questions are:

1)

public class Cell {
    public Cell(){
    }
    public char content; //The character in this cell.
    public Cell next;  // Pointer to the cell to the right of this one.
    public Cell prev;  // Pointer to the cell to the left of this one.
}

// The following method is supposed to move one node to the right in a
// doubly linked list of Cells but it contains a flaw.
// The global variable 'currentCell' is a pointer to a Cell in the list.

public void moveRight(){
    if (currentCell.next == null){
        Cell newCell = new Cell();
        newCell.content = '';
        newCell.next = null;
        newCell.prev = currentCell;
        currentCell.next = newCell;
        currentCell = currentCell.next;
     }
 }

True or False: If 'currentCell' is at the head of the list this moveRight()
method will perform its duties correctly.

For me, this question is False, as the moveRight method will not do anything because currentCell.next is NOT null when the pointer is at the head of the list. Its duties (move to the right) will not be successful.
I would like to know what the community thinks, because according to the exam this should be True?

2.

True or False: An interface contains method declarations as well as implementations.

I believe this should be True. As stated by Oracle (2021), “An interface declaration can contain method signatures, default methods, static methods, and constant definitions. The only methods that have implementations are default and static methods.”

Yet, the exam stated that the correct answer is False.

I hope someone could clarify this further for me.

Thank you!


问:
Image not taking full width of page
So I have the following html code

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}

.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #c5f3f7;
}

.banner {
  margin-top: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <title>HTML Layout</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header>
    <div class="logo">
      <img src="logo.png">
    </div>
    <nav class="navigation">
      <ul>
        <li>Home</li>
        <li>Products</li>
        <li>About</li>
        <li>News</li>
        <li>Contact</li>
      </ul>
    </nav>
  </header>
  <div class="banner">
    <img src="pagebanner.png" alt="page banner">
  </div>
</body>

</html></code>```

However the banner image does not take up the full width of the page. Instead, it is very small. I have tried doing width = 100% but this does not fix it. What can I do to make the banner image full width?

答:
One solution would be to make the image your background-image with the following styles associated. I inserted a dummy-image to reflect how your image would display.

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}

.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #c5f3f7;'
  height: 20vh;
}

.banner {
  background-image: url('https://dummyimage.com/600x400/000/fff&text=pagebanner');
  background-size: cover;
  background-position: center;
  height: 80vh;
}

body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <title>HTML Layout</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header>
    <div class="logo">
      <img src="logo.png">
    </div>
    <nav class="navigation">
      <ul>
        <li>Home</li>
        <li>Products</li>
        <li>About</li>
        <li>News</li>
        <li>Contact</li>
      </ul>
    </nav>
  </header>
  <div class="banner">
  </div>
</body>

</html></code>```

Title: Image not taking full width of page

Body:
So I have the following html code

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}

.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #c5f3f7;
}

.banner {
  margin-top: 30px;
}

<!doctype html>

  <title>HTML Layout</title>
  <link rel="stylesheet" href="style.css">

Home

Products

About

News

Contact

However the banner image does not take up the full width of the page. Instead, it is very small. I have tried doing width = 100% but this does not fix it. What can I do to make the banner image full width?

Body:
One solution would be to make the image your background-image with the following styles associated. I inserted a dummy-image to reflect how your image would display.

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}

.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #c5f3f7;'
  height: 20vh;
}

.banner {
  background-image: url('https://dummyimage.com/600x400/000/fff&text=pagebanner');
  background-size: cover;
  background-position: center;
  height: 80vh;
}

body {
  margin: 0;
}

<!doctype html>
<html>

<head>
  <title>HTML Layout</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header>
    <div class="logo">
      <img src="logo.png">
    </div>
    <nav class="navigation">
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="products.html">Products</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="news.html">News</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
    </nav>
  </header>
  <div class="banner">
  </div>
</body>

</html>


问:
How to detect change to update existing values with NULL
I need to update a table if an existing record has changes. If the record exists (APK is found), then update it if ID_NUMBER has changed. The problem is when the existing TARGET value is NOT NULL and the SOURCE value IS NULL. How can I detect that condition as unequal?

Using ISNULL() can work, but the second parameter must -not- ever occur in the data. That requires profiling all of the NUMERIC data. Can it bedone without that? In this case, zero (0) can work only if it never occurs in the data.

```<code>UPDATE T SET
    T.f1 = S.f1
FROM TARGET_TABLE T
    INNER JOIN SOURCE_TABLE S
    ON T.APK = S.APK
WHERE
    ISNULL(T.ID_NUMBER,0) <> ISNULL(S.ID_NUMBER,0)
;
</code>```

Here is the possible combinations of ID_NUMBER values in TARGET and SOURCE tables.

```<code>Target      Source
======      ======
NULL        NULL
NULL        7       -- should identify as unequal
7           NULL    -- should identify as unequal, BUT DOES NOT
7           7
</code>```

The following script shows the results. Only the third statement, comparing an existing TARGET value of 7 with the incoming SOURCE value of NULL will fail. Why is that? What code will work?

```<code>SET NOCOUNT ON;
SELECT 3 WHERE ISNULL(NULL, NULL+1) <> ISNULL(NULL,NULL+1);
GO
SELECT 3 WHERE ISNULL(NULL, 7+1) <> ISNULL(7,7+1);
GO
SELECT 3 WHERE ISNULL(7, NULL+1) <> ISNULL(NULL,NULL+1); -- WHY DOES THIS NOT SEE THE INEQUALITY?
GO
SELECT 3 WHERE ISNULL(7, 7+1) <> ISNULL(7,7+1);
GO
</code>```

Example execution:

```<code>1> SET NOCOUNT ON;
2> SELECT 3 WHERE ISNULL(NULL, NULL+1) <> ISNULL(NULL,NULL+1);
3> GO

-----------
1> SELECT 3 WHERE ISNULL(NULL, 7+1) <> ISNULL(7,7+1);
2> GO

-----------
          3
1> SELECT 3 WHERE ISNULL(7, NULL+1) <> ISNULL(NULL,NULL+1); -- WHY DOES THIS NOT SEE THE INEQUALITY?
2> GO

-----------
1> SELECT 3 WHERE ISNULL(7, 7+1) <> ISNULL(7,7+1);
2> GO

-----------
1>
</code>```

答:
Please try the following solution.

It is based on use of a checksum in CTEs via HASHBYTES() function.
This method is working with NULL values and multiple columns in the tables.

I added UpdatedOn column to show what column was updated.

SQL

```<code>-- DDL and sample data population, start
DECLARE @Table1 TABLE (APK INT IDENTITY PRIMARY KEY, ID_NUMBER INT, UpdatedOn DATETIMEOFFSET(3));
DECLARE @Table2 TABLE (APK INT IDENTITY PRIMARY KEY, ID_NUMBER INT, UpdatedOn DATETIMEOFFSET(3));

INSERT INTO @Table1 (ID_NUMBER)
  VALUES (null), (null), (7), (7), (5);

INSERT INTO @Table2 (ID_NUMBER)
  VALUES (null), (7), (null), (7), (4);
-- DDL and sample data population, end

WITH source AS
(
    SELECT sp.*, HASHBYTES('sha2_256', xmlcol) as [Checksum]
    FROM @Table1 sp
    CROSS APPLY (SELECT sp.* FOR XML RAW) x(xmlcol)
), target AS
(
    SELECT sp.*, HASHBYTES('sha2_256', xmlcol) as [Checksum]
    FROM @Table2 sp
    CROSS APPLY (SELECT sp.* FOR XML RAW) x(xmlcol)
)
UPDATE T
SET T.ID_NUMBER = S.ID_NUMBER
    , T.UpdatedOn = SYSDATETIMEOFFSET()
FROM TARGET AS T
    INNER JOIN SOURCE AS S
        ON T.APK = S.APK
WHERE T.[Checksum] <> S.[Checksum];

-- test
SELECT * FROM @Table2;
</code>```

Output

```<code>+-----+-----------+--------------------------------+
| APK | ID_NUMBER |           UpdatedOn            |
+-----+-----------+--------------------------------+
|   1 | NULL      | NULL                           |
|   2 | NULL      | 2022-02-09 18:58:10.336 -05:00 |
|   3 | 7         | 2022-02-09 18:58:10.336 -05:00 |
|   4 | 7         | NULL                           |
|   5 | 5         | 2022-02-09 18:58:10.336 -05:00 |
+-----+-----------+--------------------------------+
</code>```

Body:
I need to update a table if an existing record has changes. If the record exists (APK is found), then update it if ID_NUMBER has changed. The problem is when the existing TARGET value is NOT NULL and the SOURCE value IS NULL. How can I detect that condition as unequal?

Using ISNULL() can work, but the second parameter must -not- ever occur in the data. That requires profiling all of the NUMERIC data. Can it bedone without that? In this case, zero (0) can work only if it never occurs in the data.

UPDATE T SET
    T.f1 = S.f1
FROM TARGET_TABLE T
    INNER JOIN SOURCE_TABLE S
    ON T.APK = S.APK
WHERE
    ISNULL(T.ID_NUMBER,0) <> ISNULL(S.ID_NUMBER,0)
;

Here is the possible combinations of ID_NUMBER values in TARGET and SOURCE tables.

Target      Source
======      ======
NULL        NULL
NULL        7       -- should identify as unequal
7           NULL    -- should identify as unequal, BUT DOES NOT
7           7

The following script shows the results. Only the third statement, comparing an existing TARGET value of 7 with the incoming SOURCE value of NULL will fail. Why is that? What code will work?

SET NOCOUNT ON;
SELECT 3 WHERE ISNULL(NULL, NULL+1) <> ISNULL(NULL,NULL+1);
GO
SELECT 3 WHERE ISNULL(NULL, 7+1) <> ISNULL(7,7+1);
GO
SELECT 3 WHERE ISNULL(7, NULL+1) <> ISNULL(NULL,NULL+1); -- WHY DOES THIS NOT SEE THE INEQUALITY?
GO
SELECT 3 WHERE ISNULL(7, 7+1) <> ISNULL(7,7+1);
GO

Example execution:

1> SET NOCOUNT ON;
2> SELECT 3 WHERE ISNULL(NULL, NULL+1) <> ISNULL(NULL,NULL+1);
3> GO

-----------
1> SELECT 3 WHERE ISNULL(NULL, 7+1) <> ISNULL(7,7+1);
2> GO

-----------
          3
1> SELECT 3 WHERE ISNULL(7, NULL+1) <> ISNULL(NULL,NULL+1); -- WHY DOES THIS NOT SEE THE INEQUALITY?
2> GO

-----------
1> SELECT 3 WHERE ISNULL(7, 7+1) <> ISNULL(7,7+1);
2> GO

-----------
1>

Body:
Please try the following solution.

It is based on use of a checksum in CTEs via HASHBYTES() function.
This method is working with NULL values and multiple columns in the tables.

I added UpdatedOn column to show what column was updated.

SQL

-- DDL and sample data population, start
DECLARE @Table1 TABLE (APK INT IDENTITY PRIMARY KEY, ID_NUMBER INT, UpdatedOn DATETIMEOFFSET(3));
DECLARE @Table2 TABLE (APK INT IDENTITY PRIMARY KEY, ID_NUMBER INT, UpdatedOn DATETIMEOFFSET(3));

INSERT INTO @Table1 (ID_NUMBER)
  VALUES (null), (null), (7), (7), (5);

INSERT INTO @Table2 (ID_NUMBER)
  VALUES (null), (7), (null), (7), (4);
-- DDL and sample data population, end

WITH source AS
(
    SELECT sp.*, HASHBYTES('sha2_256', xmlcol) as [Checksum]
    FROM @Table1 sp
    CROSS APPLY (SELECT sp.* FOR XML RAW) x(xmlcol)
), target AS
(
    SELECT sp.*, HASHBYTES('sha2_256', xmlcol) as [Checksum]
    FROM @Table2 sp
    CROSS APPLY (SELECT sp.* FOR XML RAW) x(xmlcol)
)
UPDATE T
SET T.ID_NUMBER = S.ID_NUMBER
    , T.UpdatedOn = SYSDATETIMEOFFSET()
FROM TARGET AS T
    INNER JOIN SOURCE AS S
        ON T.APK = S.APK
WHERE T.[Checksum] <> S.[Checksum];

-- test
SELECT * FROM @Table2;

Output

+-----+-----------+--------------------------------+
| APK | ID_NUMBER |           UpdatedOn            |
+-----+-----------+--------------------------------+
|   1 | NULL      | NULL                           |
|   2 | NULL      | 2022-02-09 18:58:10.336 -05:00 |
|   3 | 7         | 2022-02-09 18:58:10.336 -05:00 |
|   4 | 7         | NULL                           |
|   5 | 5         | 2022-02-09 18:58:10.336 -05:00 |
+-----+-----------+--------------------------------+


问:
How do I declare the objects related to one class in other?
The error shows: no matching functions for call to birthday::birthday(). How else should I declare the objects of one class in another class?

```<code>#include <iostream>

using namespace std;

class birthday
{

public:

    birthday(int d,int m,int y)
    {
        date=d;
        month=m;
        year=y;
    }
    void printdate()
    {
        cout<<date<<"/"<<month<<"/"<<year<<endl;
    }

private:

    int date;
    int month;
    int year;
};

class person
{

public:

    person(string x)
    {
        name=x;
    }
    void printname()
    {
        cout<< "the birthday person is "<< name << " whose birthday is on "<< day.printdate();
    }

private:

    birthday day;
    string name;
};

int main()
{
   birthday b(10,11,2007);
   person p("Jessica");
   p.printname();
   return 0;
}
</code>```

答:
Just define a default constructor so you can make an object of type birthday without initializing it.

or  you can default initialize person type private data member day.

Body:
The error shows: no matching functions for call to birthday::birthday(). How else should I declare the objects of one class in another class?

#include <iostream>

using namespace std;

class birthday
{

public:

    birthday(int d,int m,int y)
    {
        date=d;
        month=m;
        year=y;
    }
    void printdate()
    {
        cout<<date<<"/"<<month<<"/"<<year<<endl;
    }

private:

    int date;
    int month;
    int year;
};

class person
{

public:

    person(string x)
    {
        name=x;
    }
    void printname()
    {
        cout<< "the birthday person is "<< name << " whose birthday is on "<< day.printdate();
    }

private:

    birthday day;
    string name;
};

int main()
{
   birthday b(10,11,2007);
   person p("Jessica");
   p.printname();
   return 0;
}


问:
How to return empty array in a case block?
working on a trigger in Postgres. Currently running into an issue where I'm trying to set a value as either an empty array or an array with just the one NEW value, depending on if there is a NEW value or not:

project_ids =
  CASE NEW.project_tracking_id
    WHEN null THEN ARRAY
    ELSE ARRAY[NEW.project_tracking_id]
  END
```
<p>"Set <code>project_ids</code> to either <code>[]</code> (if null) or <code>[NEW.project_tracking_id]</code>"</p>
<p>The else block works as expected and will store that new value as the first element in a new array. The <code>WHEN null THEN ARRAY</code> part does not work for me though. It just adds <code>null</code> to the array, producing <code>[null]</code>.</p>
<p>How do I specify that it should just be an empty array in that case? Not sure if this helps, but my <code>sequelize</code> type for that field is:</p>
<pre class="lang-js prettyprint-override"><code>type: Sequelize.ARRAY(Sequelize.STRING),
defaultValue: [],
</code>```

答:
The problem is that your CASE expression implicitly compares NEW.project_tracking_id = NULL, which is never true, even if the left side is NULL. Use the other form of CASE:

```<code>CASE WHEN NEW.project_tracking_id IS NULL
     THEN ARRAY[]::integer[]
     ELSE ARRAY[NEW.project_tracking_id]
END
</code>```

This assumes that the data type of NEW.project_tracking_id is integer; change the array type if that is not the case.

A shorter version of the above would be

```<code>coalesce(NEW.project_tracking_id, ARRAY[]::integer[])
</code>```

Body:
working on a trigger in Postgres. Currently running into an issue where I'm trying to set a value as either an empty array or an array with just the one NEW value, depending on if there is a NEW value or not:

project_ids =
  CASE NEW.project_tracking_id
    WHEN null THEN ARRAY
    ELSE ARRAY[NEW.project_tracking_id]
  END

"Set project_ids to either [] (if null) or [NEW.project_tracking_id]"

The else block works as expected and will store that new value as the first element in a new array. The WHEN null THEN ARRAY part does not work for me though. It just adds null to the array, producing [null].

How do I specify that it should just be an empty array in that case? Not sure if this helps, but my sequelize type for that field is:

type: Sequelize.ARRAY(Sequelize.STRING),
defaultValue: [],

Body:
The problem is that your CASE expression implicitly compares NEW.project_tracking_id = NULL, which is never true, even if the left side is NULL. Use the other form of CASE:

CASE WHEN NEW.project_tracking_id IS NULL
     THEN ARRAY[]::integer[]
     ELSE ARRAY[NEW.project_tracking_id]
END

This assumes that the data type of NEW.project_tracking_id is integer; change the array type if that is not the case.

A shorter version of the above would be

coalesce(NEW.project_tracking_id, ARRAY[]::integer[])


问:
.NET Core. Logs not sent to Loggly, while using Serilog
I have a small ASP.NET Core 3.1 project that should execute the Odata request and then log either info or exception into the Loggly. I'm using Serilog for this.

But for some reason, it only sends the very first message from the Program.cs only (Log.Debug($"DEBUG: Starting at:{DateTime.Now}");), but does not send anything other than that. While it works fine for the Console or File logging.
I have tried to fake an exception to trigger the Error logging. But nothing works (in the Loggly).

Any suggestions on why is that and how to make it work properly?

Here is my code:

Program.cs:

```<code>public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

        try
        {
            Log.Debug($"DEBUG: Starting at:{DateTime.Now}");
            CreateHostBuilder(args).Build().Run();
            Log.Debug($"DEBUG: Host created");
        }
        catch (Exception ex)
        {
            Log.Error("Oops something failed!");
            throw new Exception(ex.Message);
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .UseSerilog();
}
</code>```

Startup.cs:

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddDbContext<OdataTestObjectContext>(options =>
        {
            options.UseSqlServer(Configuration["ConnectionStrings:Database"]);
        });
        services.AddControllers().AddOData(opt =>
            opt.Filter().Expand().Select().OrderBy().Count().SetMaxTop(100)
                .AddRouteComponents("odata", GetEdmModel()));

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "OdataTest", Version = "v1" });
            c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
        });

        var appSettings = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
        var serilogConfig = new LoggerConfiguration().ReadFrom.Configuration(appSettings);
        services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(serilogConfig.CreateLogger(), true));

        services.AddMvc(opts => { opts.Filters.Add(new AutoLogAttribute()); });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger(c =>
            {
                c.RouteTemplate = "/swagger/{documentName}/swagger.json";
            });
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "OdataTest v1"));
        }

        app.UseHttpsRedirection();
        ////Send "~/$odata" to debug routing if enable the following middleware
        app.UseODataRouteDebug();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

    private static IEdmModel GetEdmModel()
    {
        var builder = new ODataConventionModelBuilder();
        var entitySet = builder.EntitySet<TestObject>("TestObjects");
        entitySet.EntityType.HasKey(entity => entity.Id);
        return builder.GetEdmModel();
    }
}
</code>```

Controller.cs

```<code>[ApiController]
[Route("OData")]
public class TestController : ODataController
{
    private readonly OdataTestObjectContext _context;
    private readonly ILogger<TestController> _logger;

    public TestController(ILogger<TestController> logger, OdataTestObjectContext context)
    {
        _context = context;
        _logger = logger;
    }

    [ApiExplorerSettings(IgnoreApi = true)]
    [EnableQuery]
    public IActionResult Get()
    {
        try
        {
            return Ok(_context.TestObjects);
        }
        catch (Exception ex)
        {
            _logger.LogError("Error happened for Default query! - {0}", ex.Message);
            throw new InvalidOperationException(ex.Message);
        }
    }

    [HttpGet("Top({top})")]
    [EnableQuery]
    public IEnumerable<TestObject> GetTop(int top)
    {
        return _context.TestObjects.OrderByDescending(x => x.Id).Take(top);
    }

    [HttpGet("Enumerable")]
    [EnableQuery]
    public IEnumerable<TestObject> Enumerable()
    {
        try
        {
            _logger.LogDebug("Executing ENUMERABLE now.");
            //string a = "asd";
            //int s = Convert.ToInt32(a);
            var results = _context.SaleInvoicesAndProducts.AsEnumerable();
            int z = 1;
            if (results.Any())
                z = 0;
            int i = 10 / z;
            return results;
        }
        catch (Exception ex)
        {
            _logger.LogError("Error happened for Enumerable query! - {0}", ex.Message);
            throw new Exception();
        }
    }
</code>```

AutoLogAttribute.cs  (this just outputs logs with some request's parameters):

```<code>   public class AutoLogAttribute : TypeFilterAttribute
    {
        public AutoLogAttribute() : base(typeof(AutoLogActionFilterImpl))
        {

        }

        private class AutoLogActionFilterImpl : IActionFilter
        {
            private readonly ILogger<AutoLogAttribute> _logger;
            public AutoLogActionFilterImpl(ILoggerFactory loggerFactory)
            {
                _logger = loggerFactory.CreateLogger<AutoLogAttribute>();
            }

            public void OnActionExecuting(ActionExecutingContext context)
            {
                // perform some business logic work
                _logger.LogInformation($"queryString: {context.HttpContext.Request.QueryString}");

                _logger.LogDebug($"queryString (Debug): {context.HttpContext.Request.QueryString}");
            }

            public void OnActionExecuted(ActionExecutedContext context)
            {
                //TODO: log body content and response as well
                _logger.LogInformation($"host: {context.HttpContext.Request.Host}");
                _logger.LogInformation($"patheAndQuery: {context.HttpContext.Request.GetEncodedPathAndQuery()}");

                _logger.LogDebug($"path (Debug): {context.HttpContext.Request.Path}");
                _logger.LogDebug($"host (Debug): {context.HttpContext.Request.Host}");
                _logger.LogDebug($"patheAndQuery (Debug): {context.HttpContext.Request.GetEncodedPathAndQuery()}");
            }
        }
    }
</code>```

appsetting.json

```<code>    {
      "Serilog": {
        "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Loggly" ],
        "MinimumLevel": {
          "Default": "Debug",
          "Override": {
            "Microsoft": "Debug",
            "System": "Debug"
          }
        },
        "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
        "WriteTo": [
          { "Name": "Console" },
          {
            "Name": "File",
            "Args": { "path": "C:\\ODATA\\log.json" }
          },
          {
            "Name": "Loggly",
            "Args": {
              "customerToken": "mytoken",
              "tags": "mytest"
            }
          }
        ],
    },
  "ConnectionStrings": {
    "Database": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=MyTestDB;Integrated Security=true;MultiSubnetFailover=True;MultipleActiveResultSets=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

    }
</code>```

答:
You can try to clear providers:

```<code> Host
  ****
 .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
        })
 .UseSerilog();
</code>```

Also, if you have configured logging on Host, you don't need to put the additional configuration into Startup.cs

Body:
I have a small ASP.NET Core 3.1 project that should execute the Odata request and then log either info or exception into the Loggly. I'm using Serilog for this.

But for some reason, it only sends the very first message from the Program.cs only (Log.Debug($"DEBUG: Starting at:{DateTime.Now}");), but does not send anything other than that. While it works fine for the Console or File logging.
I have tried to fake an exception to trigger the Error logging. But nothing works (in the Loggly).

Any suggestions on why is that and how to make it work properly?

Here is my code:

Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

        try
        {
            Log.Debug($"DEBUG: Starting at:{DateTime.Now}");
            CreateHostBuilder(args).Build().Run();
            Log.Debug($"DEBUG: Host created");
        }
        catch (Exception ex)
        {
            Log.Error("Oops something failed!");
            throw new Exception(ex.Message);
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .UseSerilog();
}

Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddDbContext<OdataTestObjectContext>(options =>
        {
            options.UseSqlServer(Configuration["ConnectionStrings:Database"]);
        });
        services.AddControllers().AddOData(opt =>
            opt.Filter().Expand().Select().OrderBy().Count().SetMaxTop(100)
                .AddRouteComponents("odata", GetEdmModel()));

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "OdataTest", Version = "v1" });
            c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
        });

        var appSettings = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
        var serilogConfig = new LoggerConfiguration().ReadFrom.Configuration(appSettings);
        services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(serilogConfig.CreateLogger(), true));

        services.AddMvc(opts => { opts.Filters.Add(new AutoLogAttribute()); });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger(c =>
            {
                c.RouteTemplate = "/swagger/{documentName}/swagger.json";
            });
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "OdataTest v1"));
        }

        app.UseHttpsRedirection();
        ////Send "~/$odata" to debug routing if enable the following middleware
        app.UseODataRouteDebug();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

    private static IEdmModel GetEdmModel()
    {
        var builder = new ODataConventionModelBuilder();
        var entitySet = builder.EntitySet<TestObject>("TestObjects");
        entitySet.EntityType.HasKey(entity => entity.Id);
        return builder.GetEdmModel();
    }
}

Controller.cs

[ApiController]
[Route("OData")]
public class TestController : ODataController
{
    private readonly OdataTestObjectContext _context;
    private readonly ILogger<TestController> _logger;

    public TestController(ILogger<TestController> logger, OdataTestObjectContext context)
    {
        _context = context;
        _logger = logger;
    }

    [ApiExplorerSettings(IgnoreApi = true)]
    [EnableQuery]
    public IActionResult Get()
    {
        try
        {
            return Ok(_context.TestObjects);
        }
        catch (Exception ex)
        {
            _logger.LogError("Error happened for Default query! - {0}", ex.Message);
            throw new InvalidOperationException(ex.Message);
        }
    }

    [HttpGet("Top({top})")]
    [EnableQuery]
    public IEnumerable<TestObject> GetTop(int top)
    {
        return _context.TestObjects.OrderByDescending(x => x.Id).Take(top);
    }

    [HttpGet("Enumerable")]
    [EnableQuery]
    public IEnumerable<TestObject> Enumerable()
    {
        try
        {
            _logger.LogDebug("Executing ENUMERABLE now.");
            //string a = "asd";
            //int s = Convert.ToInt32(a);
            var results = _context.SaleInvoicesAndProducts.AsEnumerable();
            int z = 1;
            if (results.Any())
                z = 0;
            int i = 10 / z;
            return results;
        }
        catch (Exception ex)
        {
            _logger.LogError("Error happened for Enumerable query! - {0}", ex.Message);
            throw new Exception();
        }
    }

AutoLogAttribute.cs  (this just outputs logs with some request's parameters):

   public class AutoLogAttribute : TypeFilterAttribute
    {
        public AutoLogAttribute() : base(typeof(AutoLogActionFilterImpl))
        {

        }

        private class AutoLogActionFilterImpl : IActionFilter
        {
            private readonly ILogger<AutoLogAttribute> _logger;
            public AutoLogActionFilterImpl(ILoggerFactory loggerFactory)
            {
                _logger = loggerFactory.CreateLogger<AutoLogAttribute>();
            }

            public void OnActionExecuting(ActionExecutingContext context)
            {
                // perform some business logic work
                _logger.LogInformation($"queryString: {context.HttpContext.Request.QueryString}");

                _logger.LogDebug($"queryString (Debug): {context.HttpContext.Request.QueryString}");
            }

            public void OnActionExecuted(ActionExecutedContext context)
            {
                //TODO: log body content and response as well
                _logger.LogInformation($"host: {context.HttpContext.Request.Host}");
                _logger.LogInformation($"patheAndQuery: {context.HttpContext.Request.GetEncodedPathAndQuery()}");

                _logger.LogDebug($"path (Debug): {context.HttpContext.Request.Path}");
                _logger.LogDebug($"host (Debug): {context.HttpContext.Request.Host}");
                _logger.LogDebug($"patheAndQuery (Debug): {context.HttpContext.Request.GetEncodedPathAndQuery()}");
            }
        }
    }

appsetting.json

    {
      "Serilog": {
        "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Loggly" ],
        "MinimumLevel": {
          "Default": "Debug",
          "Override": {
            "Microsoft": "Debug",
            "System": "Debug"
          }
        },
        "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
        "WriteTo": [
          { "Name": "Console" },
          {
            "Name": "File",
            "Args": { "path": "C:\\ODATA\\log.json" }
          },
          {
            "Name": "Loggly",
            "Args": {
              "customerToken": "mytoken",
              "tags": "mytest"
            }
          }
        ],
    },
  "ConnectionStrings": {
    "Database": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=MyTestDB;Integrated Security=true;MultiSubnetFailover=True;MultipleActiveResultSets=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

    }

Body:
You can try to clear providers:

 Host
  ****
 .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
        })
 .UseSerilog();

Also, if you have configured logging on Host, you don't need to put the additional configuration into Startup.cs