问:
Oracle sql to split data into ranges based on count
I am working on a requirement where I need to populate a table with range based on the records count from input

Sample O/p if the input has 8954 records :- The # of records from input will keep changing, where as the split based on 3K records is constant.

```<code>Entity start end
abc    1     3000
abc    3001  6000
abc    6001  8954
</code>```

I have tried using hierarchical query but it fails after 1 million records due to memory issue.

答:
You need to use hierarchy query to generate the records as follows:

```<code>SQL> SELECT
  2      'abc' AS ENTITY,
  3      ( LEVEL - 1 ) * 3000 + 1 as st,
  4      LEAST(LEVEL * 3000, 8954) as en
  5  FROM
  6      DUAL
  7  CONNECT BY
  8      LEVEL <= CEIL(8954 / 3000);

ENT         ST         EN
--- ---------- ----------
abc          1       3000
abc       3001       6000
abc       6001       8954

SQL>
</code>```

replace 8954 with actual value in above query.

Body:
I am working on a requirement where I need to populate a table with range based on the records count from input

Sample O/p if the input has 8954 records :- The # of records from input will keep changing, where as the split based on 3K records is constant.

Entity start end
abc    1     3000
abc    3001  6000
abc    6001  8954

I have tried using hierarchical query but it fails after 1 million records due to memory issue.

Body:
You need to use hierarchy query to generate the records as follows:

SQL> SELECT
  2      'abc' AS ENTITY,
  3      ( LEVEL - 1 ) * 3000 + 1 as st,
  4      LEAST(LEVEL * 3000, 8954) as en
  5  FROM
  6      DUAL
  7  CONNECT BY
  8      LEVEL <= CEIL(8954 / 3000);

ENT         ST         EN
--- ---------- ----------
abc          1       3000
abc       3001       6000
abc       6001       8954

SQL>

replace 8954 with actual value in above query.


来源: stackexchange

问:
check data if is equal from 2 foreach php
i want to check my data like this

data source result from foreach

```<code>Data Source => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17
</code>```

my data for result from foreach is:

```<code>ID_1 => 4, 5, 6, 10, 11, 13, 15
ID_2 => 1, 2, 3, 4, 5, 6, 7, 8
</code>```

how method to check if id is same or equal with data source will result true but if id not have the datasource the result will be false?

here my code to foreach the data

```<code>        @php
            $items = array();
            foreach($activity as $a){
                $items[] = $a->id;
            }
            $list = implode(', ', $items);
        @endphp
        Data Source => {{ $list }}

        @foreach($result as $detail_activity)
            ID_{{$detail_activity->id}}  => {{$detail_activity->ActivityDetail}}<br>
        @endforeach
</code>```

with the result like this

if we use that example data, maybe like

```<code>data source | id_1 | id_2 |
1             False True
2             False True
3             False True
4             True  True
</code>```

thanks for advance :D

答:
solved thanks for every response from you all... sorry if I take a long response

first we create a function

```<code>function checkfacility($facility,$datasource){
                        foreach($datasource as $ds){
                            if($facility == $ds->name){
                                return true;
                            }
                        }
                    }
</code>```

then we made a foreach with condition at blade template like this

```<code>@foreach ($facility as $key => $values)
   <td>{{ (checkfacility($values->name,$datasource)) == TRUE ? 'true' : 'false' }}</td>
@endforeach

</code>```

ContentLicense: CC BY-SA 4.0

Body:
i want to check my data like this

data source result from foreach

Data Source => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17

my data for result from foreach is:

ID_1 => 4, 5, 6, 10, 11, 13, 15
ID_2 => 1, 2, 3, 4, 5, 6, 7, 8

how method to check if id is same or equal with data source will result true but if id not have the datasource the result will be false?

here my code to foreach the data

        @php
            $items = array();
            foreach($activity as $a){
                $items[] = $a->id;
            }
            $list = implode(', ', $items);
        @endphp
        Data Source => {{ $list }}

        @foreach($result as $detail_activity)
            ID_{{$detail_activity->id}}  => {{$detail_activity->ActivityDetail}}

        @endforeach

with the result like this

if we use that example data, maybe like

data source | id_1 | id_2 |
1             False True
2             False True
3             False True
4             True  True

thanks for advance :D

Body:
solved thanks for every response from you all... sorry if I take a long response

first we create a function

function checkfacility($facility,$datasource){
                        foreach($datasource as $ds){
                            if($facility == $ds->name){
                                return true;
                            }
                        }
                    }

then we made a foreach with condition at blade template like this

@foreach ($facility as $key => $values)
   <td>{{ (checkfacility($values->name,$datasource)) == TRUE ? 'true' : 'false' }}</td>
@endforeach


问:
F# errors with ILogger in Azure Functions v2
I have a quite big project with Azure Function v2 written in F#. I create a library in C# where in the constructor I can pass a ILogger log. If only I add this library in the Azure Function project, every function returns an error.

Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'log' to type ILogger. Make sure the parameter Type is supported by the binding

In F# I tried to add

```<code>[<FunctionName("organization")>]
let public organization
    ( [<HttpTrigger(AuthorizationLevel.Function, "post", Route = "organisations/{organisationId}")>]
        request : HttpRequestMessage,
        organisationId : string,
        executionContext : ExecutionContext,
        log : ILogger) =

      let PaymentGateway = PaymentGateway(Environment.GetEnvironmentVariable "Api_Secret_Key", log)

      ...
</code>```

I saw some posts for example on GitHub or another post where other people have the same issue. Apparently, the solution is to update the Azure Function from v2 to v3 but I can't do that in my case right now.

Is there any solution?

Update

The .fsproj is

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
  </PropertyGroup>

  <ItemGroup>
    <Content Include="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Update="FSharp.Core" Version="4.6.2" />
  </ItemGroup>
</Project>
</code>```

答:
No matter what, your fs is indeed problematic. I posted here the file and code of function that can be triggered successfully:

This is the structure of my function app:

This is my .fsproj:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="HttpTrigger.fs" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
    <Content Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </Content>
  </ItemGroup>
</Project>
</code>```

And this is my trigger file HttpTrigger.fs:

```<code>namespace Company.Function

open System
open System.IO
open Microsoft.AspNetCore.Mvc
open Microsoft.Azure.WebJobs
open Microsoft.Azure.WebJobs.Extensions.Http
open Microsoft.AspNetCore.Http
open Newtonsoft.Json
open Microsoft.Extensions.Logging

module HttpTrigger =
    // Define a nullable container to deserialize into.
    [<AllowNullLiteral>]
    type NameContainer() =
        member val Name = "" with get, set

    // For convenience, it's better to have a central place for the literal.
    [<Literal>]
    let Name = "name"

    [<FunctionName("HttpTrigger")>]
    let run ([<HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)>]req: HttpRequest) (log: ILogger) =
        async {
            log.LogInformation("F# HTTP trigger function processed a request.")

            let nameOpt =
                if req.Query.ContainsKey(Name) then
                    Some(req.Query.[Name].[0])
                else
                    None

            use stream = new StreamReader(req.Body)
            let! reqBody = stream.ReadToEndAsync() |> Async.AwaitTask

            let data = JsonConvert.DeserializeObject<NameContainer>(reqBody)

            let name =
                match nameOpt with
                | Some n -> n
                | None ->
                   match data with
                   | null -> ""
                   | nc -> nc.Name

            let responseMessage =
                if (String.IsNullOrWhiteSpace(name)) then
                    "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                else
                    "Hello, " +  name + ". This HTTP triggered function executed successfully."

            return OkObjectResult(responseMessage) :> IActionResult
        } |> Async.StartAsTask
</code>```

Works fine, successful log:

These is my step to create and run F# function:

1.Run these two command in cmd:

```<code>dotnet new --install Microsoft.Azure.WebJobs.ItemTemplates

dotnet new --install Microsoft.Azure.WebJobs.ProjectTemplates
</code>```

2.Create function app:

```<code>dotnet new func --language F# --name FunctionsInFSharp
</code>```

3.Create trigger:

```<code>dotnet new http --language F# --name HttpTrigger
</code>```

4.Add trigger to compile:

```<code><Compile Include="HttpTrigger.fs" />
</code>```

Please add above code to ItemGroup in .fsproj file.

5.Change the template, change these from none to Content:

All I have given is a simple example of how the F# function can be triggered successfully, please try it and let me know whether you can solve it.:)

Body:
I have a quite big project with Azure Function v2 written in F#. I create a library in C# where in the constructor I can pass a ILogger log. If only I add this library in the Azure Function project, every function returns an error.

Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'log' to type ILogger. Make sure the parameter Type is supported by the binding

In F# I tried to add

[<FunctionName("organization")>]
let public organization
    ( [<HttpTrigger(AuthorizationLevel.Function, "post", Route = "organisations/{organisationId}")>]
        request : HttpRequestMessage,
        organisationId : string,
        executionContext : ExecutionContext,
        log : ILogger) =

      let PaymentGateway = PaymentGateway(Environment.GetEnvironmentVariable "Api_Secret_Key", log)

      ...

I saw some posts for example on GitHub or another post where other people have the same issue. Apparently, the solution is to update the Azure Function from v2 to v3 but I can't do that in my case right now.

Is there any solution?

Update

The .fsproj is

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
  </PropertyGroup>

  <ItemGroup>
    <Content Include="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Update="FSharp.Core" Version="4.6.2" />
  </ItemGroup>
</Project>

Body:
No matter what, your fs is indeed problematic. I posted here the file and code of function that can be triggered successfully:

This is the structure of my function app:

This is my .fsproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="HttpTrigger.fs" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
    <Content Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </Content>
  </ItemGroup>
</Project>

