问:
Get return value from stored procedure - LINQ
I want to get the return value in stored procedure using LINQ, EF. I have seen solutions with T-SQL but that method does not solve the problem. I need to solve it with LINQ.

Return 0 I want to take 1 and -1 according to the result

Stored procedure:

```<code>ALTER PROCEDURE [dbo].[Login]
    @inTcNu CHAR(11),
    @inPass NVARCHAR(MAX),
    @inIP NVARCHAR(40),
    @rolNu TINYINT OUTPUT,
    @kulNu INT OUTPUT
AS
BEGIN
    SELECT @kulNu = kullaniciID, @rolNu = rolID
    FROM Kullanici WITH(NOLOCK)
    WHERE tcNumarasi = @inTcNu AND parola = @inPass;

    IF @rolNu >= 0 AND @kulNu >= 0
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 1);

        RETURN 1;
    END
    ELSE
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 0);

        RETURN 0;
    END

    RETURN -1;
END
</code>```

C#, LINQ, EF

```<code>using (var ctx = new ktdbEntities())
{
    var IP = networkUtils.GetIP();
    var rolNu = new ObjectParameter("rolNu", typeof(int));
    var kulNu = new ObjectParameter("kulNu", typeof(int));

    var output = ctx.Login(model.tcNumarasi, model.parola, IP, rolNu, kulNu);

    object value1 = rolNu.Value;
    object value2 = kulNu.Value;
}
</code>```

答:
You can't return values from Stored Procedure like this. You can pass output parameter to achieve it.

Firstly I modified your sp like this;

```<code>ALTER PROCEDURE [dbo].[Login]
    @inTcNu CHAR(11),
    @inPass NVARCHAR(MAX),
    @inIP NVARCHAR(40),
    @rolNu TINYINT OUTPUT,
    @kulNu INT OUTPUT,
    @result INT OUTPUT
AS
BEGIN
    SELECT @kulNu = kullaniciID, @rolNu = rolID
    FROM Kullanici WITH(NOLOCK)
    WHERE tcNumarasi = @inTcNu AND parola = @inPass;

    IF @rolNu >= 0 AND @kulNu >= 0
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 1);

        set @result = 1;
    END
    ELSE
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 0);

        set @result = 0;
    END

    set @result = -1;
END
</code>```

And then I couldn't see ctx.Login method but I assume that you are executing the stored procedure inside it.

```<code>using (var ctx = new ktdbEntities())
{
    var IP = networkUtils.GetIP();
    var rolNu = new ObjectParameter("rolNu", typeof(int));
    var kulNu = new ObjectParameter("kulNu", typeof(int));
    var resultParam = new ObjectParameter("result", typeof(int));

    var output = ctx.Login(model.tcNumarasi, model.parola, IP, rolNu, kulNu,resultParam);

    object value1 = rolNu.Value;
    object value2 = kulNu.Value;
    object result = resultParam.Value; //Get output value
}
</code>```

Body:
I want to get the return value in stored procedure using LINQ, EF. I have seen solutions with T-SQL but that method does not solve the problem. I need to solve it with LINQ.

Return 0 I want to take 1 and -1 according to the result

Stored procedure:

ALTER PROCEDURE [dbo].[Login]
    @inTcNu CHAR(11),
    @inPass NVARCHAR(MAX),
    @inIP NVARCHAR(40),
    @rolNu TINYINT OUTPUT,
    @kulNu INT OUTPUT
AS
BEGIN
    SELECT @kulNu = kullaniciID, @rolNu = rolID
    FROM Kullanici WITH(NOLOCK)
    WHERE tcNumarasi = @inTcNu AND parola = @inPass;

    IF @rolNu >= 0 AND @kulNu >= 0
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 1);

        RETURN 1;
    END
    ELSE
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 0);

        RETURN 0;
    END

    RETURN -1;
END

C#, LINQ, EF

using (var ctx = new ktdbEntities())
{
    var IP = networkUtils.GetIP();
    var rolNu = new ObjectParameter("rolNu", typeof(int));
    var kulNu = new ObjectParameter("kulNu", typeof(int));

    var output = ctx.Login(model.tcNumarasi, model.parola, IP, rolNu, kulNu);

    object value1 = rolNu.Value;
    object value2 = kulNu.Value;
}

Body:
You can't return values from Stored Procedure like this. You can pass output parameter to achieve it.

Firstly I modified your sp like this;

ALTER PROCEDURE [dbo].[Login]
    @inTcNu CHAR(11),
    @inPass NVARCHAR(MAX),
    @inIP NVARCHAR(40),
    @rolNu TINYINT OUTPUT,
    @kulNu INT OUTPUT,
    @result INT OUTPUT
AS
BEGIN
    SELECT @kulNu = kullaniciID, @rolNu = rolID
    FROM Kullanici WITH(NOLOCK)
    WHERE tcNumarasi = @inTcNu AND parola = @inPass;

    IF @rolNu >= 0 AND @kulNu >= 0
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 1);

        set @result = 1;
    END
    ELSE
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 0);

        set @result = 0;
    END

    set @result = -1;
END

And then I couldn't see ctx.Login method but I assume that you are executing the stored procedure inside it.

using (var ctx = new ktdbEntities())
{
    var IP = networkUtils.GetIP();
    var rolNu = new ObjectParameter("rolNu", typeof(int));
    var kulNu = new ObjectParameter("kulNu", typeof(int));
    var resultParam = new ObjectParameter("result", typeof(int));

    var output = ctx.Login(model.tcNumarasi, model.parola, IP, rolNu, kulNu,resultParam);

    object value1 = rolNu.Value;
    object value2 = kulNu.Value;
    object result = resultParam.Value; //Get output value
}


来源: stackexchange

问:
How to do this task with `while` loop?
I don't know how to convert from for-loop to while-loop all my attempts have failed. I have the following code:

```<code>public static void main(String[] args) {
    int[][] arr = new int[4][];
    arr[0] = new int[4];
    arr[1] = new int[2];
    arr[2] = new int[1];
    arr[3] = new int[3];

int counter = 1;
</code>```

How can I convert this for-loops to while-loops?

```<code> //fill arr numbers from 1 to 10
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = counter++;
            }
        }

    for (int i = 0; i < arr.length; i++) {
            System.out.print(" arr [ " + i + " ] = ");
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println(" ");
        }

    }
}
</code>```

Output:

```<code>arr [ 0 ] = 1 2 3 4
arr [ 1 ] = 5 6
arr [ 2 ] = 7
arr [ 3 ] = 8 9 10
</code>```

答:
for loop and while loop just differ in their syntax. The equivalent of a for loop:

```<code>for(int i = 0; i < arr.length; i++) {
    ...
}
</code>```

is

```<code>int i = 0;
while(i < arr.length) {
    ...
    i++;
}
</code>```

Below is your code but with while loops:

```<code>public static void main(String[] args) {
    int[][] arr = new int[4][];
    arr[0] = new int[4];
    arr[1] = new int[2];
    arr[2] = new int[1];
    arr[3] = new int[3];

    int counter = 1;
    int i = 0, j = 0; // Initialize vars for while loops

    //fill arr numbers from 1 to 10
    while(i<arr.length){
        while(j<arr[i].length){
            arr[i][j] = counter++;
            j++; // Increment as in for loops
        }
        i++; // Increment as in for loops
        j = 0; // Restart j to the next outer loop step
    }

    i = 0; // Reset i for outer loop
    // No need to j=0 since when the above loop ends, j will reset to 0

    while(i<arr.length){
        System.out.print(" arr [ " + i + " ] = ");
        while(j<arr[i].length){
            System.out.print(arr[i][j] + " ");
            j++; // Increment as in for loops
        }
        i++; // Increment as in for loops
        j = 0; // Same objective as in the loop above
        System.out.println(" ");
    }
}
</code>```

Explanations in comments, hope it helped!

ContentLicense: CC BY-SA 3.0

Title: How to do this task with `while` loop?

Body:
I don't know how to convert from for-loop to while-loop all my attempts have failed. I have the following code:

public static void main(String[] args) {
    int[][] arr = new int[4][];
    arr[0] = new int[4];
    arr[1] = new int[2];
    arr[2] = new int[1];
    arr[3] = new int[3];

int counter = 1;

How can I convert this for-loops to while-loops?

 //fill arr numbers from 1 to 10
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = counter++;
            }
        }

    for (int i = 0; i < arr.length; i++) {
            System.out.print(" arr [ " + i + " ] = ");
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println(" ");
        }

    }
}

Output:

arr [ 0 ] = 1 2 3 4
arr [ 1 ] = 5 6
arr [ 2 ] = 7
arr [ 3 ] = 8 9 10

Body:
for loop and while loop just differ in their syntax. The equivalent of a for loop:

for(int i = 0; i < arr.length; i++) {
    ...
}

is

int i = 0;
while(i < arr.length) {
    ...
    i++;
}

Below is your code but with while loops:

public static void main(String[] args) {
    int[][] arr = new int[4][];
    arr[0] = new int[4];
    arr[1] = new int[2];
    arr[2] = new int[1];
    arr[3] = new int[3];

    int counter = 1;
    int i = 0, j = 0; // Initialize vars for while loops

    //fill arr numbers from 1 to 10
    while(i<arr.length){
        while(j<arr[i].length){
            arr[i][j] = counter++;
            j++; // Increment as in for loops
        }
        i++; // Increment as in for loops
        j = 0; // Restart j to the next outer loop step
    }

    i = 0; // Reset i for outer loop
    // No need to j=0 since when the above loop ends, j will reset to 0

    while(i<arr.length){
        System.out.print(" arr [ " + i + " ] = ");
        while(j<arr[i].length){
            System.out.print(arr[i][j] + " ");
            j++; // Increment as in for loops
        }
        i++; // Increment as in for loops
        j = 0; // Same objective as in the loop above
        System.out.println(" ");
    }
}

Explanations in comments, hope it helped!


问:
php code error Warning: Declaration of Digital_Signature::CreateSign()
```<code> function CreateSign()
{
$rsa_obj = new Crypt_RSA(array('private_key' => $this->_privateKey));
$this->check_error($rsa_obj);
return $rsa_obj->createSign($this->_document);
}
</code>```

this code display this error

