问:
clock gating verilog code not working correctly
I'm to trying to code a clock gating logic  that allows data to pass only at the posedge write_clk_en. the code is compiled correctly in EDA playground but the output is not as intended.So according to code,

```<code>@ (posedge write_clk_en)begin
 data_in[3] <= 1'b1;
end
</code>```

at this instance the write_clk_en is disabled, so data_in[3] NBA should be halted and it waits for next valid posedge (which is the next posedge of write_clk_en here), data_in[3] should be written. But that is not happening, rather the gated clock period is also getting considered and the NBA assignment is occurring even when write_clk_en is gated for 4th pulse.What could be the issue ?.the wave form is shown here.

the sv code :

```<code>module tb;

logic [4:0]  data_in;
logic  write_clk;
logic  write_clk_en;
logic write_clk_mod;
logic [5:0] write_clk_init;

always//write_clk 500M
  begin
        write_clk  =0;
    #10 write_clk = 1;
    #10 write_clk = 0;
  end

initial begin
  $dumpfile("dump.vcd");
  $dumpvars;
  #10000 $finish;
end

initial begin
data_in=5'b00000;
write_clk_init = 6'b000000;
write_clk_mod=0;
end

initial begin
write_clk_init =6'b110111;
end

initial begin
repeat (3) begin
@(posedge write_clk)begin
if(write_clk_init[0]==1 || write_clk_init[0]==0)
write_clk_mod<=write_clk_init[0];
end
@(posedge write_clk)begin
if(write_clk_init[1]==1 || write_clk_init[1]==0)
write_clk_mod<=write_clk_init[1];
end
@(posedge write_clk)begin
if(write_clk_init[2]==1 || write_clk_init[2]==0)
write_clk_mod<=write_clk_init[2];
end
@(posedge write_clk)begin
if(write_clk_init[3]==1 || write_clk_init[3]==0)
write_clk_mod<=write_clk_init[3];
end
@(posedge write_clk)begin
if(write_clk_init[4]==1 || write_clk_init[4]==0)
write_clk_mod<=write_clk_init[4];
end
@(posedge write_clk)begin
if(write_clk_init[5]==1 || write_clk_init[5]==0)
write_clk_mod<=write_clk_init[5];
end
end
end

  always @ (*) begin
  write_clk_en  = write_clk & write_clk_mod;
end

initial begin

@ (posedge write_clk_en)begin
data_in[0] <= 1'b1;
end
@ (posedge write_clk_en)begin
data_in[1] <= 1'b1;
end
@ (posedge write_clk_en)begin
 data_in[2] <= 1'b1;
 end
@ (posedge write_clk_en)begin
 data_in[3] <= 1'b1;
end
@ (posedge write_clk_en)begin
data_in[4] <= 1'b1;
end

end

endmodule
</code>```

答:
Within initial blocks, change your NBAs to BAs. NBAs should only be used within an always @(posedge clocksignal) block

Take also into account that in simulations, @(posedge clocksignal) blocks (without the reserved word always) are treated as delays (wait until a rising edge clk event happens, then continue simulation). By the way you have written these blocks in your initial statements, I didn't know for sure if you were aware of their true behaviour. I've rewritten those @(posedge) blocks to make the simulation flow a bit clear.

I have also merged some of your initial blocks into one. Every initial block you have is started at the same time (simulation time 0). Particulary, write_clk_init is assigned in two different initial blocks.

This edited code works as expected. It is also available at https://www.edaplayground.com/x/3VYk

```<code>module tb;
  reg [4:0]  data_in;
  reg  write_clk;
  reg  write_clk_en;
  reg write_clk_mod;
  reg [5:0] write_clk_init;

  initial begin
    $dumpfile("dump.vcd");
    $dumpvars;
    #10000 $finish;
  end

  initial begin
    data_in = 5'b00000;
    write_clk_init = 6'b110111;
    write_clk_mod = 0;
    write_clk = 0;

    repeat (3) begin
      @(posedge write_clk);
      if(write_clk_init[0]==1 || write_clk_init[0]==0)
          write_clk_mod = write_clk_init[0];

      @(posedge write_clk);
      if(write_clk_init[1]==1 || write_clk_init[1]==0)
          write_clk_mod = write_clk_init[1];

      @(posedge write_clk);
      if(write_clk_init[2]==1 || write_clk_init[2]==0)
          write_clk_mod = write_clk_init[2];

      @(posedge write_clk);
      if(write_clk_init[3]==1 || write_clk_init[3]==0)
          write_clk_mod = write_clk_init[3];

      @(posedge write_clk);
      if(write_clk_init[4]==1 || write_clk_init[4]==0)
          write_clk_mod = write_clk_init[4];

      @(posedge write_clk);
      if(write_clk_init[5]==1 || write_clk_init[5]==0)
          write_clk_mod = write_clk_init[5];
    end
  end

  always @* begin
    write_clk_en  = write_clk & write_clk_mod;
  end

  initial begin
    @(posedge write_clk_en);
    data_in[0] = 1'b1;

    @(posedge write_clk_en);
    data_in[1] = 1'b1;

    @(posedge write_clk_en);
    data_in[2] = 1'b1;

    @(posedge write_clk_en);
    data_in[3] = 1'b1;

    @(posedge write_clk_en);
    data_in[4] = 1'b1;
  end

  always begin
    write_clk = #10 ~write_clk;
  end
endmodule
</code>```

Body:
I'm to trying to code a clock gating logic  that allows data to pass only at the posedge write_clk_en. the code is compiled correctly in EDA playground but the output is not as intended.So according to code,

@ (posedge write_clk_en)begin
 data_in[3] <= 1'b1;
end

at this instance the write_clk_en is disabled, so data_in[3] NBA should be halted and it waits for next valid posedge (which is the next posedge of write_clk_en here), data_in[3] should be written. But that is not happening, rather the gated clock period is also getting considered and the NBA assignment is occurring even when write_clk_en is gated for 4th pulse.What could be the issue ?.the wave form is shown here.

the sv code :

module tb;

logic [4:0]  data_in;
logic  write_clk;
logic  write_clk_en;
logic write_clk_mod;
logic [5:0] write_clk_init;

always//write_clk 500M
  begin
        write_clk  =0;
    #10 write_clk = 1;
    #10 write_clk = 0;
  end

initial begin
  $dumpfile("dump.vcd");
  $dumpvars;
  #10000 $finish;
end

initial begin
data_in=5'b00000;
write_clk_init = 6'b000000;
write_clk_mod=0;
end

initial begin
write_clk_init =6'b110111;
end

initial begin
repeat (3) begin
@(posedge write_clk)begin
if(write_clk_init[0]==1 || write_clk_init[0]==0)
write_clk_mod<=write_clk_init[0];
end
@(posedge write_clk)begin
if(write_clk_init[1]==1 || write_clk_init[1]==0)
write_clk_mod<=write_clk_init[1];
end
@(posedge write_clk)begin
if(write_clk_init[2]==1 || write_clk_init[2]==0)
write_clk_mod<=write_clk_init[2];
end
@(posedge write_clk)begin
if(write_clk_init[3]==1 || write_clk_init[3]==0)
write_clk_mod<=write_clk_init[3];
end
@(posedge write_clk)begin
if(write_clk_init[4]==1 || write_clk_init[4]==0)
write_clk_mod<=write_clk_init[4];
end
@(posedge write_clk)begin
if(write_clk_init[5]==1 || write_clk_init[5]==0)
write_clk_mod<=write_clk_init[5];
end
end
end

  always @ (*) begin
  write_clk_en  = write_clk & write_clk_mod;
end

initial begin

@ (posedge write_clk_en)begin
data_in[0] <= 1'b1;
end
@ (posedge write_clk_en)begin
data_in[1] <= 1'b1;
end
@ (posedge write_clk_en)begin
 data_in[2] <= 1'b1;
 end
@ (posedge write_clk_en)begin
 data_in[3] <= 1'b1;
end
@ (posedge write_clk_en)begin
data_in[4] <= 1'b1;
end

end

endmodule

Body:
Within initial blocks, change your NBAs to BAs. NBAs should only be used within an always @(posedge clocksignal) block

Take also into account that in simulations, @(posedge clocksignal) blocks (without the reserved word always) are treated as delays (wait until a rising edge clk event happens, then continue simulation). By the way you have written these blocks in your initial statements, I didn't know for sure if you were aware of their true behaviour. I've rewritten those @(posedge) blocks to make the simulation flow a bit clear.

I have also merged some of your initial blocks into one. Every initial block you have is started at the same time (simulation time 0). Particulary, write_clk_init is assigned in two different initial blocks.

This edited code works as expected. It is also available at https://www.edaplayground.com/x/3VYk

module tb;
  reg [4:0]  data_in;
  reg  write_clk;
  reg  write_clk_en;
  reg write_clk_mod;
  reg [5:0] write_clk_init;

  initial begin
    $dumpfile("dump.vcd");
    $dumpvars;
    #10000 $finish;
  end

  initial begin
    data_in = 5'b00000;
    write_clk_init = 6'b110111;
    write_clk_mod = 0;
    write_clk = 0;

    repeat (3) begin
      @(posedge write_clk);
      if(write_clk_init[0]==1 || write_clk_init[0]==0)
          write_clk_mod = write_clk_init[0];

      @(posedge write_clk);
      if(write_clk_init[1]==1 || write_clk_init[1]==0)
          write_clk_mod = write_clk_init[1];

      @(posedge write_clk);
      if(write_clk_init[2]==1 || write_clk_init[2]==0)
          write_clk_mod = write_clk_init[2];

      @(posedge write_clk);
      if(write_clk_init[3]==1 || write_clk_init[3]==0)
          write_clk_mod = write_clk_init[3];

      @(posedge write_clk);
      if(write_clk_init[4]==1 || write_clk_init[4]==0)
          write_clk_mod = write_clk_init[4];

      @(posedge write_clk);
      if(write_clk_init[5]==1 || write_clk_init[5]==0)
          write_clk_mod = write_clk_init[5];
    end
  end

  always @* begin
    write_clk_en  = write_clk & write_clk_mod;
  end

  initial begin
    @(posedge write_clk_en);
    data_in[0] = 1'b1;

    @(posedge write_clk_en);
    data_in[1] = 1'b1;

    @(posedge write_clk_en);
    data_in[2] = 1'b1;

    @(posedge write_clk_en);
    data_in[3] = 1'b1;

    @(posedge write_clk_en);
    data_in[4] = 1'b1;
  end

  always begin
    write_clk = #10 ~write_clk;
  end
endmodule


来源: stackexchange

问:
Error: cannot find symbol import androidx.navigation.fragment.navArgs
I was doing the "Build Your First Android App in Java" from the website https://codelabs.developers.google.com/codelabs/build-your-first-android-app/#8.
Everything worked until I got to step 8, which was to import androidx.navigation.fragment.navArgs, but I got an error:

import androidx.navigation.fragment.navArgs;

How do I fix it? What does it mean?