And this is my trigger file HttpTrigger.fs:

namespace Company.Function

open System
open System.IO
open Microsoft.AspNetCore.Mvc
open Microsoft.Azure.WebJobs
open Microsoft.Azure.WebJobs.Extensions.Http
open Microsoft.AspNetCore.Http
open Newtonsoft.Json
open Microsoft.Extensions.Logging

module HttpTrigger =
    // Define a nullable container to deserialize into.
    [<AllowNullLiteral>]
    type NameContainer() =
        member val Name = "" with get, set

    // For convenience, it's better to have a central place for the literal.
    [<Literal>]
    let Name = "name"

    [<FunctionName("HttpTrigger")>]
    let run ([<HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)>]req: HttpRequest) (log: ILogger) =
        async {
            log.LogInformation("F# HTTP trigger function processed a request.")

            let nameOpt =
                if req.Query.ContainsKey(Name) then
                    Some(req.Query.[Name].[0])
                else
                    None

            use stream = new StreamReader(req.Body)
            let! reqBody = stream.ReadToEndAsync() |> Async.AwaitTask

            let data = JsonConvert.DeserializeObject<NameContainer>(reqBody)

            let name =
                match nameOpt with
                | Some n -> n
                | None ->
                   match data with
                   | null -> ""
                   | nc -> nc.Name

            let responseMessage =
                if (String.IsNullOrWhiteSpace(name)) then
                    "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                else
                    "Hello, " +  name + ". This HTTP triggered function executed successfully."

            return OkObjectResult(responseMessage) :> IActionResult
        } |> Async.StartAsTask

Works fine, successful log:

These is my step to create and run F# function:

1.Run these two command in cmd:

dotnet new --install Microsoft.Azure.WebJobs.ItemTemplates

dotnet new --install Microsoft.Azure.WebJobs.ProjectTemplates

2.Create function app:

dotnet new func --language F# --name FunctionsInFSharp

3.Create trigger:

dotnet new http --language F# --name HttpTrigger

4.Add trigger to compile:

<Compile Include="HttpTrigger.fs" />

Please add above code to ItemGroup in .fsproj file.

5.Change the template, change these from none to Content:

All I have given is a simple example of how the F# function can be triggered successfully, please try it and let me know whether you can solve it.:)


问:
Seekbar length manipulation
I'm using a seekbar in my android application to set the volume. However the length of the seekbar  is unesthetically  too short. So is there a way to customize the length of a seek bar ? </p>

答:
XML example:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip">
<SeekBar android:id="@+id/default_width_seek_bar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<SeekBar android:id="@+id/fixed_width_seek_bar"
    android:layout_width="100dip"
    android:layout_height="wrap_content" />
<SeekBar android:id="@+id/full_width_seek_bar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
<SeekBar android:id="@+id/padded_full_width_seek_bar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="8dip" android:paddingRight="8dip" />
</LinearLayout>
</code>```

Side note: The thumb of the SeekBar can be clipped when moved all the way to the sides. A little extra padding like in the last SeekBar fixes this problem.

ContentLicense: CC BY-SA 2.5

Title: Seekbar length manipulation

Body:
XML example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip">
<SeekBar android:id="@+id/default_width_seek_bar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<SeekBar android:id="@+id/fixed_width_seek_bar"
    android:layout_width="100dip"
    android:layout_height="wrap_content" />
<SeekBar android:id="@+id/full_width_seek_bar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
<SeekBar android:id="@+id/padded_full_width_seek_bar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="8dip" android:paddingRight="8dip" />
</LinearLayout>

Side note: The thumb of the SeekBar can be clipped when moved all the way to the sides. A little extra padding like in the last SeekBar fixes this problem.

ContentLicense: CC BY-SA 3.0


问:
What is the most efficient way to push and pop a list in Python?
In Python how do I write code which shifts off the last element of a list and adds a new one to the beginning - to run as fast as possible at execution?

There are good solutions involving the use of append, rotate etc but not all may translate to fast execution.

答:
I ran some benchmarks for you. Here are the results.

TL;DR You probably want to use a deque. Otherwise, insert / append, or pop / del are fine.

Adding to the end

```<code>from collections import deque
import perfplot

# Add to end

def use_append(n):
    "adds to end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a.append(7)
    return 1

def use_insert_end(n):
    "adds to end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a.insert(len(a),7)
    return 1

def use_add_end(n):
    "adds to end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = a + [7]
    return 1

perfplot.show(
    setup=lambda n: n,  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_append(a),
        lambda a: use_insert_end(a),
        lambda a: use_add_end(a),
    ],
    labels=["use_append", "use_insert_end", "use_add_end"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)
</code>```

Remove from end

```<code># Removing from the end

def use_pop(n):
    "removes from end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a.pop()
    return 1

def use_del_last(n):
    "removes from end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    del(a[-1])
    return 1

def use_index_to_end(n):
    "removes from end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = a[:-1]
    return 1

perfplot.show(
    setup=lambda n: n,
    kernels=[
        lambda a: use_pop(a),
        lambda a: use_del_last(a),
        lambda a: use_index_to_end(a),
    ],
    labels=["use_pop", "use_del_last", "use_index_to_end"],
    n_range=[2 ** k for k in range(20)],
    xlabel="len(a)",
)
</code>```

Adding to the beginning

```<code># Add to beginning

def use_insert(n):
    "adds to beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a.insert(0,7)
    return 1

def use_deque_appendleft(n):
    "adds to beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = deque(a)
    a.appendleft(7)
    return 1

def use_add_start(n):
    "adds to beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = [7] + a
    return 1

perfplot.show(
    setup=lambda n: n,  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_insert(a),
        lambda a: use_deque_appendleft(a),
        lambda a: use_add_start(a),
    ],
    labels=["use_insert", "use_deque_appendleft","use_add_start"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)
</code>```

Removing from the beginning

```<code># Remove from beginning

def use_del_first(n):
    "removes from beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    del(a[0])
    return 1

def use_deque_popleft(n):
    "removes from beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = deque(a)
    a.popleft()
    return 1

def use_index_start(n):
    "removes from beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = a[1:]
    return 1

perfplot.show(
    setup=lambda n: n,  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_del_first(a),
        lambda a: use_deque_popleft(a),
        lambda a: use_index_start(a),
    ],
    labels=["use_del_first", "use_deque_popleft", "use_index_start"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)
</code>```

Edit

Take these results with a grain of salt. Given how perfplot works, the remove methods would get run multiple times, while setup is only run once. Hence, the list (or deque) needs to be generated locally in each function, which adds to run time.

I've modified the add methods below, and run a separate comparison for deque, to compare the effect of generating lists locally within the functions.

Deque setup difference

```<code>
def gen_deque(n):
    a = [1,2,3,4,5,6,7,8,9,10]*n if n > 0 else [1,2,3]
    return deque(a)

def use_deque_appendleft(a):
    "adds to beginning"
    a.appendleft(7)
    return 1

def use_deque_appendleft_original(a):
    "adds to beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*(len(a)//10)
    a = deque(a)
    a.appendleft(7)
    return 1

perfplot.show(
    setup=lambda n: gen_deque(n),  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_deque_appendleft(a),
        lambda a: use_deque_appendleft_original(a),
    ],
    labels=["use_deque_appendleft", "use_deque_appendleft_original"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)
</code>```

Add to end

```<code># Add to end

def gen_data(n):
    return [1,2,3,4,5,6,7,8,9,10]*n if n > 0 else [1,2,3]

def use_append(a):
    "adds to end"
#     a = [1,2,3,4,5,6,7,8,9,10]*n
    a.append(7)
    return 1

def use_insert_end(a):
    "adds to end"
#     a = [1,2,3,4,5,6,7,8,9,10]*n
    a.insert(len(a),7)
    return 1

def use_add_end(a):
    "adds to end"
#     a = [1,2,3,4,5,6,7,8,9,10]*n
    a = a + [7]
    return 1

perfplot.show(
    setup=lambda n: gen_data(n),  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_append(a),
        lambda a: use_insert_end(a),
        lambda a: use_add_end(a),
    ],
    labels=["use_append", "use_insert_end", "use_add_end"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)
</code>```

Add to start

```<code># Add to beginning

def gen_data(n):
    return [1,2,3,4,5,6,7,8,9,10]*n if n > 0 else [1,2,3]

def use_insert(a):
    "adds to beginning"
    a.insert(0,7)
    return 1

def use_deque_appendleft(a):
    "adds to beginning"
    a = deque(a)
    a.appendleft(7)
    return 1

def use_add_start(a):
    "adds to beginning"
    a = [7] + a
    return 1