```<code>Warning: Declaration of Digital_Signature::CreateSign() should be compatible with Crypt_RSA::createSign($document, $private_key = NULL, $hash_func = NULL) in /var/www/html/shares/digital_signature.php on line 49
</code>```

can any one help

答: both functions in the parent class and child class should have the same arguments , also same default values for their arguments </p>

Body:
 function CreateSign()
{
$rsa_obj = new Crypt_RSA(array('private_key' => $this->_privateKey));
$this->check_error($rsa_obj);
return $rsa_obj->createSign($this->_document);
}

this code display this error

Warning: Declaration of Digital_Signature::CreateSign() should be compatible with Crypt_RSA::createSign($document, $private_key = NULL, $hash_func = NULL) in /var/www/html/shares/digital_signature.php on line 49

can any one help


问:
Angular 2: Functions to be used across all components
I have an angular 2 webpack project where I currently have some functions that are repeated throughout several components. I would like to inherit all of these components from a "master" class OR component (whichever works), in order to be able to call my functions from all my components that need them.

As an example, if I have a function foo in 3 different components:

```<code>foo(s: string){
  console.log(s);
}
</code>```

I would like you move this function to another file/class/components:

```<code>class parent{
  foo(s: string){
    console.log(s);
  }
}
</code>```

And having someway to call my foo function from my a given component. For instance:

```<code>class child{
  constructor(){
    foo("Hello");
  }
}
</code>```

How would I do this using Angular 2 / Typescript?

答:
You can create utils.ts which contains all common funcitons

```<code>export default class Utils {
    static doSomething(val: string) { return val; }
    static doSomethingElse(val: string) { return val; }
}
</code>```

Then you can use as below

```<code>import Utils from './utils'

export class MyClass {
     constructor()
     {
         Utils.doSomething("test");
     }
}
</code>```

Body:
I have an angular 2 webpack project where I currently have some functions that are repeated throughout several components. I would like to inherit all of these components from a "master" class OR component (whichever works), in order to be able to call my functions from all my components that need them.

As an example, if I have a function foo in 3 different components:

foo(s: string){
  console.log(s);
}

I would like you move this function to another file/class/components:

class parent{
  foo(s: string){
    console.log(s);
  }
}

And having someway to call my foo function from my a given component. For instance:

class child{
  constructor(){
    foo("Hello");
  }
}

How would I do this using Angular 2 / Typescript?

Body:
You can create utils.ts which contains all common funcitons

export default class Utils {
    static doSomething(val: string) { return val; }
    static doSomethingElse(val: string) { return val; }
}

Then you can use as below

import Utils from './utils'

export class MyClass {
     constructor()
     {
         Utils.doSomething("test");
     }
}


问:
Getting the prime/next state of a variable
Given some condition, I want to check that a variables next state holds for some proposition. I have not been able to create something that rodin has accepted.

My exact case is the following invariant. I want to make sure that the variable door never changes when the lock is on. The variable door is either Open or Closed

```<code>inv4: PrimaryLock = On ⇒ door :∣ door' = door
</code>```

If the PrimaryLock is On this means that the door state will not change, no matter what event is triggered next.

Is this possible using Event-b or do I need to solve my issue by adding additional variables?

答:
You may also use Atelier B to develop Event-B specifications. There are some variations with respect to Rodin, but the principles remain the same.
For your issue, with Atelier B, you can specify an event as follows:

```<code>door_change = BEGIN
  door :( door : { Open, Closed } &
    (PrimaryLock = On => doors = doors$0
  )
END
</code>```

There, door and door$0 stand for the values before and after the event.

You can have such an event at the most abstract level of the specification. Then, you introduce a refinement with all the events of your system that may change the state of the door and have such events refine door_change.

This "trick" allows one to specify properties about variable changes in the system. I do not know if this feature is available in Rodin, though.

Body:
Given some condition, I want to check that a variables next state holds for some proposition. I have not been able to create something that rodin has accepted.

My exact case is the following invariant. I want to make sure that the variable door never changes when the lock is on. The variable door is either Open or Closed

inv4: PrimaryLock = On ⇒ door :∣ door' = door

If the PrimaryLock is On this means that the door state will not change, no matter what event is triggered next.

Is this possible using Event-b or do I need to solve my issue by adding additional variables?

Body:
You may also use Atelier B to develop Event-B specifications. There are some variations with respect to Rodin, but the principles remain the same.
For your issue, with Atelier B, you can specify an event as follows:

door_change = BEGIN
  door :( door : { Open, Closed } &
    (PrimaryLock = On => doors = doors$0
  )
END

There, door and door$0 stand for the values before and after the event.

You can have such an event at the most abstract level of the specification. Then, you introduce a refinement with all the events of your system that may change the state of the door and have such events refine door_change.

This "trick" allows one to specify properties about variable changes in the system. I do not know if this feature is available in Rodin, though.


问:
creating float point colors

I want to to draw a pixel with float point color e.g rgb(173.373, 216, 230)
I tried using Pillow Image and Imagecolor but without success

My main Target is to be able to both read and write float point colors off images.

```<code>from PIL import Image, ImageColor

im = Image.new("RGB", (32, 32), ImageColor.getrgb("rgb(173.373, 216, 230)"))

im.save('simplePixel.png')
</code>```

But i get the following error:

```<code>raise ValueError("unknown color specifier: %r" % color)
ValueError: unknown color specifier: 'rgb(173.373, 216, 230)'
</code>```

答:
As Paulie_D said, there is no such "level" of color. You can't use floats in the color string.

The Documentation states:

RGB functions, given as rgb(red, green, blue) where the color values are integers in the range 0 to 255. Alternatively, the color values can be given as three percentages (0% to 100%). For example, rgb(255,0,0) and rgb(100%,0%,0%) both specify pure red.

So these are the only options you can use.

Title: creating float point colors

Body:
I want to to draw a pixel with float point color e.g rgb(173.373, 216, 230)
I tried using Pillow Image and Imagecolor but without success

My main Target is to be able to both read and write float point colors off images.

from PIL import Image, ImageColor

im = Image.new("RGB", (32, 32), ImageColor.getrgb("rgb(173.373, 216, 230)"))

im.save('simplePixel.png')

But i get the following error:

raise ValueError("unknown color specifier: %r" % color)
ValueError: unknown color specifier: 'rgb(173.373, 216, 230)'


问:
Have image side by side without scrollbar
I'm working on a Roulette site, i just can't get the roulette animation to work.
I have an image for the roulette but i need the image to disappear after a certain amount of % and that the image loops around to the left.

This is how it kind of needs to look like (it doesn't end at the end of the border, and doesn't loop around to the left thought.):

$("#right").click(function () {
    $("#one").css("left", "200px");
    $("#two").css("left", "200px");
    $("#three").css("left", "200px");
    $("#four").css("left", "200px");
    $("#five").css("left", "200px");
    $("#six").css("left", "200px");

});

$("#left").click(function () {
    $("#one").css("left", "0px");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
    width: 80%;
    height: 50px;
    border: 5px solid black;
    margin: auto;
    padding: 7px;
    z-index: 1;
    transition: left 2s ease;
}

div#one {
    width: 15%;
    height: 50px;
    background: black;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
    loop: true;
}

div#six {
    width: 15%;
    height: 50px;
    margin-left: 5px;
    background: red;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
    loop: true;
}

div#five {
    width: 15%;
    height: 50px;
    background: black;
    float: left;
    margin-left: 5px;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
}

div#two {
    width: 15%;
    height: 50px;
    margin-left: 5px;
    background: red;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
}

div#three {
    width: 15%;
    height: 50px;
    margin-left: 5px;
    background: black;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
}

div#four {
    width: 15%;
    height: 50px;
    margin-left: 5px;
    background: red;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
}</code>```

<button id="right">
    left: 100px;
</button>```
</div>
</div>
</p>

<p>And this is what i want it to look like, but the border has to end near the end of the screen, and the image has to be invisible outside the border, and loop around:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.numbers {
    display: inline-flex;
    border: 4px solid gray;
}

div.numbers img {
    margin-right: 5px;
}</code>```

```

so once i click on a button it should do the transition left 500px, and loop the image around to the left so the image keeps going to the right until the image is 500px further, and it should be invisible outside the border.

Thanks alot for the help!

答:
You're really close to hiding the scrolled content. You just need to hide the overflow in section with overflow: hidden;

$("#right").click(function() {
  $("#one").css("left", "200px");
  $("#two").css("left", "200px");
  $("#three").css("left", "200px");
  $("#four").css("left", "200px");
  $("#five").css("left", "200px");
  $("#six").css("left", "200px");

});

$("#left").click(function() {
  $("#one").css("left", "0px");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
  width: 80%;
  height: 50px;
  border: 5px solid black;
  margin: auto;
  padding: 7px;
  z-index: 1;
  transition: left 2s ease;
  overflow: hidden;
}

div#one {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
  loop: true;
}

div#six {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
  loop: true;
}

div#five {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  margin-left: 5px;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#two {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#three {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#four {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}</code>```

<button id="right">
left: 100px;
</button>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a Roulette site, i just can't get the roulette animation to work.
I have an image for the roulette but i need the image to disappear after a certain amount of % and that the image loops around to the left.

This is how it kind of needs to look like (it doesn't end at the end of the border, and doesn't loop around to the left thought.):

$("#right").click(function () {
    $("#one").css("left", "200px");
    $("#two").css("left", "200px");
    $("#three").css("left", "200px");
    $("#four").css("left", "200px");
    $("#five").css("left", "200px");
    $("#six").css("left", "200px");

});

$("#left").click(function () {
    $("#one").css("left", "0px");
});

section {
    width: 80%;
    height: 50px;
    border: 5px solid black;
    margin: auto;
    padding: 7px;
    z-index: 1;
    transition: left 2s ease;
}

div#one {
    width: 15%;
    height: 50px;
    background: black;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
    loop: true;
}

div#six {
    width: 15%;
    height: 50px;
    margin-left: 5px;
    background: red;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
    loop: true;
}

div#five {
    width: 15%;
    height: 50px;
    background: black;
    float: left;
    margin-left: 5px;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
}

div#two {
    width: 15%;
    height: 50px;
    margin-left: 5px;
    background: red;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
}

div#three {
    width: 15%;
    height: 50px;
    margin-left: 5px;
    background: black;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
}