答:
You have two build.gradle in your build scripts section. One of them is your project wide file and the other is your module one.

In your project one, you have to have this line inside your depencies:

```<code>    dependencies {

        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0-alpha04"
    }
</code>```

in your other file, the build.gradle that is for your module, you have to add this following line (it is usually on top of it with the other lines alike):

```<code>apply plugin: 'androidx.navigation.safeargs.kotlin'
</code>```

On other note, as you are starting to learn, I strongly recommend that you learn Kotlin instead of Java. Kotlin is the newly Google supported language to develop Android Apps.

Let me know if it fixes your issue.

ContentLicense: CC BY-SA 4.0

Body:
You have two build.gradle in your build scripts section. One of them is your project wide file and the other is your module one.

In your project one, you have to have this line inside your depencies:

    dependencies {

        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0-alpha04"
    }

in your other file, the build.gradle that is for your module, you have to add this following line (it is usually on top of it with the other lines alike):

apply plugin: 'androidx.navigation.safeargs.kotlin'

On other note, as you are starting to learn, I strongly recommend that you learn Kotlin instead of Java. Kotlin is the newly Google supported language to develop Android Apps.

Let me know if it fixes your issue.


问:
Bootstrap4 Initializing Toasts
I am working with toasts in Bootstrap 4 and there is one things that's bothering me:

If I initialize the toast

```<code><div class="toast my-3" data-delay="2500">
    <div class="toast-header text-dark">
        //fill this later
    </div>
    <div class="toast-body text-dark">
        //fill this later
    </div>
</div>
</code>```

like in the documentation

```<code>$(document).ready(function () {
  $(".toast").toast("show");
});
</code>```

the toast is show as expected, when the page loads. If I don't initialize the toast, the html code takes some place. at the bottom of my page.

How can I make the toast not to be shown when loading the page and not taking some place due to html code? I tried initialize them with toast("hide") or toast("dispose") as well.

Thanks

答:
When you write this:

```<code>$(document).ready(function () {
  $(".toast").toast("show");
});
</code>```

It means you're expecting the toast to show as soon as the DOM is loaded. If you want the toast to appear conditionnally, you have for example to create a button in your html file (click on "Run snippet" and click on the button).