perfplot.show(
    setup=lambda n: gen_data(n),  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_insert(a),
        lambda a: use_deque_appendleft(a),
        lambda a: use_add_start(a),
    ],
    labels=["use_insert", "use_deque_appendleft","use_add_start"],
    n_range=[2 ** k for k in range(5)],
    xlabel="len(a)",
)
</code>```

Conclusion

Insert and append have similar performance, and using a deque seems to have better performance than insert. As for del / pop / deque's popleft, it seems that del and pop have similar performance, but it's hard to tell if deque's popleft would be better, considering the overhead of generating lists / deques within each function for using perfplot.

Body:
I ran some benchmarks for you. Here are the results.

TL;DR You probably want to use a deque. Otherwise, insert / append, or pop / del are fine.

Adding to the end

from collections import deque
import perfplot

# Add to end

def use_append(n):
    "adds to end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a.append(7)
    return 1

def use_insert_end(n):
    "adds to end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a.insert(len(a),7)
    return 1

def use_add_end(n):
    "adds to end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = a + [7]
    return 1

perfplot.show(
    setup=lambda n: n,  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_append(a),
        lambda a: use_insert_end(a),
        lambda a: use_add_end(a),
    ],
    labels=["use_append", "use_insert_end", "use_add_end"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)

Remove from end

# Removing from the end

def use_pop(n):
    "removes from end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a.pop()
    return 1

def use_del_last(n):
    "removes from end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    del(a[-1])
    return 1

def use_index_to_end(n):
    "removes from end"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = a[:-1]
    return 1

perfplot.show(
    setup=lambda n: n,
    kernels=[
        lambda a: use_pop(a),
        lambda a: use_del_last(a),
        lambda a: use_index_to_end(a),
    ],
    labels=["use_pop", "use_del_last", "use_index_to_end"],
    n_range=[2 ** k for k in range(20)],
    xlabel="len(a)",
)

Adding to the beginning

# Add to beginning

def use_insert(n):
    "adds to beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a.insert(0,7)
    return 1

def use_deque_appendleft(n):
    "adds to beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = deque(a)
    a.appendleft(7)
    return 1

def use_add_start(n):
    "adds to beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = [7] + a
    return 1

perfplot.show(
    setup=lambda n: n,  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_insert(a),
        lambda a: use_deque_appendleft(a),
        lambda a: use_add_start(a),
    ],
    labels=["use_insert", "use_deque_appendleft","use_add_start"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)

Removing from the beginning

# Remove from beginning

def use_del_first(n):
    "removes from beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    del(a[0])
    return 1

def use_deque_popleft(n):
    "removes from beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = deque(a)
    a.popleft()
    return 1

def use_index_start(n):
    "removes from beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*n
    a = a[1:]
    return 1

perfplot.show(
    setup=lambda n: n,  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_del_first(a),
        lambda a: use_deque_popleft(a),
        lambda a: use_index_start(a),
    ],
    labels=["use_del_first", "use_deque_popleft", "use_index_start"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)

Edit

Take these results with a grain of salt. Given how perfplot works, the remove methods would get run multiple times, while setup is only run once. Hence, the list (or deque) needs to be generated locally in each function, which adds to run time.

I've modified the add methods below, and run a separate comparison for deque, to compare the effect of generating lists locally within the functions.

Deque setup difference

def gen_deque(n):
    a = [1,2,3,4,5,6,7,8,9,10]*n if n > 0 else [1,2,3]
    return deque(a)

def use_deque_appendleft(a):
    "adds to beginning"
    a.appendleft(7)
    return 1

def use_deque_appendleft_original(a):
    "adds to beginning"
    a = [1,2,3,4,5,6,7,8,9,10]*(len(a)//10)
    a = deque(a)
    a.appendleft(7)
    return 1

perfplot.show(
    setup=lambda n: gen_deque(n),  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_deque_appendleft(a),
        lambda a: use_deque_appendleft_original(a),
    ],
    labels=["use_deque_appendleft", "use_deque_appendleft_original"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)

Add to end

# Add to end

def gen_data(n):
    return [1,2,3,4,5,6,7,8,9,10]*n if n > 0 else [1,2,3]

def use_append(a):
    "adds to end"
#     a = [1,2,3,4,5,6,7,8,9,10]*n
    a.append(7)
    return 1

def use_insert_end(a):
    "adds to end"
#     a = [1,2,3,4,5,6,7,8,9,10]*n
    a.insert(len(a),7)
    return 1

def use_add_end(a):
    "adds to end"
#     a = [1,2,3,4,5,6,7,8,9,10]*n
    a = a + [7]
    return 1

perfplot.show(
    setup=lambda n: gen_data(n),  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_append(a),
        lambda a: use_insert_end(a),
        lambda a: use_add_end(a),
    ],
    labels=["use_append", "use_insert_end", "use_add_end"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
)

Add to start

# Add to beginning

def gen_data(n):
    return [1,2,3,4,5,6,7,8,9,10]*n if n > 0 else [1,2,3]

def use_insert(a):
    "adds to beginning"
    a.insert(0,7)
    return 1

def use_deque_appendleft(a):
    "adds to beginning"
    a = deque(a)
    a.appendleft(7)
    return 1

def use_add_start(a):
    "adds to beginning"
    a = [7] + a
    return 1

perfplot.show(
    setup=lambda n: gen_data(n),  # or simply setup=numpy.random.rand
    kernels=[
        lambda a: use_insert(a),
        lambda a: use_deque_appendleft(a),
        lambda a: use_add_start(a),
    ],
    labels=["use_insert", "use_deque_appendleft","use_add_start"],
    n_range=[2 ** k for k in range(5)],
    xlabel="len(a)",
)

Conclusion

Insert and append have similar performance, and using a deque seems to have better performance than insert. As for del / pop / deque's popleft, it seems that del and pop have similar performance, but it's hard to tell if deque's popleft would be better, considering the overhead of generating lists / deques within each function for using perfplot.


问:
Backpack 4.0 base configuration key "passwords"
This is my first time using Backpack and I have a question about the base.php Backpack config. One of the keys there is called passwords and it has this random string value as shown in the screenshot below.

For the life of me I don't know what that means. The only thing I know so far is that the Forgot Password form submits to a page with the following error.

```<code>InvalidArgumentException
Password resetter [c45#$%TCC)*$%tc;pvctHJ^] is not defined.
</code>```

When I set the passwords config value to null, the form works but the Reset Password link from the email shows a link like:

<mydomain>/password/reset?token=a67b566284a8415923f799682a50509cfd6ae11e4ea0f6e3026271a5446c1f61&email=xxx

instead of:

<mydomain>/password/reset/a67b566284a8415923f799682a50509cfd6ae11e4ea0f6e3026271a5446c1f61?email=xxx

So it is not matching the route defined in Backpack. But I guess that is another topic.

For now I just need to understand what the passwords config does and why is the value set like it currently is. Can anyone please explain?

答:
That config should hold the name of the password broker that Backpack uses inside the Authentication.

It should NOT be gibberish, but the actual name of the password broker to be used. By default that's backpack as you can see in our demo. If commented out, it will use the same password broker that the stock Laravel Auth uses - as explained in the comment. I recommend you write backpack there - that should fix it for you.

This value should only be changed when you want to customize the authentication, and have mixed auth for users and admins, things like that. It uses Laravel's authentication, which is unnecessarily complicated if you ask me, but that's where the password broker concept is from.

Body:
This is my first time using Backpack and I have a question about the base.php Backpack config. One of the keys there is called passwords and it has this random string value as shown in the screenshot below.

For the life of me I don't know what that means. The only thing I know so far is that the Forgot Password form submits to a page with the following error.

InvalidArgumentException
Password resetter [c45#$%TCC)*$%tc;pvctHJ^] is not defined.

When I set the passwords config value to null, the form works but the Reset Password link from the email shows a link like:

<mydomain>/password/reset?token=a67b566284a8415923f799682a50509cfd6ae11e4ea0f6e3026271a5446c1f61&email=xxx

instead of:

<mydomain>/password/reset/a67b566284a8415923f799682a50509cfd6ae11e4ea0f6e3026271a5446c1f61?email=xxx

So it is not matching the route defined in Backpack. But I guess that is another topic.

For now I just need to understand what the passwords config does and why is the value set like it currently is. Can anyone please explain?


问:
Email address is not verified (AWS SES)
I want to use Amazon's Simple Email Service to send emails.

I verified my domain as well as the email address I want to send from.

For both it says verified.

Now when I use the Send Test Email from the AWS Console to send a test email to myemail@outlook.com, I only get the error message:

Email address is not verified. The following identities failed the
check in region EU-WEST-1: myemail@outlook.com (Request ID:
9fb78de1-2673-11e6-bbbc-5f819fabe4f4)

Now it strikes me because it says myemail@outlook.com was not verified but I tried to send from admin@mydomain.example. The Send Test Email Dialog even forces you to use an email which already is registered.

How can this issue be resolved? Did I miss anything?

答: @Matt Houser has already answered the questions but I am adding a screenshot from June, 2020 that explains what he said.

Title: Email address is not verified (AWS SES)


问:
How to create jQuery Tabs out of Markdown
I'm currently running a PHP based Content-Management-System that generates its HTML content with the help of Markdown Extra. Most of the content is structured by headings and sub-headings which results in a very long page. At the beginning of each page I create a table of contents with the help of a list and Markdown Extra's Header Id Attribute.

In oder to shorten the length of a page view I'd like to use the jQuery's Tabs Plugin on the first level of headings.

The Problem is that the output of Markdown Extra is not compatible with what the jQuery Tabs Plugin is expecting because Markdown Extra is not wrapping the content of a section into a separate div-tag.

Is there a way how to make those two libraries work together?

EDIT

This is what the HTML output is looking like:

```<code> <p>Some intro text...</p>
 <h3>Table of content</h3>
 <ul>
  <li><a href="#sub1">Topic 1</a></li>
  <li><a href="#sub2">Topic 2</a></li>
  <li><a href="#sub3">Topic 3</a></li>
 </ul>
 <h3 id="sub1">Topic 1</h3>
 <p>The content of this topic.</p>
 <h3 id="sub2">Topic 2</h3>
 <p>The content of this topic.</p>
 <h3 id="sub3">Topic 3</h3>
 <p>The content of this topic.</p>
</code>```

.. and this is the corresponding Markdown code:

```<code>Some intro text...

###Table of content###

* [Topic 1](#sub1)
* [Topic 2](#sub2)
* [Topic 3](#sub3)

###Topic 1### {#sub1}

The content of this topic.

###Topic 2### {#sub2}

The content of this topic.

###Topic 3### {#sub3}

The content of this topic.
</code>```

Solution

With a little help of cobbal I made this jQuery statement that will transform the Markdown markup into something that the Tabs plugin will work with:

```<code>  $("#tabs :header").each(function()
  {
    var id = $(this).attr("id");
    if(id=="") return;
    var div = $("<div>");
    var tagName = this.tagName;
    $(this).nextAll().each(function()
    {
      if(this.tagName==tagName) return false;
      div.append(this);
    });
    $(this).removeAttr("id");
    div.attr("id", id);
    $(this).before(div);
    div.prepend(this);
  });
</code>```

But the fact that I need to transform the markup to fit the Tabs plugin rather than just tell the Tabs plugin that it should select its content in a different way may made this solution not the ideal one.

答:
on your document.ready

```<code>$("#sub1,#sub2,#sub3").each(function() {
    var containerDiv = $("<div>").attr("id", $(this).attr("id") + "div");
    $(this).before(containerDiv);
    containerDiv.append(this);
});
</code>```

and change your markdown to

```<code>...
* [Topic 1](#sub1div)
* [Topic 2](#sub2div)
* [Topic 3](#sub3div)
...
</code>```

OwnerDisplayName: mutzel

Body:
I'm currently running a PHP based Content-Management-System that generates its HTML content with the help of Markdown Extra. Most of the content is structured by headings and sub-headings which results in a very long page. At the beginning of each page I create a table of contents with the help of a list and Markdown Extra's Header Id Attribute.

In oder to shorten the length of a page view I'd like to use the jQuery's Tabs Plugin on the first level of headings.

The Problem is that the output of Markdown Extra is not compatible with what the jQuery Tabs Plugin is expecting because Markdown Extra is not wrapping the content of a section into a separate div-tag.

Is there a way how to make those two libraries work together?

EDIT

This is what the HTML output is looking like:

Some intro text...

Table of content

Topic 1

Topic 2

Topic 3

Topic 1

The content of this topic.

Topic 2

The content of this topic.

Topic 3

The content of this topic.

.. and this is the corresponding Markdown code:

Some intro text...

###Table of content###

* [Topic 1](#sub1)
* [Topic 2](#sub2)
* [Topic 3](#sub3)

###Topic 1### {#sub1}

The content of this topic.

###Topic 2### {#sub2}

The content of this topic.

###Topic 3### {#sub3}

The content of this topic.

Solution

With a little help of cobbal I made this jQuery statement that will transform the Markdown markup into something that the Tabs plugin will work with:

  $("#tabs :header").each(function()
  {
    var id = $(this).attr("id");
    if(id=="") return;
    var div = $("
");
    var tagName = this.tagName;
    $(this).nextAll().each(function()
    {
      if(this.tagName==tagName) return false;
      div.append(this);
    });
    $(this).removeAttr("id");
    div.attr("id", id);
    $(this).before(div);
    div.prepend(this);
  });

But the fact that I need to transform the markup to fit the Tabs plugin rather than just tell the Tabs plugin that it should select its content in a different way may made this solution not the ideal one.

LastEditorDisplayName: mutzel

Body:
on your document.ready

$("#sub1,#sub2,#sub3").each(function() {
    var containerDiv = $("<div>").attr("id", $(this).attr("id") + "div");
    $(this).before(containerDiv);
    containerDiv.append(this);
});

and change your markdown to

...
* [Topic 1](#sub1div)
* [Topic 2](#sub2div)
* [Topic 3](#sub3div)
...


问:
Fastest way to extract a substring in C#
I'm going to process thousands of strings (with the size of ~150kB on average). Each of them contains zero or more substrings of the following form:

```<code><a href="/link/i/want">Fixed_String</a>
</code>```

I would like to extract all such links and put them into a list.

Additionally, there is another fixed string after which the strings I am looking for will not appear.

What's the fastest way to get the strings?

答:
A bit of manual parsing is probably the fastest way to solve this. Regex would be possible, too, because it's really just a very simple case of parsing a link and not a whole HTML document, but that could easily choke on those large files, performance wise.

Now, let me preface this that I haven't tested this at all and I feel kinda dirty posting it (I'm sure it needs some more edge-case checks to avoid errors), but here you go:

```<code>    const char[] quotes = new char[] { '"', '\'' };

    private List<string> ExtractLinks(string html)
    {
        var links = new List<string>();
        string searchFor = ">Fixed_String</a>";

        for (int i = html.IndexOf(searchFor); i >= 0; i = html.IndexOf(searchFor, i + searchFor.Length))
        {
            string href = ExtractHref(html, i);
            if (!String.IsNullOrEmpty(href))
                links.Add(href);
        }

        return links;
    }

    private string ExtractHref(string html, int backtrackFrom)
    {
        int hrefStart = -1;

        // Find "<a", but limit search so we don't backtrack forever
        for (int i = backtrackFrom; i > backtrackFrom - 255; i--)
        {
            if (i < 0)
                return null;

            if (html[i] == '<' && html[i + 1] == 'a')
            {
                hrefStart = html.IndexOf("href=", i);
                break;
            }
        }

        if (hrefStart < 0)
            return null;

        int start = html.IndexOfAny(quotes, hrefStart);
        if (start < 0)
            return null;

        int end = html.IndexOfAny(quotes, start + 1);
        if (end < 0)
            return null;

        return html.Substring(start + 1, end - start - 1);
    }
</code>```

XmlReader is probably a no-go, because you most likely cannot guarantee that those files are XHTML formatted. If you want to do proper parsing, the HTML Agility Pack is probably your best choice, or maybe a properly done Regex if it can't be helped. I posted this manual parsing so you have another alternative you can do a performance test with.

Body:
I'm going to process thousands of strings (with the size of ~150kB on average). Each of them contains zero or more substrings of the following form:

Fixed_String

I would like to extract all such links and put them into a list.

Additionally, there is another fixed string after which the strings I am looking for will not appear.

What's the fastest way to get the strings?

Body:
A bit of manual parsing is probably the fastest way to solve this. Regex would be possible, too, because it's really just a very simple case of parsing a link and not a whole HTML document, but that could easily choke on those large files, performance wise.

Now, let me preface this that I haven't tested this at all and I feel kinda dirty posting it (I'm sure it needs some more edge-case checks to avoid errors), but here you go:

    const char[] quotes = new char[] { '"', '\'' };

    private List<string> ExtractLinks(string html)
    {
        var links = new List<string>();
        string searchFor = ">Fixed_String</a>";

        for (int i = html.IndexOf(searchFor); i >= 0; i = html.IndexOf(searchFor, i + searchFor.Length))
        {
            string href = ExtractHref(html, i);
            if (!String.IsNullOrEmpty(href))
                links.Add(href);
        }

        return links;
    }

    private string ExtractHref(string html, int backtrackFrom)
    {
        int hrefStart = -1;

        // Find "<a", but limit search so we don't backtrack forever
        for (int i = backtrackFrom; i > backtrackFrom - 255; i--)
        {
            if (i < 0)
                return null;

            if (html[i] == '<' && html[i + 1] == 'a')
            {
                hrefStart = html.IndexOf("href=", i);
                break;
            }
        }

        if (hrefStart < 0)
            return null;

        int start = html.IndexOfAny(quotes, hrefStart);
        if (start < 0)
            return null;

        int end = html.IndexOfAny(quotes, start + 1);
        if (end < 0)
            return null;

        return html.Substring(start + 1, end - start - 1);
    }

XmlReader is probably a no-go, because you most likely cannot guarantee that those files are XHTML formatted. If you want to do proper parsing, the HTML Agility Pack is probably your best choice, or maybe a properly done Regex if it can't be helped. I posted this manual parsing so you have another alternative you can do a performance test with.


问:
Can you prevent the first column of a table from sorting?
I use the below code to sort my table on my site LBRYnomics. It excludes the table header when sorting, but I also want to exclude the tables first column (Channel Rank) as highlighted in red. Is there a way to do this?

Any help is very much appreciated. Thanks!

Current Code:

```<code>const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) => (v1 === null) - (v2 === null) || (isFinite(v1) && isFinite(v2) ?
v1 - v2 : v1.toString().localeCompare(v2))) (getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))

.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(tr => table.appendChild(tr));
})));
</code>```

答:
If you want to do it with only HTML/CSS, or have that column behave independently, you will have to create two inline tables and have them placed side by side, one for the ranks and one for your data.  Probably is not difficult to do.

It is not otherwise possible, because td.rank is a child enclosed within the tr element, and rearranging the position of the tr will move the td with it within the hierarchy.

If you want something more flexible you could use css flex-grid and simulate a table without being bound by the hierarchy of elements a table row structure requires.

Two methods that involve replacing in sequential order.

Replace td.ranks text with sequential numbers 1-200.  Can also use .childNodes[0]

```<code>const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) => (v1 === null) - (v2 === null) || (isFinite(v1) && isFinite(v2) ?
v1 - v2 : v1.toString().localeCompare(v2))) (getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))

