问:
ECHO program in C#
i'm trying to make a program in C# that behaves like the well-known echo command. Everything works fine except when I try to print a quoted String.

For example, in the echo command you type:

```<code>echo "Hello, world!"
</code>```

And you get as output:

```<code>"Hello, world"
</code>```

But when I run my program I get:

```<code>Hello, world!
</code>```

This is the code:

```<code>using System;

namespace CSharpEcho
{
    public class Echo
    {
        public static void Main(String[] argv)
        {
            Int32 ArgsLength = argv.Length;

            if(ArgsLength == 0)
                Console.WriteLine("You have to write something!");
            else
            {
                String Str = "";

                foreach(String args in argv)
                {
                    Str += args + " ";
                }

                Console.WriteLine(String.Format("{0}", Str));
            }
        }
    }
}
</code>```

答:
If you want your output to be "Hello, world". You can use something like this:</p>

```<code>var text = "\"Hello, World\"";
</code>```

Title: ECHO program in C#

Body:
i'm trying to make a program in C# that behaves like the well-known echo command. Everything works fine except when I try to print a quoted String.

For example, in the echo command you type:

echo "Hello, world!"

And you get as output:

"Hello, world"

But when I run my program I get:

Hello, world!

This is the code:

using System;

namespace CSharpEcho
{
    public class Echo
    {
        public static void Main(String[] argv)
        {
            Int32 ArgsLength = argv.Length;

            if(ArgsLength == 0)
                Console.WriteLine("You have to write something!");
            else
            {
                String Str = "";

                foreach(String args in argv)
                {
                    Str += args + " ";
                }

                Console.WriteLine(String.Format("{0}", Str));
            }
        }
    }
}

Body:
If you want your output to be "Hello, world". You can use something like this:

var text = "\"Hello, World\"";


来源: stackexchange

问:
Windows Event Viewer xPath query doesn't work on certain strings. Escape characters?
I am trying to return an event log entry from the Windows security log using xPath (in PowerShell, in Event Viewer UI) and not succeeding.

This query doesn't work, as it returns zero results event though there is are appropriate entries in the log:

```<code>Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']='-ExecutionPolicy ByPass -File Do-Something.ps1']]" -LogName Security
</code>```

The syntax of the query seems fine as changing the query value will return the expected results:

```<code>Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']='\??\C:\Windows\system32\conhost.exe 0xffffffff -ForceV1']]" -LogName Security
</code>```

Same results if formatted as -FilterXML.

Alternative query strategy works, though is not efficient at all with big logs:

```<code>Get-WinEvent -LogName Security | Where-Object -Property Message -match '-ExecutionPolicy ByPass -File Do-Something.ps1'
</code>```

So it seems that there is something in the xPath query value that is not quite kosher. I don't know what it is. What am I missing?

Here is EventData for the desired hit:

```<code>- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" />
  <EventID>4688</EventID>
  <Version>2</Version>
  <Level>0</Level>
  <Task>13312</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2020-02-19T15:17:13.982780900Z" />
  <EventRecordID>SCRUBBED</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="256" />
  <Channel>Security</Channel>
  <Computer>SCRUBBED</Computer>
  <Security />
  </System>
- <EventData>
  <Data Name="SubjectUserSid">SCRUBBED</Data>
  <Data Name="SubjectUserName">SCRUBBED</Data>
  <Data Name="SubjectDomainName">SCRUBBED</Data>
  <Data Name="SubjectLogonId">SCRUBBED</Data>
  <Data Name="NewProcessId">SCRUBBED</Data>
  <Data Name="NewProcessName">C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Data>
  <Data Name="TokenElevationType">%%1937</Data>
  <Data Name="ProcessId">0x41c</Data>
  <Data Name="CommandLine">-ExecutionPolicy ByPass -File Do-Something.ps1</Data>
  <Data Name="TargetUserSid">S-1-0-0</Data>
  <Data Name="TargetUserName">-</Data>
  <Data Name="TargetDomainName">-</Data>
  <Data Name="TargetLogonId">0x0</Data>
  <Data Name="ParentProcessName">C:\Windows\System32\gpscript.exe</Data>
  <Data Name="MandatoryLabel">SCRUBBED</Data>
  </EventData>
  </Event>
</code>```

Here is EventData for the other hit that works but isn't interesting to me:

```<code>- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" />
  <EventID>4688</EventID>
  <Version>2</Version>
  <Level>0</Level>
  <Task>13312</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2020-02-19T15:21:21.753690000Z" />
  <EventRecordID>SCRUBBED</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="96" />
  <Channel>Security</Channel>
  <Computer>SCRUBBED</Computer>
  <Security />
  </System>
- <EventData>
  <Data Name="SubjectUserSid">SCRUBBED</Data>
  <Data Name="SubjectUserName">SCRUBBED</Data>
  <Data Name="SubjectDomainName">SCRUBBED</Data>
  <Data Name="SubjectLogonId">SCRUBBED</Data>
  <Data Name="NewProcessId">SCRUBBED</Data>
  <Data Name="NewProcessName">C:\Windows\System32\conhost.exe</Data>
  <Data Name="TokenElevationType">%%1936</Data>
  <Data Name="ProcessId">0x690</Data>
  <Data Name="CommandLine">\??\C:\Windows\system32\conhost.exe 0xffffffff -ForceV1</Data>
  <Data Name="TargetUserSid">S-1-0-0</Data>
  <Data Name="TargetUserName">-</Data>
  <Data Name="TargetDomainName">-</Data>
  <Data Name="TargetLogonId">0x0</Data>
  <Data Name="ParentProcessName">C:\Program Files\Windows Defender\MpCmdRun.exe</Data>
  <Data Name="MandatoryLabel">SCRUBBED</Data>
  </EventData>
  </Event>
</code>```

答:
Enabling command line process auditing here to reproduce this:  https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing

Searching for the NewProcessName first:

```<code>$a = Get-WinEvent -FilterXPath "*[EventData[Data[@Name='NewProcessName']='C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe']]" Security
</code>```

And looking at the xml:

```<code>$a[1] | foreach { $xml = [xml]$_.toxml(); $xml.event.eventdata.data }

Name               #text
----               -----
SubjectUserSid     S-1-5-21-1528843147-373324174-1919417755-1001
SubjectUserName    admin
SubjectDomainName  DESKTOP-JQ7B7RP
SubjectLogonId     0x31db1a
NewProcessId       0x7c4
NewProcessName     C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
TokenElevationType %%1937
ProcessId          0x19d4
CommandLine         -ExecutionPolicy ByPass -File do-something.ps1
TargetUserSid      S-1-0-0
TargetUserName     -
TargetDomainName   -
TargetLogonId      0x0
ParentProcessName  C:\Windows\System32\gpscript.exe
MandatoryLabel     S-1-16-12288
</code>```

It looks like there's strangely a space at the beginning and the end of the CommandLine property.  The xml text is trimmed in event viewer.  The spaces are still there with $xml.save('file.xml').

```<code>$a[1] | foreach { $xml = [xml]$_.toxml(); $xml.event.eventdata.data } |
  where '#text' -match bypass | % { 'x' + $_.'#text' + 'x' }

x -ExecutionPolicy ByPass -File do-something.ps1 x
</code>```

I ran this script as a group policy powershell login script.

Thus after adding the extra spaces, the nested predicate xpath becomes:

```<code>Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']=' -executionpolicy bypass -file do-something.ps1 ']]" Security

   ProviderName: Microsoft-Windows-Security-Auditing

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
2/21/2020 3:16:13 PM          4688 Information      A new process has been created....
2/21/2020 3:16:06 PM          4688 Information      A new process has been created....
2/21/2020 3:03:24 PM          4688 Information      A new process has been created....
2/21/2020 2:54:16 PM          4688 Information      A new process has been created....
</code>```

Alternative less "nested" xpath expressions.  Functions like text() or substring() can't be used with windows logs, or "//" or "/Event", for some reason.

```<code>get-winevent security -FilterXPath "*/EventData/Data[@Name='CommandLine']=' -ExecutionPolicy ByPass -File Do-Something.ps1 '"
get-winevent security -FilterXPath "*/*/*[@Name='CommandLine']=' -ExecutionPolicy ByPass -File Do-Something.ps1 '"
get-winevent security -FilterXPath "Event/EventData/Data[@Name='CommandLine']=' -ExecutionPolicy ByPass -File Do-Something.ps1 '"
</code>```

In powershell 6 and above this can be reduced to:

```<code>get-winevent @{logname = 'security'; commandline = ' -executionpolicy bypass -file do-something.ps1 ' }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to return an event log entry from the Windows security log using xPath (in PowerShell, in Event Viewer UI) and not succeeding.

This query doesn't work, as it returns zero results event though there is are appropriate entries in the log:

Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']='-ExecutionPolicy ByPass -File Do-Something.ps1']]" -LogName Security

The syntax of the query seems fine as changing the query value will return the expected results:

Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']='\??\C:\Windows\system32\conhost.exe 0xffffffff -ForceV1']]" -LogName Security

Same results if formatted as -FilterXML.

Alternative query strategy works, though is not efficient at all with big logs:

Get-WinEvent -LogName Security | Where-Object -Property Message -match '-ExecutionPolicy ByPass -File Do-Something.ps1'

So it seems that there is something in the xPath query value that is not quite kosher. I don't know what it is. What am I missing?

Here is EventData for the desired hit:

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" />
  <EventID>4688</EventID>
  <Version>2</Version>
  <Level>0</Level>
  <Task>13312</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2020-02-19T15:17:13.982780900Z" />
  <EventRecordID>SCRUBBED</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="256" />
  <Channel>Security</Channel>
  <Computer>SCRUBBED</Computer>
  <Security />
  </System>
- <EventData>
  <Data Name="SubjectUserSid">SCRUBBED</Data>
  <Data Name="SubjectUserName">SCRUBBED</Data>
  <Data Name="SubjectDomainName">SCRUBBED</Data>
  <Data Name="SubjectLogonId">SCRUBBED</Data>
  <Data Name="NewProcessId">SCRUBBED</Data>
  <Data Name="NewProcessName">C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Data>
  <Data Name="TokenElevationType">%%1937</Data>
  <Data Name="ProcessId">0x41c</Data>
  <Data Name="CommandLine">-ExecutionPolicy ByPass -File Do-Something.ps1</Data>
  <Data Name="TargetUserSid">S-1-0-0</Data>
  <Data Name="TargetUserName">-</Data>
  <Data Name="TargetDomainName">-</Data>
  <Data Name="TargetLogonId">0x0</Data>
  <Data Name="ParentProcessName">C:\Windows\System32\gpscript.exe</Data>
  <Data Name="MandatoryLabel">SCRUBBED</Data>
  </EventData>
  </Event>

Here is EventData for the other hit that works but isn't interesting to me:

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" />
  <EventID>4688</EventID>
  <Version>2</Version>
  <Level>0</Level>
  <Task>13312</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2020-02-19T15:21:21.753690000Z" />
  <EventRecordID>SCRUBBED</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="96" />
  <Channel>Security</Channel>
  <Computer>SCRUBBED</Computer>
  <Security />
  </System>
- <EventData>
  <Data Name="SubjectUserSid">SCRUBBED</Data>
  <Data Name="SubjectUserName">SCRUBBED</Data>
  <Data Name="SubjectDomainName">SCRUBBED</Data>
  <Data Name="SubjectLogonId">SCRUBBED</Data>
  <Data Name="NewProcessId">SCRUBBED</Data>
  <Data Name="NewProcessName">C:\Windows\System32\conhost.exe</Data>
  <Data Name="TokenElevationType">%%1936</Data>
  <Data Name="ProcessId">0x690</Data>
  <Data Name="CommandLine">\??\C:\Windows\system32\conhost.exe 0xffffffff -ForceV1</Data>
  <Data Name="TargetUserSid">S-1-0-0</Data>
  <Data Name="TargetUserName">-</Data>
  <Data Name="TargetDomainName">-</Data>
  <Data Name="TargetLogonId">0x0</Data>
  <Data Name="ParentProcessName">C:\Program Files\Windows Defender\MpCmdRun.exe</Data>
  <Data Name="MandatoryLabel">SCRUBBED</Data>
  </EventData>
  </Event>

Body:
Enabling command line process auditing here to reproduce this:  https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing

Searching for the NewProcessName first:

$a = Get-WinEvent -FilterXPath "*[EventData[Data[@Name='NewProcessName']='C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe']]" Security

And looking at the xml:

$a[1] | foreach { $xml = [xml]$_.toxml(); $xml.event.eventdata.data }

Name               #text
----               -----
SubjectUserSid     S-1-5-21-1528843147-373324174-1919417755-1001
SubjectUserName    admin
SubjectDomainName  DESKTOP-JQ7B7RP
SubjectLogonId     0x31db1a
NewProcessId       0x7c4
NewProcessName     C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
TokenElevationType %%1937
ProcessId          0x19d4
CommandLine         -ExecutionPolicy ByPass -File do-something.ps1
TargetUserSid      S-1-0-0
TargetUserName     -
TargetDomainName   -
TargetLogonId      0x0
ParentProcessName  C:\Windows\System32\gpscript.exe
MandatoryLabel     S-1-16-12288

It looks like there's strangely a space at the beginning and the end of the CommandLine property.  The xml text is trimmed in event viewer.  The spaces are still there with $xml.save('file.xml').

$a[1] | foreach { $xml = [xml]$_.toxml(); $xml.event.eventdata.data } |
  where '#text' -match bypass | % { 'x' + $_.'#text' + 'x' }

x -ExecutionPolicy ByPass -File do-something.ps1 x

I ran this script as a group policy powershell login script.

Thus after adding the extra spaces, the nested predicate xpath becomes:

Get-WinEvent -FilterXPath "*[EventData[Data[@Name='CommandLine']=' -executionpolicy bypass -file do-something.ps1 ']]" Security

   ProviderName: Microsoft-Windows-Security-Auditing

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
2/21/2020 3:16:13 PM          4688 Information      A new process has been created....
2/21/2020 3:16:06 PM          4688 Information      A new process has been created....
2/21/2020 3:03:24 PM          4688 Information      A new process has been created....
2/21/2020 2:54:16 PM          4688 Information      A new process has been created....

Alternative less "nested" xpath expressions.  Functions like text() or substring() can't be used with windows logs, or "//" or "/Event", for some reason.

get-winevent security -FilterXPath "*/EventData/Data[@Name='CommandLine']=' -ExecutionPolicy ByPass -File Do-Something.ps1 '"
get-winevent security -FilterXPath "*/*/*[@Name='CommandLine']=' -ExecutionPolicy ByPass -File Do-Something.ps1 '"
get-winevent security -FilterXPath "Event/EventData/Data[@Name='CommandLine']=' -ExecutionPolicy ByPass -File Do-Something.ps1 '"

In powershell 6 and above this can be reduced to:

get-winevent @{logname = 'security'; commandline = ' -executionpolicy bypass -file do-something.ps1 ' }


问:
SwiftUI - Is there a popViewController equivalent in SwiftUI?
I was playing around with SwiftUI and want to be able to come back to the previous view when tapping a button, the same we use popViewController inside a UINavigationController.
Is there a provided way to do it so far ?

I've also tried to use NavigationDestinationLink to do so without success.

struct AView: View {
    var body: some View {
        NavigationView {
            NavigationButton(destination: BView()) {
                Text("Go to B")
            }
        }
    }
}

struct BView: View {
    var body: some View {
        Button(action: {
            // Trying to go back to the previous view
            // previously: navigationController.popViewController(animated: true)
        }) {
            Text("Come back to A")
        }
    }
}
```

答:
With State Variables. Try that.

```<code>struct ContentViewRoot: View {
    @State var pushed: Bool = false
    var body: some View {
        NavigationView{
            VStack{
                NavigationLink(destination:ContentViewFirst(pushed: self.$pushed), isActive: self.$pushed) { EmptyView() }
                    .navigationBarTitle("Root")
                Button("push"){
                    self.pushed = true
                }
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct ContentViewFirst: View {
    @Binding var pushed: Bool
    @State var secondPushed: Bool = false
    var body: some View {
        VStack{
            NavigationLink(destination: ContentViewSecond(pushed: self.$pushed, secondPushed: self.$secondPushed), isActive: self.$secondPushed) { EmptyView() }
                .navigationBarTitle("1st")
            Button("push"){
                self.secondPushed = true;
            }
        }
    }
}

struct ContentViewSecond: View {
    @Binding var pushed: Bool
    @Binding var secondPushed: Bool

    var body: some View {
        VStack{
            Spacer()
            Button("PopToRoot"){
                self.pushed = false
            } .navigationBarTitle("2st")

            Spacer()
            Button("Pop"){
                         self.secondPushed = false
                     } .navigationBarTitle("1st")
            Spacer()
        }
    }
}
</code>```

Body:
With State Variables. Try that.

struct ContentViewRoot: View {
    @State var pushed: Bool = false
    var body: some View {
        NavigationView{
            VStack{
                NavigationLink(destination:ContentViewFirst(pushed: self.$pushed), isActive: self.$pushed) { EmptyView() }
                    .navigationBarTitle("Root")
                Button("push"){
                    self.pushed = true
                }
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct ContentViewFirst: View {
    @Binding var pushed: Bool
    @State var secondPushed: Bool = false
    var body: some View {
        VStack{
            NavigationLink(destination: ContentViewSecond(pushed: self.$pushed, secondPushed: self.$secondPushed), isActive: self.$secondPushed) { EmptyView() }
                .navigationBarTitle("1st")
            Button("push"){
                self.secondPushed = true;
            }
        }
    }
}

struct ContentViewSecond: View {
    @Binding var pushed: Bool
    @Binding var secondPushed: Bool

    var body: some View {
        VStack{
            Spacer()
            Button("PopToRoot"){
                self.pushed = false
            } .navigationBarTitle("2st")

            Spacer()
            Button("Pop"){
                         self.secondPushed = false
                     } .navigationBarTitle("1st")
            Spacer()
        }
    }
}


问:
How can I send data via TCP
I have a client front panel that will send whatever button is being pressed over to the server which is listening for the signals. How should I send the signal?

block diagram of client

答: NI's Basic TCP/IP Communication in LabVIEW is a good place to start. Take whatever data you want to send over TCP and flatten to string. NI also has a good writeup on the concept of flattening. Simply unflatten from string on the receiving end.</p>

Title: How can I send data via TCP


问:
Get all Numbers that are not existing from a Microsoft SQL-VarChar-Column
I have a table with a Column for ID-Numbers that are not increased in single steps.

So there are Numbers that are not used and this i need. The Column is a VarChar-Column.

For Example:

Used Numbers in the table = 2, 5, 7, 9, 10 etc.

So i need a Query that gives me = 1, 3, 4, 6, 8 etc.

Pseudo-Code something like:

select numbers from Table NOT IN (select numbers from table)!

I have tried with NOT IN and NOT EXISTS, but nothing works.

Can someone help me to achieve this?

EDIT: Range of Numbers is from 0 to 99999999 !!!

答:
As you don't mention what the upper limit is, and recursive Common Table Expressions are inherently slow, you would likely be better off with a Tally to achieve this:

```<code>CREATE TABLE dbo.YourTable (ID int);

INSERT INTO dbo.YourTable (ID)
VALUES(1),(3),(5),(7),(9),(11),(13),(15),(216); --Big jump on purpose

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP (SELECT MAX(ID) FROM dbo.YourTable) --Limit the tally for performance
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3) --1000 rows, add more Ns for more rows
SELECT I AS ID
FROM Tally T
     LEFT JOIN dbo.YourTable YT ON T.I = YT.ID
WHERE YT.ID IS NULL;
</code>```

Warning: Based on the comment on another answer:

This is the right Direction. When I do it in my Situation, I get only 100 Numbers. But the Numbers have 8 Digits and there are MUCH more then 100 Numbers!

8 digits means you have IDs with a value of 10,000,000 (10 Million) plus. Creating over 10 million rows in a tally will be very IO intensive. I strongly suggest putting this into batches.

Edit2: Ok, the max (from a comment on this answer) is 99,999,999! This is information that definitely should have been in the question. This process must be batched or you will kill your transaction Logs.

Body:
As you don't mention what the upper limit is, and recursive Common Table Expressions are inherently slow, you would likely be better off with a Tally to achieve this:

CREATE TABLE dbo.YourTable (ID int);

INSERT INTO dbo.YourTable (ID)
VALUES(1),(3),(5),(7),(9),(11),(13),(15),(216); --Big jump on purpose

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP (SELECT MAX(ID) FROM dbo.YourTable) --Limit the tally for performance
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3) --1000 rows, add more Ns for more rows
SELECT I AS ID
FROM Tally T
     LEFT JOIN dbo.YourTable YT ON T.I = YT.ID
WHERE YT.ID IS NULL;

Warning: Based on the comment on another answer:

This is the right Direction. When I do it in my Situation, I get only 100 Numbers. But the Numbers have 8 Digits and there are MUCH more then 100 Numbers!

8 digits means you have IDs with a value of 10,000,000 (10 Million) plus. Creating over 10 million rows in a tally will be very IO intensive. I strongly suggest putting this into batches.

Edit2: Ok, the max (from a comment on this answer) is 99,999,999! This is information that definitely should have been in the question. This process must be batched or you will kill your transaction Logs.


问:
How to configure dotnet core 3 to serve up React SPA while using Http.sys and a URLPrefix?
After changing the URLPrefix I get the following error:

The SPA default page middleware could not return the default page
  '/index.html' because it was not found, and no other middleware handled the request.

Something thus is required to tell dotnet core about the prefix but I can't seem to find the right combination of settings.

Help much appreciated.

The code is below:

HostBuilder is setup with:

```<code>public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseHttpSys(options =>
        {
            options.AllowSynchronousIO = false;
            options.Authentication.Schemes = AuthenticationSchemes.None;
            options.Authentication.AllowAnonymous = true;
            options.MaxConnections = null;
            options.MaxRequestBodySize = 30000000;
            options.UrlPrefixes.Add("http://localhost:5005/Product/Site");
        });
        webBuilder.UseStartup<Startup>();
    });
</code>```

ConfigureServices:

```<code>public override void ConfigureServices(IServiceCollection services)
{
  services.AddRazorPages();

  services.AddSpaStaticFiles(configuration =>
  {
    configuration.RootPath = "ClientApp/build";
  });

  services.AddMvc();
  services.AddResponseCompression(opts =>
  {
    opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
              new[] { "application/octet-stream" });
  });
}
</code>```

And then Configure is:

```<code>      app.UseSpaStaticFiles();
      app.UseRouting();
      app.UseEndpoints
      (
        endpoints =>
        {
          endpoints.MapControllerRoute(
              name: "default",
              pattern: "{controller}/{action=Index}/{id?}");
        }
      );

      app.UseSpa(spa =>
      {
        //spa.Options.DefaultPage = reactPath + "/index.html";
        spa.Options.DefaultPage = "/index.html";

        spa.Options.SourcePath = "ClientApp";

      });
</code>```

答:
This appears to be an issue where the path to the actual static files is lost. In your StaticFilesOptions ensure that you are providing a File provider with the path to your index.html static files.

```<code>spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
            {
              FileProvider = new PhysicalFileProvider
              (
                @"<YourPath>"
              )
            }
</code>```

Further details for these options can be found in Microsoft's documentation.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

Body:
After changing the URLPrefix I get the following error:

The SPA default page middleware could not return the default page
  '/index.html' because it was not found, and no other middleware handled the request.

Something thus is required to tell dotnet core about the prefix but I can't seem to find the right combination of settings.

Help much appreciated.

The code is below:

HostBuilder is setup with:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseHttpSys(options =>
        {
            options.AllowSynchronousIO = false;
            options.Authentication.Schemes = AuthenticationSchemes.None;
            options.Authentication.AllowAnonymous = true;
            options.MaxConnections = null;
            options.MaxRequestBodySize = 30000000;
            options.UrlPrefixes.Add("http://localhost:5005/Product/Site");
        });
        webBuilder.UseStartup<Startup>();
    });

ConfigureServices:

public override void ConfigureServices(IServiceCollection services)
{
  services.AddRazorPages();

  services.AddSpaStaticFiles(configuration =>
  {
    configuration.RootPath = "ClientApp/build";
  });

  services.AddMvc();
  services.AddResponseCompression(opts =>
  {
    opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
              new[] { "application/octet-stream" });
  });
}