$(document).ready(function () {
  $('#toastThis').on( "click", function() {
    $(".toast").toast("show");
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.toast {
  position: absolute;
  top: 0;
  right: 0;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" id="toastThis" class="btn btn-primary">Primary</button>

    Bootstrap
    11 mins ago
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
      ×
    </button>

    Hello, world! This is a toast message.

```

Title: Bootstrap4 Initializing Toasts

Body:
I am working with toasts in Bootstrap 4 and there is one things that's bothering me:

If I initialize the toast

        //fill this later

        //fill this later

like in the documentation

$(document).ready(function () {
  $(".toast").toast("show");
});

the toast is show as expected, when the page loads. If I don't initialize the toast, the html code takes some place. at the bottom of my page.

How can I make the toast not to be shown when loading the page and not taking some place due to html code? I tried initialize them with toast("hide") or toast("dispose") as well.

Thanks

Body:
When you write this:

$(document).ready(function () {
  $(".toast").toast("show");
});

It means you're expecting the toast to show as soon as the DOM is loaded. If you want the toast to appear conditionnally, you have for example to create a button in your html file (click on "Run snippet" and click on the button).

$(document).ready(function () {
  $('#toastThis').on( "click", function() {
    $(".toast").toast("show");
  });

});

.toast {
  position: absolute;
  top: 0;
  right: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.bundle.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" id="toastThis" class="btn btn-primary">Primary</button>

<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded mr-2" alt="...">
    <strong class="mr-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>


问:
DNS redirection from root domain to www for a heroku app
I can't configure my DNS in order to redirect my root domain to www.domain for a Heroku app.

I'm using Vultr's DNS. The problem is Heroku does not provide IP address so I can't add an A record, nor a CNAM record to redirect root to www (source):

DNS A-records require that an IP address be hard-coded into your
  application’s DNS configuration. This prevents your infrastructure
  provider from assigning your app a new IP address on your behalf when
  adverse conditions arise and can have a serious impact to your app’s
  uptime.

A CNAME record does not require hard-coded IP addresses and allows
  Heroku to manage the set of IPs associated with your domain. However,
  CNAME records are not available at the zone apex and can’t be used to
  configure root domains.

Here is my DNS configuration:

Thus, the SSL certificate fails in Heroku:

My question is: how can I easily redirect the root domain of my Heroku app to www.domain.com?

Thanks.

答:
ping with the DNS target you have got from Heroku. you will get the IP for that. Use that as Dns targe in vultr. worked for me.

example:

```<code>➜  ~ ping botletter.com.herokudns.com
PING botletter.com.herokudns.com (3.212.117.40): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
</code>```

Here use 3.212.117.40 IP in vultr DNS target

ContentLicense: CC BY-SA 3.0

Body:
ping with the DNS target you have got from Heroku. you will get the IP for that. Use that as Dns targe in vultr. worked for me.

example:

➜  ~ ping botletter.com.herokudns.com
PING botletter.com.herokudns.com (3.212.117.40): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1

Here use 3.212.117.40 IP in vultr DNS target


问:
Getting Squarespace to add Access-control-allow-origin header
I'm trying to load some audio files into a squarespace page that will be run through Web Audio API and I get the following error:
"MediaElementAudioSource outputs zeroes due to CORS access restrictions for..."
I inspected the response header from the Squarespace site it does not have the Access-Control-Allow-Origin header.  From what I understand, Web Audio API requires the header or else it outputs zeros.  Is there a way to get Squarespace to add the header in the response or am going to be forced to find a different solution?  I need to process the audio with the API so I can't use HTML's <audio> elements which would work.

答: Unfortunately, you won't be able to allow cross-origin requests to assets stored on a Squarespace site. The assets are served from Squarespace's global CDN (unspecific to your website) and, correspondingly, they don't provide access to change such restrictions.</p>


问:
Binary serialization protocol
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

```<code>class Person
{
   int age;
   string name;
};
</code>```

Java class

```<code>class Person
{
   int age;
   String name;
}
</code>```

C++ encoding

```<code>Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);
</code>```

Java decoding

```<code>byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);
</code>```

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.

答:
You might want to check out these projects and choose one:

Protocol Buffers

Thrift

Apache Avro

Here is a Thrift-vs-PB comparison I read recently. You should also refer to this Wiki for performance comparisons between these libraries.

Title: Binary serialization protocol

Body:
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

class Person
{
   int age;
   string name;
};

Java class

class Person
{
   int age;
   String name;
}

C++ encoding

Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);

Java decoding

byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.


问:
is there any way to apply formmatter to all column or whole table?
```<code>var table = new Tabulator("#Mytable",
    {
        layout:"fitColumns",
       columns: [
           { title: "Name",formatter:html, variableHeight:true},
           { title: "Ingredients in1 L" ,formatter:html, variableHeight:true},
           { title: "Type of solution",formatter:html, variableHeight:true},
           { title: "pH",formatter:html, variableHeight:true},//"html" }
           { title: "Normal osmolarity (240‐340 mOsm/L)",formatter:htmlWrapFormatter, variableHeight:true},//"html" }
        ]
    });
</code>```

<p>Inside column[] is there any way to apply the same attribute property without specifying the column name.  </p>

答:
Take a look at:

```<code>http://tabulator.info/docs/4.6/modules#default
</code>```

It provides a method to provide default setup options.

Body:
var table = new Tabulator("#Mytable",
    {
        layout:"fitColumns",
       columns: [
           { title: "Name",formatter:html, variableHeight:true},
           { title: "Ingredients in1 L" ,formatter:html, variableHeight:true},
           { title: "Type of solution",formatter:html, variableHeight:true},
           { title: "pH",formatter:html, variableHeight:true},//"html" }
           { title: "Normal osmolarity (240‐340 mOsm/L)",formatter:htmlWrapFormatter, variableHeight:true},//"html" }
        ]
    });

Inside column[] is there any way to apply the same attribute property without specifying the column name.

Body:
Take a look at:

http://tabulator.info/docs/4.6/modules#default

It provides a method to provide default setup options.


问:
How to create two foreign keys to the same table with SQLite in Xamari Form
I working in a project with Xamarin Form using C#. I'm trying to create two foreign keys to the same table, using this code:

```<code>[Table("Posts")]
public class Post
{
    [PrimaryKey]
    public long PostID { get; set; }
    public string Name { get; set; }

    public TypeEntity mode = null;
    [ManyToOne(CascadeOperations = CascadeOperation.CascadeInsert)]
    public TypeEntity Mode
    {
        get
        {
            return mode;
        }
        set
        {
            mode = value;
        }
    }
    [ForeignKey(typeof(TypeEntity))]
    public long ModeID { get; set; }

    public TypeEntity level = null;
    [ManyToOne(CascadeOperations = CascadeOperation.CascadeInsert)]
    public TypeEntity Level
    {
        get
        {
            return level;
        }
        set
        {
            level = value;
        }
    }
    [ForeignKey(typeof(TypeEntity))]
    public long LevelID { get; set; }
}

[Table("Types")]
public class TypeEntity
{
    [PrimaryKey]
    public long TypeID { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}
</code>```

As you can see, the properties Mode and Level are type "TypeEntty", so I need to create the relations.
When I try to insert data, only "Mode" property is inserted ok, "Level" property stay null.

```<code>public abstract class BaseStore<T> where T : new()
{
    public static SQLiteConnection sql;

    public BaseStore()
    {
        sql = DependencyService.Get<ISQLite>().GetConnection();
        Init();
    }
    public void Init()
    {
        sql.CreateTable<T>();
    }

    public void Insert(T entity)
    {
        sql.InsertWithChildren(entity);
    }
}
</code>```

I switched properties order, I added Level first than Mode, and Level got the value. It means, that SQLIte take only the first property to create the relation.

Does anyone know why this isn't working?

I'm working with SQLite.Net.Core-PCL 3.1.1 and SQLiteNetExtensions 2.1.0.

答:
You have to manually specify which foreign key corresponds to each relation. To do so, pass the ForeignKey parameter in each ManyToOne attribute.

Can't test it right now, but it would probably look something like this:

```<code>[ManyToOne(ForeignKey = "ModeID", CascadeOperations = CascadeOperation.CascadeInsert)]
public TypeEntity Mode

(...)

[ManyToOne(ForeignKey = "LevelID", CascadeOperations = CascadeOperation.CascadeInsert)]
public TypeEntity Level
</code>```

Body:
I working in a project with Xamarin Form using C#. I'm trying to create two foreign keys to the same table, using this code:

[Table("Posts")]
public class Post
{
    [PrimaryKey]
    public long PostID { get; set; }
    public string Name { get; set; }

    public TypeEntity mode = null;
    [ManyToOne(CascadeOperations = CascadeOperation.CascadeInsert)]
    public TypeEntity Mode
    {
        get
        {
            return mode;
        }
        set
        {
            mode = value;
        }
    }
    [ForeignKey(typeof(TypeEntity))]
    public long ModeID { get; set; }

    public TypeEntity level = null;
    [ManyToOne(CascadeOperations = CascadeOperation.CascadeInsert)]
    public TypeEntity Level
    {
        get
        {
            return level;
        }
        set
        {
            level = value;
        }
    }
    [ForeignKey(typeof(TypeEntity))]
    public long LevelID { get; set; }
}

[Table("Types")]
public class TypeEntity
{
    [PrimaryKey]
    public long TypeID { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

As you can see, the properties Mode and Level are type "TypeEntty", so I need to create the relations.
When I try to insert data, only "Mode" property is inserted ok, "Level" property stay null.

public abstract class BaseStore<T> where T : new()
{
    public static SQLiteConnection sql;

    public BaseStore()
    {
        sql = DependencyService.Get<ISQLite>().GetConnection();
        Init();
    }
    public void Init()
    {
        sql.CreateTable<T>();
    }

    public void Insert(T entity)
    {
        sql.InsertWithChildren(entity);
    }
}

I switched properties order, I added Level first than Mode, and Level got the value. It means, that SQLIte take only the first property to create the relation.

Does anyone know why this isn't working?

I'm working with SQLite.Net.Core-PCL 3.1.1 and SQLiteNetExtensions 2.1.0.

Body:
You have to manually specify which foreign key corresponds to each relation. To do so, pass the ForeignKey parameter in each ManyToOne attribute.

Can't test it right now, but it would probably look something like this:

[ManyToOne(ForeignKey = "ModeID", CascadeOperations = CascadeOperation.CascadeInsert)]
public TypeEntity Mode

(...)

[ManyToOne(ForeignKey = "LevelID", CascadeOperations = CascadeOperation.CascadeInsert)]
public TypeEntity Level


问:
How to remove "Text selection" context action bar for EditText but keep text selection functionality
I want to create custom interface for basic copy, cut, paste and format operations on EditText. But when I start to select text, text selection context bar shows up at the top. And I'm unable to figure out how to remove CAB and still keep ability to select text.

Using setCustomSelectionActionModeCallback with overwritten ActionMode.Callback removes context bar, but it also removes ability to select text.

答:
You can completely remove ActionBarContextView.

So, use this code:

```<code>    tv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            removeActionBar(getWindow().getDecorView());
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });

    private void removeActionBar(View v) {
            ViewGroup viewgroup = (ViewGroup) v;

            for (int i = 0; i < viewgroup.getChildCount(); i++) {
                    View v1=viewgroup.getChildAt(i);
                    if ( v1 instanceof ViewGroup )
                            removeActionBar(v1);
                    if ( v1 instanceof ActionBarContextView ) {
                            viewgroup.removeView(v1);
                    }
            }
    }
</code>```

Body:
You can completely remove ActionBarContextView.

So, use this code:

    tv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            removeActionBar(getWindow().getDecorView());
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });

    private void removeActionBar(View v) {
            ViewGroup viewgroup = (ViewGroup) v;

            for (int i = 0; i < viewgroup.getChildCount(); i++) {
                    View v1=viewgroup.getChildAt(i);
                    if ( v1 instanceof ViewGroup )
                            removeActionBar(v1);
                    if ( v1 instanceof ActionBarContextView ) {
                            viewgroup.removeView(v1);
                    }
            }
    }


问:
Entity Framework .Include() with compile time checking?
Consider the following code, which is calling against an EF generated data context:

```<code>var context = new DataContext();
var employees = context.Employees.Include("Department");
</code>```

If I change the name of the  Department relationship then this code is going to start throwing a runtime error.  So is there any way to call the .Include() method in a safe manner, so I get compile time checking for all the relationships being referenced?

答:
Taking moi_meme's idea a step further, my colleague developed the following solution that works in all cases.  He introduced a new method caled Includes() for dealing with one-to-many and many-to-many relationships.  It allows you to write this:

```<code>context.Customer
    .Include("Address")
    .Include("Orders")
    .Include("Orders.OrderLines")
</code>```

as this:

```<code>context.Customer
    .Include(c => c.Address)
    .Includes(c => c.Include(customer => customer.Orders)
                    .Include(order => order.OrderLines))
</code>```

All credit goes to https://stackoverflow.com/users/70427/bojan-resnik, so go give him some love if you like the solution.

```<code>public static class ObjectQueryExtensions
{
    public static ObjectQuery<T> Includes<T>(this ObjectQuery<T> query, Action<IncludeObjectQuery<T, T>> action)
    {
        var sb = new StringBuilder();
        var queryBuilder = new IncludeObjectQuery<T, T>(query, sb);
        action(queryBuilder);
        return queryBuilder.Query;
    }

    public static ObjectQuery<TEntity> Include<TEntity, TProperty>(this ObjectQuery<TEntity> query, Expression<Func<TEntity, TProperty>> expression)
    {
        var sb = new StringBuilder();
        return IncludeAllLevels(expression, sb, query);
    }

    static ObjectQuery<TQuery> IncludeAllLevels<TEntity, TProperty, TQuery>(Expression<Func<TEntity, TProperty>> expression, StringBuilder sb, ObjectQuery<TQuery> query)
    {
        foreach (var name in expression.GetPropertyLevels())
        {
            sb.Append(name);
            query = query.Include(sb.ToString());
            Debug.WriteLine(string.Format("Include(\"{0}\")", sb));
            sb.Append('.');
        }
        return query;
    }

    static IEnumerable<string> GetPropertyLevels<TClass, TProperty>(this Expression<Func<TClass, TProperty>> expression)
    {
        var namesInReverse = new List<string>();

        var unaryExpression = expression as UnaryExpression;
        var body = unaryExpression != null ? unaryExpression.Operand : expression.Body;

        while (body != null)
        {
            var memberExpression = body as MemberExpression;
            if (memberExpression == null)
                break;

            namesInReverse.Add(memberExpression.Member.Name);
            body = memberExpression.Expression;
        }

        namesInReverse.Reverse();
        return namesInReverse;
    }

    public class IncludeObjectQuery<TQuery, T>
    {
        readonly StringBuilder _pathBuilder;
        public ObjectQuery<TQuery> Query { get; private set; }

        public IncludeObjectQuery(ObjectQuery<TQuery> query, StringBuilder builder)
        {
            _pathBuilder = builder;
            Query = query;
        }

        public IncludeObjectQuery<TQuery, U> Include<U>(Expression<Func<T, U>> expression)
        {
            Query = ObjectQueryExtensions.IncludeAllLevels(expression, _pathBuilder, Query);
            return new IncludeObjectQuery<TQuery, U>(Query, _pathBuilder);
        }

        public IncludeObjectQuery<TQuery, U> Include<U>(Expression<Func<T, EntityCollection<U>>> expression) where U : class
        {
            Query = ObjectQueryExtensions.IncludeAllLevels(expression, _pathBuilder, Query);
            return new IncludeObjectQuery<TQuery, U>(Query, _pathBuilder);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Consider the following code, which is calling against an EF generated data context:

var context = new DataContext();
var employees = context.Employees.Include("Department");

If I change the name of the  Department relationship then this code is going to start throwing a runtime error.  So is there any way to call the .Include() method in a safe manner, so I get compile time checking for all the relationships being referenced?

Body:
Taking moi_meme's idea a step further, my colleague developed the following solution that works in all cases.  He introduced a new method caled Includes() for dealing with one-to-many and many-to-many relationships.  It allows you to write this:

context.Customer
    .Include("Address")
    .Include("Orders")
    .Include("Orders.OrderLines")

as this:

context.Customer
    .Include(c => c.Address)
    .Includes(c => c.Include(customer => customer.Orders)
                    .Include(order => order.OrderLines))

All credit goes to https://stackoverflow.com/users/70427/bojan-resnik, so go give him some love if you like the solution.

public static class ObjectQueryExtensions
{
    public static ObjectQuery<T> Includes<T>(this ObjectQuery<T> query, Action<IncludeObjectQuery<T, T>> action)
    {
        var sb = new StringBuilder();
        var queryBuilder = new IncludeObjectQuery<T, T>(query, sb);
        action(queryBuilder);
        return queryBuilder.Query;
    }

    public static ObjectQuery<TEntity> Include<TEntity, TProperty>(this ObjectQuery<TEntity> query, Expression<Func<TEntity, TProperty>> expression)
    {
        var sb = new StringBuilder();
        return IncludeAllLevels(expression, sb, query);
    }

    static ObjectQuery<TQuery> IncludeAllLevels<TEntity, TProperty, TQuery>(Expression<Func<TEntity, TProperty>> expression, StringBuilder sb, ObjectQuery<TQuery> query)
    {
        foreach (var name in expression.GetPropertyLevels())
        {
            sb.Append(name);
            query = query.Include(sb.ToString());
            Debug.WriteLine(string.Format("Include(\"{0}\")", sb));
            sb.Append('.');
        }
        return query;
    }

    static IEnumerable<string> GetPropertyLevels<TClass, TProperty>(this Expression<Func<TClass, TProperty>> expression)
    {
        var namesInReverse = new List<string>();

        var unaryExpression = expression as UnaryExpression;
        var body = unaryExpression != null ? unaryExpression.Operand : expression.Body;

        while (body != null)
        {
            var memberExpression = body as MemberExpression;
            if (memberExpression == null)
                break;

            namesInReverse.Add(memberExpression.Member.Name);
            body = memberExpression.Expression;
        }

        namesInReverse.Reverse();
        return namesInReverse;
    }

    public class IncludeObjectQuery<TQuery, T>
    {
        readonly StringBuilder _pathBuilder;
        public ObjectQuery<TQuery> Query { get; private set; }

        public IncludeObjectQuery(ObjectQuery<TQuery> query, StringBuilder builder)
        {
            _pathBuilder = builder;
            Query = query;
        }

        public IncludeObjectQuery<TQuery, U> Include<U>(Expression<Func<T, U>> expression)
        {
            Query = ObjectQueryExtensions.IncludeAllLevels(expression, _pathBuilder, Query);
            return new IncludeObjectQuery<TQuery, U>(Query, _pathBuilder);
        }

        public IncludeObjectQuery<TQuery, U> Include<U>(Expression<Func<T, EntityCollection<U>>> expression) where U : class
        {
            Query = ObjectQueryExtensions.IncludeAllLevels(expression, _pathBuilder, Query);
            return new IncludeObjectQuery<TQuery, U>(Query, _pathBuilder);
        }
    }
}


问:
Identify if a Unicode code point represents a character from a certain script such as the Latin script?
Unicode categorizes characters as belonging to a script, such as the Latin script.

How do I test whether a particular character (code point) is in a particular script?

答:
Java represents the various Unicode scripts in the Character.UnicodeScript enum, including for example Character.UnicodeScript.LATIN. These match the Unicode Script Properties.

You can test a character by submitting its code point integer number to the of method on that enum.

```<code>int codePoint = "a".codePointAt( 0 ) ;
Character.UnicodeScript script = Character.UnicodeScript.of( codePoint ) ;
if( Character.UnicodeScript.LATIN.equals( script ) ) { … }
</code>```

Alternatively:

```<code>boolean isLatinScript =
        Character.UnicodeScript.LATIN
        .equals(
            Character.UnicodeScript.of( codePoint )
        )
;
</code>```

Example usage.

```<code>System.out.println(
        Character.UnicodeScript.LATIN      // Constant defined on the enum.
        .equals(                           // `java.lang.Enum.equals()` comparing two constants defined on the enum.
            Character.UnicodeScript.of(    // Determine which Unicode script for this character.
                "".codePointAt( 0 )      // Get the code point integer number of the first (and only) character in this string.
            )                              // Returns a `Character.UnicodeScript` enum object.
        )                                  // Returns `boolean`.
);
</code>```

See this code run at IdeOne.com.

false

FYI, the Character class lets you ask if a code point represents a character that isDigit, isLetter, isLetterOrDigit, isLowerCase, and more.

Body:
Java represents the various Unicode scripts in the Character.UnicodeScript enum, including for example Character.UnicodeScript.LATIN. These match the Unicode Script Properties.

You can test a character by submitting its code point integer number to the of method on that enum.

int codePoint = "a".codePointAt( 0 ) ;
Character.UnicodeScript script = Character.UnicodeScript.of( codePoint ) ;
if( Character.UnicodeScript.LATIN.equals( script ) ) { … }

Alternatively:

boolean isLatinScript =
        Character.UnicodeScript.LATIN
        .equals(
            Character.UnicodeScript.of( codePoint )
        )
;

Example usage.

System.out.println(
        Character.UnicodeScript.LATIN      // Constant defined on the enum.
        .equals(                           // `java.lang.Enum.equals()` comparing two constants defined on the enum.
            Character.UnicodeScript.of(    // Determine which Unicode script for this character.
                "".codePointAt( 0 )      // Get the code point integer number of the first (and only) character in this string.
            )                              // Returns a `Character.UnicodeScript` enum object.
        )                                  // Returns `boolean`.
);

See this code run at IdeOne.com.

false

FYI, the Character class lets you ask if a code point represents a character that isDigit, isLetter, isLetterOrDigit, isLowerCase, and more.


问:
Check if we can travel from source to destination
Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island ai and Island bi.

Cat Snuke is on Island 1 now, and wants to go to Island N. However, it turned out that there is no direct boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Example:

```<code>N = 3
First boat services : 1 2
Second boat services: 2 3
</code>```

Output:
POSSIBLE

Explanation:
Using first boat, I can start from source point 1, and go to 2. Now using second boat I can go from 2 to 3, here 3 is my destination.

I am trying to understand what is the approach we need to follow to solve this problem?

I tried this basic approach, which will work for this test case, but I know that i am going in wrong way.

```<code>public static String check(List<Integer> boat1, List<Integer> boat2, int N) {
        Map<Integer, Integer> first = new HashMap<>();
        for (int i = 0; i < boat1.size() - 1; i++) {
            first.put(boat1.get(i), boat1.get(i + 1));
        }

        Map<Integer, Integer> second = new HashMap<>();
        for (int i = 0; i < boat2.size() - 1; i++) {
            second.put(boat2.get(i), boat2.get(i + 1));
        }

        if (first.get(1) != null) {
            int island = first.get(1);
            if (second.get(island) != null) {
                island = second.get(island);
                if (island == N) {
                    return "POSSIBLE";
                }
            }
        }
        return "Impossible";
    }
</code>```

Update:

Lets say boat 1 services are 1, 2, 3, 4 and boat 2 services are 3,5.
Trying with Josep answer now:

```<code>public static void main(String[] args) {
    GrafDirLlistes s = new GrafDirLlistes(5);
    s.afegirAresta(1, 2, 1);
    s.afegirAresta(2, 3, 1);
    s.afegirAresta(3, 4, 1);
    s.afegirAresta(3, 5, 1);
    s.dfs();
    System.out.println(s.existeixAresta(1, 5));

}
</code>```

I am expecting true for above program as we can travel from 1 to 5 like this 1->2->3->5, but the program is returning false.

答:
The services are pairs of integers [from, to]. You need to first find the set of islands that can be reached from 1 in a single step. Then use all of those and build a new set of all that can be reached from any of them in one more step. You have some elements of this, but you're missing some ingredients.  Using Map and Set appropriately will make this computation very efficient. Key reasons to use Set are that it takes care of the issue where a given island can be reached by more than one path, and it's very quick to check whether the islands reachable in the second step contain the one you're interested in.

Here's one way to implement. Java streams simplify things.

```<code>class Length2Paths {
  private static final Set<Integer> NONE = (Set<Integer>) EMPTY_SET;

  static class Service {
    final int from, to;
    public Service(int from, int to) {
      this.from = from;
      this.to = to;
    }
  }

  static Set<Integer> getReachableIn2Steps(int from, List<Service> services) {
    Map<Integer, Set<Integer>> edges =
        services.stream().collect(groupingBy(s -> s.from, mapping(s -> s.to,  toSet())));
    Set<Integer> reachableIn1Step = edges.getOrDefault(from, NONE);
    return reachableIn1Step.stream().flatMap(i -> edges.getOrDefault(i, NONE).stream()).collect(toSet());
  }

  static void printIfPossibleIn2StepsFrom1(int destination, List<Service> services) {
     System.out.println(getReachableIn2Steps(1, services).contains(destination) ? "POSSIBLE" : "IMPOSSIBLE");
  }

  public static void main(String [] args) {
    Service [] services = { new Service(1, 2), new Service(2, 3) };
    printIfPossibleIn2StepsFrom1(3, Arrays.asList(services));
    printIfPossibleIn2StepsFrom1(2, Arrays.asList(services));
  }
}
</code>```

This prints:

```<code>POSSIBLE
IMPOSSIBLE
</code>```

Body:
Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island ai and Island bi.

Cat Snuke is on Island 1 now, and wants to go to Island N. However, it turned out that there is no direct boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Example:

N = 3
First boat services : 1 2
Second boat services: 2 3

Output:
POSSIBLE

Explanation:
Using first boat, I can start from source point 1, and go to 2. Now using second boat I can go from 2 to 3, here 3 is my destination.

I am trying to understand what is the approach we need to follow to solve this problem?

I tried this basic approach, which will work for this test case, but I know that i am going in wrong way.

public static String check(List<Integer> boat1, List<Integer> boat2, int N) {
        Map<Integer, Integer> first = new HashMap<>();
        for (int i = 0; i < boat1.size() - 1; i++) {
            first.put(boat1.get(i), boat1.get(i + 1));
        }

        Map<Integer, Integer> second = new HashMap<>();
        for (int i = 0; i < boat2.size() - 1; i++) {
            second.put(boat2.get(i), boat2.get(i + 1));
        }

        if (first.get(1) != null) {
            int island = first.get(1);
            if (second.get(island) != null) {
                island = second.get(island);
                if (island == N) {
                    return "POSSIBLE";
                }
            }
        }
        return "Impossible";
    }

Update:

Lets say boat 1 services are 1, 2, 3, 4 and boat 2 services are 3,5.
Trying with Josep answer now:

public static void main(String[] args) {
    GrafDirLlistes s = new GrafDirLlistes(5);
    s.afegirAresta(1, 2, 1);
    s.afegirAresta(2, 3, 1);
    s.afegirAresta(3, 4, 1);
    s.afegirAresta(3, 5, 1);
    s.dfs();
    System.out.println(s.existeixAresta(1, 5));

}

I am expecting true for above program as we can travel from 1 to 5 like this 1->2->3->5, but the program is returning false.

Body:
The services are pairs of integers [from, to]. You need to first find the set of islands that can be reached from 1 in a single step. Then use all of those and build a new set of all that can be reached from any of them in one more step. You have some elements of this, but you're missing some ingredients.  Using Map and Set appropriately will make this computation very efficient. Key reasons to use Set are that it takes care of the issue where a given island can be reached by more than one path, and it's very quick to check whether the islands reachable in the second step contain the one you're interested in.

Here's one way to implement. Java streams simplify things.

class Length2Paths {
  private static final Set<Integer> NONE = (Set<Integer>) EMPTY_SET;

  static class Service {
    final int from, to;
    public Service(int from, int to) {
      this.from = from;
      this.to = to;
    }
  }

  static Set<Integer> getReachableIn2Steps(int from, List<Service> services) {
    Map<Integer, Set<Integer>> edges =
        services.stream().collect(groupingBy(s -> s.from, mapping(s -> s.to,  toSet())));
    Set<Integer> reachableIn1Step = edges.getOrDefault(from, NONE);
    return reachableIn1Step.stream().flatMap(i -> edges.getOrDefault(i, NONE).stream()).collect(toSet());
  }

  static void printIfPossibleIn2StepsFrom1(int destination, List<Service> services) {
     System.out.println(getReachableIn2Steps(1, services).contains(destination) ? "POSSIBLE" : "IMPOSSIBLE");
  }

  public static void main(String [] args) {
    Service [] services = { new Service(1, 2), new Service(2, 3) };
    printIfPossibleIn2StepsFrom1(3, Arrays.asList(services));
    printIfPossibleIn2StepsFrom1(2, Arrays.asList(services));
  }
}

This prints:

POSSIBLE
IMPOSSIBLE


问:
Convert peano number s(N) to integer in Prolog
I came across this natural number evaluation of logical numbers in a tutorial and it's been giving me some headache:

```<code>natural_number(0).
natural_number(s(N)) :- natural_number(N).
</code>```

The rule roughly states that: if N is 0 it's natural, if not we try to send the contents of s/1 back recursively to the rule until the content is 0, then it's a natural number if not then it's not.

So I tested the above logic implementation, thought to myself, well this works if I want to represent s(0) as 1 and s(s(0)) as 2, but I´d like to be able to convert s(0) to 1 instead.

I´ve thought of the base rule:

```<code>sToInt(0,0). %sToInt(X,Y) Where X=s(N) and Y=integer of X
</code>```

So here is my question: How can I convert s(0) to 1 and s(s(0)) to 2?

Has been answered

Edit: I modified the base rule in the implementation which the answer I accepted pointed me towards:

```<code>decode(0,0). %was orignally decode(z,0).
decode(s(N),D):- decode(N,E), D is E +1.

encode(0,0). %was orignally encode(0,z).
encode(D,s(N)):- D > 0, E is D-1, encode(E,N).
</code>```

So I can now use it like I wanted to, thanks everyone!

答:
Here is mine:

Peano numbers that are actually better adapted to Prolog, in the form of lists.

Why lists?

There is an isomorphism between

a list of length N containing only s and terminating in the empty list

a recursive linear structure of depth N with function symbols s
terminating in the symbol zero

... so these are the same things (at least in this context).

There is no particular reason to hang onto what 19th century mathematicians
(i.e Giuseppe Peano )
considered "good structure structure to reason with" (born from function
application I imagine).

It's been done before: Does anyone actually use Gödelization to encode
strings? No! People use arrays of characters. Fancy that.

Let's get going, and in the middle there is a little riddle I don't know how to
solve (use annotated variables, maybe?)

```<code>% ===
% Something to replace (frankly badly named and ugly) "var(X)" and "nonvar(X)"
% ===

ff(X) :- var(X).     % is X a variable referencing a fresh/unbound/uninstantiated term? (is X a "freshvar"?)
bb(X) :- nonvar(X).  % is X a variable referencing an nonfresh/bound/instantiated term? (is X a "boundvar"?)

% ===
% This works if:
% Xn is boundvar and Xp is freshvar:
%    Map Xn from the domain of integers >=0 to Xp from the domain of lists-of-only-s.
% Xp is boundvar and Xn is freshvar:
%    Map from the domain of lists-of-only-s to the domain of integers >=0
% Xp is boundvar and Xp is boundvar:
%    Make sure the two representations are isomorphic to each other (map either
%    way and fail if the mapping gives something else than passed)
% Xp is freshvar and Xp is freshvar:
%    WE DON'T HANDLE THAT!
%    If you have a freshvar in one domain and the other (these cannot be the same!)
%    you need to set up a constraint between the freshvars (via coroutining?) so that
%    if any of the variables is bound with a value from its respective domain, the
%    other is bound auotmatically with the corresponding value from ITS domain. How to
%    do that? I did it awkwardly using a lookup structure that is passed as 3rd/4th
%    argument, but that's not a solution I would like to see.
% ===

peanoify(Xn,Xp) :-
   (bb(Xn) -> integer(Xn),Xn>=0 ; true),                  % make sure Xn is a good value if bound
   (bb(Xp) -> is_list(Xp),maplist(==(s),Xp) ; true),      % make sure Xp is a good value if bound
   ((ff(Xn),ff(Xp)) -> throw("Not implemented!") ; true), % TODO
   length(Xp,Xn),maplist(=(s),Xp).

% ===
% Testing is rewarding!
% Run with: ?- rt(_).
% ===

:- begin_tests(peano).

test(left0,true(Xp=[]))          :- peanoify(0,Xp).
test(right0,true(Xn=0))          :- peanoify(Xn,[]).
test(left1,true(Xp=[s]))         :- peanoify(1,Xp).
test(right1,true(Xn=1))          :- peanoify(Xn,[s]).
test(left2,true(Xp=[s,s]))       :- peanoify(2,Xp).
test(right2,true(Xn=2))          :- peanoify(Xn,[s,s]).
test(left3,true(Xp=[s,s,s]))     :- peanoify(3,Xp).
test(right3,true(Xn=3))          :- peanoify(Xn,[s,s,s]).
test(f1,fail)                    :- peanoify(-1,_).
test(f2,fail)                    :- peanoify(_,[k]).
test(f3,fail)                    :- peanoify(a,_).
test(f4,fail)                    :- peanoify(_,a).
test(f5,fail)                    :- peanoify([s],_).
test(f6,fail)                    :- peanoify(_,1).
test(bi0)                        :- peanoify(0,[]).
test(bi1)                        :- peanoify(1,[s]).
test(bi2)                        :- peanoify(2,[s,s]).

:- end_tests(peano).

rt(peano) :- run_tests(peano).
</code>```

Body:
I came across this natural number evaluation of logical numbers in a tutorial and it's been giving me some headache:

natural_number(0).
natural_number(s(N)) :- natural_number(N).

The rule roughly states that: if N is 0 it's natural, if not we try to send the contents of s/1 back recursively to the rule until the content is 0, then it's a natural number if not then it's not.

So I tested the above logic implementation, thought to myself, well this works if I want to represent s(0) as 1 and s(s(0)) as 2, but I´d like to be able to convert s(0) to 1 instead.

I´ve thought of the base rule:

sToInt(0,0). %sToInt(X,Y) Where X=s(N) and Y=integer of X

So here is my question: How can I convert s(0) to 1 and s(s(0)) to 2?

Has been answered

Edit: I modified the base rule in the implementation which the answer I accepted pointed me towards:

decode(0,0). %was orignally decode(z,0).
decode(s(N),D):- decode(N,E), D is E +1.

encode(0,0). %was orignally encode(0,z).
encode(D,s(N)):- D > 0, E is D-1, encode(E,N).

So I can now use it like I wanted to, thanks everyone!

Body:
Here is mine:

Peano numbers that are actually better adapted to Prolog, in the form of lists.

Why lists?

There is an isomorphism between

a list of length N containing only s and terminating in the empty list

a recursive linear structure of depth N with function symbols s
terminating in the symbol zero

... so these are the same things (at least in this context).

There is no particular reason to hang onto what 19th century mathematicians
(i.e Giuseppe Peano )
considered "good structure structure to reason with" (born from function
application I imagine).

It's been done before: Does anyone actually use Gödelization to encode
strings? No! People use arrays of characters. Fancy that.

Let's get going, and in the middle there is a little riddle I don't know how to
solve (use annotated variables, maybe?)

% ===
% Something to replace (frankly badly named and ugly) "var(X)" and "nonvar(X)"
% ===

ff(X) :- var(X).     % is X a variable referencing a fresh/unbound/uninstantiated term? (is X a "freshvar"?)
bb(X) :- nonvar(X).  % is X a variable referencing an nonfresh/bound/instantiated term? (is X a "boundvar"?)

% ===
% This works if:
% Xn is boundvar and Xp is freshvar:
%    Map Xn from the domain of integers >=0 to Xp from the domain of lists-of-only-s.
% Xp is boundvar and Xn is freshvar:
%    Map from the domain of lists-of-only-s to the domain of integers >=0
% Xp is boundvar and Xp is boundvar:
%    Make sure the two representations are isomorphic to each other (map either
%    way and fail if the mapping gives something else than passed)
% Xp is freshvar and Xp is freshvar:
%    WE DON'T HANDLE THAT!
%    If you have a freshvar in one domain and the other (these cannot be the same!)
%    you need to set up a constraint between the freshvars (via coroutining?) so that
%    if any of the variables is bound with a value from its respective domain, the
%    other is bound auotmatically with the corresponding value from ITS domain. How to
%    do that? I did it awkwardly using a lookup structure that is passed as 3rd/4th
%    argument, but that's not a solution I would like to see.
% ===

peanoify(Xn,Xp) :-
   (bb(Xn) -> integer(Xn),Xn>=0 ; true),                  % make sure Xn is a good value if bound
   (bb(Xp) -> is_list(Xp),maplist(==(s),Xp) ; true),      % make sure Xp is a good value if bound
   ((ff(Xn),ff(Xp)) -> throw("Not implemented!") ; true), % TODO
   length(Xp,Xn),maplist(=(s),Xp).

% ===
% Testing is rewarding!
% Run with: ?- rt(_).
% ===

:- begin_tests(peano).

test(left0,true(Xp=[]))          :- peanoify(0,Xp).
test(right0,true(Xn=0))          :- peanoify(Xn,[]).
test(left1,true(Xp=[s]))         :- peanoify(1,Xp).
test(right1,true(Xn=1))          :- peanoify(Xn,[s]).
test(left2,true(Xp=[s,s]))       :- peanoify(2,Xp).
test(right2,true(Xn=2))          :- peanoify(Xn,[s,s]).
test(left3,true(Xp=[s,s,s]))     :- peanoify(3,Xp).
test(right3,true(Xn=3))          :- peanoify(Xn,[s,s,s]).
test(f1,fail)                    :- peanoify(-1,_).
test(f2,fail)                    :- peanoify(_,[k]).
test(f3,fail)                    :- peanoify(a,_).
test(f4,fail)                    :- peanoify(_,a).
test(f5,fail)                    :- peanoify([s],_).
test(f6,fail)                    :- peanoify(_,1).
test(bi0)                        :- peanoify(0,[]).
test(bi1)                        :- peanoify(1,[s]).
test(bi2)                        :- peanoify(2,[s,s]).

:- end_tests(peano).

rt(peano) :- run_tests(peano).


问:
Unable to Link Glue and Feature File
I am new to Cucumber and practicing it. I just created a simple project and try to compile it.I have mentioned the feature path and glue path in cucumber. But still whenever I am compiling with Junit keeps showing test is skipped Undefined scenarios.

```<code>TestRunner

 package runner;

    import org.junit.runner.RunWith;

    import io.cucumber.junit.CucumberOptions;
    import io.cucumber.junit.Cucumber;

    @RunWith(Cucumber.class)
    @CucumberOptions(
            features = "src/test/resources/feature/feature.feature"
            ,glue = {"src/test/java/stepDefinition"} //have tried with "/HomeWork/src/test/java/stepDefinition/" also. but not working. giving error message like undefined scenarios
            ,monochrome = true
            ,plugin = {"html:target/Report/cucumber-html-report", "json:target/Report/cucumber-json-report.json" }
    )
    public class TestRunner {

    }

    stepDefinition File:

package stepDefinition;

    import io.cucumber.java.en.Then;
    import io.cucumber.java.en.When;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;

    import cucumber.api.java.en.Given;

    public class firstLogin {
        WebDriver driver;

        // TODO Auto-generated method stub
        @Given("^User sets the property^")
        public void User_sets_the_property() {
            System.setProperty("webdriver. chrome.driver",
                    "C:\\Arnab\\Softwares\\ChromeDriver\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application");

            driver = new ChromeDriver();
            driver.get("https://www.facebook.com/");
        }

        @When("^User navigates to login page^")
        public void User_navigates_to_login_page() {
            driver.findElement(By.xpath("//input[@type=émail']")).sendKeys(
                    "arnab.test1115@gail.com");
            driver.findElement(
                    By.xpath("//input[@class='inputtext login_form_input_box']"))
                    .sendKeys("mandira1990");
            driver.findElement(By.cssSelector("input[value='Log In']")).click();
        }

        @Then("user is on Homepage^")
        public void user_is_on_Homepage() throws InterruptedException {
            String Title = driver.getTitle();
            System.out.println(Title);
            Thread.sleep(5000);
        }

        // driver.close();

    }
</code>```

Feature File:

```<code> Feature: User is on Facebook Login Page

    Scenario: User Needs to Login

    Given User sets the property

    When User navigates to login page

    Then user is on Homepage
</code>```

答:
The parameter values you have provided in @CucumberOptions may not be configured correctly as required by Cucumber.

features is for a filesystem folder path of where a feature file can be found and not the full file path.

glue is the package name of where your step definition class is, not the filesystem path to the package itself.

So your configuration should be like this:

```<code>    @CucumberOptions(
        features = "src/test/resources/feature"
        ,glue = {"stepDefinition"}
        ,monochrome = true
        ,plugin = {"html:target/Report/cucumber-html-report", "json:target/Report/cucumber-json-report.json" }
)
</code>```

Title: Unable to Link Glue and Feature File

Body:
I am new to Cucumber and practicing it. I just created a simple project and try to compile it.I have mentioned the feature path and glue path in cucumber. But still whenever I am compiling with Junit keeps showing test is skipped Undefined scenarios.

TestRunner

 package runner;

    import org.junit.runner.RunWith;

    import io.cucumber.junit.CucumberOptions;
    import io.cucumber.junit.Cucumber;

    @RunWith(Cucumber.class)
    @CucumberOptions(
            features = "src/test/resources/feature/feature.feature"
            ,glue = {"src/test/java/stepDefinition"} //have tried with "/HomeWork/src/test/java/stepDefinition/" also. but not working. giving error message like undefined scenarios
            ,monochrome = true
            ,plugin = {"html:target/Report/cucumber-html-report", "json:target/Report/cucumber-json-report.json" }
    )
    public class TestRunner {

    }

    stepDefinition File:

package stepDefinition;

    import io.cucumber.java.en.Then;
    import io.cucumber.java.en.When;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;

    import cucumber.api.java.en.Given;

    public class firstLogin {
        WebDriver driver;

        // TODO Auto-generated method stub
        @Given("^User sets the property^")
        public void User_sets_the_property() {
            System.setProperty("webdriver. chrome.driver",
                    "C:\\Arnab\\Softwares\\ChromeDriver\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application");

            driver = new ChromeDriver();
            driver.get("https://www.facebook.com/");
        }

        @When("^User navigates to login page^")
        public void User_navigates_to_login_page() {
            driver.findElement(By.xpath("//input[@type=émail']")).sendKeys(
                    "arnab.test1115@gail.com");
            driver.findElement(
                    By.xpath("//input[@class='inputtext login_form_input_box']"))
                    .sendKeys("mandira1990");
            driver.findElement(By.cssSelector("input[value='Log In']")).click();
        }

        @Then("user is on Homepage^")
        public void user_is_on_Homepage() throws InterruptedException {
            String Title = driver.getTitle();
            System.out.println(Title);
            Thread.sleep(5000);
        }

        // driver.close();

    }

Feature File:

 Feature: User is on Facebook Login Page

    Scenario: User Needs to Login

    Given User sets the property

    When User navigates to login page

    Then user is on Homepage

Body:
The parameter values you have provided in @CucumberOptions may not be configured correctly as required by Cucumber.

features is for a filesystem folder path of where a feature file can be found and not the full file path.

glue is the package name of where your step definition class is, not the filesystem path to the package itself.

So your configuration should be like this:

    @CucumberOptions(
        features = "src/test/resources/feature"
        ,glue = {"stepDefinition"}
        ,monochrome = true
        ,plugin = {"html:target/Report/cucumber-html-report", "json:target/Report/cucumber-json-report.json" }
)


问:
How to test/mock API calls using JEST in Create react app
I'm trying to test my async action creators in create-react-app but I don't have enough information to fix the issue. This is my first time to test async actions in React. I'm using Axios for fetching API and Jest mock to create a mock functions.

Here's fetch function:

```<code>export async function signUpAPI(userSignupInfo: ILoginSignUpFormParams): Promise<ILoginSignupResponse> {
  const { username, email, password } = userSignupInfo;
  try {
    const res = await axiosInstance.post('/signup', {
      username,
      email,
      password
    });
    return res.data;
  } catch (error) {
    throw error.response.data;
  }
}
</code>```

Here's my test:

```<code>import * as sessionActions from '../Actions';
import { sessionInitialState } from 'models/Session/sessionInitialState';
import { SessionActionTypes } from '../Types';
import axios from 'axios';
import { signUpAPI } from 'api/sessions';

jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

describe('Session Action Test', () => {
  describe('async ACTION Test', () => {
    describe('On signup', () => {
      it('should success response on signup', async () => {
        mockedAxios.post.mockResolvedValue({ data: {} });

        const t = await signUpAPI({ username: 'yousir1', password: 'Password1!', email: 'yousir1@gmail.com' });
        console.log(t);
      });
    });
  });
});
</code>```

Here's the error that I'm getting but don't understand because I am mocking it as a Resolved value but it goes to my catch block in my actual API call.

答:
Took me some time to get it but I finally figured it out.

So I have this folder structure:

```<code>src
├── api
│   └── sessions.ts
├── assets
├── components
├── helper
│   └── sessionSetup.ts
├── index.css
├── index.tsx
├── interfaces
├── lib
│   ├── __mocks__   <<-- you have to create a mock like this first----------
│   │   └── api.ts
│   ├── axios.instance.ts
│   └── axios.interceptors.ts
├── models
├── react-app-env.d.ts
├── routes
├── serviceWorker.ts
├── setupTests.ts
└── store
    ├── root
    ├── session
    │   ├── Actions.ts
    │   ├── Reducers.ts
    │   ├── Selectors.ts
    │   ├── Types.ts
    │   └── test
    │       ├── session.action.test.ts
    │       └── session.reducer.test.ts
    └── user
        ├── Actions.ts
        ├── Reducers.ts
        ├── Selectors.ts
        ├── Types.ts
        └── test
            ├── user.action.test.ts
            └── user.reducer.test.ts
</code>```

then inside the __mock__ folder I have this. This will simulate my "POST" singup API

```<code>export default {
  post: jest.fn(() =>
    Promise.resolve({
      data: {}
    })
  )
};
</code>```

since I'm using axios instance like:

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

const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_BASE_API_URL
});

export default axiosInstance;

</code>```

then consuming it in my API folder like:

```<code>import axiosInstance from '../lib/axios.instance';
import { ILoginSignupResponse, ILoginSignUpFormParams } from 'interfaces/session';

export async function signUpAPI(userSignupInfo: ILoginSignUpFormParams): Promise<ILoginSignupResponse> {
  const { username, email, password } = userSignupInfo;
  try {
    const res = await axiosInstance.post('/signup', {
      username,
      email,
      password
    });
    return res.data;
  } catch (error) {
    throw error.response.data;
  }
}
</code>```

then I have to setup my test like this:

```<code>import * as sessionActions from '../Actions';
import { sessionInitialState } from 'models/Session/sessionInitialState';
import { SessionActionTypes } from '../Types';
import axios from 'axios';
import { signUpAPI } from 'api/sessions';
import axiosInstance from 'lib/axios.instance';

jest.mock('../../../lib/axios.instance.ts');
const mockedAxios = axiosInstance as jest.Mocked<typeof axiosInstance>;

describe('Session Action Test', () => {
  describe('async ACTION Test', () => {
    describe('On signup', () => {
      it('should success response on signup', async () => {
        mockedAxios.post.mockImplementationOnce(() => Promise.resolve({ data: { foo: 'bar' } }));

        const t = await signUpAPI({ username: 'yousir1', password: 'Password1!', email: 'yousir1@gmail.com' });
        console.log(t);
      });
    });
  });
});

</code>```

jest.mock() will take path to your mocked folder. Then I can used my mockedAxios variable to get all properties in my __mock__/api.ts file and test my API by giving it a Promise. The return of the t variable will be whatever you put inside the Promise.resolve method.

Body:
I'm trying to test my async action creators in create-react-app but I don't have enough information to fix the issue. This is my first time to test async actions in React. I'm using Axios for fetching API and Jest mock to create a mock functions.

Here's fetch function:

export async function signUpAPI(userSignupInfo: ILoginSignUpFormParams): Promise<ILoginSignupResponse> {
  const { username, email, password } = userSignupInfo;
  try {
    const res = await axiosInstance.post('/signup', {
      username,
      email,
      password
    });
    return res.data;
  } catch (error) {
    throw error.response.data;
  }
}

Here's my test:

import * as sessionActions from '../Actions';
import { sessionInitialState } from 'models/Session/sessionInitialState';
import { SessionActionTypes } from '../Types';
import axios from 'axios';
import { signUpAPI } from 'api/sessions';

jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

describe('Session Action Test', () => {
  describe('async ACTION Test', () => {
    describe('On signup', () => {
      it('should success response on signup', async () => {
        mockedAxios.post.mockResolvedValue({ data: {} });

        const t = await signUpAPI({ username: 'yousir1', password: 'Password1!', email: 'yousir1@gmail.com' });
        console.log(t);
      });
    });
  });
});

Here's the error that I'm getting but don't understand because I am mocking it as a Resolved value but it goes to my catch block in my actual API call.

Body:
Took me some time to get it but I finally figured it out.

So I have this folder structure:

src
├── api
│   └── sessions.ts
├── assets
├── components
├── helper
│   └── sessionSetup.ts
├── index.css
├── index.tsx
├── interfaces
├── lib
│   ├── __mocks__   <<-- you have to create a mock like this first----------
│   │   └── api.ts
│   ├── axios.instance.ts
│   └── axios.interceptors.ts
├── models
├── react-app-env.d.ts
├── routes
├── serviceWorker.ts
├── setupTests.ts
└── store
    ├── root
    ├── session
    │   ├── Actions.ts
    │   ├── Reducers.ts
    │   ├── Selectors.ts
    │   ├── Types.ts
    │   └── test
    │       ├── session.action.test.ts
    │       └── session.reducer.test.ts
    └── user
        ├── Actions.ts
        ├── Reducers.ts
        ├── Selectors.ts
        ├── Types.ts
        └── test
            ├── user.action.test.ts
            └── user.reducer.test.ts

then inside the __mock__ folder I have this. This will simulate my "POST" singup API

export default {
  post: jest.fn(() =>
    Promise.resolve({
      data: {}
    })
  )
};

since I'm using axios instance like:

import axios from 'axios';

const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_BASE_API_URL
});

export default axiosInstance;

then consuming it in my API folder like:

import axiosInstance from '../lib/axios.instance';
import { ILoginSignupResponse, ILoginSignUpFormParams } from 'interfaces/session';

export async function signUpAPI(userSignupInfo: ILoginSignUpFormParams): Promise<ILoginSignupResponse> {
  const { username, email, password } = userSignupInfo;
  try {
    const res = await axiosInstance.post('/signup', {
      username,
      email,
      password
    });
    return res.data;
  } catch (error) {
    throw error.response.data;
  }
}

then I have to setup my test like this:

import * as sessionActions from '../Actions';
import { sessionInitialState } from 'models/Session/sessionInitialState';
import { SessionActionTypes } from '../Types';
import axios from 'axios';
import { signUpAPI } from 'api/sessions';
import axiosInstance from 'lib/axios.instance';

jest.mock('../../../lib/axios.instance.ts');
const mockedAxios = axiosInstance as jest.Mocked<typeof axiosInstance>;

describe('Session Action Test', () => {
  describe('async ACTION Test', () => {
    describe('On signup', () => {
      it('should success response on signup', async () => {
        mockedAxios.post.mockImplementationOnce(() => Promise.resolve({ data: { foo: 'bar' } }));

        const t = await signUpAPI({ username: 'yousir1', password: 'Password1!', email: 'yousir1@gmail.com' });
        console.log(t);
      });
    });
  });
});

jest.mock() will take path to your mocked folder. Then I can used my mockedAxios variable to get all properties in my __mock__/api.ts file and test my API by giving it a Promise. The return of the t variable will be whatever you put inside the Promise.resolve method.


问:
Discord JS - How to get links to connected accounts of a user
Is there a way in which I can retrieve the links to all the social medias and other accounts a person has connected to their discord account?

I searched the docs to no avail and tried looking in the user object but I found nothing. I assume there must be some way in which I can retrieve this information?

答: As far as I know it's not possible with just the code of the bot. To get the connections, you must bring the user to authorize your application Oauth. Its like adding a bot to a server, but instead of doing this the user authenticates the bot to get some information about the user. </p>


问:
Laravel forms broken after including Vue
I am in the process of adding real-time messaging functionality to a Laravel 6.x site. The messaging seems to be working, but as soon as I include
 just after the main menu, some of the existing forms stop working. E.g., this form:

```<code><div class="modal-body">
  <div class="form-controls">
    <div class="row">
      <div class="col-lg-4">
        <form id="form-status{{$task->id}}" action="{{ url('xxx') }}" method="POST" style="display: none;">
          @csrf
          <label for="status{{$task->id}}">Status: </label>
          <select class="form-control" id="status{{$task->id}}" name="status">
            <option value="0" selected="selected">Not started</option>
            <option value="10">Started</option>
            <option value="20">Finished</option>
          </select>
        </form>
      </div>
    </div>
  </div>
</div>
<div class="modal-footer">
  <a href="#" class="btn btn-primary" onclick="event.preventDefault();document.getElementById('{{'form-status'.$task->id}}').submit();"> Update
  </a>
</div>
</code>```

The post action is still executed, but I get a 419 "page expired" error, so I assume the csrf value is not sent with the post data anymore.

Does anyone know why this may be happening? For now, I've moved the APP id to a small section of the website with no pre-existing forms, but in future I would like to have more Vue components on the page, so I will have to fix it at some stage.

I am using Bootstrap 3, so I removed Bootstrap 4 in Laravel using npm, and I import it using a script tag. The HTML header includes:

```<code>  <link href="http://myurl/css/bootstrap.min.css" rel="stylesheet">
  <link href="http://myurl/css/reset.css" rel="stylesheet">
  <link href="http://myurl/css/dashboard.css" rel="stylesheet">
  <link href="http://myurl/css/sticky-footer-navbar.css" rel="stylesheet">
  <link href="http://myurl/css/bootstrap-datepicker.css" rel="stylesheet">
  <!-- Script imported for laravel echo and vue -->
  <script src="http://myurl/js/app.js" defer></script>
  <!-- Scripts -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"  defer></script>
  <script src="http://myurl/js/bootstrap.min.js"  defer></script>
  <script src="http://myurl/js/bootstrap-datepicker.js" defer></script>
</code>```

Thanks,
Hendrik.

EDIT:
The html sent to the client is as follows:

```<code><div class="modal-body">
  <div class="form-controls">
    <div class="row">
      <div class="col-lg-4">
        <form id="form-status94" action="myurl/projects/35/nodes/68/tasks/94/status" method="POST" style="display: none;">
          <input type="hidden" name="_token" value="7ynFCghH2yNGpaO5Pfpd45EMYGIQHdXdNjYooNtJ">
          <label for="status94">Status: </label>
          <select class="form-control" id="status94" name="status">
            <option value="0" selected="selected">Not started</option>
            <option value="10">Started</option>
            <option value="20">Finished</option>
          </select>
        </form>
      </div>
    </div>
  </div>
</div>
<div class="modal-footer">
  <a href="#" class="btn btn-primary" onclick="event.preventDefault();document.getElementById('form-status94').submit();">Update
  </a>
</div>
</code>```

答:
Your curly braces conflict with Vue.js. There's a Blade & JavaScript Frameworks section in Laravel's documentation, saying:

Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched. For example:

Laravel

Hello, @{{ name }}.
```

In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework.

Body:
I am in the process of adding real-time messaging functionality to a Laravel 6.x site. The messaging seems to be working, but as soon as I include
 just after the main menu, some of the existing forms stop working. E.g., this form:

        <form id="form-status{{$task->id}}" action="{{ url('xxx') }}" method="POST" style="display: none;">
          @csrf
          id}}">Status:
          <select class="form-control" id="status{{$task->id}}" name="status">
            <option value="0" selected="selected">Not started</option>
            <option value="10">Started</option>
            <option value="20">Finished</option>
          </select>
        </form>

  id}}').submit();"> Update