.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach((tr,i) => {tr.querySelector('.rank').innerText=i+1+'';table.appendChild(tr)});
})));
</code>```

Storing td.ranks in an array, and replaceChild the row in order.

```<code>const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) => (v1 === null) - (v2 === null) || (isFinite(v1) && isFinite(v2) ?
v1 - v2 : v1.toString().localeCompare(v2))) (getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
const col1 = table.querySelectorAll('.rank:nth-child(n+2)');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))

.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach((tr,i) => {
   tr.replaceChild(col1[i],tr.childNodes[0]);
   table.appendChild(tr);
});
})));
</code>```

Body:
I use the below code to sort my table on my site LBRYnomics. It excludes the table header when sorting, but I also want to exclude the tables first column (Channel Rank) as highlighted in red. Is there a way to do this?

Any help is very much appreciated. Thanks!

Current Code:

const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) => (v1 === null) - (v2 === null) || (isFinite(v1) && isFinite(v2) ?
v1 - v2 : v1.toString().localeCompare(v2))) (getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))

.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(tr => table.appendChild(tr));
})));

Body:
If you want to do it with only HTML/CSS, or have that column behave independently, you will have to create two inline tables and have them placed side by side, one for the ranks and one for your data.  Probably is not difficult to do.

It is not otherwise possible, because td.rank is a child enclosed within the tr element, and rearranging the position of the tr will move the td with it within the hierarchy.

If you want something more flexible you could use css flex-grid and simulate a table without being bound by the hierarchy of elements a table row structure requires.

Two methods that involve replacing in sequential order.

Replace td.ranks text with sequential numbers 1-200.  Can also use .childNodes[0]

const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) => (v1 === null) - (v2 === null) || (isFinite(v1) && isFinite(v2) ?
v1 - v2 : v1.toString().localeCompare(v2))) (getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))

.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach((tr,i) => {tr.querySelector('.rank').innerText=i+1+'';table.appendChild(tr)});
})));

Storing td.ranks in an array, and replaceChild the row in order.

const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) => (v1 === null) - (v2 === null) || (isFinite(v1) && isFinite(v2) ?
v1 - v2 : v1.toString().localeCompare(v2))) (getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
const col1 = table.querySelectorAll('.rank:nth-child(n+2)');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))

.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach((tr,i) => {
   tr.replaceChild(col1[i],tr.childNodes[0]);
   table.appendChild(tr);
});
})));


问:
Show divs based on dropdown-menu-option selected by user
The purpose with the code is to let user choose a number from a dropdown-menu and show corresponding divs. The startpoint of divs is always that all are hidden. The "user-selected-number" should be used by Javascript to decide how many divs to show. In this case as following:

Dropdown-value: 1 = show balance 0

Dropdown-value: 2 = show balance 0,1

Dropdown-value: 3 = show balance 0,1,2

Dropdown-value: 4 = show balance 0,1,2,3

Observation:

I suspect the problem is that the javavascript picks up only the option that is predefined as "selected" which would mean it does never take the user-selected-value for further processing.

The var_dump of $_POST shows correct result/printout, everytime user selects an option from the dropdown menu.

Wanted behavour:

The user should on the frontend be able to pick a value in dropdown between 1-4 and the corrensponding divs (see list above) should be made visible.

```<code><!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8">
  <title>Show divs based on dropdown</title>

  <style>
    .balance_0,
    .balance_1,
    .balance_2,
    .balance_3
     {
      display: none;
    }
  </style>