And then Configure is:

      app.UseSpaStaticFiles();
      app.UseRouting();
      app.UseEndpoints
      (
        endpoints =>
        {
          endpoints.MapControllerRoute(
              name: "default",
              pattern: "{controller}/{action=Index}/{id?}");
        }
      );

      app.UseSpa(spa =>
      {
        //spa.Options.DefaultPage = reactPath + "/index.html";
        spa.Options.DefaultPage = "/index.html";

        spa.Options.SourcePath = "ClientApp";

      });

Body:
This appears to be an issue where the path to the actual static files is lost. In your StaticFilesOptions ensure that you are providing a File provider with the path to your index.html static files.

spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
            {
              FileProvider = new PhysicalFileProvider
              (
                @"<YourPath>"
              )
            }

Further details for these options can be found in Microsoft's documentation.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1


问:
ORA-00904: invalid identifier
I tried to write the following inner join query using an Oracle database:

```<code> SELECT Employee.EMPLID as EmpID,
        Employee.FIRST_NAME AS Name,
        Team.DEPARTMENT_CODE AS TeamID,
        Team.Department_Name AS teamname
 FROM PS_TBL_EMPLOYEE_DETAILS Employee
 INNER JOIN PS_TBL_DEPARTMENT_DETAILS Team
 ON Team.DEPARTMENT_CODE = Employee.DEPTID
</code>```

That gives the below error:

```<code> INNER JOIN PS_TBL_DEPARTMENT_DETAILS Team ON Team.DEPARTMENT_CODE = Employee.DEPTID
                                              *
ERROR at line 4:
ORA-00904: "TEAM"."DEPARTMENT_CODE": invalid identifier
</code>```

The DDL of one table is:

```<code>CREATE TABLE "HRMS"."PS_TBL_DEPARTMENT_DETAILS"
(
  "Company Code" VARCHAR2(255),
  "Company Name" VARCHAR2(255),
  "Sector_Code" VARCHAR2(255),
  "Sector_Name" VARCHAR2(255),
  "Business_Unit_Code" VARCHAR2(255),
  "Business_Unit_Name" VARCHAR2(255),
  "Department_Code" VARCHAR2(255),
  "Department_Name" VARCHAR2(255),
  "HR_ORG_ID" VARCHAR2(255),
  "HR_ORG_Name" VARCHAR2(255),
  "Cost_Center_Number" VARCHAR2(255),
  " " VARCHAR2(255)
)
SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS
</code>```

答:
Your problem is those pernicious double quotes.

```<code>SQL> CREATE TABLE "APC"."PS_TBL_DEPARTMENT_DETAILS"
  2  (
  3    "Company Code" VARCHAR2(255),
  4    "Company Name" VARCHAR2(255),
  5    "Sector_Code" VARCHAR2(255),
  6    "Sector_Name" VARCHAR2(255),
  7    "Business_Unit_Code" VARCHAR2(255),
  8    "Business_Unit_Name" VARCHAR2(255),
  9    "Department_Code" VARCHAR2(255),
 10    "Department_Name" VARCHAR2(255),
 11    "HR_ORG_ID" VARCHAR2(255),
 12    "HR_ORG_Name" VARCHAR2(255),
 13    "Cost_Center_Number" VARCHAR2(255),
 14    " " VARCHAR2(255)
 15  )
 16  /

Table created.

SQL>
</code>```

Oracle SQL allows us to ignore the case of database object names provided we either create them with names all in upper case, or without using double quotes.  If we use mixed case or  lower case in the script and wrapped the identifiers in double quotes we are condemned to using double quotes and the precise case whenever we refer to the object or its attributes:

```<code>SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
  2  where Department_Code = 'BAH'
  3  /
where Department_Code = 'BAH'
      *
ERROR at line 2:
ORA-00904: "DEPARTMENT_CODE": invalid identifier

SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
  2  where "Department_Code" = 'BAH'
  3  /

  COUNT(*)
----------
         0

SQL>
</code>```

tl;dr

don't use double quotes in DDL scripts

(I know most third party code generators do, but they are disciplined enough to put all their object names in UPPER CASE.)

The reverse is also true. If we create the table without using double-quotes …

```<code>create table PS_TBL_DEPARTMENT_DETAILS
( company_code VARCHAR2(255),
  company_name VARCHAR2(255),
  Cost_Center_Number VARCHAR2(255))
;
</code>```

… we can reference it and its columns in whatever case takes our fancy:

```<code>select * from ps_tbl_department_details
</code>```

… or

```<code>select * from PS_TBL_DEPARTMENT_DETAILS;
</code>```

… or

```<code>select * from PS_Tbl_Department_Details
where COMAPNY_CODE = 'ORCL'
and cost_center_number = '0980'
</code>```

ContentLicense: CC BY-SA 3.0

Title: ORA-00904: invalid identifier

Body:
I tried to write the following inner join query using an Oracle database:

 SELECT Employee.EMPLID as EmpID,
        Employee.FIRST_NAME AS Name,
        Team.DEPARTMENT_CODE AS TeamID,
        Team.Department_Name AS teamname
 FROM PS_TBL_EMPLOYEE_DETAILS Employee
 INNER JOIN PS_TBL_DEPARTMENT_DETAILS Team
 ON Team.DEPARTMENT_CODE = Employee.DEPTID

That gives the below error:

 INNER JOIN PS_TBL_DEPARTMENT_DETAILS Team ON Team.DEPARTMENT_CODE = Employee.DEPTID
                                              *
ERROR at line 4:
ORA-00904: "TEAM"."DEPARTMENT_CODE": invalid identifier

The DDL of one table is:

CREATE TABLE "HRMS"."PS_TBL_DEPARTMENT_DETAILS"
(
  "Company Code" VARCHAR2(255),
  "Company Name" VARCHAR2(255),
  "Sector_Code" VARCHAR2(255),
  "Sector_Name" VARCHAR2(255),
  "Business_Unit_Code" VARCHAR2(255),
  "Business_Unit_Name" VARCHAR2(255),
  "Department_Code" VARCHAR2(255),
  "Department_Name" VARCHAR2(255),
  "HR_ORG_ID" VARCHAR2(255),
  "HR_ORG_Name" VARCHAR2(255),
  "Cost_Center_Number" VARCHAR2(255),
  " " VARCHAR2(255)
)
SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS

Body:
Your problem is those pernicious double quotes.

SQL> CREATE TABLE "APC"."PS_TBL_DEPARTMENT_DETAILS"
  2  (
  3    "Company Code" VARCHAR2(255),
  4    "Company Name" VARCHAR2(255),
  5    "Sector_Code" VARCHAR2(255),
  6    "Sector_Name" VARCHAR2(255),
  7    "Business_Unit_Code" VARCHAR2(255),
  8    "Business_Unit_Name" VARCHAR2(255),
  9    "Department_Code" VARCHAR2(255),
 10    "Department_Name" VARCHAR2(255),
 11    "HR_ORG_ID" VARCHAR2(255),
 12    "HR_ORG_Name" VARCHAR2(255),
 13    "Cost_Center_Number" VARCHAR2(255),
 14    " " VARCHAR2(255)
 15  )
 16  /