The post action is still executed, but I get a 419 "page expired" error, so I assume the csrf value is not sent with the post data anymore.

Does anyone know why this may be happening? For now, I've moved the APP id to a small section of the website with no pre-existing forms, but in future I would like to have more Vue components on the page, so I will have to fix it at some stage.

I am using Bootstrap 3, so I removed Bootstrap 4 in Laravel using npm, and I import it using a script tag. The HTML header includes:

  <link href="http://myurl/css/bootstrap.min.css" rel="stylesheet">
  <link href="http://myurl/css/reset.css" rel="stylesheet">
  <link href="http://myurl/css/dashboard.css" rel="stylesheet">
  <link href="http://myurl/css/sticky-footer-navbar.css" rel="stylesheet">
  <link href="http://myurl/css/bootstrap-datepicker.css" rel="stylesheet">

Thanks,
Hendrik.

EDIT:
The html sent to the client is as follows:

        <form id="form-status94" action="myurl/projects/35/nodes/68/tasks/94/status" method="POST" style="display: none;">
          <input type="hidden" name="_token" value="7ynFCghH2yNGpaO5Pfpd45EMYGIQHdXdNjYooNtJ">
          Status:
          <select class="form-control" id="status94" name="status">
            <option value="0" selected="selected">Not started</option>
            <option value="10">Started</option>
            <option value="20">Finished</option>
          </select>
        </form>

  Update