</head>
<body>

<!-- Form (Years-selector) -->

<form class="year-selector" method="post">

  <select class="dropdown_result" id="dropdown_result" name="selection">

    <option value="" selected="selected" hidden="hidden">Select amount of years to report...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>

  </select>

  <button type="submit" name="button">Send</button>

</form>

<!-- Divs -->

<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>

```

<?php var_dump($_POST); ?>

```

答:
There are several things you should consider in your code.

You are using button with type="submit" which causes to pages get reload each time and run the same script, so the value of amountOfBalanceColumnsToShow will always be the same (which is in your case it is your first option in the dropdown).

You are always just showing the blocks in each particular condition and don't get any consideration of hiding unnecessary ones.

You are getting element by its id where the balance div's have classes instead of id's.

To fix these things, you should first add an event listener to your submit button and prevent its default action, then get all the elements with balance class and after that with your conditions iterate through them and specify which one has to be shown and which one has to hidden.

So your final code should be something like this:

// Extract selected dropdown menu option.
var element = document.getElementById("dropdown_result");
var submitButton = document.querySelector('button[type="submit"]');
var balanceDivs = document.querySelectorAll("[class*='balance']");
var balanceDivsLength = balanceDivs.length;

submitButton.addEventListener("click", function(event) {
  event.preventDefault();

  var amountOfBalanceColumnsToShow =
    element.options[element.selectedIndex].value;

  // Show amount of balance divs based on above form.

  if (amountOfBalanceColumnsToShow == 1) {
    for (var i = 0; i < balanceDivsLength; i++) {
      if (balanceDivs[i].classList.contains("balance_0")) {
        balanceDivs[i].style.display = "block";
      } else {
        balanceDivs[i].style.display = "none";
      }
    }
  } else if (amountOfBalanceColumnsToShow == 2) {
    for (var i = 0; i < balanceDivsLength; i++) {
      if (
        balanceDivs[i].classList.contains("balance_0") ||
        balanceDivs[i].classList.contains("balance_1")
      ) {
        balanceDivs[i].style.display = "block";
      } else {
        balanceDivs[i].style.display = "none";
      }
    }
  } else if (amountOfBalanceColumnsToShow == 3) {
    for (var i = 0; i < balanceDivsLength; i++) {
      if (!balanceDivs[i].classList.contains("balance_3")) {
        balanceDivs[i].style.display = "block";
      } else {
        balanceDivs[i].style.display = "none";
      }
    }
  } else if (amountOfBalanceColumnsToShow == 4) {
    for (var i = 0; i < balanceDivsLength; i++) {
      balanceDivs[i].style.display = "block";
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.balance_0,
.balance_1,
.balance_2,
.balance_3 {
  display: none;
}</code>```

<form class="year-selector" method="post">

  <select class="dropdown_result" id="dropdown_result" name="selection">

    <option value="" selected="selected" hidden="hidden">Select amount of years to report...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>

  </select>

  <button type="submit" name="button">Send</button>

</form>

Balance-0

Balance-1

Balance-2

Balance-3
```

Body:
The purpose with the code is to let user choose a number from a dropdown-menu and show corresponding divs. The startpoint of divs is always that all are hidden. The "user-selected-number" should be used by Javascript to decide how many divs to show. In this case as following:

Dropdown-value: 1 = show balance 0

Dropdown-value: 2 = show balance 0,1

Dropdown-value: 3 = show balance 0,1,2

Dropdown-value: 4 = show balance 0,1,2,3

Observation:

I suspect the problem is that the javavascript picks up only the option that is predefined as "selected" which would mean it does never take the user-selected-value for further processing.

The var_dump of $_POST shows correct result/printout, everytime user selects an option from the dropdown menu.

Wanted behavour:

The user should on the frontend be able to pick a value in dropdown between 1-4 and the corrensponding divs (see list above) should be made visible.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Show divs based on dropdown</title>

<form class="year-selector" method="post">

  <select class="dropdown_result" id="dropdown_result" name="selection">

    <option value="" selected="selected" hidden="hidden">Select amount of years to report...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>

  </select>

  <button type="submit" name="button">Send</button>

</form>

Balance-0

Balance-1

Balance-2

Balance-3

<?php var_dump($_POST); ?>

Body:
There are several things you should consider in your code.

You are using button with type="submit" which causes to pages get reload each time and run the same script, so the value of amountOfBalanceColumnsToShow will always be the same (which is in your case it is your first option in the dropdown).

You are always just showing the blocks in each particular condition and don't get any consideration of hiding unnecessary ones.

You are getting element by its id where the balance div's have classes instead of id's.

To fix these things, you should first add an event listener to your submit button and prevent its default action, then get all the elements with balance class and after that with your conditions iterate through them and specify which one has to be shown and which one has to hidden.

So your final code should be something like this:

// Extract selected dropdown menu option.
var element = document.getElementById("dropdown_result");
var submitButton = document.querySelector('button[type="submit"]');
var balanceDivs = document.querySelectorAll("[class*='balance']");
var balanceDivsLength = balanceDivs.length;

submitButton.addEventListener("click", function(event) {
  event.preventDefault();

  var amountOfBalanceColumnsToShow =
    element.options[element.selectedIndex].value;

  // Show amount of balance divs based on above form.

  if (amountOfBalanceColumnsToShow == 1) {
    for (var i = 0; i < balanceDivsLength; i++) {
      if (balanceDivs[i].classList.contains("balance_0")) {
        balanceDivs[i].style.display = "block";
      } else {
        balanceDivs[i].style.display = "none";
      }
    }
  } else if (amountOfBalanceColumnsToShow == 2) {
    for (var i = 0; i < balanceDivsLength; i++) {
      if (
        balanceDivs[i].classList.contains("balance_0") ||
        balanceDivs[i].classList.contains("balance_1")
      ) {
        balanceDivs[i].style.display = "block";
      } else {
        balanceDivs[i].style.display = "none";
      }
    }
  } else if (amountOfBalanceColumnsToShow == 3) {
    for (var i = 0; i < balanceDivsLength; i++) {
      if (!balanceDivs[i].classList.contains("balance_3")) {
        balanceDivs[i].style.display = "block";
      } else {
        balanceDivs[i].style.display = "none";
      }
    }
  } else if (amountOfBalanceColumnsToShow == 4) {
    for (var i = 0; i < balanceDivsLength; i++) {
      balanceDivs[i].style.display = "block";
    }
  }
});

.balance_0,
.balance_1,
.balance_2,
.balance_3 {
  display: none;
}

<!-- Form (Years-selector) -->

<form class="year-selector" method="post">

  <select class="dropdown_result" id="dropdown_result" name="selection">

    <option value="" selected="selected" hidden="hidden">Select amount of years to report...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>

  </select>

  <button type="submit" name="button">Send</button>

</form>

<!-- Divs -->

<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>


问:
Check if an object is present in a nested array reactjs
I have the following set of data:

person:

```<code>person: { id:1
          groups:[
                  {id:1 , name: john, permissions : [{id:1 , codename="can_edit"},{id:2,codename="can_write"},{id:3,codename="can_delete"}]} ,

                  ]
            }
</code>```

What i wish to do is conduct some conditional rendering based on whether this user has a permission.

```<code>             { this.passtest()?
            <Button type="primary" shape="circle" icon={<EditOutlined />}/>
              :
              null
              }
</code>```

This will then call the this.passtest() method which will contain the logic for checking if the user has the permission i require :

```<code>   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      // Not sure what logic I can put here to return true as long as the permission 'codename' field tallies
     });

    return passing
  }
</code>```

Would appreciate your help! Thanks!

答:
```<code>passtest(codeName){
    return !!this.props.person.groups.find(group => group.permissions.find(permission => permission.codename === codeName));
}
</code>```

Using:

```<code>{
  this.passtest('can_edit')?
  <Button type="primary" shape="circle" icon={<EditOutlined />}/>
  : null
}
</code>```

For array of codeNames:

```<code>passtest(codeNames){
  return codeNames.every(
    codeName => !!this.props.person.groups.find(
      group => group.permissions.find(
        permission => permission.codeName === codeName
      )
    )
  )
}
</code>```

Using:

```<code>{
  this.passtest(['can_edit', 'can_write'])?
  <Button type="primary" shape="circle" icon={<EditOutlined />}/>
  : null
}
</code>```

Body:
I have the following set of data:

person:

person: { id:1
          groups:[
                  {id:1 , name: john, permissions : [{id:1 , codename="can_edit"},{id:2,codename="can_write"},{id:3,codename="can_delete"}]} ,

                  ]
            }

What i wish to do is conduct some conditional rendering based on whether this user has a permission.

             { this.passtest()?
            <Button type="primary" shape="circle" icon={<EditOutlined />}/>
              :
              null
              }

This will then call the this.passtest() method which will contain the logic for checking if the user has the permission i require :

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      // Not sure what logic I can put here to return true as long as the permission 'codename' field tallies
     });

    return passing
  }

Would appreciate your help! Thanks!

Body:
passtest(codeName){
    return !!this.props.person.groups.find(group => group.permissions.find(permission => permission.codename === codeName));
}

Using:

{
  this.passtest('can_edit')?
  <Button type="primary" shape="circle" icon={<EditOutlined />}/>
  : null
}

For array of codeNames:

passtest(codeNames){
  return codeNames.every(
    codeName => !!this.props.person.groups.find(
      group => group.permissions.find(
        permission => permission.codeName === codeName
      )
    )
  )
}

Using:

{
  this.passtest(['can_edit', 'can_write'])?
  <Button type="primary" shape="circle" icon={<EditOutlined />}/>
  : null
}


问:
How to remove bootstrap modal overlay?
How to remove bootstrap modal overlay for particular modal.
when modal appears background has black color with some opacity
is there any option for removing that elements...</p>

答:
```<code>$("#myModal").on('hide.bs.modal', function(){
    $('.modal-backdrop').remove()
});
</code>```

This should work as a charm

Title: How to remove bootstrap modal overlay?

Body:
$("#myModal").on('hide.bs.modal', function(){
    $('.modal-backdrop').remove()
});

This should work as a charm


问:
How to call method in ViewController from viewmodel in swift?
I am using MVVM design pattern in iOS project. I am trying to call method in viewcontroller from viewmodel.

```<code>import Foundation

class NotificationViewModel {

    var onCompletion: ((_ success: Bool) -> ())?

    func saveNotification(notification: Dictionary<String, Any>) {
        print("notification save")
        //other logic
        onCompletion?(true)
    }
   }
</code>```

"saveNotification" method getting called from appdelegate when notification received

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSMutableDictionary
            else {
                // handle any error here
                return
            }

        NotificationViewModel().saveNotification(notification: alert as! Dictionary<String, Any>)
        }