Table created.

SQL>

Oracle SQL allows us to ignore the case of database object names provided we either create them with names all in upper case, or without using double quotes.  If we use mixed case or  lower case in the script and wrapped the identifiers in double quotes we are condemned to using double quotes and the precise case whenever we refer to the object or its attributes:

SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
  2  where Department_Code = 'BAH'
  3  /
where Department_Code = 'BAH'
      *
ERROR at line 2:
ORA-00904: "DEPARTMENT_CODE": invalid identifier

SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
  2  where "Department_Code" = 'BAH'
  3  /

  COUNT(*)
----------
         0

SQL>

tl;dr

don't use double quotes in DDL scripts

(I know most third party code generators do, but they are disciplined enough to put all their object names in UPPER CASE.)

The reverse is also true. If we create the table without using double-quotes …

create table PS_TBL_DEPARTMENT_DETAILS
( company_code VARCHAR2(255),
  company_name VARCHAR2(255),
  Cost_Center_Number VARCHAR2(255))
;

… we can reference it and its columns in whatever case takes our fancy:

select * from ps_tbl_department_details

… or

select * from PS_TBL_DEPARTMENT_DETAILS;

… or

select * from PS_Tbl_Department_Details
where COMAPNY_CODE = 'ORCL'
and cost_center_number = '0980'


问:
Override http status code from 404 to 200
All pages of my website will be accessible by 2 urls: one is normal english and one - IDN. Example:

```<code>www.example.com/examplepage
пример.рф/примерстраницы
</code>```

On server I just have english files, so I decided to create 2 arrays in php:

```<code>$realUrl=array('examplepage');
$fakeUrl=array('примерстраницы');
</code>```

And check in 404.php file: if user requests url from $fakeUrl array - I just include a page from $realUrl and changes http status code to 200 (NO redirect, so he sees his IDN request in address bar). Is it a good way? Everything works but I am not able to change a response code of such page, I've tried both:

```<code>header("HTTP/1.1 200 OK");
http_response_code(200);
</code>```

but response code is still 404.

答:
This works How can I replace Apache HTTP code 404 to 200

```<code><?php header("Status: 200 OK"); ?>
</code>```

This code has to be put at the top of the .php file in the first line of code. Search engines, crawlers, browsers and anyone accessing the site will see the errordocument 404 page as a header 200.

Header 200 means the page exists. Google will crawl and index sites with header status 200.

Body:
All pages of my website will be accessible by 2 urls: one is normal english and one - IDN. Example:

www.example.com/examplepage
пример.рф/примерстраницы

On server I just have english files, so I decided to create 2 arrays in php:

$realUrl=array('examplepage');
$fakeUrl=array('примерстраницы');

And check in 404.php file: if user requests url from $fakeUrl array - I just include a page from $realUrl and changes http status code to 200 (NO redirect, so he sees his IDN request in address bar). Is it a good way? Everything works but I am not able to change a response code of such page, I've tried both:

header("HTTP/1.1 200 OK");
http_response_code(200);

but response code is still 404.

Body:
This works How can I replace Apache HTTP code 404 to 200

<?php header("Status: 200 OK"); ?>

This code has to be put at the top of the .php file in the first line of code. Search engines, crawlers, browsers and anyone accessing the site will see the errordocument 404 page as a header 200.

Header 200 means the page exists. Google will crawl and index sites with header status 200.


问:
Owned types collection is never updated in EF Core
I have an aggregate defined like this:

```<code>public class Product {
    public int LocalId { get; private set; }
    public Something Something { get; private set; }
    public ICollection<Price> Prices { get; private set; }
}

public class Something {
    public string Name { get; set; }
}

public class Price {
    public int Type { get; set; }
    public decimal Value { get; set; }
}
</code>```

And a schema defined like this:

```<code>private void DefineProduct(ModelBuilder builder) =>
    builder
        .Entity<Product>(builder =>
        {
            builder.HasKey(p => p.LocalId);
            builder
                .OwnsOne(p => p.Something, smth =>
                {
                    smth.ToTable("somethings");
                })
                .OwnsMany(p => p.Prices, pp =>
                {
                    pp.ToTable("prices");
                });
        });
</code>```

When a price change is requested, I do this (inside the product method not included here for brevity):

```<code>Prices.First(p => p.Type == type).Value = newValue;
</code>```

And then I try to save the product like this:

```<code>public async Task UpdateProperties(Product product, IEnumerable<object> props)
{
    _context.Attach(product);
    _context.Update(product);

    foreach (var prop in props)
    {
        _context.Update(prop);
    }

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Who the hell allowed such a bug to go into a production release?");
    }
}
</code>```

Now I should mention that the product comes in from an initial query whose results were not tracked (via AsNoTracking() call), that's why I'm calling the Attach method in the first line of the method body. The problem is that I'm hitting that catch statement with an exception message saying:

Database operation expected to affect 1 row(s) but actually affected 0
  row(s). Data may have been modified or deleted since entities were
  loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for
  information on understanding and handling optimistic concurrency
  exceptions."}

The thing is that I'm not updating the same product anywhere else and that's the only place touching it. Also I use AsNoTracking as the default. If I comment out the line with _context.Update(prop);, then there's no exception raised, but the price is not being updated. Also, if I don't update that prices collection but the Something property, everything goes well. What. The. Hell.

答: I'm posting this answer for the future lost travelers out there, although I would gladly hear an explanation from someone who knows more than me about EF Core. I also think I understand the reason for that behavior, but I'm not sure. My code started behaving properly when I added an Id field on the Price object. My suspicion is that without an explicitly visible id property, no amount of attaching or updating would make EF see and that object. I would welcome a documentation section about it though...

Body:
I have an aggregate defined like this:

public class Product {
    public int LocalId { get; private set; }
    public Something Something { get; private set; }
    public ICollection<Price> Prices { get; private set; }
}

public class Something {
    public string Name { get; set; }
}

public class Price {
    public int Type { get; set; }
    public decimal Value { get; set; }
}

And a schema defined like this:

private void DefineProduct(ModelBuilder builder) =>
    builder
        .Entity<Product>(builder =>
        {
            builder.HasKey(p => p.LocalId);
            builder
                .OwnsOne(p => p.Something, smth =>
                {
                    smth.ToTable("somethings");
                })
                .OwnsMany(p => p.Prices, pp =>
                {
                    pp.ToTable("prices");
                });
        });

When a price change is requested, I do this (inside the product method not included here for brevity):

Prices.First(p => p.Type == type).Value = newValue;

And then I try to save the product like this:

public async Task UpdateProperties(Product product, IEnumerable<object> props)
{
    _context.Attach(product);
    _context.Update(product);

    foreach (var prop in props)
    {
        _context.Update(prop);
    }

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Who the hell allowed such a bug to go into a production release?");
    }
}

Now I should mention that the product comes in from an initial query whose results were not tracked (via AsNoTracking() call), that's why I'm calling the Attach method in the first line of the method body. The problem is that I'm hitting that catch statement with an exception message saying:

Database operation expected to affect 1 row(s) but actually affected 0
  row(s). Data may have been modified or deleted since entities were
  loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for
  information on understanding and handling optimistic concurrency
  exceptions."}

The thing is that I'm not updating the same product anywhere else and that's the only place touching it. Also I use AsNoTracking as the default. If I comment out the line with _context.Update(prop);, then there's no exception raised, but the price is not being updated. Also, if I don't update that prices collection but the Something property, everything goes well. What. The. Hell.


问:
HTML Form Textarea carriage return causing Line breaks when read
I have a basic textarea inside a HTML Form like this:

```<code><textarea id="description" name="description"></textarea>
</code>```

When text is inputted and submitted, it is sent to an SQL Database on an Amazon web server.

In my iOS App, I run a php file which returns a jSON Object which contains the content of this database.

When I print the content of this database in my App there are line breaks whenever a carriage return occurred in the textarea.

So the input box looks something like this:

Now, I never hit the Enter key once. These carriage returns happen automatically inside the input box.

And when I read the String in the app it looks something like this:

```<code>This is a multiline test to

check that everything is

working fine.
</code>```

How do I ignore these returns and store the text in the database as if it were one straight line of text.

I want it to look like this:

```<code>This is a multiline test to check that everything is working fine.
</code>```

Do I need to do this at the iOS end? Or the HTML end? Or the PHP end?

答:
Just change the replace as suggested to remove one of the two carriage return (\r or \n as you need)
For example:

```<code>preg_replace('/\n/', '',$description)
</code>```

for the new line only

Body:
I have a basic textarea inside a HTML Form like this:

<textarea id="description" name="description"></textarea>

When text is inputted and submitted, it is sent to an SQL Database on an Amazon web server.

In my iOS App, I run a php file which returns a jSON Object which contains the content of this database.

When I print the content of this database in my App there are line breaks whenever a carriage return occurred in the textarea.

So the input box looks something like this:

Now, I never hit the Enter key once. These carriage returns happen automatically inside the input box.

And when I read the String in the app it looks something like this:

This is a multiline test to

check that everything is

working fine.

How do I ignore these returns and store the text in the database as if it were one straight line of text.

I want it to look like this:

This is a multiline test to check that everything is working fine.

Do I need to do this at the iOS end? Or the HTML end? Or the PHP end?

Body:
Just change the replace as suggested to remove one of the two carriage return (\r or \n as you need)
For example:

preg_replace('/\n/', '',$description)

for the new line only


问:
redirect user on previous page after successfull task
What should be good way to redirect user after successful action like edit or delete any item, in delete condition we could use $_SERVER['HTTP_REFERER'] but in case of edit, we show first of all edit form and then user clicks update, so if we use same approach user would be redirected to edit page not main page. I hope you got idea about my confusion. thanks.

答:
Similar to the previous answer, I would suggest keeping track of the page you wish to redirect to using sessions., and then once you want to redirect, just use

```<code>header('Location: '.$redirect_var);
</code>```

The reason why I would put it in the session, rather than posting in a form, is that form posting can be manipulated by the user, whereas sessions are server side, and are entirely under your own control.

Body:
Similar to the previous answer, I would suggest keeping track of the page you wish to redirect to using sessions., and then once you want to redirect, just use

header('Location: '.$redirect_var);