Body:
Your curly braces conflict with Vue.js. There's a Blade & JavaScript Frameworks section in Laravel's documentation, saying:

Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched. For example:

<h1>Laravel</h1>

Hello, @{{ name }}.

In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework.


问:
Implementing a show password toggle with JavaFX
I wanted to add a toggle button that allows for the PasswordField to show the written contents, so I created a Textfield and a PasswordField that share the location in the GridPane and clicking the check box will toggle between the two. The problem is, however, that when I press Tab to navigate from the Username TextField to the PasswordField, it focuses on the invisible TextField first and then I have to press Tab again. So, all in all, to navigate from the Username TextField to the PasswordField I have to press Tab twice.
picture of GUI

Is there a function in JavaFX that would better allow me to do this?

Here is my code:

Controller:

```<code>package sample;

import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.event.ActionEvent;

public class FXML_Login{

    String[] usernames = {"user", "user2", "user3"};
    String[] passwords = {"pass", "pass2", "pass3"};

    @FXML private Text loginText;
    @FXML private TextField username;
    @FXML private TextField passwordShown;
    @FXML private PasswordField passwordBullets;
    @FXML private CheckBox passToggle;

    @FXML protected void handleLoginSubmission(ActionEvent event){

        if(username.getText().equals(usernames[0]) && (passwordBullets.getText().equals(passwords[0])
                || passwordShown.getText().equals(passwords[0]))){

            loginText.setFill(Color.GREEN);
            loginText.setText("Login successful.");
        }

        else{
            loginText.setFill(Color.RED);
            loginText.setText("Login failed.");
        }
    }

    @FXML protected void togglePasswordVisible(ActionEvent event){

        if(passToggle.isSelected()){
            passwordShown.setText(passwordBullets.getText());
            passwordShown.setVisible(true);
            passwordBullets.setVisible(false);
            return;
        }

        passwordBullets.setText(passwordShown.getText());
        passwordBullets.setVisible(true);
        passwordShown.setVisible(false);
    }

    @FXML protected void initialize(){
    }
}
</code>```