div#four {
    width: 15%;
    height: 50px;
    margin-left: 5px;
    background: red;
    float: left;
    z-index: -1;
    left: 0px;
    position: relative;
    transition: left 2s ease;
}

<button id="right">
    left: 100px;
</button>

And this is what i want it to look like, but the border has to end near the end of the screen, and the image has to be invisible outside the border, and loop around:

div.numbers {
    display: inline-flex;
    border: 4px solid gray;
}

div.numbers img {
    margin-right: 5px;
}

so once i click on a button it should do the transition left 500px, and loop the image around to the left so the image keeps going to the right until the image is 500px further, and it should be invisible outside the border.

Thanks alot for the help!

Body:
You're really close to hiding the scrolled content. You just need to hide the overflow in section with overflow: hidden;

$("#right").click(function() {
  $("#one").css("left", "200px");
  $("#two").css("left", "200px");
  $("#three").css("left", "200px");
  $("#four").css("left", "200px");
  $("#five").css("left", "200px");
  $("#six").css("left", "200px");

});

$("#left").click(function() {
  $("#one").css("left", "0px");
});

section {
  width: 80%;
  height: 50px;
  border: 5px solid black;
  margin: auto;
  padding: 7px;
  z-index: 1;
  transition: left 2s ease;
  overflow: hidden;
}

div#one {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
  loop: true;
}

div#six {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
  loop: true;
}

div#five {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  margin-left: 5px;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#two {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#three {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#four {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <div id="one"></div>
  <div id="two"></div>
  <div id="three"></div>
  <div id="four"></div>
  <div id="five"></div>
  <div id="six"></div>
  <div id="seven"></div>
  <div id="eight"></div>
</section>

<button id="right">
left: 100px;
</button>


问:
What Authorized IPs should I enter to request BlueSnap API credentials?
I'm developing an Ionic Cordova hybrid mobile app. I need to integrate BlueSnap's Hosted Payment Page into it. So I started with creating a request to get API credentials, following
this tutorial

But I don't know what IP address should I provide. I need enter the IP address to be used for API calls The backend for app is on Heroku platform. So what IP address should I type to get my API credentials ?

Thanks

答:
Use a Heroku add-on that provides applications with a fixed set of static IP addresses for outbound requests. There are multiple free and paid options:

Fixie

QuotaGuard Static

Proximo


问:
how to compare elements in lists
How can I store values in lists and later compare against each other

```<code>all_click = []
all_click_red = []

while True:

    a = input('give a number: ')
    b = input('give a second number: ')

    if a == 1:
        all_click.append(a)

    if b == 1:
        all_click_red.append(b)

    if all_click_red[-1] and all_click[-1] == 1:
        print('all good')

    else:
        print('false')
</code>```

Because I get an error like this:

```<code> if all_click_red[-1] and all_click[-1] == 1:
     IndexError: list index out of range
</code>```

答: You are append something to the list only if it's value is equal 1. If it's not equal 1, the list is empty, and list[-1] will be out of range, raising this error.</p>

Title: how to compare elements in lists

Body:
How can I store values in lists and later compare against each other

all_click = []
all_click_red = []

while True:

    a = input('give a number: ')
    b = input('give a second number: ')

    if a == 1:
        all_click.append(a)

    if b == 1:
        all_click_red.append(b)

    if all_click_red[-1] and all_click[-1] == 1:
        print('all good')

    else:
        print('false')

Because I get an error like this:

 if all_click_red[-1] and all_click[-1] == 1:
     IndexError: list index out of range


问:
Count all the active products inside a category; Left Join not working as expected
my schema is designed to handle product sizes, so products belong to an item, and an item with a certain size is a product.

I need to select all the categories and count the active products inside them (Products.IsHidden = false).

Here is my schema;

```<code>CREATE TABLE CATEGORIES (
  CategoryId int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  Name varchar(255)
);

CREATE TABLE ITEMS (
  ItemId int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  CategoryId int NOT NULL,
  Name varchar(255),
  Description varchar(255),
  FOREIGN KEY (CategoryId) REFERENCES CATEGORIES(CategoryId)
);

CREATE TABLE SIZES (
  SizeId int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  Name varchar(255)
);

CREATE TABLE PRODUCTS (
  ProductId int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  ItemId int NOT NULL,
  SizeId int NOT NULL,
  Price float,
  Weight float,
  Stock int NOT NULL,
  Discount float NULL,
  CreatedAt DateTime,
  PictureLoc varchar(255),
  IsHidden boolean,
  FOREIGN KEY (SizeId) REFERENCES SIZES(SizeId),
  FOREIGN KEY (ItemId) REFERENCES ITEMS(ItemId)
);
</code>```

Here is my code (my aim is to count all the active products inside a category);
Assuming I have 2 active Products (IsHidden=false) in Category A.

```<code>SELECT
  CATEGORIES.CategoryId,
  CATEGORIES.Name,
  Count(PRODUCTS.ProductId) as ActiveProducts
FROM CATEGORIES
  LEFT JOIN ITEMS
   ON CATEGORIES.CategoryId = ITEMS.CategoryId
  LEFT JOIN PRODUCTS
   ON ITEMS.ItemId = PRODUCTS.ItemId
WHERE PRODUCTS.IsHidden = FALSE
GROUP BY CATEGORIES.CategoryId
</code>```

but this code returns only 1 row.

```<code>CategoryId | Category Name | ActiveProducts
1          | A             | 2
</code>```

Shouldn't the other categories with 0 product count show up in the results? My expected result is:

```<code>CategoryId | Category Name | ActiveProducts
1          | A             | 2
2          | B             | 0
3          | C             | 0
</code>```

How do I come up with my expected result?

答:
Conditions on the second table in a left join belong in the on clause, not the where clause:

```<code>SELECT c.CategoryId, c.Name, Count(p.ProductId) as ActiveProducts
FROM CATEGORIES c LEFT JOIN
     ITEMS i
     ON c.CategoryId = i.CategoryId LEFT JOIN
     PRODUCTS p
     ON i.ItemId = p.ItemId AND p.IsHidden = FALSE
GROUP BY c.CategoryId;
</code>```

Body:
my schema is designed to handle product sizes, so products belong to an item, and an item with a certain size is a product.

I need to select all the categories and count the active products inside them (Products.IsHidden = false).

Here is my schema;

CREATE TABLE CATEGORIES (
  CategoryId int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  Name varchar(255)
);

CREATE TABLE ITEMS (
  ItemId int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  CategoryId int NOT NULL,
  Name varchar(255),
  Description varchar(255),
  FOREIGN KEY (CategoryId) REFERENCES CATEGORIES(CategoryId)
);

CREATE TABLE SIZES (
  SizeId int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  Name varchar(255)
);

CREATE TABLE PRODUCTS (
  ProductId int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  ItemId int NOT NULL,
  SizeId int NOT NULL,
  Price float,
  Weight float,
  Stock int NOT NULL,
  Discount float NULL,
  CreatedAt DateTime,
  PictureLoc varchar(255),
  IsHidden boolean,
  FOREIGN KEY (SizeId) REFERENCES SIZES(SizeId),
  FOREIGN KEY (ItemId) REFERENCES ITEMS(ItemId)
);

Here is my code (my aim is to count all the active products inside a category);
Assuming I have 2 active Products (IsHidden=false) in Category A.

SELECT
  CATEGORIES.CategoryId,
  CATEGORIES.Name,
  Count(PRODUCTS.ProductId) as ActiveProducts
FROM CATEGORIES
  LEFT JOIN ITEMS
   ON CATEGORIES.CategoryId = ITEMS.CategoryId
  LEFT JOIN PRODUCTS
   ON ITEMS.ItemId = PRODUCTS.ItemId
WHERE PRODUCTS.IsHidden = FALSE
GROUP BY CATEGORIES.CategoryId

but this code returns only 1 row.

CategoryId | Category Name | ActiveProducts
1          | A             | 2

Shouldn't the other categories with 0 product count show up in the results? My expected result is:

CategoryId | Category Name | ActiveProducts
1          | A             | 2
2          | B             | 0
3          | C             | 0

How do I come up with my expected result?

Body:
Conditions on the second table in a left join belong in the on clause, not the where clause:

SELECT c.CategoryId, c.Name, Count(p.ProductId) as ActiveProducts
FROM CATEGORIES c LEFT JOIN
     ITEMS i
     ON c.CategoryId = i.CategoryId LEFT JOIN
     PRODUCTS p
     ON i.ItemId = p.ItemId AND p.IsHidden = FALSE
GROUP BY c.CategoryId;


问:
Why build bazel everytime we need to run something in TensorFlow?
I've install TensorFlow from sources via bazel build. Everything works fine as expected. But when I'm going through tutorials here https://github.com/tensorflow/models/tree/master/research/slim in readme, it's mentioned to bazel build for each script and I assume bazel is building a lot of sources which it has previouxly built.

Is there a script to build all TensorFlow sources?

答:
it's mentioned to bazel build for each script and I assume bazel is building a lot of sources which it has previouxly built.

Bazel caches build outputs from previous builds, and only builds what's not yet available, or what may have changed since the last build.

If you bazel build //foo:a, then, without changing anything in the source tree, you build bazel build //bar:b, then whatever //foo:a and //bar:b both depend on, Bazel will not build again in the second build.

Does that answer your question?

Is there a script to build all TensorFlow sources?

You can tell Bazel to build everything under a given path, e.g. bazel build //foo/bar/..., to build everything in //foo/bar and in all of its subpackages. In this case, you'd want to build everything in the workspace, so you'd run:

```<code>bazel build //...
</code>```

Body:
it's mentioned to bazel build for each script and I assume bazel is building a lot of sources which it has previouxly built.

Bazel caches build outputs from previous builds, and only builds what's not yet available, or what may have changed since the last build.

If you bazel build //foo:a, then, without changing anything in the source tree, you build bazel build //bar:b, then whatever //foo:a and //bar:b both depend on, Bazel will not build again in the second build.

Does that answer your question?

Is there a script to build all TensorFlow sources?

You can tell Bazel to build everything under a given path, e.g. bazel build //foo/bar/..., to build everything in //foo/bar and in all of its subpackages. In this case, you'd want to build everything in the workspace, so you'd run:

bazel build //...


问:
Error resconf using OVSDB plugin
I'm using ODL-Carbon and trying to get a simple REST:

http://ip-controller:8181/restconf/config/network-topology:network-topology/topology/ovsdb:1/

but I get this error message:

```<code>> {
>     "errors": {
>         "error": [
>             {
>                 "error-type": "application",
>                 "error-tag": "operation-failed",
>                 "error-message": "Error executeRead ReadData for path /(urn:TBD:params:xml:ns:yang:network-topology?revision=2013-10-21)network-topology/topology/topology[{(urn:TBD:params:xml:ns:yang:network-topology?revision=2013-10-21)topology-id=ovsdb:1}]",
>                 "error-info": "org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException:
> Found primary shard member-1-shard-topology-config but it's not
> initialized yet. Please try again later\n\tat
> org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.createNotInitializedException(ShardManager.java:948)\n\tat
> org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.onShardNotInitializedTimeout(ShardManager.java:769)\n\tat
> org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.handleCommand(ShardManager.java:251)\n\tat
> org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor.onReceiveCommand(AbstractUntypedPersistentActor.java:31)\n\tat
> akka.persistence.UntypedPersistentActor.onReceive(PersistentActor.scala:170)\n\tat
> org.opendaylight.controller.cluster.common.actor.MeteringBehavior.apply(MeteringBehavior.java:104)\n\tat
> akka.actor.ActorCell$$anonfun$become$1.applyOrElse(ActorCell.scala:544)\n\tat
> akka.actor.Actor$class.aroundReceive(Actor.scala:502)\n\tat
> akka.persistence.UntypedPersistentActor.akka$persistence$Eventsourced$$super$aroundReceive(PersistentActor.scala:168)\n\tat
> akka.persistence.Eventsourced$$anon$1.stateReceive(Eventsourced.scala:727)\n\tat
> akka.persistence.Eventsourced$class.aroundReceive(Eventsourced.scala:183)\n\tat
> akka.persistence.UntypedPersistentActor.aroundReceive(PersistentActor.scala:168)\n\tat
> akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)\n\tat
> akka.actor.ActorCell.invoke(ActorCell.scala:495)\n\tat
> akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)\n\tat
> akka.dispatch.Mailbox.run(Mailbox.scala:224)\n\tat
> akka.dispatch.Mailbox.exec(Mailbox.scala:234)\n\tat
> scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)\n\tat
> scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)\n\tat
> scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)\n\tat
> scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)\n"
>             }
>         ]
>     } }
</code>```

My OS is Debian 9.

答: I've never seen this "it's not initialized yet. Please try again later" NotInitializedException, but it seems to indicate that the Data Store is not ready.. either you just need to wait a bit, or it perhaps there was serious error during start up.  Have you checked if your karaf.log has any errors that could explain why?</p>

Title: Error resconf using OVSDB plugin

Body:
I'm using ODL-Carbon and trying to get a simple REST:

http://ip-controller:8181/restconf/config/network-topology:network-topology/topology/ovsdb:1/

but I get this error message:

> {
>     "errors": {
>         "error": [
>             {
>                 "error-type": "application",
>                 "error-tag": "operation-failed",
>                 "error-message": "Error executeRead ReadData for path /(urn:TBD:params:xml:ns:yang:network-topology?revision=2013-10-21)network-topology/topology/topology[{(urn:TBD:params:xml:ns:yang:network-topology?revision=2013-10-21)topology-id=ovsdb:1}]",
>                 "error-info": "org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException:
> Found primary shard member-1-shard-topology-config but it's not
> initialized yet. Please try again later\n\tat
> org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.createNotInitializedException(ShardManager.java:948)\n\tat
> org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.onShardNotInitializedTimeout(ShardManager.java:769)\n\tat
> org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.handleCommand(ShardManager.java:251)\n\tat
> org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor.onReceiveCommand(AbstractUntypedPersistentActor.java:31)\n\tat
> akka.persistence.UntypedPersistentActor.onReceive(PersistentActor.scala:170)\n\tat
> org.opendaylight.controller.cluster.common.actor.MeteringBehavior.apply(MeteringBehavior.java:104)\n\tat
> akka.actor.ActorCell$$anonfun$become$1.applyOrElse(ActorCell.scala:544)\n\tat
> akka.actor.Actor$class.aroundReceive(Actor.scala:502)\n\tat
> akka.persistence.UntypedPersistentActor.akka$persistence$Eventsourced$$super$aroundReceive(PersistentActor.scala:168)\n\tat
> akka.persistence.Eventsourced$$anon$1.stateReceive(Eventsourced.scala:727)\n\tat
> akka.persistence.Eventsourced$class.aroundReceive(Eventsourced.scala:183)\n\tat
> akka.persistence.UntypedPersistentActor.aroundReceive(PersistentActor.scala:168)\n\tat
> akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)\n\tat
> akka.actor.ActorCell.invoke(ActorCell.scala:495)\n\tat
> akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)\n\tat
> akka.dispatch.Mailbox.run(Mailbox.scala:224)\n\tat
> akka.dispatch.Mailbox.exec(Mailbox.scala:234)\n\tat
> scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)\n\tat
> scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)\n\tat
> scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)\n\tat
> scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)\n"
>             }
>         ]
>     } }

My OS is Debian 9.


问:
How to resolve error: value reduceByKey is not a member of org.apache.spark.rdd.RDD[(Int, Int)]?
I am learning apache spark and trying to execute a small program on scala terminal.

I have started the dfs, yarn and history server using the following commands:

```<code>start-dfs.sh
start-yarn.sh
mr-jobhistory-deamon.sh start historyserver
</code>```

and then in the scala terminal, i have written the following commands:

```<code> var file = sc.textFile("/Users/****/Documents/backups/h/*****/input/ncdc/micro-tab/sample.txt");
 val records = lines.map(_.split("\t"));
 val filters = records.filter(rec => (rec(1) != "9999" && rec(2).matches("[01459]")));
 val tuples = filters.map(rec => (rec(0).toInt, rec(1).toInt));
 val maxTemps = tuples.reduceByKey((a,b) => Math.max(a,b));
</code>```

all commands are executed successfully, except the last one, which throws the following error:

```<code>error: value reduceByKey is not a member of org.apache.spark.rdd.RDD[(Int, Int)]
</code>```

i found some solutions like:

This comes from using a pair rdd function generically. The reduceByKey method is actually a method of the PairRDDFunctions class, which has an implicit conversion from RDD.So it requires several implicit typeclasses. Normally when working with simple concrete types, those are already in scope. But you should be able to amend your method to also require those same implicit.

But i am not sure how to achieve this.

Any help, how to resolve this issue?

答:
It seems you are missing an import. Try writing this in the console:

```<code>import org.apache.spark.SparkContext._
</code>```

And then running the above commands. This import brings an implicit conversion which lets you use the reduceByKey method.

Body:
I am learning apache spark and trying to execute a small program on scala terminal.

I have started the dfs, yarn and history server using the following commands:

start-dfs.sh
start-yarn.sh
mr-jobhistory-deamon.sh start historyserver

and then in the scala terminal, i have written the following commands:

 var file = sc.textFile("/Users/****/Documents/backups/h/*****/input/ncdc/micro-tab/sample.txt");
 val records = lines.map(_.split("\t"));
 val filters = records.filter(rec => (rec(1) != "9999" && rec(2).matches("[01459]")));
 val tuples = filters.map(rec => (rec(0).toInt, rec(1).toInt));
 val maxTemps = tuples.reduceByKey((a,b) => Math.max(a,b));

all commands are executed successfully, except the last one, which throws the following error:

error: value reduceByKey is not a member of org.apache.spark.rdd.RDD[(Int, Int)]

i found some solutions like:

This comes from using a pair rdd function generically. The reduceByKey method is actually a method of the PairRDDFunctions class, which has an implicit conversion from RDD.So it requires several implicit typeclasses. Normally when working with simple concrete types, those are already in scope. But you should be able to amend your method to also require those same implicit.

But i am not sure how to achieve this.

Any help, how to resolve this issue?

Body:
It seems you are missing an import. Try writing this in the console:

import org.apache.spark.SparkContext._

And then running the above commands. This import brings an implicit conversion which lets you use the reduceByKey method.


问:
Retrieve only a specific child from firebase realtime database into the Recyclerview
I have the following firebase database structure:

Where, under the user id child, I have created a child by System date.Date child will be created from system date and will be more than one.Suppose I have list of System date child which I will fetch from my firebase database and also show in Recyclerview?How can I achieve that?And what will be the data model class?

答:
you'll need to create your own adapter that:

listens to onDataChange calls from Firebase

keeps an internal copy of the data from Firebase

informs the RecyclerView when the data changes

creates view holders when those are needed

binds data from the Firebase data to the view

The minimum I could come up with quickly is:

```<code>public static class MenuHomeAdapter extends RecyclerView.Adapter<MenuViewHolder> {
    ArrayList<Menu> items = new ArrayList<>();

    public MenuHomeAdapter(Firebase ref) {
        ref.addValueEventListener(new ValueEventListener() {
            public void onDataChange(DataSnapshot snapshot) {
                items.clear();
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Menu menu = postSnapshot.getValue(Menu.class);
                    items.add(menu);
                }
                notifyDataSetChanged();
            }

            public void onCancelled(FirebaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });
    }

    public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        return new MenuViewHolder(view);
    }

    public void onBindViewHolder(MenuViewHolder holder, int position) {
        Menu item = items.get(position);
        holder.getTitleView().setText(item.getTitle());
    }

    public int getItemCount() {
        return items.size();
    }
};
</code>```

Body:
you'll need to create your own adapter that:

listens to onDataChange calls from Firebase

keeps an internal copy of the data from Firebase

informs the RecyclerView when the data changes

creates view holders when those are needed

binds data from the Firebase data to the view

The minimum I could come up with quickly is:

public static class MenuHomeAdapter extends RecyclerView.Adapter<MenuViewHolder> {
    ArrayList<Menu> items = new ArrayList<>();

    public MenuHomeAdapter(Firebase ref) {
        ref.addValueEventListener(new ValueEventListener() {
            public void onDataChange(DataSnapshot snapshot) {
                items.clear();
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Menu menu = postSnapshot.getValue(Menu.class);
                    items.add(menu);
                }
                notifyDataSetChanged();
            }

            public void onCancelled(FirebaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });
    }