The reason why I would put it in the session, rather than posting in a form, is that form posting can be manipulated by the user, whereas sessions are server side, and are entirely under your own control.


问:
How to remove menu header in php?
I have menu header in my php that I'd like to remove.How?

PHP:

```<code>if ( ! empty( $item->attr_title ) ) {
            $item_output .= '<a' . $attributes . '><span class="glyphicon ' . esc_attr( $item->attr_title ) . '"></span> ';
        } else {
            $item_output .= '<a' . $attributes . '>';
        }

        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= ( $args->has_children ) ? ' </a><span class="dropdown-toggle shapely-dropdown" data-toggle="dropdown"><i class="fa fa-angle-down" aria-hidden="true"></i></span>' : '</a>';
        $item_output .= $args->after;

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }// End if().
}
</code>```

HTML Output:

```<code><div class="collapse navbar-collapse navbar-ex1-collapse"><ul id="menu" class="menu"><li id="menu-item-3530" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-3530 dropdown"><a title="Contact" href="https://4309.co.uk/contact/">Contact </a><span class="dropdown-toggle shapely-dropdown" data-toggle="dropdown"><i class="fa fa-angle-down"  aria-hidden="true"></i></span>
</code>```

The header menu item is contact along with fa-angle-down

Or could this be achieved with CSS? Tried.fa-angle-down {display: none;}and.menu-item-3530 {display:none;} but it doesn't do what I want-namely getting menu to go from bars to menu whilst not displaying contact header item.

Please see here for full navwalker.php https://github.com/ColorlibHQ/shapely/blob/master/inc/class-wp-bootstrap-navwalker.php

And here for my header.php https://github.com/ColorlibHQ/shapely/blob/master/header.php

Please see page here

This seems to be an issue not just with Shapely Theme, but that WordPress puts header menu item by default.

Does it have anything to do with aria-hidden?https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-hidden_attribute

答:
It's your theme. It's set up to show a hamburger icon for the menu for all screen sizes.

```<code>@media (min-width: 992px)
</code>```

This statement makes it true for a desktop. And on top of that, the icon is defined as a child of a flex item, which means you can't just set display: none. that doesn't work with flex.

I did get rid of the icon by overriding flex with inline: block, then setting display: none on the icon, but the menu still doesn't show up.

My recommendation: change themes.

Title: How to remove menu header in php?

Body:
I have menu header in my php that I'd like to remove.How?

PHP:

if ( ! empty( $item->attr_title ) ) {
            $item_output .= 'attr_title ) . '"> ';
        } else {
            $item_output .= '';
        }

        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= ( $args->has_children ) ? ' ' : '';
        $item_output .= $args->after;

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }// End if().
}

HTML Output:

Contact

The header menu item is contact along with fa-angle-down

Or could this be achieved with CSS? Tried.fa-angle-down {display: none;}and.menu-item-3530 {display:none;} but it doesn't do what I want-namely getting menu to go from bars to menu whilst not displaying contact header item.

Please see here for full navwalker.php https://github.com/ColorlibHQ/shapely/blob/master/inc/class-wp-bootstrap-navwalker.php

And here for my header.php https://github.com/ColorlibHQ/shapely/blob/master/header.php

Please see page here

This seems to be an issue not just with Shapely Theme, but that WordPress puts header menu item by default.

Does it have anything to do with aria-hidden?https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-hidden_attribute

Body:
It's your theme. It's set up to show a hamburger icon for the menu for all screen sizes.

@media (min-width: 992px)

This statement makes it true for a desktop. And on top of that, the icon is defined as a child of a flex item, which means you can't just set display: none. that doesn't work with flex.

I did get rid of the icon by overriding flex with inline: block, then setting display: none on the icon, but the menu still doesn't show up.

My recommendation: change themes.


问:
PhpStorm show CodeSniffer annoying message when install Xdebug
After install Xdebug on PhpStorm, CodeSniffer start show this annoying balloon message:

phpcs: Can not correctly run the tool with parameters:
  /tmp/phpcs_temp.tmp/app/Http/Controllers/PostController.php
  --encoding=utf-8 --report=xml

Environment: PhpStorm 2017.1.2, Xdebug 2.5.3, CodeSniffer 3.0, Nginx

PS: I try this solution, but it dose not help :(

答:
As Alex Slipknot suggested in the comments, the link PhpStorm Is throwing an error for phpcs provide a working solution for me :

Under Settings/Preferences | Languages & Frameworks | PHP | Quality tools you can see which quality plugins are enabled (PHP CS or PHP MD).
When you click on the "PHP CS Fixer Inspection" link (or on one of the other tools link here), you're redirected on the editor > inspections configuration in phpstorm. On this page, if you uncheck all the quality tools items (ie : PHP CS Fixer Validation), you should not have the problem anymore.

Hope it helps


问:
How to access the values inside resolved promises?
I'm having difficulty accessing the values from getPeople(0,4).

```<code>function getPeople(start, end) {
    const peopleArray = [];
    for (let i = start; i <= end; i++) {
      peopleArray.push(
        axios.get(`https://www.testsite.net/api/test/workers/${i}`)
      );
    }
    return peopleArray;
  }

  useEffect(() => {
    Promise.all([getData(), getPeople(0, 4)]).then(item => {
      //console.log(item[0].data.orders); //
      setData(item);
      setPersonData(item);
    });
  }, []);
</code>```

item[0] works fine.
Here's the result I'm getting when I console.log(item[1]) How can I access the data?

item[1] is an array of promises.

答:
This is can be made more readable using an async function in useEffect</p>

```<code>//make sure this actually returns the people rather than a load of promises
async function getPeople(start, end) {

    const peopleArray = [];
    for (let i = start; i <= end; i++) {
      let person = await axios.get(`https://www.hatchways.io/api/assessment/workers/${i}`);
      peopleArray.push(person);
    }
    return peopleArray;

}

//then in useEffect you need to create another async function
useEffect(() => {
    async function getDataAndPersons() {

      const data = await getData();
      setData(data);
      const people = await getPeople(0, 4);
      people.forEach(person => setPersonData(person));

    };
    getDataAndPersons();
}, []);
</code>```

Body:
I'm having difficulty accessing the values from getPeople(0,4).

function getPeople(start, end) {
    const peopleArray = [];
    for (let i = start; i <= end; i++) {
      peopleArray.push(
        axios.get(`https://www.testsite.net/api/test/workers/${i}`)
      );
    }
    return peopleArray;
  }

  useEffect(() => {
    Promise.all([getData(), getPeople(0, 4)]).then(item => {
      //console.log(item[0].data.orders); //
      setData(item);
      setPersonData(item);
    });
  }, []);

item[0] works fine.
Here's the result I'm getting when I console.log(item[1]) How can I access the data?

item[1] is an array of promises.

Body:
This is can be made more readable using an async function in useEffect

//make sure this actually returns the people rather than a load of promises
async function getPeople(start, end) {

    const peopleArray = [];
    for (let i = start; i <= end; i++) {
      let person = await axios.get(`https://www.hatchways.io/api/assessment/workers/${i}`);
      peopleArray.push(person);
    }
    return peopleArray;

}

//then in useEffect you need to create another async function
useEffect(() => {
    async function getDataAndPersons() {

      const data = await getData();
      setData(data);
      const people = await getPeople(0, 4);
      people.forEach(person => setPersonData(person));

    };
    getDataAndPersons();
}, []);


问:
Problems with Dispatcher.Invoke and thread access
I've trying to handle threads in C#, but i've occurred in a wierd exception I don't know how to resolve. I've got a method running by BackgroundWorker, in which there's this piece of code:

```<code>GridView gridView;
DataView dataView;

queryTable.GetViewAndDataView(out gridView, out dataView);

this.listView.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
    delegate() {
        listViewView = gridView;
        listView.ItemsSource = dataView;
    }
));
</code>```

GetViewAndDataView fills a gridView and dataView, while the delegate code sets the current listView. The using of Invoke is supposed not to raise exceptions, but when I try to run it, I obtain this: The calling thread cannot access this object because a different thread owns it.

Anyone knows of to handle such exception, or at least, how to disable the thread object owning?

答: The message is correct, you cant create the controls on a background thread and use them on your UI Thread. You have to both create and assign them on your UI thread. I recommend loading your data first in your background thread followed by doing the rest of your work in the UI Thread</p>

Body:
I've trying to handle threads in C#, but i've occurred in a wierd exception I don't know how to resolve. I've got a method running by BackgroundWorker, in which there's this piece of code:

GridView gridView;
DataView dataView;

queryTable.GetViewAndDataView(out gridView, out dataView);

this.listView.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
    delegate() {
        listViewView = gridView;
        listView.ItemsSource = dataView;
    }
));

GetViewAndDataView fills a gridView and dataView, while the delegate code sets the current listView. The using of Invoke is supposed not to raise exceptions, but when I try to run it, I obtain this: The calling thread cannot access this object because a different thread owns it.

Anyone knows of to handle such exception, or at least, how to disable the thread object owning?


问:
angular 2 azure deploy refresh error : The resource you are looking for has been removed, had its name changed, or is temporarily unavailable
I have an Angular 2 rc-2 app with basic routing implemented.The paths are /path1 which is the default path and /path2.The home path / redirects to /path1. When I run it locally (lite-server) everything works fine. I managed to deploy this app to an Azure web app. The app works OK BUT if I refresh the page when I m in /path1 or /path2 I get this error : The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

A possible approach is to implement url rewrite. I added a web.config file in my  project