FXML:

```<code><?import javafx.scene.control.CheckBox?>
<GridPane fx:controller="sample.FXML_Login"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"
          stylesheets = "/sample/styles.css">

    <Text id = "welcome"
          text="Welcome"
          GridPane.columnIndex="0"
          GridPane.rowIndex="0"
          GridPane.columnSpan="2"/>

    <Label text = "User Name: "
           GridPane.columnIndex="0"
           GridPane.rowIndex="1" />

    <TextField fx:id = "username"
               promptText = "Username"
               GridPane.columnIndex="1"
               GridPane.rowIndex="1"
               onAction="#handleLoginSubmission"/>

    <Label text = "Password: "
           GridPane.columnIndex="0"
           GridPane.rowIndex="2" />

    <TextField fx:id = "passwordShown"
               promptText = "Password"
               GridPane.columnIndex="1"
               GridPane.rowIndex="2"
               onAction="#handleLoginSubmission"/>

    <PasswordField fx:id = "passwordBullets"
                   promptText="Password"
                   GridPane.columnIndex="1"
                   GridPane.rowIndex="2"
                   onAction="#handleLoginSubmission"/>

    <Label text="Show password"
           GridPane.columnIndex="0"
           GridPane.rowIndex="3"/>

    <CheckBox fx:id="passToggle" onAction="#togglePasswordVisible"
              GridPane.columnIndex="1"
              GridPane.rowIndex="3"/>

    <HBox spacing="10"
          alignment="BOTTOM_RIGHT"
          GridPane.columnIndex="1"
          GridPane.rowIndex="4">
          <Button text="Sign In"
                  onAction="#handleLoginSubmission"/>
    </HBox>

    <Text fx:id = "loginText"
          GridPane.columnIndex="1"
          GridPane.rowIndex="6"/>

</GridPane>
</code>```