    public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        return new MenuViewHolder(view);
    }

    public void onBindViewHolder(MenuViewHolder holder, int position) {
        Menu item = items.get(position);
        holder.getTitleView().setText(item.getTitle());
    }

    public int getItemCount() {
        return items.size();
    }
};


问:
Delphi SQL return with multidimensional array
i created a type

```<code>type
  TStringArray = array of array of string;

function TDataModule4.GetList(TableName: String): TStringArray;
var
  i : Integer;
begin
  i:= 0;
  with TFDQuery.Create(Nil) do
  begin
    Connection := ADConnectionMySQL;
    SQL.Add(Format('Select * from %s', [TableName]));
    Open;
    First;
    while not Eof do
    begin

    end;
    Free;
  end;
end;
</code>```

I know get data using FieldByName, but i want to return all data in multidimensional array. How can i do this?

Here is how i want  to return :

array[0]["column1"] = "value1"

array[0]["column2"] = "value2"

array[1]["column1"] = "value3"

array[1]["column2"] = "value4"

array[2]["column1"] = "value5"

array[2]["column2"] = "value6"

答:
Here is one way to do it (though I can't make sense for doing such a thing):</p>

```<code>type
  TStringArray = array of array of string;
var
  Col: Integer;
  Row: Integer;
  Arr: TStringArray;
begin
  SetLength(Arr, FDQuery.Table.Rows.Count, FDQuery.Table.Columns.Count);

  for Row := 0 to FDQuery.Table.Rows.Count - 1 do
    for Col := 0 to FDQuery.Table.Columns.Count - 1 do
      Arr[Row][Col] := FDQuery.Table.Rows[Row].GetData(Col);
end;
</code>```

Body:
i created a type

type
  TStringArray = array of array of string;

function TDataModule4.GetList(TableName: String): TStringArray;
var
  i : Integer;
begin
  i:= 0;
  with TFDQuery.Create(Nil) do
  begin
    Connection := ADConnectionMySQL;
    SQL.Add(Format('Select * from %s', [TableName]));
    Open;
    First;
    while not Eof do
    begin

    end;
    Free;
  end;
end;

I know get data using FieldByName, but i want to return all data in multidimensional array. How can i do this?

Here is how i want  to return :

array[0]["column1"] = "value1"

array[0]["column2"] = "value2"

array[1]["column1"] = "value3"

array[1]["column2"] = "value4"

array[2]["column1"] = "value5"

array[2]["column2"] = "value6"

Body:
Here is one way to do it (though I can't make sense for doing such a thing):

type
  TStringArray = array of array of string;
var
  Col: Integer;
  Row: Integer;
  Arr: TStringArray;
begin
  SetLength(Arr, FDQuery.Table.Rows.Count, FDQuery.Table.Columns.Count);

  for Row := 0 to FDQuery.Table.Rows.Count - 1 do
    for Col := 0 to FDQuery.Table.Columns.Count - 1 do
      Arr[Row][Col] := FDQuery.Table.Rows[Row].GetData(Col);
end;


答: The parent element needs { overflow-y: hidden; } in your css code

Title: Have image side by side without scrollbar


问:
how to get the index of the end string in a list
```<code>for root, subdirs, files in os.walk(dir):
    for i in range(0, files.index(files[-1]) + 1):
</code>```

files.index(files[-1]) here is the end index of item in files, and I got it.

But I want to know is there a simple way to get it?
I know if I got the end item, say, like "d", after typing in files.index("d"), I would have gotten the index.

答:
files is a list, then you can use len() function. So, files.index(files[-1]) is equal to len(files) - 1.

Actually your question is about finding the last index. Take a look at this link.

Body:
for root, subdirs, files in os.walk(dir):
    for i in range(0, files.index(files[-1]) + 1):

files.index(files[-1]) here is the end index of item in files, and I got it.

But I want to know is there a simple way to get it?
I know if I got the end item, say, like "d", after typing in files.index("d"), I would have gotten the index.


问:
Array value overwrites instead of retaining old value - Javascript
This is what I want.

User enters a numerical input. If he enters 2, the code prompts to enter two player names.

The player names are stored in an array. There is a 'next' button in the page, when user clicks it, the code prompts to enter another two names.

The next is the tricky part: Right now there are four names entered on two separate sessions. Now I need a nested array should hold the usernames in separate arrays based on the session.

I've tried many codes but only the following at least comes closer.
But what happens is, every time user enters a new list of usernames, a new array is created but previous arrays are also over written.

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = new Array(new Array());
var NextList = document.querySelector("#NextList");
var tempArr = [];

addValue();

function addValue() {
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="NextList">Next list</button></code>```

答:
I am creating an array of arrays to insert names. tempArr is declared as empty inside addValue and later pushed into global array allnames

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = new Array(new Array());
var NextList = document.querySelector("#NextList");
var allnames = [];

addValue();

function addValue() {
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
  allnames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();
  console.log(allnames)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="NextList">Next list</button></code>```

Body:
This is what I want.

User enters a numerical input. If he enters 2, the code prompts to enter two player names.

The player names are stored in an array. There is a 'next' button in the page, when user clicks it, the code prompts to enter another two names.

The next is the tricky part: Right now there are four names entered on two separate sessions. Now I need a nested array should hold the usernames in separate arrays based on the session.

I've tried many codes but only the following at least comes closer.
But what happens is, every time user enters a new list of usernames, a new array is created but previous arrays are also over written.

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = new Array(new Array());
var NextList = document.querySelector("#NextList");
var tempArr = [];

addValue();

function addValue() {
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();

});

<button id="NextList">Next list</button>

Body:
I am creating an array of arrays to insert names. tempArr is declared as empty inside addValue and later pushed into global array allnames

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = new Array(new Array());
var NextList = document.querySelector("#NextList");
var allnames = [];

addValue();

function addValue() {
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
  allnames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();
  console.log(allnames)
});

<button id="NextList">Next list</button>


问:
How to find a string in char Array without using string functions?(c++)
I have following code:

```<code>char x[30]="computer";
char y[30]="put";
</code>```

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.

答:
Library function(c++ style)

```<code>std::string a = "computer", b = "put";
bool found = a.find(b) != std::string::npos;
</code>```

Without Library function(c style)

I assume you don't hope to get terrible complexity, so KMP is what you are looking for.

Body:
I have following code:

char x[30]="computer";
char y[30]="put";

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.

Body:
Library function(c++ style)

std::string a = "computer", b = "put";
bool found = a.find(b) != std::string::npos;

Without Library function(c style)

I assume you don't hope to get terrible complexity, so KMP is what you are looking for.


问:
SQLite query for Full Text Search to MATCH on both sides like LIKE
I am having an issue for both side MATCH in SQLite FTS in Android.

Say suppose I have this text item in my VIRTUAL FTS TABLE

Hello World I am here

HelloWorld I am Here

HelloWorldIamHere

I want to achieve that for Search String 'World' I should get all this THREE results.

I am able to achieve that using LIKE and % wildcard as WHERE column LIKE '%World%' but that is not meant to use as data grows. So I am using MATCH and * wildcard with Full Text Search Virtual Table as WHERE column MATCH 'World*'

BUT with this i am just getting this result...

Hello World I am here

How should i implement my MATCH query to get all the three items as my result

答:
FTS allows you to search only for terms generated by the tokenizer.

There is no information in the FTS index that would allow fast searching for suffixes.
You have to use LIKE, or construct your own index manually.


问:
Why does fopen() not recognize my file's name?
The programm should be able to open a file like myFile.txt,
alltough it's real name is myFile without the extension .txt.
So I wrote the function called removeFileExtension() in order
to achieve that.

It does open my file by copying the string from text into filename:

```<code>strcpy(filename,text);
FILE *fp = fopen(filename, "r");
</code>```

So I tried to check what the difference between text and my processed
string from removeFileExtension is.

To check if it even works I mate a function called strComparison(),
which returns either 0 when it is qual or 1 if unequal.
The thing is, after removing the file extension, it shows that both strings
are qual, but I am still not able to open the file.

When I type in ./a.out myFile.txt my comparison function returns 0,
it is equal, but fopen() still is not able to open the file,
respectively I allways get a Segmentation fault.

Does anyone see the problem here?
Why am I getting a Segmentation fault?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removeFileExtension(char *haystack);
int strComparison(char *one, char *two);

int main(int argc, char const *argv[])
{
  //----------------------------------------------------------------------------
  // CHECK INPUT VALIDITY
  //
  if (argc != 2)
  {
    printf("Usage: ./ass2 [file-name]\n");
    return 1;
  }

  //----------------------------------------------------------------------------
  // OPEN FILE (INITIAL)
  //
  char filename[32];
  strcpy(filename, argv[1]);
  FILE *fp = fopen(filename, "r");                                       //FOPEN
  //FILE *fp = fopen("start_of_story\0txt", "r");   // this way does work
  if (fp == NULL)
  {
    // IF NOT FOUND: REMOVE EXTENSION
    removeFileExtension(filename);
    char text[] = "myFile\0";
    int ret_val = -1;
    ret_val = strComparison(filename, text);
    if (ret_val == 0)
      printf("[DEBUG] equal\n");
    else
      printf("[DEBUG] unequal\n");

    printf("[DEBUG] ret_val: %d\n", ret_val);
    printf("[DEBUG] '%s'\n", filename);
    FILE *fp = fopen(filename, "r");                                     //FOPEN

    // IF STILL DOESN'T WORK: ERROR
    if (fp == NULL)
    {
      printf("[ERR] Could not read file %s.\n", filename);
      return 3;
    }
  }

  //--------------------------------------------------------------------------
  // READ DATA (INITIAL)
  //
  int bufsize = 1024;
  char *buffer = malloc(bufsize * sizeof(char));                      //MALLOC
  if (!buffer)
  {
    printf("[ERR] Out of memory.\n");
    return 2;
  }
  fseek(fp, 0, SEEK_SET);
  fread(buffer, bufsize, 1, fp);

  printf("[DEBUG] %s\n", buffer);
  fclose(fp);                                                           //FCLOSE

  free(buffer);
  buffer = NULL;
  return 0;
}

void removeFileExtension(char *haystack)
{
  char needle[1] = ".";
  char *retp;   // return pointer
  retp = strstr(haystack,needle);
  if (*retp == '.')
  {
    while (*retp != '\0')
    {
      *retp++ = '\0';
    }
    printf("[DEBUG] %s\n", haystack);
  }
}

int strComparison(char *one, char *two)
{
  do
  {
    printf("[DEBUG] '%c' == '%c'\n", *one, *two);
    if (*one++ != *two++)
    {
      return 1; // return 1 if unqual
    }
  }
  while ( (*one != '\0') || (*two != '\0') );
  return 0; // return 0 if qual
}
</code>```

Resulting output:

```<code>user@host ~/Desktop $ ./a.out myFile.txt
[DEBUG] myFile
[DEBUG] 'm' == 'm'
[DEBUG] 'y' == 'y'
[DEBUG] 'F' == 'F'
[DEBUG] 'i' == 'i'
[DEBUG] 'l' == 'l'
[DEBUG] 'e' == 'e'
[DEBUG] equal
[DEBUG] ret_val: 0
[DEBUG] 'myFile'
[ERR] Could not read file myFile.
user@host ~/Desktop $
</code>```

答:
At least I found the problem:

After removing the file's extension, I am still
trying to open the old file pointer fp, which
gave me the NULL-pointer back. The new file pointer
inside the body of the if(fp == NULL){...} only
exists inside the scope of the if-statement.

So I created a test_pointer, which first looks if
the file even exists, if not, he removes the extension.
Than I try again to open the file, this time with fp.

Thanks to everybody for the hints, especially to
Sourav Ghosh
for your improvement suggestions!

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int removeFileExtension(char *haystack);

int main(int argc, char const *argv[])
{
  char filename[64];
  strcpy(filename, argv[1]);

  //----------------------------------------------------------------------------
  // CHECK INPUT VALIDITY
  //
  if (argc != 2)
  {
    printf("Usage: ./ass2 [file-name]\n");
    return 1;
  }

  //----------------------------------------------------------------------------
  // CHECK FILE EXISTENSE
  //
  FILE *test_pointer = fopen(filename, "r");                             //FOPEN
  if (test_pointer == NULL)   // if not found: remove extension
  {
    int ret_val = removeFileExtension(filename);
    if (ret_val == -1)
    {
      printf("[ERR] Could not remove file extension.\n");
      return 3;
    }
  }

  //----------------------------------------------------------------------------
  // OPEN FILE (INITIAL)
  //
  FILE *fp = fopen(filename, "r");                                       //FOPEN
  if (fp == NULL)   // if still doesn't work: error
  {
    printf("[ERR] Could not read file %s.\n", filename);
    return 3;
  }

  //----------------------------------------------------------------------------
  // READ DATA (INITIAL)
  //
  int bufsize = 1024;
  char *buffer = malloc(bufsize * sizeof(char));                        //MALLOC
  if (!buffer)
  {
    printf("[ERR] Out of memory.\n");
    return 2;
  }
  fseek(fp, 0, SEEK_SET);
  fread(buffer, bufsize, 1, fp);
  fclose(fp);                                                           //FCLOSE

  printf("[DEBUG] %s\n", buffer);
  free(buffer);                                                           //FREE
  buffer = NULL;
  return 0;
}

int removeFileExtension(char *haystack)
{
  char needle[] = ".";
  char *retp;   // return pointer
  retp = strstr(haystack,needle);
  if(!retp)     // to prevent UB
    return -1;

  if (*retp == '.')
  {
    while (*retp != '\0')
    {
      *retp++ = '\0';
    }
    printf("[DEBUG] %s\n", haystack);
  }
  return 0;
}
</code>```

Body:
The programm should be able to open a file like myFile.txt,
alltough it's real name is myFile without the extension .txt.
So I wrote the function called removeFileExtension() in order
to achieve that.

It does open my file by copying the string from text into filename:

strcpy(filename,text);
FILE *fp = fopen(filename, "r");

So I tried to check what the difference between text and my processed
string from removeFileExtension is.

To check if it even works I mate a function called strComparison(),
which returns either 0 when it is qual or 1 if unequal.
The thing is, after removing the file extension, it shows that both strings
are qual, but I am still not able to open the file.

When I type in ./a.out myFile.txt my comparison function returns 0,
it is equal, but fopen() still is not able to open the file,
respectively I allways get a Segmentation fault.

Does anyone see the problem here?
Why am I getting a Segmentation fault?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removeFileExtension(char *haystack);
int strComparison(char *one, char *two);

int main(int argc, char const *argv[])
{
  //----------------------------------------------------------------------------
  // CHECK INPUT VALIDITY
  //
  if (argc != 2)
  {
    printf("Usage: ./ass2 [file-name]\n");
    return 1;
  }

  //----------------------------------------------------------------------------
  // OPEN FILE (INITIAL)
  //
  char filename[32];
  strcpy(filename, argv[1]);
  FILE *fp = fopen(filename, "r");                                       //FOPEN
  //FILE *fp = fopen("start_of_story\0txt", "r");   // this way does work
  if (fp == NULL)
  {
    // IF NOT FOUND: REMOVE EXTENSION
    removeFileExtension(filename);
    char text[] = "myFile\0";
    int ret_val = -1;
    ret_val = strComparison(filename, text);
    if (ret_val == 0)
      printf("[DEBUG] equal\n");
    else
      printf("[DEBUG] unequal\n");

    printf("[DEBUG] ret_val: %d\n", ret_val);
    printf("[DEBUG] '%s'\n", filename);
    FILE *fp = fopen(filename, "r");                                     //FOPEN

    // IF STILL DOESN'T WORK: ERROR
    if (fp == NULL)
    {
      printf("[ERR] Could not read file %s.\n", filename);
      return 3;
    }
  }

  //--------------------------------------------------------------------------
  // READ DATA (INITIAL)
  //
  int bufsize = 1024;
  char *buffer = malloc(bufsize * sizeof(char));                      //MALLOC
  if (!buffer)
  {
    printf("[ERR] Out of memory.\n");
    return 2;
  }
  fseek(fp, 0, SEEK_SET);
  fread(buffer, bufsize, 1, fp);

  printf("[DEBUG] %s\n", buffer);
  fclose(fp);                                                           //FCLOSE

  free(buffer);
  buffer = NULL;
  return 0;
}

void removeFileExtension(char *haystack)
{
  char needle[1] = ".";
  char *retp;   // return pointer
  retp = strstr(haystack,needle);
  if (*retp == '.')
  {
    while (*retp != '\0')
    {
      *retp++ = '\0';
    }
    printf("[DEBUG] %s\n", haystack);
  }
}

int strComparison(char *one, char *two)
{
  do
  {
    printf("[DEBUG] '%c' == '%c'\n", *one, *two);
    if (*one++ != *two++)
    {
      return 1; // return 1 if unqual
    }
  }
  while ( (*one != '\0') || (*two != '\0') );
  return 0; // return 0 if qual
}

Resulting output:

user@host ~/Desktop $ ./a.out myFile.txt
[DEBUG] myFile
[DEBUG] 'm' == 'm'
[DEBUG] 'y' == 'y'
[DEBUG] 'F' == 'F'
[DEBUG] 'i' == 'i'
[DEBUG] 'l' == 'l'
[DEBUG] 'e' == 'e'
[DEBUG] equal
[DEBUG] ret_val: 0
[DEBUG] 'myFile'
[ERR] Could not read file myFile.
user@host ~/Desktop $

Body:
At least I found the problem:

After removing the file's extension, I am still
trying to open the old file pointer fp, which
gave me the NULL-pointer back. The new file pointer
inside the body of the if(fp == NULL){...} only
exists inside the scope of the if-statement.

So I created a test_pointer, which first looks if
the file even exists, if not, he removes the extension.
Than I try again to open the file, this time with fp.

Thanks to everybody for the hints, especially to
Sourav Ghosh
for your improvement suggestions!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int removeFileExtension(char *haystack);

int main(int argc, char const *argv[])
{
  char filename[64];
  strcpy(filename, argv[1]);

  //----------------------------------------------------------------------------
  // CHECK INPUT VALIDITY
  //
  if (argc != 2)
  {
    printf("Usage: ./ass2 [file-name]\n");
    return 1;
  }

  //----------------------------------------------------------------------------
  // CHECK FILE EXISTENSE
  //
  FILE *test_pointer = fopen(filename, "r");                             //FOPEN
  if (test_pointer == NULL)   // if not found: remove extension
  {
    int ret_val = removeFileExtension(filename);
    if (ret_val == -1)
    {
      printf("[ERR] Could not remove file extension.\n");
      return 3;
    }
  }

  //----------------------------------------------------------------------------
  // OPEN FILE (INITIAL)
  //
  FILE *fp = fopen(filename, "r");                                       //FOPEN
  if (fp == NULL)   // if still doesn't work: error
  {
    printf("[ERR] Could not read file %s.\n", filename);
    return 3;
  }

  //----------------------------------------------------------------------------
  // READ DATA (INITIAL)
  //
  int bufsize = 1024;
  char *buffer = malloc(bufsize * sizeof(char));                        //MALLOC
  if (!buffer)
  {
    printf("[ERR] Out of memory.\n");
    return 2;
  }
  fseek(fp, 0, SEEK_SET);
  fread(buffer, bufsize, 1, fp);
  fclose(fp);                                                           //FCLOSE

  printf("[DEBUG] %s\n", buffer);
  free(buffer);                                                           //FREE
  buffer = NULL;
  return 0;
}

int removeFileExtension(char *haystack)
{
  char needle[] = ".";
  char *retp;   // return pointer
  retp = strstr(haystack,needle);
  if(!retp)     // to prevent UB
    return -1;

  if (*retp == '.')
  {
    while (*retp != '\0')
    {
      *retp++ = '\0';
    }
    printf("[DEBUG] %s\n", haystack);
  }
  return 0;
}


问:
How to get the http get response data value to outer scope
```<code>.config([
    '$provide',
    function ($provide) {
        'use strict';

        var initInjector = angular.injector(['ng']);

        var apiUrl;

        initInjector.get('$http').get('customer/api/')

       .then(function (response) {
            console.log("dddd" + response.data.url);

            apiUrl = response.data.url;

          });

       console.log(apiUrl);
</code>```

//This print as Undefined

```<code>        $provide.constant('GLOBAL', global);
    }
]);
</code>```

when i print the apiUrl value tetrived from http get service print as undefined.

can some one hep me to get the value of response.data.url to outer scope.

Edit:

```<code>    var apiUrl;

    var initInjector = angular.injector(['ng']);

    var self = this;

    initInjector.get('$http').get('customer/api/')

    .then(function(response) {

        console.log("ddddd" + response.data.url); //print value
        self.apiUrl = response.data.url;

        console.log("selff" +self.apiUrl); //print value
    });

    console.log("outerr" +self.apiUrl); // print undefined
</code>```

答:
Declare a global variable and then assign value after http call.</p>

```<code>var apiUrl ='';
.config([
    '$provide',
    function ($provide) {
        'use strict';
        var initInjector = angular.injector(['ng']);

        var apiUrl;

        initInjector.get('$http').get('customer/api/').then(function (response) {
            console.log("dddd" + response.data.url);

            this.apiUrl = response.data.url;

          });

       console.log(this.apiUrl);
</code>```

Body:
.config([
    '$provide',
    function ($provide) {
        'use strict';

        var initInjector = angular.injector(['ng']);

        var apiUrl;

        initInjector.get('$http').get('customer/api/')

       .then(function (response) {
            console.log("dddd" + response.data.url);

            apiUrl = response.data.url;

          });

       console.log(apiUrl);

//This print as Undefined

        $provide.constant('GLOBAL', global);
    }
]);

when i print the apiUrl value tetrived from http get service print as undefined.

can some one hep me to get the value of response.data.url to outer scope.

Edit:

    var apiUrl;

    var initInjector = angular.injector(['ng']);

    var self = this;

    initInjector.get('$http').get('customer/api/')

    .then(function(response) {

        console.log("ddddd" + response.data.url); //print value
        self.apiUrl = response.data.url;

        console.log("selff" +self.apiUrl); //print value
    });

    console.log("outerr" +self.apiUrl); // print undefined

Body:
Declare a global variable and then assign value after http call.

var apiUrl ='';
.config([
    '$provide',
    function ($provide) {
        'use strict';
        var initInjector = angular.injector(['ng']);

        var apiUrl;

        initInjector.get('$http').get('customer/api/').then(function (response) {
            console.log("dddd" + response.data.url);

            this.apiUrl = response.data.url;

          });

       console.log(this.apiUrl);


问:
error in Generic
Why following code does not work?</p>

```<code>public void getData<T>(T ConnectionStirng)
{
    OleDbConnection con = new OleDbConnection(connectionString);  \\compile error
}
</code>```

答: Because OleDbConnection's constructor only takes a string.</p>

ContentLicense: CC BY-SA 2.5

Title: error in Generic

Body:
Why following code does not work?

public void getData<T>(T ConnectionStirng)
{
    OleDbConnection con = new OleDbConnection(connectionString);  \\compile error
}


问:
Native to NodeJS Callback
I'm trying to write a native NodeJS module that will make callbacks periodically from a loop. I've think I've got my head round the libuv bits needed to get back onto the main thread to make the callback, but it's still crashing with a sigsegv at the moment that it makes the calback.

test_sbio.cpp:

```<code>#include <node.h>
#include "SBIONative.h"

namespace sbio {

using v8::Local;
using v8::Object;

void InitAll(Local<Object> exports) {
  SBIONative::Init(exports);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

}
</code>```

SBIONative.h:

```<code>#ifndef SBIONative_H
#define SBIONative_H

#include <iostream>
#include <unistd.h>

#include <uv.h>
#include <node.h>
#include <node_object_wrap.h>

namespace sbio {
    class SBIONative : public node::ObjectWrap {
    public:
        static void Init(v8::Local<v8::Object> exports);

    private:
        explicit SBIONative();
        ~SBIONative();

        static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
        static v8::Persistent<v8::Function> constructor;
        static void Start(const v8::FunctionCallbackInfo<v8::Value>& args);
        static void Stop(const v8::FunctionCallbackInfo<v8::Value>& args);

        static void loop(void *arg);
        static void asyncmsg(uv_async_t* handle);
        v8::Persistent<v8::Function> cb;
        bool run_;
        uv_async_t async;
        uv_thread_t event_loop;
    };
}
#endif
</code>```

SBIONative.cpp:

```<code>#include <SBIONative.h>

namespace sbio {
    using v8::Context;
    using v8::Function;
    using v8::FunctionCallbackInfo;
    using v8::FunctionTemplate;
    using v8::Isolate;
    using v8::HandleScope;
    using v8::Local;
    using v8::Number;
    using v8::Object;
    using v8::Persistent;
    using v8::String;
    using v8::Value;

    Persistent<Function> SBIONative::constructor;

    SBIONative::SBIONative()  {
    }

    SBIONative::~SBIONative() {
    }

    void SBIONative::Init(Local<Object> exports) {
      Isolate* isolate = exports->GetIsolate();

      // Prepare constructor template
      Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
      tpl->SetClassName(String::NewFromUtf8(isolate, "SBIONative"));
      tpl->InstanceTemplate()->SetInternalFieldCount(2);

      // Prototype
      NODE_SET_PROTOTYPE_METHOD(tpl, "start", Start);
      NODE_SET_PROTOTYPE_METHOD(tpl, "stop", Stop);

      constructor.Reset(isolate, tpl->GetFunction());
      exports->Set(String::NewFromUtf8(isolate, "SBIONative"),
                   tpl->GetFunction());

    }

    void SBIONative::New(const FunctionCallbackInfo<Value>& args) {
      Isolate* isolate = args.GetIsolate();

      if (args.IsConstructCall()) {
        // Invoked as constructor: `new MyObject(...)`
        SBIONative* obj = new SBIONative();
        obj->Wrap(args.This());
        args.GetReturnValue().Set(args.This());

        uv_loop_t* loop = uv_default_loop();
        uv_async_init(loop, &obj->async, asyncmsg);
      } else {
        // Invoked as plain function `MyObject(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        Local<Context> context = isolate->GetCurrentContext();
        Local<Function> cons = Local<Function>::New(isolate, constructor);
        Local<Object> result =
            cons->NewInstance(context, argc, argv).ToLocalChecked();
        args.GetReturnValue().Set(result);
      }
    }

    void SBIONative::Start(const FunctionCallbackInfo<Value>& args) {
        std::cout << "Start\n";
        Isolate* isolate = args.GetIsolate();
        SBIONative* obj = ObjectWrap::Unwrap<SBIONative>(args.Holder());
        obj->run_ = true;

        Local<Function> callback = Local<v8::Function>::Cast(args[0]);
        obj->cb.Reset(isolate, callback);

        uv_thread_create(&obj->event_loop, SBIONative::loop, (void*)obj);
    }

    void SBIONative::Stop(const FunctionCallbackInfo<Value>& args) {
        std::cout << "Stop\n";
        SBIONative* obj = ObjectWrap::Unwrap<SBIONative>(args.Holder());
        obj->run_ = false;
        uv_close((uv_handle_t*) &obj->async, NULL);
    }

    void SBIONative::loop(void *arg) {
        SBIONative* obj = (SBIONative*)arg;

        while(obj->run_) {
            usleep(1 * 1000 * 1000);
            std::cout << "loop\n";
            obj->async.data = &obj->cb;
            uv_async_send(&obj->async);
        }

        std::cout << "after loop" << std::endl;
    }

    void SBIONative::asyncmsg(uv_async_t* handle) {
        v8::Isolate* isolate = v8::Isolate::GetCurrent();
        v8::HandleScope scope(isolate);
        Local<Value> argv[] = { v8::String::NewFromUtf8(isolate, "Hello world") };
        //TODO This breaks here
        ((v8::Function*)handle->data)->Call(isolate->GetCurrentContext()->Global(), 1, argv);
        std::cout << "callback" << std::endl;
    }
}
</code>```

This fails in the same place if I build it on a Mac or on Linux. My best guess to date is to do with the storing of the callback in the object or casting it in the asyncmsg function

答:
After having another go at this today I've got a working solution. The trick was to use Nan rather than try and roll my own native interface.

addon.c:

```<code>#include <nan.h>
#include "test.h"

void InitAll(v8::Local<v8::Object> exports) {
  test::Test::Init(exports);
}

NODE_MODULE(addon, InitAll)
</code>```

test.h:

```<code>#ifndef TEST_H
#define TEST_H

#include <nan.h>

#include <iostream>
#include <unistd.h>

namespace test {
    class Test : public Nan::ObjectWrap {
    public:
        static void Init(v8::Local<v8::Object> exports);
    private:
        explicit Test();
        ~Test();

        static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
        static void Start(const Nan::FunctionCallbackInfo<v8::Value>& info);
        static void Stop(const Nan::FunctionCallbackInfo<v8::Value>& info);
        static void loop(void *arg);
        static void asyncmsg(uv_async_t* handle);
        static Nan::Persistent<v8::Function> constructor;

        bool run_;
        Nan::Callback* callback;

        uv_async_t async;
        uv_thread_t event_loop;
    };
}

#endif
</code>```

test.cpp:

```<code>#include "test.h"

namespace test {

    Nan::Persistent<v8::Function> Test::constructor;

    Test::Test(){}

    Test::~Test(){}

    void Test::Init(v8::Local<v8::Object> exports) {
        Nan::HandleScope scope;

        v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
        tpl->SetClassName(Nan::New("Test").ToLocalChecked());
        tpl->InstanceTemplate()->SetInternalFieldCount(1);

        Nan::SetPrototypeMethod(tpl, "start", Start);
        Nan::SetPrototypeMethod(tpl, "stop", Stop);

        constructor.Reset(tpl->GetFunction());
        exports->Set(Nan::New("Test").ToLocalChecked(), tpl->GetFunction());
    }

    void Test::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
        if (info.IsConstructCall()) {
        // Invoked as constructor: `new Test(...)`
        test::Test* obj = new test::Test();
        obj->Wrap(info.This());
        info.GetReturnValue().Set(info.This());
        uv_loop_t* loop = uv_default_loop();
            uv_async_init(loop, &obj->async, asyncmsg);
      } else {
        // Invoked as plain function `Test(...)`, turn into construct call.
        const int argc = 1;
        v8::Local<v8::Value> argv[argc] = { info[0] };
        v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
        info.GetReturnValue().Set(cons->NewInstance(argc, argv));
      }
    }

    void Test::Start(const Nan::FunctionCallbackInfo<v8::Value>& info) {
        Test* obj = ObjectWrap::Unwrap<Test>(info.Holder());
        obj->callback = new Nan::Callback(info[0].As<v8::Function>());
        obj->run_ = true;

        uv_thread_create(&obj->event_loop, Test::loop, (void*)obj);
    }

    void Test::Stop(const Nan::FunctionCallbackInfo<v8::Value>& info) {
        Test* obj = ObjectWrap::Unwrap<Test>(info.Holder());
        obj->run_ = false;
    }

    void Test::loop(void *arg) {
        Test* obj = (Test*)arg;

        while(obj->run_) {
            usleep(1 * 1000 * 1000);
            obj->async.data = obj->callback;
            uv_async_send(&obj->async);
        }

        uv_close((uv_handle_t*) &obj->async, NULL);
    }

    void Test::asyncmsg(uv_async_t* handle) {
        Nan::HandleScope scope;
        v8::Isolate* isolate = v8::Isolate::GetCurrent();
        v8::Local<v8::Value> argv[] = { v8::String::NewFromUtf8(isolate, "Loop Callback") };
        ((Nan::Callback*)handle->data)->Call(1,argv);
    }

}
</code>```

Write up and link to full project code on github here

Title: Native to NodeJS Callback

Body:
I'm trying to write a native NodeJS module that will make callbacks periodically from a loop. I've think I've got my head round the libuv bits needed to get back onto the main thread to make the callback, but it's still crashing with a sigsegv at the moment that it makes the calback.

test_sbio.cpp:

#include <node.h>
#include "SBIONative.h"

namespace sbio {

using v8::Local;
using v8::Object;

void InitAll(Local<Object> exports) {
  SBIONative::Init(exports);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

}

SBIONative.h:

#ifndef SBIONative_H
#define SBIONative_H

#include <iostream>
#include <unistd.h>

#include <uv.h>
#include <node.h>
#include <node_object_wrap.h>

namespace sbio {
    class SBIONative : public node::ObjectWrap {
    public:
        static void Init(v8::Local<v8::Object> exports);

    private:
        explicit SBIONative();
        ~SBIONative();

        static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
        static v8::Persistent<v8::Function> constructor;
        static void Start(const v8::FunctionCallbackInfo<v8::Value>& args);
        static void Stop(const v8::FunctionCallbackInfo<v8::Value>& args);

        static void loop(void *arg);
        static void asyncmsg(uv_async_t* handle);
        v8::Persistent<v8::Function> cb;
        bool run_;
        uv_async_t async;
        uv_thread_t event_loop;
    };
}
#endif

SBIONative.cpp:

#include <SBIONative.h>

namespace sbio {
    using v8::Context;
    using v8::Function;
    using v8::FunctionCallbackInfo;
    using v8::FunctionTemplate;
    using v8::Isolate;
    using v8::HandleScope;
    using v8::Local;
    using v8::Number;
    using v8::Object;
    using v8::Persistent;
    using v8::String;
    using v8::Value;

    Persistent<Function> SBIONative::constructor;

    SBIONative::SBIONative()  {
    }

    SBIONative::~SBIONative() {
    }

    void SBIONative::Init(Local<Object> exports) {
      Isolate* isolate = exports->GetIsolate();

      // Prepare constructor template
      Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
      tpl->SetClassName(String::NewFromUtf8(isolate, "SBIONative"));
      tpl->InstanceTemplate()->SetInternalFieldCount(2);

      // Prototype
      NODE_SET_PROTOTYPE_METHOD(tpl, "start", Start);
      NODE_SET_PROTOTYPE_METHOD(tpl, "stop", Stop);

      constructor.Reset(isolate, tpl->GetFunction());
      exports->Set(String::NewFromUtf8(isolate, "SBIONative"),
                   tpl->GetFunction());

    }

    void SBIONative::New(const FunctionCallbackInfo<Value>& args) {
      Isolate* isolate = args.GetIsolate();

      if (args.IsConstructCall()) {
        // Invoked as constructor: `new MyObject(...)`
        SBIONative* obj = new SBIONative();
        obj->Wrap(args.This());
        args.GetReturnValue().Set(args.This());

        uv_loop_t* loop = uv_default_loop();
        uv_async_init(loop, &obj->async, asyncmsg);
      } else {
        // Invoked as plain function `MyObject(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        Local<Context> context = isolate->GetCurrentContext();
        Local<Function> cons = Local<Function>::New(isolate, constructor);
        Local<Object> result =
            cons->NewInstance(context, argc, argv).ToLocalChecked();
        args.GetReturnValue().Set(result);
      }
    }

    void SBIONative::Start(const FunctionCallbackInfo<Value>& args) {
        std::cout << "Start\n";
        Isolate* isolate = args.GetIsolate();
        SBIONative* obj = ObjectWrap::Unwrap<SBIONative>(args.Holder());
        obj->run_ = true;

        Local<Function> callback = Local<v8::Function>::Cast(args[0]);
        obj->cb.Reset(isolate, callback);

        uv_thread_create(&obj->event_loop, SBIONative::loop, (void*)obj);
    }

    void SBIONative::Stop(const FunctionCallbackInfo<Value>& args) {
        std::cout << "Stop\n";
        SBIONative* obj = ObjectWrap::Unwrap<SBIONative>(args.Holder());
        obj->run_ = false;
        uv_close((uv_handle_t*) &obj->async, NULL);
    }

    void SBIONative::loop(void *arg) {
        SBIONative* obj = (SBIONative*)arg;

        while(obj->run_) {
            usleep(1 * 1000 * 1000);
            std::cout << "loop\n";
            obj->async.data = &obj->cb;
            uv_async_send(&obj->async);
        }

        std::cout << "after loop" << std::endl;
    }

    void SBIONative::asyncmsg(uv_async_t* handle) {
        v8::Isolate* isolate = v8::Isolate::GetCurrent();
        v8::HandleScope scope(isolate);
        Local<Value> argv[] = { v8::String::NewFromUtf8(isolate, "Hello world") };
        //TODO This breaks here
        ((v8::Function*)handle->data)->Call(isolate->GetCurrentContext()->Global(), 1, argv);
        std::cout << "callback" << std::endl;
    }
}