```<code><?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

         <!-- check if its path1 url and navigate to default page -->
        <rule name="Path1 Request" enabled="true" stopProcessing="true">
        <match url="^path1" />
        <action type="Redirect" url="/index.html" logRewrittenUrl="true" />
        </rule>

         <!-- check if its path2 url and navigate to default page -->
        <rule name="Path2 Request" enabled="true" stopProcessing="true">
        <match url="^path2" />
        <action type="Redirect" url="/index.html" logRewrittenUrl="true" />
        </rule>

         </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

In this case I can make a refresh without getting this error message.But any refresh redirects me to the default url. I refresh from /path2 and it redirects me to /path1 (default url).

Any thoughts to improve refresh ? :)

答:
I ran into an issue where I had my angular.json file set up correctly with:

```<code>"assets": [
    "src/assets",
    "src/web.config"
],
</code>```

but the web.config file was not being copied into the built dist/ folder.

I did not think about the fact that I was also using a custom webpack config file (extra-webpack.config.js) with a CopyPlugin plugin. Once I added the web.config path to my custom webpack config and re-built my project, the web.config file was there!

Body:
I have an Angular 2 rc-2 app with basic routing implemented.The paths are /path1 which is the default path and /path2.The home path / redirects to /path1. When I run it locally (lite-server) everything works fine. I managed to deploy this app to an Azure web app. The app works OK BUT if I refresh the page when I m in /path1 or /path2 I get this error : The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

A possible approach is to implement url rewrite. I added a web.config file in my  project

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <rule name="Path1 Request" enabled="true" stopProcessing="true">
        <match url="^path1" />
        <action type="Redirect" url="/index.html" logRewrittenUrl="true" />
        </rule>

        <rule name="Path2 Request" enabled="true" stopProcessing="true">
        <match url="^path2" />
        <action type="Redirect" url="/index.html" logRewrittenUrl="true" />
        </rule>

         </rules>
        </rewrite>
    </system.webServer>
</configuration>

In this case I can make a refresh without getting this error message.But any refresh redirects me to the default url. I refresh from /path2 and it redirects me to /path1 (default url).

Any thoughts to improve refresh ? :)

Body:
I ran into an issue where I had my angular.json file set up correctly with:

"assets": [
    "src/assets",
    "src/web.config"
],

but the web.config file was not being copied into the built dist/ folder.

I did not think about the fact that I was also using a custom webpack config file (extra-webpack.config.js) with a CopyPlugin plugin. Once I added the web.config path to my custom webpack config and re-built my project, the web.config file was there!


问:
Python parse and flatten only some fields of a dict in a list
I have a JSON that I have converted to a list of python dicts that looks like so:

```<code>[
{'id': 8675309,
 'slug': 'name',
 'campaigns': [
   {
   'part_id': 'sfgsdfgsd',
   'client_id': '1sdfgsdfg',
   'business_id': None,
   'metadata': {'field':1}},
   {
   'part_id': '354yyr',
   'client_id': 'erty465',
   'business_id': None,
   'metadata': {'field':10}
   }
   ]
},
{'id': 1234567,
 'slug': 'name2',
 'campaigns': [
   {
   'part_id': 'wertyw',
   'client_id': 'sighs',
   'business_id': None,
   'metadata': {'field':1}}
   ]
}
</code>```

and I basically need to flatten the part_id, client_id, and business_id from the campaigns list while maintaining the id and slug fields. Basically I'm looking for a result that looks like this:

```<code>[
    {
     'id': 8675309,
     'slug': 'name',
     'part_id': 'sfgsdfgsd',
     'client_id': '1sdfgsdfg',
     'business_id': None,
    },
    {
     'id': 8675309,
     'slug': 'name',
     'part_id': '354yyr',
     'client_id': 'erty465',
     'business_id': None,
    },
    {
     'id': 1234567,
     'slug': 'name2',
     'part_id': 'wertyw',
     'client_id': 'sighs',
     'business_id': None,
    }
]
</code>```

I know how to flatten the campaign data like this:

```<code>campaigns = [i['campaigns'] for i in data]
campaigns = [item for sublist in campaigns for item in sublist]
</code>```

where data is the list of dicts but how do I do that while maintaining the id and slug fields?

答:
Give this a try. The trick is to create a base dict to perform a merge with your campaign data.</p>

```<code>def squash(data):
    results = []
    for item in data:
        base = {
          'id': item['id'],
          'slug': item['slug']
        }
        for campaign in item.get('campaigns', []):
            results.append({
                **base,
                'part_id': campaign['part_id'],
                'business_id': campaign['business_id'],
                'client_id': campaign['client_id']
            })
    return results
</code>```

Body:
I have a JSON that I have converted to a list of python dicts that looks like so:

[
{'id': 8675309,
 'slug': 'name',
 'campaigns': [
   {
   'part_id': 'sfgsdfgsd',
   'client_id': '1sdfgsdfg',
   'business_id': None,
   'metadata': {'field':1}},
   {
   'part_id': '354yyr',
   'client_id': 'erty465',
   'business_id': None,
   'metadata': {'field':10}
   }
   ]
},
{'id': 1234567,
 'slug': 'name2',
 'campaigns': [
   {
   'part_id': 'wertyw',
   'client_id': 'sighs',
   'business_id': None,
   'metadata': {'field':1}}
   ]
}

and I basically need to flatten the part_id, client_id, and business_id from the campaigns list while maintaining the id and slug fields. Basically I'm looking for a result that looks like this:

[
    {
     'id': 8675309,
     'slug': 'name',
     'part_id': 'sfgsdfgsd',
     'client_id': '1sdfgsdfg',
     'business_id': None,
    },
    {
     'id': 8675309,
     'slug': 'name',
     'part_id': '354yyr',
     'client_id': 'erty465',
     'business_id': None,
    },
    {
     'id': 1234567,
     'slug': 'name2',
     'part_id': 'wertyw',
     'client_id': 'sighs',
     'business_id': None,
    }
]

I know how to flatten the campaign data like this:

campaigns = [i['campaigns'] for i in data]
campaigns = [item for sublist in campaigns for item in sublist]

where data is the list of dicts but how do I do that while maintaining the id and slug fields?

Body:
Give this a try. The trick is to create a base dict to perform a merge with your campaign data.

def squash(data):
    results = []
    for item in data:
        base = {
          'id': item['id'],
          'slug': item['slug']
        }
        for campaign in item.get('campaigns', []):
            results.append({
                **base,
                'part_id': campaign['part_id'],
                'business_id': campaign['business_id'],
                'client_id': campaign['client_id']
            })
    return results


问:
Making the configuration available to all classes
I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration object which contains all these settings, and the main class holds this object.

However, the config data is required on almost every level of the server - classes within classes within classes...

My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?

答:
Making it a singleton seems like a reasonable solution. I think it would be a mistake to pass the config around as a parameter to other other classes constructors or method calls as this will tend to pollute the method arguments and make them unnecessarily complex.

If you do decide to make a singleton, then I'd recommend devising a mechanism whereby you can inject new instances of the config into the singleton class so that the singleton doesn't make your unit tests very hard to run.


问:
Searching in WPF
I have a WPF MVVM application with a dynamic UI (meaning there may be many different elements shown within a certain User Control).

I'd like to add the ability for the user to search the whole screen to find the text they are looking for...  similar to how one would use the web browser built-in search capabilities.

I've not been able to find a universal solution for this and am thinking of searching the visual tree for displayed text, but I'm hopeful, since this seems like a general purpose need, that I'm missing some relatively out of the box solution here.

答:
This is tricky.

For now it's only a part of the solution but here is an example to highlight a search in all Textblocks of in the VisualTree of a root object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

public class GlobalTextHighlighter
{
    public static Brush GetHighlightBackground(DependencyObject obj)
    {
        return (Brush)obj.GetValue(HighlightBackgroundProperty);
    }

    public static void SetHighlightBackground(DependencyObject obj, Brush value)
    {
        obj.SetValue(HighlightBackgroundProperty, value);
    }

    // Using a DependencyProperty as the backing store for HighlightBackground.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HighlightBackgroundProperty =
        DependencyProperty.RegisterAttached("HighlightBackground", typeof(Brush), typeof(GlobalTextHighlighter), new PropertyMetadata(Brushes.Yellow, new PropertyChangedCallback(RefreshHighlighting)));

    public static Brush GetHighlightForeground(DependencyObject obj)
    {
        return (Brush)obj.GetValue(HighlightForegroundProperty);
    }

    public static void SetHighlightForeground(DependencyObject obj, Brush value)
    {
        obj.SetValue(HighlightForegroundProperty, value);
    }

    // Using a DependencyProperty as the backing store for HighlightForeground.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HighlightForegroundProperty =
        DependencyProperty.RegisterAttached("HighlightForeground", typeof(Brush), typeof(GlobalTextHighlighter), new PropertyMetadata(Brushes.Black, new PropertyChangedCallback(RefreshHighlighting)));

    public static string GetSearchText(DependencyObject obj)
    {
        return (string)obj.GetValue(SearchTextProperty);
    }

    public static void SetSearchText(DependencyObject obj, string value)
    {
        obj.SetValue(SearchTextProperty, value);
    }

    // Using a DependencyProperty as the backing store for SearchText.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SearchTextProperty =
        DependencyProperty.RegisterAttached("SearchText", typeof(string), typeof(GlobalTextHighlighter), new PropertyMetadata(string.Empty, new PropertyChangedCallback(RefreshHighlighting)));

    private static void RefreshHighlighting(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if(d != null)
        {
            try
            {
                Brush background = (Brush)d.GetValue(HighlightBackgroundProperty);
                Brush foreground = (Brush)d.GetValue(HighlightForegroundProperty);
                string highlightText = (string)d.GetValue(SearchTextProperty);

                FindVisualChildren<TextBlock>(d)
                    .ToList()
                    .ForEach(textBlock =>
                    {
                        try
                        {
                            string text = textBlock.Text;

                            if (!string.IsNullOrEmpty(text))
                            {
                                if (string.IsNullOrEmpty(highlightText))
                                {
                                    textBlock.Text = text;
                                }
                                else
                                {
                                    int index = text.IndexOf(highlightText, StringComparison.CurrentCultureIgnoreCase);

                                    if (index < 0)
                                        textBlock.Text = text;
                                    else
                                        textBlock.Inlines.Clear();

                                    while (index >= 0)
                                    {
                                        textBlock.Inlines.AddRange(new Inline[]
                                        {
                                            new Run(text.Substring(0, index)),
                                            new Run(text.Substring(index, highlightText.Length))
                                            {
                                                Background = background,
                                                Foreground = foreground
                                            }
                                        });

                                        text = text.Substring(index + highlightText.Length);
                                        index = text.IndexOf(highlightText, StringComparison.CurrentCultureIgnoreCase);

                                        if (index < 0)
                                        {
                                            textBlock.Inlines.Add(new Run(text));
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        { }
                    });
            }
            catch { }
        }
    }

    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }

                foreach (T childOfChild in FindVisualChildren<T>(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }
}
```

<p>And you can use it on the root object from where you want to search.</p>

<p>Example :</p>

<pre class="lang-xml prettyprint-override"><code><TextBox x:Name="GlobalSearchTextBox"
         Text="{Binding GlobalSearch, UpdateSourceTrigger=PropertyChanged, Delay=100}"/>
<DockPanel local:GlobalTextHighlighter.SearchText="{Binding GlobalSearch}"
           local:GlobalTextHighlighter.HighlightBackground="Orange"
           local:GlobalTextHighlighter.HighlightForeground="Blue">
    <!-- ... -->
</DockPanel>
</code>```

It's based on WPF TextBlock Highlighter and Find all controls in WPF Window by type.

As I said it's not yet a complete solution.

And it comes with some drawbacks.

It doesn't work with all components that use AccessText like Labels.

It doesn't work with editing components like TextBoxs or RichTextBox.

It's not browsing from one match to an other.

If you want that you need to manage nested ScrollAreas.

I hope it already helps to approach the solution.

Title: Searching in WPF

Body:
This is tricky.

For now it's only a part of the solution but here is an example to highlight a search in all Textblocks of in the VisualTree of a root object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

public class GlobalTextHighlighter
{
    public static Brush GetHighlightBackground(DependencyObject obj)
    {
        return (Brush)obj.GetValue(HighlightBackgroundProperty);
    }

    public static void SetHighlightBackground(DependencyObject obj, Brush value)
    {
        obj.SetValue(HighlightBackgroundProperty, value);
    }

    // Using a DependencyProperty as the backing store for HighlightBackground.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HighlightBackgroundProperty =
        DependencyProperty.RegisterAttached("HighlightBackground", typeof(Brush), typeof(GlobalTextHighlighter), new PropertyMetadata(Brushes.Yellow, new PropertyChangedCallback(RefreshHighlighting)));

    public static Brush GetHighlightForeground(DependencyObject obj)
    {
        return (Brush)obj.GetValue(HighlightForegroundProperty);
    }

    public static void SetHighlightForeground(DependencyObject obj, Brush value)
    {
        obj.SetValue(HighlightForegroundProperty, value);
    }

    // Using a DependencyProperty as the backing store for HighlightForeground.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HighlightForegroundProperty =
        DependencyProperty.RegisterAttached("HighlightForeground", typeof(Brush), typeof(GlobalTextHighlighter), new PropertyMetadata(Brushes.Black, new PropertyChangedCallback(RefreshHighlighting)));

    public static string GetSearchText(DependencyObject obj)
    {
        return (string)obj.GetValue(SearchTextProperty);
    }

    public static void SetSearchText(DependencyObject obj, string value)
    {
        obj.SetValue(SearchTextProperty, value);
    }

    // Using a DependencyProperty as the backing store for SearchText.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SearchTextProperty =
        DependencyProperty.RegisterAttached("SearchText", typeof(string), typeof(GlobalTextHighlighter), new PropertyMetadata(string.Empty, new PropertyChangedCallback(RefreshHighlighting)));

    private static void RefreshHighlighting(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if(d != null)
        {
            try
            {
                Brush background = (Brush)d.GetValue(HighlightBackgroundProperty);
                Brush foreground = (Brush)d.GetValue(HighlightForegroundProperty);
                string highlightText = (string)d.GetValue(SearchTextProperty);

                FindVisualChildren<TextBlock>(d)
                    .ToList()
                    .ForEach(textBlock =>
                    {
                        try
                        {
                            string text = textBlock.Text;

                            if (!string.IsNullOrEmpty(text))
                            {
                                if (string.IsNullOrEmpty(highlightText))
                                {
                                    textBlock.Text = text;
                                }
                                else
                                {
                                    int index = text.IndexOf(highlightText, StringComparison.CurrentCultureIgnoreCase);

                                    if (index < 0)
                                        textBlock.Text = text;
                                    else
                                        textBlock.Inlines.Clear();

                                    while (index >= 0)
                                    {
                                        textBlock.Inlines.AddRange(new Inline[]
                                        {
                                            new Run(text.Substring(0, index)),
                                            new Run(text.Substring(index, highlightText.Length))
                                            {
                                                Background = background,
                                                Foreground = foreground
                                            }
                                        });

                                        text = text.Substring(index + highlightText.Length);
                                        index = text.IndexOf(highlightText, StringComparison.CurrentCultureIgnoreCase);

                                        if (index < 0)
                                        {
                                            textBlock.Inlines.Add(new Run(text));
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        { }
                    });
            }
            catch { }
        }
    }

    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }

                foreach (T childOfChild in FindVisualChildren<T>(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }
}

And you can use it on the root object from where you want to search.

Example :

<TextBox x:Name="GlobalSearchTextBox"
         Text="{Binding GlobalSearch, UpdateSourceTrigger=PropertyChanged, Delay=100}"/>
<DockPanel local:GlobalTextHighlighter.SearchText="{Binding GlobalSearch}"
           local:GlobalTextHighlighter.HighlightBackground="Orange"
           local:GlobalTextHighlighter.HighlightForeground="Blue">
    <!-- ... -->
</DockPanel>

It's based on WPF TextBlock Highlighter and Find all controls in WPF Window by type.

As I said it's not yet a complete solution.

And it comes with some drawbacks.

It doesn't work with all components that use AccessText like Labels.

It doesn't work with editing components like TextBoxs or RichTextBox.

It's not browsing from one match to an other.

If you want that you need to manage nested ScrollAreas.

I hope it already helps to approach the solution.


问:
Visual Studio 2019 showing duplicate tests in Test Explorer
Duplicate Unit Tests started showing up for me in Visual Studio 2019, which I recently upgraded from 2017.
I’ve a side by side comparison of Visual Studio 2017 and 2019 below, which shows some test were duplicated and categorised under tests not run:

Cleaning the solution didn’t get rid of these tests and the only thing that did, was deleting the git repository and cloning it again.

Has anybody come across this issue and have a better solution that this sledge hammer approach?

答:
I was talking to a colleague who also came across the same issue and he suggested another solution that worked for him.

Close Visual Studio.

Delete the ".vs" folder. You will find this folder where your solution (.sln) file exists.

Open Visual Studio.

This resolved the issue for him and is a less drastic measure that a delete and clone.


问:
split big dataframe into multiple ones under condition
I got a dataframe of 453627 rows like :

```<code>number  action
1        34
34       2
45       1
42       0
33       3
3        4
</code>```

I need to split it to 2000 row each, but if total action sum reaches 5000 I split it till that

example: if sum of actions column reaches 5000 at row 1200 split the dataframe to that row, if no split it to row 2000 and so on

how can I do so?

also, how can I read multiple CSVs files in folder each in individual dataframe?

答:
I cannot imagine a vectorized way, so I would just iterate the action column to produce a Series with a distinct value per slot.

After that, a mere groupby would be enough to split the initial dataframe:

```<code>maxlen = 2000
thresh = 5000
cursum = 0
curlen = 0
curval = 0
arr = df['action'].values
cat = np.zeros(len(arr), int)
for i in range(len(arr)):
    curlen += 1
    cursum += arr[i]
    if curlen != 1 and (curlen >= maxlen or cursum >= thresh):
        cursum = 0
        curlen = 0
        curval += 1
    cat[i] = curval
cat = pd.Series(cat, df.index)

dfs = [dg for _, dg in df.groupby(cat)]
</code>```

dfs contains the list of the splitted dataframe

Body:
I got a dataframe of 453627 rows like :

number  action
1        34
34       2
45       1
42       0
33       3
3        4

I need to split it to 2000 row each, but if total action sum reaches 5000 I split it till that

example: if sum of actions column reaches 5000 at row 1200 split the dataframe to that row, if no split it to row 2000 and so on

how can I do so?

also, how can I read multiple CSVs files in folder each in individual dataframe?

Body:
I cannot imagine a vectorized way, so I would just iterate the action column to produce a Series with a distinct value per slot.

After that, a mere groupby would be enough to split the initial dataframe:

maxlen = 2000
thresh = 5000
cursum = 0
curlen = 0
curval = 0
arr = df['action'].values
cat = np.zeros(len(arr), int)
for i in range(len(arr)):
    curlen += 1
    cursum += arr[i]
    if curlen != 1 and (curlen >= maxlen or cursum >= thresh):
        cursum = 0
        curlen = 0
        curval += 1
    cat[i] = curval
cat = pd.Series(cat, df.index)

dfs = [dg for _, dg in df.groupby(cat)]

dfs contains the list of the splitted dataframe


问:
Convert 2D List to 2D ArrayList in Java
I am trying to convert a 2D List to a 2D ArrayList in Java
I will then convert the 2D ArrayList to a 2D Array and implement for loops to return the absolute difference of the 2 diagonals of the matrix.

How would I convert the 2D ArrayList arr to a 2D ArrayList?

Here is my work so far in attempting to convert the input List to an ArrayList:

```<code>    public static int diagonalDifference(List<List<Integer>> arr) {

    //first: 2D List --> 2D ArrayList
    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);

    //second: 2D ArrayList --> int[][]

    //third: nested for loop through int[][]to difference between diagonals of 2d array
    }