答:
There is an option called "Focus Traversable" that lets you navigate to it or not.

you only need to call the method "setFocusTraversable(boolean b)" with switching the checkBox and make a field traversable or not according to your desire.

here is the link to the documentation.

Body:
I wanted to add a toggle button that allows for the PasswordField to show the written contents, so I created a Textfield and a PasswordField that share the location in the GridPane and clicking the check box will toggle between the two. The problem is, however, that when I press Tab to navigate from the Username TextField to the PasswordField, it focuses on the invisible TextField first and then I have to press Tab again. So, all in all, to navigate from the Username TextField to the PasswordField I have to press Tab twice.
picture of GUI

Is there a function in JavaFX that would better allow me to do this?

Here is my code:

Controller:

package sample;

import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.event.ActionEvent;

public class FXML_Login{

    String[] usernames = {"user", "user2", "user3"};
    String[] passwords = {"pass", "pass2", "pass3"};

    @FXML private Text loginText;
    @FXML private TextField username;
    @FXML private TextField passwordShown;
    @FXML private PasswordField passwordBullets;
    @FXML private CheckBox passToggle;

    @FXML protected void handleLoginSubmission(ActionEvent event){

        if(username.getText().equals(usernames[0]) && (passwordBullets.getText().equals(passwords[0])
                || passwordShown.getText().equals(passwords[0]))){

            loginText.setFill(Color.GREEN);
            loginText.setText("Login successful.");
        }

        else{
            loginText.setFill(Color.RED);
            loginText.setText("Login failed.");
        }
    }