This fails in the same place if I build it on a Mac or on Linux. My best guess to date is to do with the storing of the callback in the object or casting it in the asyncmsg function

Body:
After having another go at this today I've got a working solution. The trick was to use Nan rather than try and roll my own native interface.

addon.c:

#include <nan.h>
#include "test.h"

void InitAll(v8::Local<v8::Object> exports) {
  test::Test::Init(exports);
}

NODE_MODULE(addon, InitAll)

test.h:

#ifndef TEST_H
#define TEST_H

#include <nan.h>

#include <iostream>
#include <unistd.h>

namespace test {
    class Test : public Nan::ObjectWrap {
    public:
        static void Init(v8::Local<v8::Object> exports);
    private:
        explicit Test();
        ~Test();

        static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
        static void Start(const Nan::FunctionCallbackInfo<v8::Value>& info);
        static void Stop(const Nan::FunctionCallbackInfo<v8::Value>& info);
        static void loop(void *arg);
        static void asyncmsg(uv_async_t* handle);
        static Nan::Persistent<v8::Function> constructor;

        bool run_;
        Nan::Callback* callback;

        uv_async_t async;
        uv_thread_t event_loop;
    };
}

#endif

test.cpp:

#include "test.h"

namespace test {

    Nan::Persistent<v8::Function> Test::constructor;