</code>```

Here is my full code so far.

```<code> public static int diagonalDifference(List<List<Integer>> arr) {
    List<List<Intger>> arrList = new ArrayList<>();

    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);
    }

        int pri = 0;
        int sec =0;

    for(int i=0; i<a.length; i++) {
        for(int j=0; j <a.length; j++) {

            if (a[i] == a[j]) {
                pri += a[i];
            }

            if (i == a.length - j - 1) {
                sec += a[i];
            }

        }
    }
    return Math.abs(pri - sec);

}
</code>```

答:
This should also work: I tested just now.

row.stream().mapToInt(Integer::intValue).toArray();

Title: Convert 2D List to 2D ArrayList in Java

Body:
I am trying to convert a 2D List to a 2D ArrayList in Java
I will then convert the 2D ArrayList to a 2D Array and implement for loops to return the absolute difference of the 2 diagonals of the matrix.

How would I convert the 2D ArrayList arr to a 2D ArrayList?

Here is my work so far in attempting to convert the input List to an ArrayList:

    public static int diagonalDifference(List<List<Integer>> arr) {

    //first: 2D List --> 2D ArrayList
    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);

    //second: 2D ArrayList --> int[][]

    //third: nested for loop through int[][]to difference between diagonals of 2d array
    }

Here is my full code so far.

 public static int diagonalDifference(List<List<Integer>> arr) {
    List<List<Intger>> arrList = new ArrayList<>();

    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);
    }

        int pri = 0;
        int sec =0;

    for(int i=0; i<a.length; i++) {
        for(int j=0; j <a.length; j++) {

            if (a[i] == a[j]) {
                pri += a[i];
            }

            if (i == a.length - j - 1) {
                sec += a[i];
            }

        }
    }
    return Math.abs(pri - sec);

}


问:
Hadoop: specify yarn queue for distcp
On our cluster we have set up dynamic resource pools.

The rules are set so that first yarn will look at the specified queue, then to the username, then to primary group ...

However with a distcp I can't seem to be able to specify a queue, it just sets it to the primary group.

This is how I run it now (which doesn't work):

```<code> hadoop distcp -Dmapred.job.queue.name:root.default .......
</code>```

答:
Similarly, hadoop archive can be instructed to target a custom queue :

hadoop archive -Dmapreduce.job.queuename='<leaf.queue.name> ...

I take the opporunity of this response to give a tip for hadoop archive:
as it will create one map task per file to create (by default, the destination file size is 2GB). This can lead to thousands of maps when archiving terabytes of data.

The size of part-* files of hadoop archives is controlled with undocumented har.partfile.size : you can increase it by setting a value (in bytes) higher than 2GiB with -Dhar.partfile.size=<value in bytes>

Title: Hadoop: specify yarn queue for distcp

Body:
On our cluster we have set up dynamic resource pools.

The rules are set so that first yarn will look at the specified queue, then to the username, then to primary group ...

However with a distcp I can't seem to be able to specify a queue, it just sets it to the primary group.

This is how I run it now (which doesn't work):

 hadoop distcp -Dmapred.job.queue.name:root.default .......


问:
angular v8 - how to get production build template errors also during development mode
I have the latest angular v8 installed and I want to receive basic template errors i get during production also while runing ng serve.

For example

Template

ERROR: {{ errorMessage }}

```