    @FXML protected void togglePasswordVisible(ActionEvent event){

        if(passToggle.isSelected()){
            passwordShown.setText(passwordBullets.getText());
            passwordShown.setVisible(true);
            passwordBullets.setVisible(false);
            return;
        }

        passwordBullets.setText(passwordShown.getText());
        passwordBullets.setVisible(true);
        passwordShown.setVisible(false);
    }

    @FXML protected void initialize(){
    }
}

FXML:

<?import javafx.scene.control.CheckBox?>
<GridPane fx:controller="sample.FXML_Login"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"
          stylesheets = "/sample/styles.css">

    <Text id = "welcome"
          text="Welcome"
          GridPane.columnIndex="0"
          GridPane.rowIndex="0"
          GridPane.columnSpan="2"/>

    <TextField fx:id = "username"
               promptText = "Username"
               GridPane.columnIndex="1"
               GridPane.rowIndex="1"
               onAction="#handleLoginSubmission"/>

    <TextField fx:id = "passwordShown"
               promptText = "Password"
               GridPane.columnIndex="1"
               GridPane.rowIndex="2"
               onAction="#handleLoginSubmission"/>

    <PasswordField fx:id = "passwordBullets"
                   promptText="Password"
                   GridPane.columnIndex="1"
                   GridPane.rowIndex="2"
                   onAction="#handleLoginSubmission"/>

    <CheckBox fx:id="passToggle" onAction="#togglePasswordVisible"
              GridPane.columnIndex="1"
              GridPane.rowIndex="3"/>

    <HBox spacing="10"
          alignment="BOTTOM_RIGHT"
          GridPane.columnIndex="1"
          GridPane.rowIndex="4">
          <Button text="Sign In"
                  onAction="#handleLoginSubmission"/>
    </HBox>

    <Text fx:id = "loginText"
          GridPane.columnIndex="1"
          GridPane.rowIndex="6"/>

</GridPane>


问:
Kernel dying while importing Tensorflow
In anaconda3 after creating a new environment for tensorflow and installing tensorflow and keras. Whenever I import tensorflow, the kernel just dies.I tried importing numpy first and then tensorflow still no change.

I have dowloaded the latest version of tensorflow and anaconda (as of may 2020). Does anyone know what might cause this error?

答: I believe that one solution to this would be to downgrade the tensorFlow version and test to see if it works. </p>

Title: Kernel dying while importing Tensorflow


问:
How do you map an array of objects within an object?
I am trying to map an array of objects within an object and I can't seem to get it working. My code's goal is to map and then display the content within the "menu" array.

Here is the structure of the object (logged to console from a state).

```<code>Object {
  "id": 1,
  "img": "https://cuisinederue.org/wp-content/uploads/2019/08/Greg2.png",
  "menu": Array [
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Greg's Burger",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Poutine double cheese bacon",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Cône de poulet pop corn et frites maison",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Grilled cheese Philly steak",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Poutine Philly cheese steak",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Boulette de mac'n'cheese",
      "price": 1,
    },
  ],
  "name": "Greg's dinner",
  "type": "SOUTHERN COMFORT",
}
</code>```

And here is the code that I'm trying to get to work: (specifically the details.menu.map part)

```<code>
const Details = ({navigation, idTruck}) =>{
  const [details, setDetails] = useState([]);
  const [detailsDone, setDetailsDone] = useState(false);

  const getDetails = () => {
    fetch("https://foodtrack-420kbc-lg.herokuapp.com/trucks/1").then(res => res.json()).then(resp => setDetails(resp));
  }

  if(!detailsDone)
  {
    getDetails();
    setDetailsDone(true);
  }
  console.log(details);
  return (
    <View style={styles.container}>
      <Header title='Details'></Header>
      <Image name="logo" style={styles.detailsImage} source={{uri: details.img}}></Image>
      <Text name="nom">{details.name}</Text>
      <Text name="style">{details.type}</Text>

        {

          details.menu.map(({description, name, price}) =>
            <View style={styles.container}>
              <Text name="nom">{name}</Text>
              <Text name="prix">{price}</Text>
              <Text name="desc">{description}</Text>
            </View>
          )
        }

    </View>
  )
}

</code>```

The error I am getting is: TypeError: undefined is not an object (evaluating 'details.menu.map'

Any help is greatly appreciated!

答:
You have big problem in controlling JS asynchronous. Please try to understand it first before you start to study reactJS. Some async functions: setTimeout, setInterval, Ajax (call api), here is small tut  . From this point, you don't need to use detailsDone state.

High performance when use useEffect for calling api only 1 time.

const initValue = {
    id: 0,
    name: "",
    type: "",
    img: "",
    menu: []
}
const [details, setDetails] = useState(initValue); // init value is object, not array

React.useEffect(() => {
    fetch("https://foodtrack-420kbc-lg.herokuapp.com/trucks/1")
        .then(res => res.json())
        .then(resp => setDetails(resp));
}, []); // ensure call api run 1 time when this component render.
```

Body:
I am trying to map an array of objects within an object and I can't seem to get it working. My code's goal is to map and then display the content within the "menu" array.

Here is the structure of the object (logged to console from a state).

Object {
  "id": 1,
  "img": "https://cuisinederue.org/wp-content/uploads/2019/08/Greg2.png",
  "menu": Array [
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Greg's Burger",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Poutine double cheese bacon",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Cône de poulet pop corn et frites maison",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Grilled cheese Philly steak",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Poutine Philly cheese steak",
      "price": 1,
    },
    Object {
      "description": "Les prix sont défini à la tête du client",
      "name": "Boulette de mac'n'cheese",
      "price": 1,
    },
  ],
  "name": "Greg's dinner",
  "type": "SOUTHERN COMFORT",
}

And here is the code that I'm trying to get to work: (specifically the details.menu.map part)

const Details = ({navigation, idTruck}) =>{
  const [details, setDetails] = useState([]);
  const [detailsDone, setDetailsDone] = useState(false);

  const getDetails = () => {
    fetch("https://foodtrack-420kbc-lg.herokuapp.com/trucks/1").then(res => res.json()).then(resp => setDetails(resp));
  }

  if(!detailsDone)
  {
    getDetails();
    setDetailsDone(true);
  }
  console.log(details);
  return (
    <View style={styles.container}>

      <Image name="logo" style={styles.detailsImage} source={{uri: details.img}}></Image>
      <Text name="nom">{details.name}</Text>
      <Text name="style">{details.type}</Text>

        {

          details.menu.map(({description, name, price}) =>
            <View style={styles.container}>
              <Text name="nom">{name}</Text>
              <Text name="prix">{price}</Text>
              <Text name="desc">{description}</Text>
            </View>
          )
        }

    </View>
  )
}

The error I am getting is: TypeError: undefined is not an object (evaluating 'details.menu.map'

Any help is greatly appreciated!


问:
Creating a dictionary from two lists? While taking an average of values?
Wizards of stackoverflow,

I wish to combine two lists to create a dictionary, I have used dict & zip, however it does not meet what I require.

If had these lists

```<code>  keys = ['a', 'a', 'b', 'c']
values = [6, 2, 3, 4]
</code>```

I would like for the dictionary to reflect the average value such that the output would be:

```<code>a_dict = {'a' : 4, 'b' : 3, 'c' : 4}
</code>```

as a bonus but not required, if this is possible is there anyway to get a count of each duplicate?
i.e. output would be followed by 'a' was counted twice, other than just doing the count in the keys.

答:
A straightforward solution (thanks @DeepSpace for dict-comprehension suggestion):

```<code>keys = ['a', 'a', 'b', 'c']
values = [6, 2, 3, 4]

out = {}
for k, v in zip(keys, values):
    out.setdefault(k, []).append(v)

out = {key: sum(value) / len(value) for key, value in out.items()}

print(out)
</code>```

Prints:

```<code>{'a': 4.0, 'b': 3.0, 'c': 4.0}
</code>```

If you want count of keys, you can do for example:

```<code>out = {}
for k, v in zip(keys, values):
    out.setdefault(k, []).append(v)

out = {key: (sum(value) / len(value), len(value)) for key, value in out.items()}

print(out)
</code>```

Prints:

```<code>{'a': (4.0, 2), 'b': (3.0, 1), 'c': (4.0, 1)}
</code>```

Where the second element of values is a count of key.

Solution with itertools (if keys are sorted):

```<code>keys = ['a', 'a', 'b', 'c']
values = [6, 2, 3, 4]

from itertools import groupby
from statistics import mean

out = {}
for k, g in groupby(zip(keys, values), lambda k: k[0]):
    out[k] = mean(v for _, v in g)

print(out)
</code>```

Prints:

```<code>{'a': 4, 'b': 3, 'c': 4}
</code>```

Body:
Wizards of stackoverflow,

I wish to combine two lists to create a dictionary, I have used dict & zip, however it does not meet what I require.

If had these lists

  keys = ['a', 'a', 'b', 'c']
values = [6, 2, 3, 4]

I would like for the dictionary to reflect the average value such that the output would be:

a_dict = {'a' : 4, 'b' : 3, 'c' : 4}

as a bonus but not required, if this is possible is there anyway to get a count of each duplicate?
i.e. output would be followed by 'a' was counted twice, other than just doing the count in the keys.

Body:
A straightforward solution (thanks @DeepSpace for dict-comprehension suggestion):

keys = ['a', 'a', 'b', 'c']
values = [6, 2, 3, 4]

out = {}
for k, v in zip(keys, values):
    out.setdefault(k, []).append(v)

out = {key: sum(value) / len(value) for key, value in out.items()}

print(out)

Prints:

{'a': 4.0, 'b': 3.0, 'c': 4.0}

If you want count of keys, you can do for example:

out = {}
for k, v in zip(keys, values):
    out.setdefault(k, []).append(v)

out = {key: (sum(value) / len(value), len(value)) for key, value in out.items()}

print(out)

Prints:

{'a': (4.0, 2), 'b': (3.0, 1), 'c': (4.0, 1)}

Where the second element of values is a count of key.

Solution with itertools (if keys are sorted):

keys = ['a', 'a', 'b', 'c']
values = [6, 2, 3, 4]

from itertools import groupby
from statistics import mean

out = {}
for k, g in groupby(zip(keys, values), lambda k: k[0]):
    out[k] = mean(v for _, v in g)

print(out)

Prints:

{'a': 4, 'b': 3, 'c': 4}


问:
Visual studio code user snippets not working for php
Visual studio code user snippets not working for php. Have restarted VS code and the PC. Still does not work.

User snippet code:

No snippet shows up:

Visual studio code version:

答: Put it in the html snippets file. It is what php files use unless you are inside <?php ?> tags.