    Test::Test(){}

    Test::~Test(){}

    void Test::Init(v8::Local<v8::Object> exports) {
        Nan::HandleScope scope;

        v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
        tpl->SetClassName(Nan::New("Test").ToLocalChecked());
        tpl->InstanceTemplate()->SetInternalFieldCount(1);

        Nan::SetPrototypeMethod(tpl, "start", Start);
        Nan::SetPrototypeMethod(tpl, "stop", Stop);

        constructor.Reset(tpl->GetFunction());
        exports->Set(Nan::New("Test").ToLocalChecked(), tpl->GetFunction());
    }

    void Test::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
        if (info.IsConstructCall()) {
        // Invoked as constructor: `new Test(...)`
        test::Test* obj = new test::Test();
        obj->Wrap(info.This());
        info.GetReturnValue().Set(info.This());
        uv_loop_t* loop = uv_default_loop();
            uv_async_init(loop, &obj->async, asyncmsg);
      } else {
        // Invoked as plain function `Test(...)`, turn into construct call.
        const int argc = 1;
        v8::Local<v8::Value> argv[argc] = { info[0] };
        v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
        info.GetReturnValue().Set(cons->NewInstance(argc, argv));
      }
    }

    void Test::Start(const Nan::FunctionCallbackInfo<v8::Value>& info) {
        Test* obj = ObjectWrap::Unwrap<Test>(info.Holder());
        obj->callback = new Nan::Callback(info[0].As<v8::Function>());
        obj->run_ = true;

        uv_thread_create(&obj->event_loop, Test::loop, (void*)obj);
    }

    void Test::Stop(const Nan::FunctionCallbackInfo<v8::Value>& info) {
        Test* obj = ObjectWrap::Unwrap<Test>(info.Holder());
        obj->run_ = false;
    }

    void Test::loop(void *arg) {
        Test* obj = (Test*)arg;

        while(obj->run_) {
            usleep(1 * 1000 * 1000);
            obj->async.data = obj->callback;
            uv_async_send(&obj->async);
        }

        uv_close((uv_handle_t*) &obj->async, NULL);
    }

    void Test::asyncmsg(uv_async_t* handle) {
        Nan::HandleScope scope;
        v8::Isolate* isolate = v8::Isolate::GetCurrent();
        v8::Local<v8::Value> argv[] = { v8::String::NewFromUtf8(isolate, "Loop Callback") };
        ((Nan::Callback*)handle->data)->Call(1,argv);
    }

}

Write up and link to full project code on github here