<p>Controller</p>

<pre class="lang-js prettyprint-override"><code>log(a){}
</code>```

Build error

ERROR in apps/manufacturing-tv/src/app/app.component.ts.AppComponent.html(7,9): Expected 1 arguments, but got 0.

or

Template

ERROR: {{ errorMessages }}

```

<p><code>ERROR in apps/manufacturing-tv/src/app/app.component.ts.AppComponent.html(7,25): Property 'errorMessages' does not exist on type 'AppComponent'. Did you mean 'errorMessage'?</code></p>

<p>I've already tried to add the <code>fullTemplateTypeCheck</code> flag but running ng build or ng serve doesn't yield the errors.</p>

```{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "types": ["jasmine"]
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true
    },
    "include": ["**/*.ts"]
}

```

答:
Enable ahead-of-time compilation by calling:

```<code>ng serve --aot
</code>```

or configure aot as the default compiler by adding it to your angular.json

"architect": {
  "serve": {
    "options": {
      "aot": true
    }
  }
}
```

and call ng serve.

The same can be done for build.

Body:
I have the latest angular v8 installed and I want to receive basic template errors i get during production also while runing ng serve.

For example

Template

ERROR: {{ errorMessage }}

Controller

log(a){}

Build error

ERROR in apps/manufacturing-tv/src/app/app.component.ts.AppComponent.html(7,9): Expected 1 arguments, but got 0.

or

Template

ERROR: {{ errorMessages }}

ERROR in apps/manufacturing-tv/src/app/app.component.ts.AppComponent.html(7,25): Property 'errorMessages' does not exist on type 'AppComponent'. Did you mean 'errorMessage'?

I've already tried to add the fullTemplateTypeCheck flag but running ng build or ng serve doesn't yield the errors.

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "types": ["jasmine"]
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true
    },
    "include": ["**/*.ts"]
}

Body:
Enable ahead-of-time compilation by calling:

ng serve --aot

or configure aot as the default compiler by adding it to your angular.json

"architect": {
  "serve": {
    "options": {
      "aot": true
    }
  }
}

and call ng serve.

The same can be done for build.


问:
Does Location.convert() yield values with comma as separator?
My Android app deals with geo-location.

This is a code snippet from the source code:

```<code>...
String latDegrees = Location.convert(latitude, Location.FORMAT_DEGREES);
...
</code>```

In my test it has

```<code>latitude 44.4929057
</code>```

but

```<code>latDegrees "44,49291"
</code>```

You see that the comma is used as separator, while it seems that the dot is the standard, for example in Gmaps urls, if I am not wrong.

In my app I have to perform much "substringing" so I have to be sure that the convert function yields the same format in all Locales.

So can I assume that the DD,DDDDD format (with comma separator) is safe to use for substringing in general? Or is my code wrong?

答:
I found that the separator character in the result from Location.convert method can be found in both forms dot='.' or comma=','

Maybe other forms exist according to locales.

It seems thar dot and comma are the most common, while some other decimal separators exist:

https://en.wikipedia.org/wiki/Decimal_separator

Furthermore some countries have other separators for groups of digits but here I am dealing with a particular method for converting location coordinates.

Body:
My Android app deals with geo-location.

This is a code snippet from the source code:

...
String latDegrees = Location.convert(latitude, Location.FORMAT_DEGREES);
...

In my test it has

latitude 44.4929057

but

latDegrees "44,49291"

You see that the comma is used as separator, while it seems that the dot is the standard, for example in Gmaps urls, if I am not wrong.

In my app I have to perform much "substringing" so I have to be sure that the convert function yields the same format in all Locales.

So can I assume that the DD,DDDDD format (with comma separator) is safe to use for substringing in general? Or is my code wrong?


问:
How to Get First Week Saturday date of current month in php?
how to get Saturday first week date of the current month...Actually I have two input data field first is start date and second date input what I am looking for
is first start date is always starts from every week on Saturday and submit report date is always next week Wednesday

First Start Date Input

```<code>$date=date('m/d/Y');
<input id="mock_test_date" name="start date" placeholder="" type="text" class="form-control"
value="date('m/d/Y')" readonly="readonly" />
</code>```

Second Date Input

```<code><input id="mock_test_date" name="start date" placeholder="" type="text" class="form-control"  value="date('m/d/Y', strtotime($date .' +4 day'))" readonly="readonly" />
</code>```

how can I get the First Week Saturday on every month and on the second field I will get date of next Wednesday....if first input Saturday is on month end then i will get next month wednesday date

答:
You can simply use DateTimeImmutable to get the next Saturday and the next Wednesday relatively to the already found Saturday:

```<code>$saturday = (new DateTimeImmutable)->modify('next Saturday');
$wednesday = $saturday->modify('next Wednesday');

var_dump(
    $saturday->format('D M j G:i:s T Y'),
    $wednesday->format('D M j G:i:s T Y')
);
</code>```

The result would be:

```<code>string(27) "Sat Feb 22 0:00:00 EST 2020"
string(27) "Wed Feb 26 0:00:00 EST 2020"
</code>```

Body:
how to get Saturday first week date of the current month...Actually I have two input data field first is start date and second date input what I am looking for
is first start date is always starts from every week on Saturday and submit report date is always next week Wednesday

First Start Date Input

$date=date('m/d/Y');
<input id="mock_test_date" name="start date" placeholder="" type="text" class="form-control"
value="date('m/d/Y')" readonly="readonly" />

Second Date Input

<input id="mock_test_date" name="start date" placeholder="" type="text" class="form-control"  value="date('m/d/Y', strtotime($date .' +4 day'))" readonly="readonly" />

how can I get the First Week Saturday on every month and on the second field I will get date of next Wednesday....if first input Saturday is on month end then i will get next month wednesday date

Body:
You can simply use DateTimeImmutable to get the next Saturday and the next Wednesday relatively to the already found Saturday:

$saturday = (new DateTimeImmutable)->modify('next Saturday');
$wednesday = $saturday->modify('next Wednesday');

var_dump(
    $saturday->format('D M j G:i:s T Y'),
    $wednesday->format('D M j G:i:s T Y')
);

The result would be:

string(27) "Sat Feb 22 0:00:00 EST 2020"
string(27) "Wed Feb 26 0:00:00 EST 2020"


问:
Connecting to orient DB distributed server
how does one connect to a distributed setup in orientdb. I have 3 servers cluster setup and running. They are communicating and data from one is available from the other. But how do I connect to them as a cluster in my program?
in mongo there is the connection URI :

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]

is there something similar in orientdb? Currently, I connect to just one and insert my data but the program stops when this server stops for some reason. can I automatically have the program connect to one of the other servers and continue? All 3 are masters in this case, no replication servers.

答:
You need to first authenticate the user, using basic auth, with the /connect/ API which will return the OSESSIONID as a cookie.
Then pass the OSESSIONID as a header to other APIs (in postman it is auto passed to other APIs).
Some of the OrientDB REST APIs require basic auth - they document it as "Requires additional authentication to the server."</p>


问:
How to develop a hybrid Fiori application and launch it on Fiori custom client?
I develop SAPUI5 and Fiori applications by SAP WEBIDE and deploy them on SAP Getway server, which is using as the applications web server. After deploying, we expose the application to the user by Fiori Launchpad (Fiori Client).
We do not have SAP Cloud platform or SMP.
I asked to develop a hybrid Fiori application that uses device capabilities (like barcode, camera, etc). I used node JS CLI for adding Cordova plugins to SAPUI5 and wrapping the application for getting APK. How can I develop a hybrid application, which can be reached by Fiori launchpad / Fiori client (Not standalone APK)?</p>

答:
If you were build your application with sap/m/* libraries, you can use existing SAP Fiori Client (Android / IOS) for barcode scanning, camera, etc. Also you can use it for UI5 applications.

If you create own app with SAP Fiori Client SDK, you need extra license for it.

It is theoretically possible to run Fiori app in Cordova, but I think you need a lot of custom work. I prefer use SAP Fiori Client.


问:
Trying to import xml into Google Sheet but not pulling any data
I'm trying to pull the "followers" from this page https://www.kickstarter.com/projects/two19/kingless into a google sheet using the importxml function.

This isn't pulling any data back:

```<code>=importxml("https://www.kickstarter.com/projects/two19/kingless", "//span[@class='type-14 block text-center text-left-md']")
</code>```

Am I missing something here?

答:
unfortunately, it is not possible to be scraped. all you can get is:</p>

```<code>=ARRAY_CONSTRAIN(IMPORTDATA("https://www.kickstarter.com/projects/two19/kingless"); 5000; 20)
</code>```

Body:
I'm trying to pull the "followers" from this page https://www.kickstarter.com/projects/two19/kingless into a google sheet using the importxml function.

This isn't pulling any data back:

=importxml("https://www.kickstarter.com/projects/two19/kingless", "//span[@class='type-14 block text-center text-left-md']")

Am I missing something here?

Body:
unfortunately, it is not possible to be scraped. all you can get is:

=ARRAY_CONSTRAIN(IMPORTDATA("https://www.kickstarter.com/projects/two19/kingless"); 5000; 20)