</code>```

trying to call method in viewcontroller when "saveNotification" trigger

```<code>     class AlertViewController: BaseViewController{

            var viewModel = NotificationViewModel()

            override func viewDidLoad() {
                super.viewDidLoad()

                self.viewModel.onCompletion = { success in
                    // this should be executed when `saveNotification()` will be called
// **** this is never getting called ******
                    print("calling from viewmodel")
                    methodToCall()
                }
            }

          func methodToCall(){
            //logic
          }
      }
</code>```

But the method in viewdidload is not getting called anytime.

Please suggest if its possible or any other way to achieve this?
Thanks for help

答:
MVVM without Rx framework(RxSwift,ReactiveCocoa or Apple Combine) is a pain.
Below is my Solution in MVVM + RxSwift.Hopefully that will inspire you.

```<code>import Foundation
import RxSwift
import RxCocoa

final class NotificationViewModel: ViewModel, ViewModelType {

    struct Input { }

    struct Output {
        let compelete: PublishSubject<Bool>
    }

    let input: Input = Input()

    let output: Output = Output(compelete: PublishSubject<Bool>())
}

import UIKit
import RxSwift
import RxCocoa
import Rswift

final class NotificationViewController: ViewController<LoginViewModel> {

    override func bindViewModel() {

        vm.output.compelete
            .subscribe(onNext: { [unowned self] _ in
                // this will be executed when `saveNotification()` will be called
                print("calling from viewmodel")
                methodToCall()
            })
            .disposed(by: disposeBag)

    }

    private func methodToCall(){
        //logic
    }

}
</code>```

Whenever you would like to ask view controller to invoke methodToCall function.Simply call output.complete.onNext(true) in your view model.

Body:
I am using MVVM design pattern in iOS project. I am trying to call method in viewcontroller from viewmodel.

import Foundation

class NotificationViewModel {

    var onCompletion: ((_ success: Bool) -> ())?

    func saveNotification(notification: Dictionary<String, Any>) {
        print("notification save")
        //other logic
        onCompletion?(true)
    }
   }

"saveNotification" method getting called from appdelegate when notification received

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSMutableDictionary
            else {
                // handle any error here
                return
            }

        NotificationViewModel().saveNotification(notification: alert as! Dictionary<String, Any>)
        }

trying to call method in viewcontroller when "saveNotification" trigger

     class AlertViewController: BaseViewController{

            var viewModel = NotificationViewModel()

            override func viewDidLoad() {
                super.viewDidLoad()

                self.viewModel.onCompletion = { success in
                    // this should be executed when `saveNotification()` will be called
// **** this is never getting called ******
                    print("calling from viewmodel")
                    methodToCall()
                }
            }

          func methodToCall(){
            //logic
          }
      }

But the method in viewdidload is not getting called anytime.

Please suggest if its possible or any other way to achieve this?
Thanks for help

Body:
MVVM without Rx framework(RxSwift,ReactiveCocoa or Apple Combine) is a pain.
Below is my Solution in MVVM + RxSwift.Hopefully that will inspire you.

import Foundation
import RxSwift
import RxCocoa

final class NotificationViewModel: ViewModel, ViewModelType {

    struct Input { }

    struct Output {
        let compelete: PublishSubject<Bool>
    }

    let input: Input = Input()

    let output: Output = Output(compelete: PublishSubject<Bool>())
}

import UIKit
import RxSwift
import RxCocoa
import Rswift

final class NotificationViewController: ViewController<LoginViewModel> {

    override func bindViewModel() {

        vm.output.compelete
            .subscribe(onNext: { [unowned self] _ in
                // this will be executed when `saveNotification()` will be called
                print("calling from viewmodel")
                methodToCall()
            })
            .disposed(by: disposeBag)

    }

    private func methodToCall(){
        //logic
    }

}

Whenever you would like to ask view controller to invoke methodToCall function.Simply call output.complete.onNext(true) in your view model.


答:
it depends what permission you are looking for. if you're just looking for any you can do this:

```<code>   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      return group.permission // this will true if permission array is > 0
     });

    return passing
  }
</code>```

or if you're looking for something more specific

```<code>   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      if  (group.permissions[0].id === 1) {
         return true
      }
      return false
     });

    return passing
  }
</code>```

you can change this line: if(group.permissions[0].id === 1) to match any of the permissions you want

EDIT BELOW

if you change the permissions to be structured like this it should work:

permissions : {codename: 'codename'}

Title: Check if an object is present in a nested array reactjs

Body:
it depends what permission you are looking for. if you're just looking for any you can do this:

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      return group.permission // this will true if permission array is > 0
     });

    return passing
  }

or if you're looking for something more specific

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      if  (group.permissions[0].id === 1) {
         return true
      }
      return false
     });

    return passing
  }

you can change this line: if(group.permissions[0].id === 1) to match any of the permissions you want

EDIT BELOW

if you change the permissions to be structured like this it should work:

permissions : {codename: 'codename'}


问:
Can I dock a div against another div in IE 8?
Consider this page: http://losthobbit.net/temp/docking.html

Here's the HTML:

```<code><html>
<head>
    <title></title>
</head>
<body>
    <div style="position: absolute; bottom: 0; right: 0; top: 0; width: 259; background-color: #00FF00">
        <input type="button" style="position: absolute; left: 161; top: 30; width: 75; height: 25"/>
    </div>
    <div style="position: absolute; bottom: 0; right: 259; left: 0; height: 100; background-color: #00FFFF">
        <input type="button" style="position: absolute; right: 10; top: 30; width: 75; height: 25"/>
    </div>
</body>
</html>
</code>```

In Chrome & FireFox this works perfectly.  The second div docks against the first div.

Is it possible to get this working in IE8?

Thank you in advance, wonderful people :)

答:
http://jsfiddle.net/X2QYs/

Try this, does what you have asked.

Not sure why you would ever want to do that though, is not like any webpage design I have seen before.

Body:
Consider this page: http://losthobbit.net/temp/docking.html

Here's the HTML:

    <title></title>

        <input type="button" style="position: absolute; left: 161; top: 30; width: 75; height: 25"/>

        <input type="button" style="position: absolute; right: 10; top: 30; width: 75; height: 25"/>

In Chrome & FireFox this works perfectly.  The second div docks against the first div.

Is it possible to get this working in IE8?

Thank you in advance, wonderful people :)


问:
intellij/scala/play application not building - port bind error
I am unable to build my scala/play application.

```<code>[error] a.i.TcpListener - Bind failed for TCP channel on endpoint [/0.0.0.0:9000]
java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:433)
    at sun.nio.ch.Net.bind(Net.java:425)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at akka.io.TcpListener.liftedTree1$1(TcpListener.scala:56)
    at akka.io.TcpListener.<init>(TcpListener.scala:53)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
akka.stream.impl.io.ConnectionSourceStage$$anon$2$$anon$1: Bind failed because of Address already in use: bind
Caused by: java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:433)
    at sun.nio.ch.Net.bind(Net.java:425)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at akka.io.TcpListener.liftedTree1$1(TcpListener.scala:56)
    at akka.io.TcpListener.<init>(TcpListener.scala:53)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at akka.util.Reflect$.instantiate(Reflect.scala:65)
    at akka.actor.ArgsReflectConstructor.produce(IndirectActorProducer.scala:96)
    at akka.actor.Props.newActor(Props.scala:213)
    at akka.actor.ActorCell.newActor(ActorCell.scala:626)
    at akka.actor.ActorCell.create(ActorCell.scala:652)
    at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:525)
    at akka.actor.ActorCell.systemInvoke(ActorCell.scala:547)
    at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:282)
    at akka.dispatch.Mailbox.run(Mailbox.scala:223)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
[trace] Stack trace suppressed: run 'last compile:run' for the full output.
[error] (compile:run) java.lang.reflect.InvocationTargetException
[error] Total time: 2 s, completed 01-Jun-2020 19:58:45
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256M; support was removed in 8.0

Process finished with exit code 1
</code>```

Interestingly, the process occupying the port 9000 is idea.exe!!

答: PHP plug-in may use port 9000 for XDebug. Either disable the plug-in or change the port via VM Options in the Run confuguration like this: -Dhttp.port=9090.

Body:
I am unable to build my scala/play application.

[error] a.i.TcpListener - Bind failed for TCP channel on endpoint [/0.0.0.0:9000]
java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:433)
    at sun.nio.ch.Net.bind(Net.java:425)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at akka.io.TcpListener.liftedTree1$1(TcpListener.scala:56)
    at akka.io.TcpListener.<init>(TcpListener.scala:53)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
akka.stream.impl.io.ConnectionSourceStage$$anon$2$$anon$1: Bind failed because of Address already in use: bind
Caused by: java.net.BindException: Address already in use: bind
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:433)
    at sun.nio.ch.Net.bind(Net.java:425)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at akka.io.TcpListener.liftedTree1$1(TcpListener.scala:56)
    at akka.io.TcpListener.<init>(TcpListener.scala:53)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at akka.util.Reflect$.instantiate(Reflect.scala:65)
    at akka.actor.ArgsReflectConstructor.produce(IndirectActorProducer.scala:96)
    at akka.actor.Props.newActor(Props.scala:213)
    at akka.actor.ActorCell.newActor(ActorCell.scala:626)
    at akka.actor.ActorCell.create(ActorCell.scala:652)
    at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:525)
    at akka.actor.ActorCell.systemInvoke(ActorCell.scala:547)
    at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:282)
    at akka.dispatch.Mailbox.run(Mailbox.scala:223)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
[trace] Stack trace suppressed: run 'last compile:run' for the full output.
[error] (compile:run) java.lang.reflect.InvocationTargetException
[error] Total time: 2 s, completed 01-Jun-2020 19:58:45
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256M; support was removed in 8.0

Process finished with exit code 1

Interestingly, the process occupying the port 9000 is idea.exe!!


问:
How to serialize JSON string containing date and time property using DataContractJsonSerializer?
we are trying to serialize a JSON object [as a string] into a custom class. While we rather not use any third-party packages such as Newtonsoft.Json or Json.NET, we tried to utilize DataContractJsonSerializer.
The JSON object contains a DateTime property that is provided in the "yyyy-MM-dd HH:mm:ss" and when it comes to serialization the expectation below is thrown.

There was an error deserializing the object of type  DateTime content
  '2020-05-29 09:05:39' does not start with '\/Date(' and end with
  ')\/' as required for JSON

IMPORTANT: the issue will be solved with NewtonSoft package and adding JsonSerializerSettings to JsonConvert.DeserializeObject. As the final product is is a COM Object, our final target dll must have no dependant DLLs.

You can find the technical details below:

JSON object is :

```<code>{
  ...,
  "export_time": "2020-05-29 09:05:39",
  "app_version": "1.1.0",
  "allowed_mac_addresses": [
    "XX-XX-XX-XX-XX-XX"
  ],
  "signature": ""
}
</code>```

Target class:

```<code>[DataContract]
public class MainFractionatorConfigFile
{
    [DataMember]
    internal string[] allowed_mac_addresses;

    [DataMember]
    internal DateTime export_time;

    [DataMember]
    internal string app_version;

    [DataMember]
    internal string signature;
}
</code>```

and the serializer method is :

```<code>public static MainFractionatorConfigFile ReadMainFractionatorConfigFile(string json)
{
    var deserializedUser = new MainFractionatorConfigFile();
    var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
    var ser = new DataContractJsonSerializer(deserializedUser.GetType());
    deserializedUser = ser.ReadObject(ms) as MainFractionatorConfigFile;
    ms.Close();
    return deserializedUser;
}
</code>```

Attempt 1: There are some other suggestions in the community such as this solution but they demand other packages to be referenced.

Attempt 2 was trying to add DateTimeDataContractSurrogate to DataContractJsonSerializer but was unsuccessful too.

To sum up we are looking for an alternative method for the code below:

```<code> var mainFObj = JsonConvert.DeserializeObject<MainFractionatorConfigFile>(myJson, new JsonSerializerSettings
                {
                    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
                });
</code>```

Any help or idea will be appreciated.

答:
In the case of having a constraint about adding third-party NuGet packages, why not trying to clone/download the package (i.e. Newtonsoft.JSON) from Github and add them directly to your project. So that you won't have any third-party dll your deployment (bin folder).

Please note that the latest versions of the Newtonsoft.JSON are implemented in .netcore and while your project is on .net framework 4, you have to download the compatible version. You can use the tags to find the best version to download.

Body:
we are trying to serialize a JSON object [as a string] into a custom class. While we rather not use any third-party packages such as Newtonsoft.Json or Json.NET, we tried to utilize DataContractJsonSerializer.
The JSON object contains a DateTime property that is provided in the "yyyy-MM-dd HH:mm:ss" and when it comes to serialization the expectation below is thrown.

There was an error deserializing the object of type  DateTime content
  '2020-05-29 09:05:39' does not start with '\/Date(' and end with
  ')\/' as required for JSON

IMPORTANT: the issue will be solved with NewtonSoft package and adding JsonSerializerSettings to JsonConvert.DeserializeObject. As the final product is is a COM Object, our final target dll must have no dependant DLLs.

You can find the technical details below:

JSON object is :

{
  ...,
  "export_time": "2020-05-29 09:05:39",
  "app_version": "1.1.0",
  "allowed_mac_addresses": [
    "XX-XX-XX-XX-XX-XX"
  ],
  "signature": ""
}

Target class:

[DataContract]
public class MainFractionatorConfigFile
{
    [DataMember]
    internal string[] allowed_mac_addresses;

    [DataMember]
    internal DateTime export_time;

    [DataMember]
    internal string app_version;

    [DataMember]
    internal string signature;
}

and the serializer method is :

public static MainFractionatorConfigFile ReadMainFractionatorConfigFile(string json)
{
    var deserializedUser = new MainFractionatorConfigFile();
    var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
    var ser = new DataContractJsonSerializer(deserializedUser.GetType());
    deserializedUser = ser.ReadObject(ms) as MainFractionatorConfigFile;
    ms.Close();
    return deserializedUser;
}

Attempt 1: There are some other suggestions in the community such as this solution but they demand other packages to be referenced.

Attempt 2 was trying to add DateTimeDataContractSurrogate to DataContractJsonSerializer but was unsuccessful too.

To sum up we are looking for an alternative method for the code below:

 var mainFObj = JsonConvert.DeserializeObject<MainFractionatorConfigFile>(myJson, new JsonSerializerSettings
                {
                    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
                });

Any help or idea will be appreciated.


问:
How to manually set the Culture during a ASP.NET Core MVC request?
I'm looking for something similar like the old behaviour of setting the Culture and everything in the request after that has that Culture.

Similar like ASP.NET 4.5:

```<code>Thread.CurrentThread.CurrentCulture     = culture_info;
Thread.CurrentThread.CurrentUICulture   = culture_info;
</code>```

When I do this right now, some code seems to be constantly resetting the Culture to English at various points in the MVC pipeline.

Why do I want that? Because I want to set the culture through my extended routing logic in a very large (and customizable) platform-type of web project.

The default RouteDataRequestCultureProvider doesn't seem to work at all - see explained here:

https://irensaltali.com/en/asp-net-core-mvc-localization-by-url-routedatarequestcultureprovider/

and

Localization works when culture is set via QueryString but not when culture is in route

I don't want to use the "hardcoded" url parsing that is being presented as a solution, because my routing logic is complicated - not all routes will have a culture defined in the same spot in the URL.

I tried setting this, but that also didn't work:

```<code>httpContext.Features.Set<IRequestCultureFeature>(new RequestCultureFeature(request_culture, new DummyProvider()));
</code>```

Is there any workaround for just simply setting the Culture for the rest of the request?

答:
A workaround for simply setting the Culture for the rest of the request is to use default QueryStringRequestCultureProvider.

Here is the whole demo:

Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddControllersWithViews()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();
    //...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    var supportedCultures = new[]
    {
        new CultureInfo("en-US"),
        new CultureInfo("de"),
        new CultureInfo("fr"),
    };

    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture("en-US"),
        // Formatting numbers, dates, etc.
        SupportedCultures = supportedCultures,
        // UI strings that we have localized.
        SupportedUICultures = supportedCultures
    });

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthorization();

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

Create Resource folder and add resource file as below:

Configure resource file like below:

Controllers.HomeController.de.resx

Controllers.HomeController.fr.resx

Reference:Resource file naming

Controller:

```<code>public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _localizer;

    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult Index()
    {
        ViewData["Title"] = _localizer["Your Title"];
        return View();
    }
}
</code>```

Index.cshtml:

```<code>@ViewData["Title"]
</code>```

Result:

Body:
I'm looking for something similar like the old behaviour of setting the Culture and everything in the request after that has that Culture.

Similar like ASP.NET 4.5:

Thread.CurrentThread.CurrentCulture     = culture_info;
Thread.CurrentThread.CurrentUICulture   = culture_info;

When I do this right now, some code seems to be constantly resetting the Culture to English at various points in the MVC pipeline.

Why do I want that? Because I want to set the culture through my extended routing logic in a very large (and customizable) platform-type of web project.

The default RouteDataRequestCultureProvider doesn't seem to work at all - see explained here:

https://irensaltali.com/en/asp-net-core-mvc-localization-by-url-routedatarequestcultureprovider/

and

Localization works when culture is set via QueryString but not when culture is in route

I don't want to use the "hardcoded" url parsing that is being presented as a solution, because my routing logic is complicated - not all routes will have a culture defined in the same spot in the URL.

I tried setting this, but that also didn't work:

httpContext.Features.Set<IRequestCultureFeature>(new RequestCultureFeature(request_culture, new DummyProvider()));

Is there any workaround for just simply setting the Culture for the rest of the request?

Body:
A workaround for simply setting the Culture for the rest of the request is to use default QueryStringRequestCultureProvider.

Here is the whole demo:

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddControllersWithViews()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();
    //...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    var supportedCultures = new[]
    {
        new CultureInfo("en-US"),
        new CultureInfo("de"),
        new CultureInfo("fr"),
    };

    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture("en-US"),
        // Formatting numbers, dates, etc.
        SupportedCultures = supportedCultures,
        // UI strings that we have localized.
        SupportedUICultures = supportedCultures
    });

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthorization();

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

Create Resource folder and add resource file as below:

Configure resource file like below:

Controllers.HomeController.de.resx

Controllers.HomeController.fr.resx

Reference:Resource file naming

Controller:

public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _localizer;

    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult Index()
    {
        ViewData["Title"] = _localizer["Your Title"];
        return View();
    }
}

Index.cshtml:

@ViewData["Title"]

Result:


问:
Get WASD keys to follow camera rotation in Unity
I understand there are many answers to this online but I was unable to apply them correctly to my code.
I have tried using pre-made player assets but could not get that to work.</p>

```<code>    Vector3 pos = transform.position;

    public float X;
    public float Y;
    public float Z;

// Used to tilt camera up and down
float tilt = 0;

        if (Input.GetMouseButton(1))
    {
        transform.Rotate(new Vector3(Input.GetAxis("Mouse Y") * panSpeed, Input.GetAxis("Mouse X") * panSpeed, 0));
        X = transform.rotation.eulerAngles.x;
        Y = transform.rotation.eulerAngles.y;
        Z = transform.rotation.eulerAngles.z;
        // Add current position of mouse input
        tilt += X;
        transform.rotation = Quaternion.Euler(0, Y, tilt);
    }

    //Spaceship does not go in direction it is facing once panned
    if (Input.GetKey("w"))
    {
        //transform.rotation = Quaternion.Euler(0, Y, tilt);
        pos.z += speed * Time.deltaTime;
    }
    if (Input.GetKey("s"))
    {
        pos.z -= speed * Time.deltaTime;
    }
    if (Input.GetKey("d"))
    {
        pos.x += speed * Time.deltaTime;
        // DEBUG Does not work properly while mouse held down
        //transform.Rotate(-1, 0, 0);
    }
    if (Input.GetKey("a"))
    {
        pos.x -= speed * Time.deltaTime;
    }

    transform.position = pos;
</code>```

答:
Assuming here the "Camera" equals transform you can simply use its local axis transform.forward

Returns a normalized vector representing the blue axis of the transform in world space.

and transform.right

Returns a normalized vector representing the red axis of the transform in world space.

like e.g.

```<code>private void Update()
{
    if (Input.GetMouseButton(1))
    {
        // NOTE: I DON'T UNDERSTAND THIS CODE BLOCK YET
        // YOU KNOW E.G. THAT IF YOU "transform.eulerAngles.x" ALREADY IS "45°"
        // THE "tilt" WOULD JUMP EVERY FRAME IN HUGER STEPS (45 -> 90 -> 180 - 360 ....)

        // ALSO WHY ROTATE IN X AXIS IF AFTERWARDS YOU RESET THE X ROTATION
        // AND RATHER APPLY IT TO Z?

        transform.Rotate(new Vector3(Input.GetAxis("Mouse Y") * panSpeed, Input.GetAxis("Mouse X") * panSpeed, 0));
        X = transform.eulerAngles.x;
        Y = transform.eulerAngles.y;
        Z = transform.eulerAngles.z;
        // Add current position of mouse input
        tilt += X;
        transform.rotation = Quaternion.Euler(0, Y, tilt);
    }

    Vector3 movement = Vector3.zero;

    if (Input.GetKey(KeyCode.W))
    {
        movement += transform.forward;
    }
    if (Input.GetKey(KeyCode.S))
    {
        movement -= transform.forward;
    }
    if (Input.GetKey(KeyCode.D))
    {
        movement += transform.right;
    }
    if (Input.GetKey(KeyCode.A))
    {
        movement -= transform.right;
    }

    // I would do it like this to make sure that diagonal movement
    // does not move faster
    transform.position = movement.normalized * speed * Time.deltaTime;
}
</code>```

Body:
I understand there are many answers to this online but I was unable to apply them correctly to my code.
I have tried using pre-made player assets but could not get that to work.

    Vector3 pos = transform.position;

    public float X;
    public float Y;
    public float Z;

// Used to tilt camera up and down
float tilt = 0;

        if (Input.GetMouseButton(1))
    {
        transform.Rotate(new Vector3(Input.GetAxis("Mouse Y") * panSpeed, Input.GetAxis("Mouse X") * panSpeed, 0));
        X = transform.rotation.eulerAngles.x;
        Y = transform.rotation.eulerAngles.y;
        Z = transform.rotation.eulerAngles.z;
        // Add current position of mouse input
        tilt += X;
        transform.rotation = Quaternion.Euler(0, Y, tilt);
    }

    //Spaceship does not go in direction it is facing once panned
    if (Input.GetKey("w"))
    {
        //transform.rotation = Quaternion.Euler(0, Y, tilt);
        pos.z += speed * Time.deltaTime;
    }
    if (Input.GetKey("s"))
    {
        pos.z -= speed * Time.deltaTime;
    }
    if (Input.GetKey("d"))
    {
        pos.x += speed * Time.deltaTime;
        // DEBUG Does not work properly while mouse held down
        //transform.Rotate(-1, 0, 0);
    }
    if (Input.GetKey("a"))
    {
        pos.x -= speed * Time.deltaTime;
    }

    transform.position = pos;

Body:
Assuming here the "Camera" equals transform you can simply use its local axis transform.forward

Returns a normalized vector representing the blue axis of the transform in world space.

and transform.right

Returns a normalized vector representing the red axis of the transform in world space.

like e.g.

private void Update()
{
    if (Input.GetMouseButton(1))
    {
        // NOTE: I DON'T UNDERSTAND THIS CODE BLOCK YET
        // YOU KNOW E.G. THAT IF YOU "transform.eulerAngles.x" ALREADY IS "45°"
        // THE "tilt" WOULD JUMP EVERY FRAME IN HUGER STEPS (45 -> 90 -> 180 - 360 ....)

        // ALSO WHY ROTATE IN X AXIS IF AFTERWARDS YOU RESET THE X ROTATION
        // AND RATHER APPLY IT TO Z?

        transform.Rotate(new Vector3(Input.GetAxis("Mouse Y") * panSpeed, Input.GetAxis("Mouse X") * panSpeed, 0));
        X = transform.eulerAngles.x;
        Y = transform.eulerAngles.y;
        Z = transform.eulerAngles.z;
        // Add current position of mouse input
        tilt += X;
        transform.rotation = Quaternion.Euler(0, Y, tilt);
    }

    Vector3 movement = Vector3.zero;

    if (Input.GetKey(KeyCode.W))
    {
        movement += transform.forward;
    }
    if (Input.GetKey(KeyCode.S))
    {
        movement -= transform.forward;
    }
    if (Input.GetKey(KeyCode.D))
    {
        movement += transform.right;
    }
    if (Input.GetKey(KeyCode.A))
    {
        movement -= transform.right;
    }

    // I would do it like this to make sure that diagonal movement
    // does not move faster
    transform.position = movement.normalized * speed * Time.deltaTime;
}