问:
PHP classes is this right
still getting used to PHP classes so a bit of "help /guidance" please

I have a class like this:

```<code>class ansa_accounturl_query {

    function __construct() {

     global $DBH;
     global $limit;
     $STH = $DBH->query("SELECT frm_url.frm_urlID,frm_url.frm_url FROM frm_url WHERE frm_url.accountID='SOMETHING' ".$limit." ");
     $STH->setFetchMode(PDO::FETCH_OBJ);
     $this->noforms = $STH->rowCount();
     while($row  = $STH->fetch()):
         $this->frm_urlID[]  = $row->frm_urlID;
         $this->frm_url[] = $row->frm_url;
     endwhile;
    }

}
</code>```

The limit comes from a PHP function - and works.

What I would really like to do is create extend classes for  the above example which gives say $this-frm_url as a function. so that on the "page" I call the class $classcall = new class(); but rather than have to go echo $classcall->frm_url[$key]; I can just call a function like this echo frm_url(); So in the example above there would be 2 extend classes one for frm_urlID and one for frm_url.

Also, in the "master class" am I right in in setting as array? i.e. $this->frm_url[] as without that I cannot seem to run a loop but the loop does seem "over" complex if you do it this way as you (well I) have to get a count of the array items then run the loop so you (again I) have a for() statement then a foreach().  Seems longwinded to me.

Thanks in adavance.

答:
```<code>
<?php

 class ansa_accounturl_query {
   private static $FIND_ALL_QUERY = "SELECT frm_url.frm_urlID,frm_url.frm_url FROM frm_url WHERE frm_url.accountID='SOMETHING' %s";

   private $dbh;

   public function __construct( $dbh ) {
     $this->dbh = $dbh;
   }

   public function findUrls() {
      $query = $this->dbh->query(vsprintf($queryString, array( func_get_args() ) ) );

       $query->setFetchMode(PDO::FETCH_OBJ);

       $result = array();
       $result["count"] = $query->rowCount();
       $result["records"] = array();
       while( null !== ( $row  = $query->fetch() ) ) {
          $result["records"][] = array(
              "id" => $row->frm_urlID,
              "url" => $row->rm_url
          );
       }

      return $result;
   }

}

$ansaQuery = new ansa_accounturl_query($DBH);
$result = $ansaQuery->findUrls();
foreach ( $result['records'] as $row ) {
   print sprintf("ID: %d; URL: %s", $row['id'], $row['url']);
}

print sprintf("URLs count: " . $result['count'] );
</code>
```

Title: PHP classes is this right

Body:
still getting used to PHP classes so a bit of "help /guidance" please

I have a class like this:

class ansa_accounturl_query {

    function __construct() {

     global $DBH;
     global $limit;
     $STH = $DBH->query("SELECT frm_url.frm_urlID,frm_url.frm_url FROM frm_url WHERE frm_url.accountID='SOMETHING' ".$limit." ");
     $STH->setFetchMode(PDO::FETCH_OBJ);
     $this->noforms = $STH->rowCount();
     while($row  = $STH->fetch()):
         $this->frm_urlID[]  = $row->frm_urlID;
         $this->frm_url[] = $row->frm_url;
     endwhile;
    }

}

The limit comes from a PHP function - and works.

What I would really like to do is create extend classes for  the above example which gives say $this-frm_url as a function. so that on the "page" I call the class $classcall = new class(); but rather than have to go echo $classcall->frm_url[$key]; I can just call a function like this echo frm_url(); So in the example above there would be 2 extend classes one for frm_urlID and one for frm_url.

Also, in the "master class" am I right in in setting as array? i.e. $this->frm_url[] as without that I cannot seem to run a loop but the loop does seem "over" complex if you do it this way as you (well I) have to get a count of the array items then run the loop so you (again I) have a for() statement then a foreach().  Seems longwinded to me.

Thanks in adavance.


来源: stackexchange

问:
opencv - video looks good but frames are rotated 90 degrees
We save a video on a mobile client and send it to a server. On the server, I use the following code to save the frames:>

```<code>import skvideo.io
import cv2

haar =
'/home/ubuntu/opencv/data/haarcascades/haarcascade_frontalface_alt.xml'
face_cascade = cv2.CascadeClassifier(haar)

ret = True

video = 'my_video.mov'
i = 0
while ret == True:
    cap = skvideo.io.VideoCapture(video)
    ret, frame = cap.read()
    cv2.imwrite('frame_'+str(i)+'.jpg',frame)
    i+=1
</code>```

When we play the video on a windows media player or itunes, it looks good. I.e. the player knows how to orient it.

But skvideo.io does not know that, and those frames we saved are rotated 90 degrees counterclockwise.

How can we embed info into the video file (a .mov) file that that skvideo knows the correct orientation?

答:
It looks like OpenCV does not record the rotation metadata of the video file with VideoCapture() as you can see by the propIds that it stores.

I'm not sure if scikit-video does. It looks like they have a metadata puller called ffprobe which might be able to pull the rotation. See here for an example of how to call and see the output. This shows a hefty list of metadata---no rotation---but that might just be because it's not set or of a movie type which doesn't have rotation metadata.

Another way to grab it would be to read the metadata directly from ffmpeg. I found an old StackOverflow answer that wrote a little python code to extract specifically the rotation metadata from a video using ffmpeg.

ContentLicense: CC BY-SA 3.0

Body:
We save a video on a mobile client and send it to a server. On the server, I use the following code to save the frames:>

import skvideo.io
import cv2

haar =
'/home/ubuntu/opencv/data/haarcascades/haarcascade_frontalface_alt.xml'
face_cascade = cv2.CascadeClassifier(haar)

ret = True

video = 'my_video.mov'
i = 0
while ret == True:
    cap = skvideo.io.VideoCapture(video)
    ret, frame = cap.read()
    cv2.imwrite('frame_'+str(i)+'.jpg',frame)
    i+=1

When we play the video on a windows media player or itunes, it looks good. I.e. the player knows how to orient it.

But skvideo.io does not know that, and those frames we saved are rotated 90 degrees counterclockwise.

How can we embed info into the video file (a .mov) file that that skvideo knows the correct orientation?


问:
efficiency of a program that checks range of variable vs another that checks values one by one?
Let assume that I have a Boolean function that receives a random number as its argument and then return True if the random number is 200, 201 or 202 and return False for other values.

The question is which one of the following functions are more efficient?

f1:

```<code>bool f1(int number) {
    if (number >= 200 && number <= 202)
        return true;
    return false;
}
</code>```

f2:

```<code>bool f2(int number) {
    if (number == 200 || number == 201 || number == 202)
        return true;
    return false;
}
</code>```

答:
I benchmarked it (something you should learn how to do):

```<code>#!/bin/sh -e
cat > bench.c <<EOF
#include <stdio.h>
#include <stdlib.h>

_Bool f1(int number) { return (number >= 200 && number <= 202); }
_Bool f2(int number) { return (number == 200 || number == 201 || number == 202); }

int main(int c, char **v)
{
    int it = c>1 ? atoi(v[1]) : 10000000000;
    int cnt=0;
    for(int j=0; j<10;j++)
    for(int i=0;i<it;i++){
#ifdef F2
        cnt+=f2(i);
#else
        cnt+=f1(i);
#endif
    }
    printf("%d\n", cnt);

}
EOF

gcc -O3 bench.c
./a.out 1
time ./a.out
gcc -DF2 -O3 bench.c
./a.out 1
time ./a.out
</code>```

Couldn't measure a statistically significant difference.
Then I checked the generated assembly and gcc generates the same output for both cases, starting at -O1 (clang isn't so smart):

```<code>f1:
        subl    $200, %edi
        cmpl    $2, %edi
        setbe   %al
        ret
f2:
        subl    $200, %edi
        cmpl    $2, %edi
        setbe   %al
        ret
</code>```

(looks like a pretty neat optimization trick)

So the answer is the usual: do the more readable thing and leave optimization to the optimizer until you've measured and found it's not doing its job as well as it could.

Body:
Let assume that I have a Boolean function that receives a random number as its argument and then return True if the random number is 200, 201 or 202 and return False for other values.

The question is which one of the following functions are more efficient?

f1:

bool f1(int number) {
    if (number >= 200 && number <= 202)
        return true;
    return false;
}

f2:

bool f2(int number) {
    if (number == 200 || number == 201 || number == 202)
        return true;
    return false;
}

Body:
I benchmarked it (something you should learn how to do):

#!/bin/sh -e
cat > bench.c <<EOF
#include <stdio.h>
#include <stdlib.h>

_Bool f1(int number) { return (number >= 200 && number <= 202); }
_Bool f2(int number) { return (number == 200 || number == 201 || number == 202); }

int main(int c, char **v)
{
    int it = c>1 ? atoi(v[1]) : 10000000000;
    int cnt=0;
    for(int j=0; j<10;j++)
    for(int i=0;i<it;i++){
#ifdef F2
        cnt+=f2(i);
#else
        cnt+=f1(i);
#endif
    }
    printf("%d\n", cnt);

}
EOF

gcc -O3 bench.c
./a.out 1
time ./a.out
gcc -DF2 -O3 bench.c
./a.out 1
time ./a.out

Couldn't measure a statistically significant difference.
Then I checked the generated assembly and gcc generates the same output for both cases, starting at -O1 (clang isn't so smart):

f1:
        subl    $200, %edi
        cmpl    $2, %edi
        setbe   %al
        ret
f2:
        subl    $200, %edi
        cmpl    $2, %edi
        setbe   %al
        ret

(looks like a pretty neat optimization trick)

So the answer is the usual: do the more readable thing and leave optimization to the optimizer until you've measured and found it's not doing its job as well as it could.


问:
div grid tab not in content
I use a php function to put my page content in the index.php, but when I use a grid (tab) in the content it goes out of the content borders.

I put a little bit of the code underneath, you can see the site here: (link deleted > problem solved)

答:
Changes CSS use overflow: hidden; it recover box</p>

```<code>.content {
    background-color: #fff;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.2);
    padding: 15px;
    margin-bottom: 20px;
    clear: both;
    overflow: hidden;
}
</code>```

Title: div grid tab not in content

Body:
Changes CSS use overflow: hidden; it recover box

.content {
    background-color: #fff;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.2);
    padding: 15px;
    margin-bottom: 20px;
    clear: both;
    overflow: hidden;
}


问:
Read txt and add in jtable
I am new to java and I need to create a program that reads text from a txt file and puts it into a jtable, the format in the txt file  will be like "b3:42".  And I need to read those and put b3 in the first column of the table and 42 in the next column. Could you help me ? And sorry for my english.</p>

答:
Some suggestions

You can read txt file line by line using BufferedReader and related chained stream in this way:

```<code>public class TestSO {

    public static void main(String[] args) {

        String line = "";
        try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("yourfile.txt")))){
                while ((line = br.readLine()) != null) {

                // Process the line

                }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

In order to split your line into pieces you need you must use line.split(":") You get 2 tokens, the one before the colon and the one after it.

```<code>String tokens[] = line.split(":");
</code>```

According to JTable documentation you can create a JTable as JTable(Object[][] rowData, Object[] columnNames)

So you can use tokens you read and parsed above to create the rowData array.

Then create the array for the column names:

```<code>//headers for the table
String[] columns = new String[] {
    "Col1", "Col2"
};
</code>```

At the end just creare the JTable passing it the arrays with data and column names:

```<code>//create table with data
JTable table = new JTable(rowData, columnNames);
</code>```

Title: Read txt and add in jtable

Body:
Some suggestions

You can read txt file line by line using BufferedReader and related chained stream in this way:

public class TestSO {

    public static void main(String[] args) {

        String line = "";
        try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("yourfile.txt")))){
                while ((line = br.readLine()) != null) {

                // Process the line

                }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

In order to split your line into pieces you need you must use line.split(":") You get 2 tokens, the one before the colon and the one after it.

String tokens[] = line.split(":");

According to JTable documentation you can create a JTable as JTable(Object[][] rowData, Object[] columnNames)

So you can use tokens you read and parsed above to create the rowData array.

Then create the array for the column names:

//headers for the table
String[] columns = new String[] {
    "Col1", "Col2"
};

At the end just creare the JTable passing it the arrays with data and column names:

//create table with data
JTable table = new JTable(rowData, columnNames);


问:
How to compare two text files having json replies
I've 2 text files having json replies which I would like to compare everyline. Below is the code snippet I've been trying.

```<code>if (expectedResponse == actualResponse){
    log.info "PASS"
}
else {
    log.info "FAIL"
}
</code>```

}

While comparing the files, is it must to read lines and do so? Any suggestions please..

答:
```<code>import groovy.json.JsonSlurper;

def a= new JsonSlurper().parse(new File("path-to-a.json"))
def b= new JsonSlurper().parse(new File("path-to-b.json"))

assert a==b
//or you can do if instead of assert
</code>```

Body:
I've 2 text files having json replies which I would like to compare everyline. Below is the code snippet I've been trying.

if (expectedResponse == actualResponse){
    log.info "PASS"
}
else {
    log.info "FAIL"
}

}

While comparing the files, is it must to read lines and do so? Any suggestions please..


问:
pydev not recognizing python installation with django
I have python installed with django. I know the installation is there because I installed it following the directions and in the command line I can do "import python" and there is no crash.

When I try creating a django project in pydev, I get an error: "Django not found."

What could the problem be?

答: I had the same problem and had solved it by adding the python home directory to the PATH variable and reconfigure the python interpreter on pydev.</p>

ContentLicense: CC BY-SA 2.5


问:
Creating a Linked List of Odd Numbers (C)
I'm fairly new to coding and am taking a course at school that teaches the C programming language. We are learning about data structures in C and have been given an assignment which requires us to create a linked list with the odd integers from 1 to 10, and also print that list. However, the code that I have written seems to be having some problems. Here it is:

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

struct listNode {
    int value;
    struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

void createList(ListNodePtr *sPtr);
void printList(ListNodePtr currentPtr);

int main(void) {
    ListNodePtr list1Ptr;

    list1Ptr = NULL;

    list1Ptr->value = 1;
    createList(&list1Ptr);
    printf("List 1 is: ");
    printList(list1Ptr);

    printf("End of run.\n");

    return 0;
}

void createList(ListNodePtr *sPtr) {
    ListNodePtr previousPtr;
    ListNodePtr newPtr;

    newPtr = malloc(sizeof(ListNodePtr));

    if (newPtr != NULL) {
        newPtr = *sPtr;

        previousPtr = NULL;

        while (((*sPtr)->value) <= 10) {
            previousPtr = *sPtr;
            *sPtr = (*sPtr)->nextPtr;
            (*sPtr)->value = previousPtr->value + 2;
        }
    }
    else {
        printf("No memory available.\n");
    }
}

int isEmpty(ListNodePtr sPtr) {
    return sPtr == NULL;
}

void printList(ListNodePtr currentPtr) {
    if (currentPtr == NULL) {
        printf("List is empty.\n\n");
    }
    else {
        while (currentPtr != NULL) {
            printf("%d ", currentPtr->value);
            currentPtr = currentPtr->nextPtr;
        }
        printf("*\n");
    }
}
</code>```

The desired output it: [List 1 is: 1 3 5 7 9 *]
The environment I use keeps telling me that there are either "unhandled exceptions" (I'm not so sure what that means) or just ceases running midway. Any ideas of how I might be able to reach the desired outcome?

Any other tips and words of advice are greatly appreciated. Thank you!

答:
```<code>while (((*sPtr)->value) <= 10) {  <<<<<
    previousPtr = *sPtr;
    *sPtr = (*sPtr)->nextPtr;
    (*sPtr)->value = previousPtr->value + 2;  <<<<<
}
</code>```

You must check (*sPtr) for NULL, before trying dereferencing it.

Body:
I'm fairly new to coding and am taking a course at school that teaches the C programming language. We are learning about data structures in C and have been given an assignment which requires us to create a linked list with the odd integers from 1 to 10, and also print that list. However, the code that I have written seems to be having some problems. Here it is:

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

struct listNode {
    int value;
    struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

void createList(ListNodePtr *sPtr);
void printList(ListNodePtr currentPtr);

int main(void) {
    ListNodePtr list1Ptr;

    list1Ptr = NULL;

    list1Ptr->value = 1;
    createList(&list1Ptr);
    printf("List 1 is: ");
    printList(list1Ptr);

    printf("End of run.\n");

    return 0;
}

void createList(ListNodePtr *sPtr) {
    ListNodePtr previousPtr;
    ListNodePtr newPtr;

    newPtr = malloc(sizeof(ListNodePtr));

    if (newPtr != NULL) {
        newPtr = *sPtr;

        previousPtr = NULL;

        while (((*sPtr)->value) <= 10) {
            previousPtr = *sPtr;
            *sPtr = (*sPtr)->nextPtr;
            (*sPtr)->value = previousPtr->value + 2;
        }
    }
    else {
        printf("No memory available.\n");
    }
}

int isEmpty(ListNodePtr sPtr) {
    return sPtr == NULL;
}

void printList(ListNodePtr currentPtr) {
    if (currentPtr == NULL) {
        printf("List is empty.\n\n");
    }
    else {
        while (currentPtr != NULL) {
            printf("%d ", currentPtr->value);
            currentPtr = currentPtr->nextPtr;
        }
        printf("*\n");
    }
}

The desired output it: [List 1 is: 1 3 5 7 9 *]
The environment I use keeps telling me that there are either "unhandled exceptions" (I'm not so sure what that means) or just ceases running midway. Any ideas of how I might be able to reach the desired outcome?

Any other tips and words of advice are greatly appreciated. Thank you!

Body:
while (((*sPtr)->value) <= 10) {  <<<<<
    previousPtr = *sPtr;
    *sPtr = (*sPtr)->nextPtr;
    (*sPtr)->value = previousPtr->value + 2;  <<<<<
}

You must check (*sPtr) for NULL, before trying dereferencing it.


问:
How to use ItemContainerTransitions when using custom GridViewItem template?
When I replace ListItemPresenter in ControlTemplate of GridView.ItemContainerStyle, the ItemContainerTransitions stop working.

How do I achieve the Staggering effect, when using custom ItemContainerTemplate?

```<code><GridView ItemsSource="{Binding Items}">
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
       </ItemsPanelTemplate>
    </GridView.ItemsPanel>

    <GridView.ItemContainerTransitions>
        <TransitionCollection>
            <EntranceThemeTransition FromHorizontalOffset="50" IsStaggeringEnabled="True" />
        </TransitionCollection>
    </GridView.ItemContainerTransitions>

    <GridView.ItemContainerStyle>
        <Style TargetType="GridViewItem">
            <Setter Property="IsHoldingEnabled" Value="True"/>
            <Setter Property="Background" Value="White"/>
            <Setter Property="Foreground" Value="Black"/>
            <Setter Property="Margin" Value="3,3,18,18"/>
            <Setter Property="MinWidth" Value="350"/>
            <Setter Property="MinHeight" Value="350"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="GridViewItem">
                        <toolkit:DropShadowPanel x:Name="dropShadowPanel" OffsetY="2" BlurRadius="4"  ShadowOpacity="0.3" RenderTransformOrigin="0.5,0.5"
                                                 Transitions="{TemplateBinding Transitions}">
                            <Border x:Name="Root" Background="{TemplateBinding Background}">
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition />
                                        <RowDefinition Height="100" />
                                    </Grid.RowDefinitions>
                                    <Path x:Name="Icon" Height="100" Width="100" HorizontalAlignment="Center" VerticalAlignment="Center"
                                          Data="{StaticResource PersonAddIconGeometry}" Stretch="Uniform"
                                          Stroke="{StaticResource HighlightBrush1}" StrokeThickness="2" />
                                    <TextBlock x:Name="textBlock" Grid.Row="1"
                                               Text="{Binding Title}" FontSize="42" FontWeight="Light"
                                               HorizontalAlignment="Center"
                                               VerticalAlignment="Top" />
                                </Grid>
                            </Border>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal">
                                    </VisualState>
                                    <VisualState x:Name="PointerOver">
                                        <VisualState.Setters>
                                            <Setter Target="textBlock.Foreground" Value="White" />
                                            <Setter Target="Root.Background" Value="{ThemeResource GridViewItemBackgroundPointerOver}" />
                                            <Setter Target="Icon.Stroke" Value="White" />
                                        </VisualState.Setters>
                                    </VisualState>
                                    <VisualState x:Name="Pressed">
                                        <VisualState.Setters>
                                            <Setter Target="textBlock.Foreground" Value="White" />
                                            <Setter Target="Root.Background" Value="{ThemeResource GridViewItemBackgroundPressed}" />
                                            <Setter Target="Icon.Stroke" Value="White" />
                                        </VisualState.Setters>
                                        <Storyboard>
                                            <PointerDownThemeAnimation TargetName="dropShadowPanel" />
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="PointerOverPressed"/>
                                    <VisualState x:Name="Disabled">
                                        <VisualState.Setters>
                                            <Setter Target="Icon.Stroke" Value="Gray" />
                                            <Setter Target="Root.Opacity" Value="0.5" />
                                        </VisualState.Setters>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                        </toolkit:DropShadowPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </GridView.ItemContainerStyle>
<GridView/>
</code>```

答:
ItemContainerTransitions can work with custom item container. The problem here is related to the custom panel you've used. You can test this with a simplest GridView like the following:

```<code><GridView ItemsSource="{x:Bind Items}">
    <GridView.ItemContainerTransitions>
        <TransitionCollection>
            <EntranceThemeTransition FromHorizontalOffset="50" IsStaggeringEnabled="True"/>
        </TransitionCollection>
    </GridView.ItemContainerTransitions>

    <!--<GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>-->
</GridView>
</code>```

```<code>public ObservableCollection<int> Items { get; set; } = new ObservableCollection<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
</code>```

Here the EntranceThemeTransition works. But if you use the StackPanel as ItemsPanel, you will find the transition does not work anymore.

Generally, when using data binding in an ItemsControl, the ItemContainerTransitions can only work with panels that support virtualization such as ItemsWrapGrid or ItemsStackPanel. If we use some other panels like StackPanel, it won't work.

So to fix this problem, you can replace StackPanel with ItemsStackPanel. ItemsStackPanel arranges child elements into a single line that can be oriented horizontally or vertically just the same as StackPanel.

If you do want to use StackPanel then you can add items to the Items collection instead of setting the ItemsSource property to a data source.

```<code><GridView x:Name="MyGridView" Loaded="MyGridView_Loaded">
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>

    <GridView.ItemContainerTransitions>
        <TransitionCollection>
            <EntranceThemeTransition FromHorizontalOffset="50" IsStaggeringEnabled="True" />
        </TransitionCollection>
    </GridView.ItemContainerTransitions>
</GridView>
</code>```

```<code>public ObservableCollection<int> Items { get; set; } = new ObservableCollection<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

private void MyGridView_Loaded(object sender, RoutedEventArgs e)
{
    foreach (var item in Items)
        MyGridView.Items.Add(item);
}
</code>```

Body:
When I replace ListItemPresenter in ControlTemplate of GridView.ItemContainerStyle, the ItemContainerTransitions stop working.

How do I achieve the Staggering effect, when using custom ItemContainerTemplate?

<GridView ItemsSource="{Binding Items}">
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
       </ItemsPanelTemplate>
    </GridView.ItemsPanel>

    <GridView.ItemContainerTransitions>
        <TransitionCollection>
            <EntranceThemeTransition FromHorizontalOffset="50" IsStaggeringEnabled="True" />
        </TransitionCollection>
    </GridView.ItemContainerTransitions>

    <GridView.ItemContainerStyle>

    </GridView.ItemContainerStyle>
<GridView/>

Body:
ItemContainerTransitions can work with custom item container. The problem here is related to the custom panel you've used. You can test this with a simplest GridView like the following:

<GridView ItemsSource="{x:Bind Items}">
    <GridView.ItemContainerTransitions>
        <TransitionCollection>
            <EntranceThemeTransition FromHorizontalOffset="50" IsStaggeringEnabled="True"/>
        </TransitionCollection>
    </GridView.ItemContainerTransitions>

    <!--<GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>-->
</GridView>

public ObservableCollection<int> Items { get; set; } = new ObservableCollection<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Here the EntranceThemeTransition works. But if you use the StackPanel as ItemsPanel, you will find the transition does not work anymore.

Generally, when using data binding in an ItemsControl, the ItemContainerTransitions can only work with panels that support virtualization such as ItemsWrapGrid or ItemsStackPanel. If we use some other panels like StackPanel, it won't work.

So to fix this problem, you can replace StackPanel with ItemsStackPanel. ItemsStackPanel arranges child elements into a single line that can be oriented horizontally or vertically just the same as StackPanel.

If you do want to use StackPanel then you can add items to the Items collection instead of setting the ItemsSource property to a data source.

<GridView x:Name="MyGridView" Loaded="MyGridView_Loaded">
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>

    <GridView.ItemContainerTransitions>
        <TransitionCollection>
            <EntranceThemeTransition FromHorizontalOffset="50" IsStaggeringEnabled="True" />
        </TransitionCollection>
    </GridView.ItemContainerTransitions>
</GridView>

public ObservableCollection<int> Items { get; set; } = new ObservableCollection<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

private void MyGridView_Loaded(object sender, RoutedEventArgs e)
{
    foreach (var item in Items)
        MyGridView.Items.Add(item);
}


问:
How to properly from VBA connection from Excel sheet to another Excel sheet?
I currently have 2 separate Excel worksheets. One is data entry and another is display.

The display uses VBA to connect to data entry to obtain data. Normally, it functions well enough. However I'm required to have the 2 worksheets in separate windows, meaning both can be displayed at the same time in separate windows, in the same screen.

The issue in this scenario is that when I click Execute in display to begin SQL query, the display window opens another data entry worksheet (read-only) and reads that instead of the one I opened initially. Is this issue due to my connection string or my ADODB.Recordset has issues?

Here is the sub which contains the connection string and ADODB.Recordset.
Edit: Full code is included to provide full context for those who need it.

```<code>Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub

ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False

End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")  ' arrange record by newest
Call testsql("4th")  ' show final results
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range    'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("3rd Summary").Range("A2")
End If
If AB = "4th" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B5").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("3rd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A5:BR5000").Value = Empty
End Sub
</code>```

Also another thing I noticed. Depending on which file I open first, it can result in both files creating a read-only copy when I click Execute. If I open Display first then Entry form, both in different instances of Excel, it will create read-only copies of both files.

If I open Entry form first, then Display in again, different instances of Excel, only the read-only copy of Display will appear.

The only time a read-only does not appear is when both files are in a single instance of Excel, which is not what I want.

Edit2:

For more info, here is the SQL I used (4 total)

SQL1 - select * from EntryTable

SQL2 - select A.*,[Date + Time] from Summary1 A left join (select [Die No], max (Date + Time) as [Date + Time] from Summary1 group by [Die No]) B on A.[Die No] = B.[Die No]

SQL3 - select * from Summary2 where [Date + Time] = Date + Time

SQL4 - select Project_No, Die_No, Description, Repair_Details, Status from Summary3

Workbook name in cell B9 = V:\Die Maintenance System v2\Die Maintenance Menu.xlsx

Update: My colleague has tested the system on her PC and tested no problems. I've been told its most likely my Excel settings. But for the life of me, I can't figure out what is causing it. What type of setting is used to prevent the read-only file from appearing?

Edit: I can see that this post has gone on too long. I decided to continue this on a new thread right here.

答:
So i would do it with the Workbook.Open() Method.

```<code>Sub Example()
Dim wb as Workbook
Dim path as String

path = "C:\Users\User\Desktop\1.xlsx"

set wb = Workbook.Open(path)
End Sub
</code>```

Now you can use wb to execute every vba function. Then there a options to check if a workbook is already opened, look here. I dont think you can do that with adodb.

Body:
I currently have 2 separate Excel worksheets. One is data entry and another is display.

The display uses VBA to connect to data entry to obtain data. Normally, it functions well enough. However I'm required to have the 2 worksheets in separate windows, meaning both can be displayed at the same time in separate windows, in the same screen.

The issue in this scenario is that when I click Execute in display to begin SQL query, the display window opens another data entry worksheet (read-only) and reads that instead of the one I opened initially. Is this issue due to my connection string or my ADODB.Recordset has issues?

Here is the sub which contains the connection string and ADODB.Recordset.
Edit: Full code is included to provide full context for those who need it.

Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub

ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False

End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")  ' arrange record by newest
Call testsql("4th")  ' show final results
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range    'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("3rd Summary").Range("A2")
End If
If AB = "4th" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B5").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("3rd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A5:BR5000").Value = Empty
End Sub

Also another thing I noticed. Depending on which file I open first, it can result in both files creating a read-only copy when I click Execute. If I open Display first then Entry form, both in different instances of Excel, it will create read-only copies of both files.

If I open Entry form first, then Display in again, different instances of Excel, only the read-only copy of Display will appear.

The only time a read-only does not appear is when both files are in a single instance of Excel, which is not what I want.

Edit2:

For more info, here is the SQL I used (4 total)

SQL1 - select * from EntryTable

SQL2 - select A.*,[Date + Time] from Summary1 A left join (select [Die No], max (Date + Time) as [Date + Time] from Summary1 group by [Die No]) B on A.[Die No] = B.[Die No]

SQL3 - select * from Summary2 where [Date + Time] = Date + Time

SQL4 - select Project_No, Die_No, Description, Repair_Details, Status from Summary3

Workbook name in cell B9 = V:\Die Maintenance System v2\Die Maintenance Menu.xlsx

Update: My colleague has tested the system on her PC and tested no problems. I've been told its most likely my Excel settings. But for the life of me, I can't figure out what is causing it. What type of setting is used to prevent the read-only file from appearing?

Edit: I can see that this post has gone on too long. I decided to continue this on a new thread right here.

Body:
So i would do it with the Workbook.Open() Method.

Sub Example()
Dim wb as Workbook
Dim path as String

path = "C:\Users\User\Desktop\1.xlsx"

set wb = Workbook.Open(path)
End Sub

Now you can use wb to execute every vba function. Then there a options to check if a workbook is already opened, look here. I dont think you can do that with adodb.


问:
JQuery - Why event.target doesn't work in this situation?
just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.

Also how would I test for the children inside?

https://jsfiddle.net/w8fd3m67/

$(window).on("click", function(event) {
  var container = $("#container");
  if ((event.target) !== container) {
    alert("clicked outside");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}</code>```

```

Cheers

答:
try this:</p>

```<code>$(window).on("click", function(event) {
var container = $("#container");
if ((event.target) !== container[0]) {
    alert("clicked outside");
}});
</code>```

Body:
just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.

Also how would I test for the children inside?

https://jsfiddle.net/w8fd3m67/

$(window).on("click", function(event) {
  var container = $("#container");
  if ((event.target) !== container) {
    alert("clicked outside");
  }
});

body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}

Cheers

Body:
try this:

$(window).on("click", function(event) {
var container = $("#container");
if ((event.target) !== container[0]) {
    alert("clicked outside");
}});


问:
data union with tables
I have below query

```<code>SELECT Vehicle_ID,Total_Weight,date,bilty_No FROM harvesting
UNION
SELECT Vehicle_ID,Total_Weight,date,Bilty_No FROM Blade_Harvesting
</code>```

Now i want to show vehicle_name instead of vehicle_ID from vehicle table..
how can i add vehicle table and show name instead of ID?

答:
Here we union your tables as before, aliasing the result as "h", and join onto your vehicle table. This assumes your vehicle table has columns "id" and "vehicle_name". Note that any Vehicle_IDs not present in both the vehicle table and the harvesting table will be omitted from the results, as this is an inner join. To show all vehicles, change "inner join" to "left join". This tells the database to retain everything in your vehicle table, and return NULL values from your harvesting table where there is no corresponding harvesting data.</p>

```<code>Select v.vehicle_name, h.Total_Weight, h.date, h.bilty_No
from
vehicle_table v
inner join
(
  SELECT Vehicle_ID,Total_Weight,date,bilty_No FROM harvesting
  UNION
  SELECT Vehicle_ID,Total_Weight,date,Bilty_No FROM Blade_Harvesting
) h
on h.Vehicle_ID = v.id
</code>```

Title: data union with tables

Body:
I have below query

SELECT Vehicle_ID,Total_Weight,date,bilty_No FROM harvesting
UNION
SELECT Vehicle_ID,Total_Weight,date,Bilty_No FROM Blade_Harvesting

Now i want to show vehicle_name instead of vehicle_ID from vehicle table..
how can i add vehicle table and show name instead of ID?

Body:
Here we union your tables as before, aliasing the result as "h", and join onto your vehicle table. This assumes your vehicle table has columns "id" and "vehicle_name". Note that any Vehicle_IDs not present in both the vehicle table and the harvesting table will be omitted from the results, as this is an inner join. To show all vehicles, change "inner join" to "left join". This tells the database to retain everything in your vehicle table, and return NULL values from your harvesting table where there is no corresponding harvesting data.

Select v.vehicle_name, h.Total_Weight, h.date, h.bilty_No
from
vehicle_table v
inner join
(
  SELECT Vehicle_ID,Total_Weight,date,bilty_No FROM harvesting
  UNION
  SELECT Vehicle_ID,Total_Weight,date,Bilty_No FROM Blade_Harvesting
) h
on h.Vehicle_ID = v.id


问:
Nodejs - https.request Error: connect ECONNREFUSED
I'm trying to make a http call in my node server(URL I'm trying is the skackexchange public url), below is the code

```<code>httpsServer.js

var https = require('https');

function httpsRequest() {
    var options = {
        hostname: 'api.stackexchange.com',
        path: '/2.2/answers',
        method: 'GET'
    };

    var req = https.request(options, (res) => {
        res.on('data', function (data) {
            console.dir(data);
        });
        req.end();
    });

    req.on('error', function (e) {
        console.error(e);
    });
}

httpsRequest();
</code>```

And and i did node httpsServer in my console

But I am getting the below error.

```<code>Error:

{ Error: connect ECONNREFUSED xxx.xxx.xxx.xx:443
    at Object.exports._errnoException (util.js:1050:11)
    at exports._exceptionWithHostPort (util.js:1073:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1093:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: 'xxx.xxx.xxx.xx',
  port: 443 }
</code>```

NOTE: I'm behind a proxy server.

What am i doing wrong? If its because I'm behind proxy is there a way to make it work?

答:
You have req.end() in wrong place. You need to end your request before you can get response from server.

```<code>var https = require('https');
function httpsRequest() {
    var options = {
        hostname : 'api.stackexchange.com',
        path : '/2.2/answers',
        method : 'GET'
    };
    var req = https.request(options, (res) => {
        res.on('data', function (data) {
            console.dir(data);
        });
    });
    req.on('error', function (e) {
        console.error(e);
    });
    req.end(); // correct place
}
httpsRequest();
</code>```

Body:
I'm trying to make a http call in my node server(URL I'm trying is the skackexchange public url), below is the code

httpsServer.js

var https = require('https');

function httpsRequest() {
    var options = {
        hostname: 'api.stackexchange.com',
        path: '/2.2/answers',
        method: 'GET'
    };

    var req = https.request(options, (res) => {
        res.on('data', function (data) {
            console.dir(data);
        });
        req.end();
    });

    req.on('error', function (e) {
        console.error(e);
    });
}

httpsRequest();

And and i did node httpsServer in my console

But I am getting the below error.

Error:

{ Error: connect ECONNREFUSED xxx.xxx.xxx.xx:443
    at Object.exports._errnoException (util.js:1050:11)
    at exports._exceptionWithHostPort (util.js:1073:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1093:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: 'xxx.xxx.xxx.xx',
  port: 443 }

NOTE: I'm behind a proxy server.

What am i doing wrong? If its because I'm behind proxy is there a way to make it work?

Body:
You have req.end() in wrong place. You need to end your request before you can get response from server.

var https = require('https');
function httpsRequest() {
    var options = {
        hostname : 'api.stackexchange.com',
        path : '/2.2/answers',
        method : 'GET'
    };
    var req = https.request(options, (res) => {
        res.on('data', function (data) {
            console.dir(data);
        });
    });
    req.on('error', function (e) {
        console.error(e);
    });
    req.end(); // correct place
}
httpsRequest();


问:
While speedily clicking on item of gridview, same method has been called twice a time
I have used grid view in my project. When I click on grid view item speedily, it calls the same method twice a time. But I slowly click, then it works perfectly.

In method below I call the dialog box. When I click the item it opens the dialog box but when I speedily click the item then dialog box open two times. What should I do to solve this?

```<code>grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
        showDialog(position);
    }
});
</code>```

答:
You can use this code which doesn't allow multiple speed clicks instead of your onclicklistener.

```<code>public abstract class SingleClickListener implements View.OnClickListener {
    private static final long THRESHOLD_MILLIS = 500L;
    private long lastClickMillis;

    @Override
    public void onClick(View v) {
        long now = SystemClock.elapsedRealtime();
        if (now - lastClickMillis > THRESHOLD_MILLIS) {
            onClicked(v);
            lastClickMillis = 0;
        } else {
            lastClickMillis = now;
        }
    }

    public abstract void onClicked(View v);
}
</code>```

and instead of normal onclicklistener use this

```<code> stage1_nxt.setOnClickListener(new SingleClickListener() {
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have used grid view in my project. When I click on grid view item speedily, it calls the same method twice a time. But I slowly click, then it works perfectly.

In method below I call the dialog box. When I click the item it opens the dialog box but when I speedily click the item then dialog box open two times. What should I do to solve this?

grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
        showDialog(position);
    }
});

Body:
You can use this code which doesn't allow multiple speed clicks instead of your onclicklistener.

public abstract class SingleClickListener implements View.OnClickListener {
    private static final long THRESHOLD_MILLIS = 500L;
    private long lastClickMillis;

    @Override
    public void onClick(View v) {
        long now = SystemClock.elapsedRealtime();
        if (now - lastClickMillis > THRESHOLD_MILLIS) {
            onClicked(v);
            lastClickMillis = 0;
        } else {
            lastClickMillis = now;
        }
    }

    public abstract void onClicked(View v);
}

and instead of normal onclicklistener use this

 stage1_nxt.setOnClickListener(new SingleClickListener() {


问:
Cannot unmarshal object into Go value of type []uint8
I am fairly new to Go. I have the following code:

```<code>package main

import (
    "encoding/json"
    "fmt"
)
func main() {

    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    dat := []byte(`{"num":7.13,"strs":["c","d"]}`)
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)

}
</code>```

Getting the error:

cannot "unmarshal object into Go value of type []uint8".

How can I fix this please?

答:
You have 2 JSON inputs, and you're trying to unmarshal one into the other. That doesn't make any sense.

Model your JSON input (the object) with a type (struct), and unmarshal into that. For example:

```<code>type Obj struct {
    Num  float64  `json:"num"`
    Strs []string `json:"strs"`
}

func main() {
    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)

    var obj Obj
    if err := json.Unmarshal(byt, &obj); err != nil {
        panic(err)
    }
    fmt.Println(obj)

}
</code>```

Output (try it on the Go Playground):

```<code>{6.13 [a b]}
</code>```

Body:
I am fairly new to Go. I have the following code:

package main

import (
    "encoding/json"
    "fmt"
)
func main() {

    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    dat := []byte(`{"num":7.13,"strs":["c","d"]}`)
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)

}

Getting the error:

cannot "unmarshal object into Go value of type []uint8".

How can I fix this please?

Body:
You have 2 JSON inputs, and you're trying to unmarshal one into the other. That doesn't make any sense.

Model your JSON input (the object) with a type (struct), and unmarshal into that. For example:

type Obj struct {
    Num  float64  `json:"num"`
    Strs []string `json:"strs"`
}

func main() {
    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)

    var obj Obj
    if err := json.Unmarshal(byt, &obj); err != nil {
        panic(err)
    }
    fmt.Println(obj)

}

Output (try it on the Go Playground):

{6.13 [a b]}


问:
unity how to count turns to change players
I would like to make a bowling game in unity and I want to change the players after they threw the ball two times and the whole game to continue for 4 turns.
so I have two balls and each one has a script with a playerController that moves around the balls and after collision they respawn in the original position.
so for the turns I made a gameController that enables player1 (ball) input and disables player2 input then it enables player2 and disables player1.
How can I make player 1 to play twice and then change to player 2.

the script is:

```<code>public IEnumerator gamePlay()
{
    if (pl1.hasPlay == false)
    {
        pl1.gameObject.SendMessage("Activate");
        pl2.gameObject.SendMessage("Deactivate");
    }

    if (pl1.hasPlay == true)
    {

        pl2.gameObject.SendMessage("Activate");
        pl1.gameObject.SendMessage("Deactivate");

    }
    yield return 0;
}
</code>```

答:
I'd recommend using two integers: one to store the number of plays and another to store the number of rounds.

It would look like this:

```<code>private int plays;
private int rounds;

private void Start()
{
    plays = 0;
    rounds = 0;
    StartCoroutine(gamePlay());
}

public void NextBall()
{
    plays++;
    // Here you can change the logic behind the 2 balls
    // (I remember it changes depending on whether you did a strike or not, if it's your last play or not, ...)
    if (plays >= 2)
    {
        plays = 0;
        rounds++;
        StartCoroutine(gamePlay());
    }
}

public IEnumerator gamePlay()
{
    // This is based on player 1 being the first player
    pl1.hasPlay = (rounds % 2 == 0);
    pl2.hasPlay = !pl1.hasPlay;

    pl1.gameObject.SendMessage(pl1.hasPlay ? "Activate" : "Deactivate");
    pl2.gameObject.SendMessage(pl2.hasPlay ? "Activate" : "Deactivate");

    yield return 0;
}
</code>```

Also i'm not sure why you declared gamePlay() as an IEnumerator and not as a method but I guess you needed it this way :)

I changed the if/else condition by a ternary operator since the content on both part was similar, I find it easier to read like this.

Hope this helps,

Body:
I would like to make a bowling game in unity and I want to change the players after they threw the ball two times and the whole game to continue for 4 turns.
so I have two balls and each one has a script with a playerController that moves around the balls and after collision they respawn in the original position.
so for the turns I made a gameController that enables player1 (ball) input and disables player2 input then it enables player2 and disables player1.
How can I make player 1 to play twice and then change to player 2.

the script is:

public IEnumerator gamePlay()
{
    if (pl1.hasPlay == false)
    {
        pl1.gameObject.SendMessage("Activate");
        pl2.gameObject.SendMessage("Deactivate");
    }

    if (pl1.hasPlay == true)
    {

        pl2.gameObject.SendMessage("Activate");
        pl1.gameObject.SendMessage("Deactivate");

    }
    yield return 0;
}

Body:
I'd recommend using two integers: one to store the number of plays and another to store the number of rounds.

It would look like this:

private int plays;
private int rounds;

private void Start()
{
    plays = 0;
    rounds = 0;
    StartCoroutine(gamePlay());
}

public void NextBall()
{
    plays++;
    // Here you can change the logic behind the 2 balls
    // (I remember it changes depending on whether you did a strike or not, if it's your last play or not, ...)
    if (plays >= 2)
    {
        plays = 0;
        rounds++;
        StartCoroutine(gamePlay());
    }
}

public IEnumerator gamePlay()
{
    // This is based on player 1 being the first player
    pl1.hasPlay = (rounds % 2 == 0);
    pl2.hasPlay = !pl1.hasPlay;

    pl1.gameObject.SendMessage(pl1.hasPlay ? "Activate" : "Deactivate");
    pl2.gameObject.SendMessage(pl2.hasPlay ? "Activate" : "Deactivate");

    yield return 0;
}

Also i'm not sure why you declared gamePlay() as an IEnumerator and not as a method but I guess you needed it this way :)

I changed the if/else condition by a ternary operator since the content on both part was similar, I find it easier to read like this.

Hope this helps,


问:
Unable to locate element in nightwatch using its id
I have encountered the following error while testing using nightwatch.

Expected element  to be visible - element was not found  -
  expected "visible" but got: "not found"

I have following two files:-

page-object model(simpleLogin.js)

module.exports = {
  url: 'http://google.com',
 sections :{
  google: {
   selector:'div#fkbx',
    elements: {
     searchBar :{
      selector : 'input[type=text]'
     },

     searchButton :{
      selector : 'button[name=btnG]'
     },
    }
  }
 }
};```
</div>
</div>
</p>

<p>the test js</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-js lang-js prettyprint-override"><code>module.exports = {
  'Test': function (client) {
    var homepage = client.page.simpleLogin();
 homepage.navigate()
 homepage.expect.section('@google').to.be.visible;
    var googleSection = homepage.section.google;
 client.end();
  }
};</code>```

Can anybody help me resolve this issue?

答:
Try it with the following code and let me know if it is working:

```<code>module.exports = {
url: 'http://google.com',
sections: {

google: {

  selector: 'div#fkbx',

  elements: {
    searchBar: {
      selector: 'input[type=text]',
    },
    searchButton: {
      selector: 'button[name=btnG]',
    },
   },
  },
 },
};
</code>```

Also, please take a look at
this link to see if it can help you a bit.

Body:
I have encountered the following error while testing using nightwatch.

Expected element  to be visible - element was not found  -
  expected "visible" but got: "not found"

I have following two files:-

page-object model(simpleLogin.js)

module.exports = {
  url: 'http://google.com',
 sections :{
  google: {
   selector:'div#fkbx',
    elements: {
     searchBar :{
      selector : 'input[type=text]'
     },

     searchButton :{
      selector : 'button[name=btnG]'
     },
    }
  }
 }
};

the test js

module.exports = {
  'Test': function (client) {
    var homepage = client.page.simpleLogin();
 homepage.navigate()
 homepage.expect.section('@google').to.be.visible;
    var googleSection = homepage.section.google;
 client.end();
  }
};

Can anybody help me resolve this issue?

Body:
Try it with the following code and let me know if it is working:

module.exports = {
url: 'http://google.com',
sections: {

google: {

  selector: 'div#fkbx',

  elements: {
    searchBar: {
      selector: 'input[type=text]',
    },
    searchButton: {
      selector: 'button[name=btnG]',
    },
   },
  },
 },
};

Also, please take a look at
this link to see if it can help you a bit.


问:
FileMaker :- Compare textbox values with OBBC SQL DB
I am trying to implement an Login module where,I need to Compare the list of values in  SQL DB. Here i want to compare text  box entered values with SQL DB.
Please share any views.</p>

答:
Depends on your SQL DB. You can add your SQL DB as ESS or you can use "Execute SQL" and run a SQL query on ODBC DNS to your database.

If you are in 16 and your SQL has any API, you can call them through CURL. You can do the same with previous versions of FileMaker using plugins.


问:
Too much time when starting Intent (to disable Home button)
I downloaded this tutorial to disable home button, the problem is : when I press my home button the activity take too much time to restart (4 seconds).

I tried to replace the service by putting :

```<code>@Override
public void onPause(){
    Intent i = getIntent();
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);

    //disable rencent app button
    ActivityManager activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);

    activityManager.moveTaskToFront(getTaskId(), 0);

    super.onPause();
}
</code>```

but it's the same, the activity take nearly 5 seconds to restart (in 5 seconds you have the time to go to settings or else and do what you want)

Is it ok that it takes that much time to start an Intent?

答:
Add this lines in your Manifest.xml file</p>

```<code><intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.HOME" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.MONKEY"/>
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</code>```

Body:
I downloaded this tutorial to disable home button, the problem is : when I press my home button the activity take too much time to restart (4 seconds).

I tried to replace the service by putting :

@Override
public void onPause(){
    Intent i = getIntent();
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);

    //disable rencent app button
    ActivityManager activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);

    activityManager.moveTaskToFront(getTaskId(), 0);

    super.onPause();
}

but it's the same, the activity take nearly 5 seconds to restart (in 5 seconds you have the time to go to settings or else and do what you want)

Is it ok that it takes that much time to start an Intent?

Body:
Add this lines in your Manifest.xml file

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.HOME" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.MONKEY"/>
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>


问:
How do pyplot functions (show, savefig, etc) work without "object" being passed in?
How do pyplot functions such as show() and savefig() not require a "plot object" to work?

For example, the following code works, but somehow I expect to use a file handler or pass a "plot object" into plt.show() and plot.savefig("venn3.pdf").

```<code>from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles

# Subset sizes
s = (2,3,4,3,1,0.5,4)

v = venn3(subsets=s, set_labels=('A', 'B', 'C'))

# Subset labels
v.get_label_by_id('100').set_text('Abc')
v.get_label_by_id('010').set_text('aBc')
v.get_label_by_id('110').set_text('ABc')
v.get_label_by_id('001').set_text('Abc')
v.get_label_by_id('101').set_text('aBc')
v.get_label_by_id('011').set_text('ABc')
v.get_label_by_id('111').set_text('ABC')

# Subset colors
v.get_patch_by_id('100').set_color('c')
v.get_patch_by_id('010').set_color('#993333')
v.get_patch_by_id('110').set_color('blue')

# Subset alphas
v.get_patch_by_id('101').set_alpha(0.4)
v.get_patch_by_id('011').set_alpha(1.0)
v.get_patch_by_id('111').set_alpha(0.7)

# Border styles
c = venn3_circles(subsets=s, linestyle='solid')
c[0].set_ls('dotted')  # Line style
c[1].set_ls('dashed')
c[2].set_lw(1.0)       # Line width

plt.show() # For show() to work without using variable v seems counter-intuitive to me.
plt.savefig("venn3.pdf") # For savefig() to work without using variable v seems counter-intuitive to me.
</code>```

2[]

答: Pyplot uses a global variable to hold the figure object. All pyplot functions work with that variable(s). If you are working interactively, pyplot is perfectly fine since only you will modify that variable. If you are writing multi-threaded or multi-user code pyplot will not work, and you would have to use the layer benath it, which needs the figure object passed in (and is a terrible interface).</p>

Body:
How do pyplot functions such as show() and savefig() not require a "plot object" to work?

For example, the following code works, but somehow I expect to use a file handler or pass a "plot object" into plt.show() and plot.savefig("venn3.pdf").

from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles

# Subset sizes
s = (2,3,4,3,1,0.5,4)

v = venn3(subsets=s, set_labels=('A', 'B', 'C'))

# Subset labels
v.get_label_by_id('100').set_text('Abc')
v.get_label_by_id('010').set_text('aBc')
v.get_label_by_id('110').set_text('ABc')
v.get_label_by_id('001').set_text('Abc')
v.get_label_by_id('101').set_text('aBc')
v.get_label_by_id('011').set_text('ABc')
v.get_label_by_id('111').set_text('ABC')

# Subset colors
v.get_patch_by_id('100').set_color('c')
v.get_patch_by_id('010').set_color('#993333')
v.get_patch_by_id('110').set_color('blue')

# Subset alphas
v.get_patch_by_id('101').set_alpha(0.4)
v.get_patch_by_id('011').set_alpha(1.0)
v.get_patch_by_id('111').set_alpha(0.7)

# Border styles
c = venn3_circles(subsets=s, linestyle='solid')
c[0].set_ls('dotted')  # Line style
c[1].set_ls('dashed')
c[2].set_lw(1.0)       # Line width

plt.show() # For show() to work without using variable v seems counter-intuitive to me.
plt.savefig("venn3.pdf") # For savefig() to work without using variable v seems counter-intuitive to me.

2[]


问:
How can I OOM sooner in excessive GC?
Occasionally my JVM runs out of memory, but rather then OOMing which I can recover from (or heapDumpOnOOM and debug) it tends to thrash in GC for hours before throwing out of memory.
This is essentially the same as the (unanswered) question: How can I configure the Java GC Overhead Limit?
But I suspect the answer is you can't tune the 98%/2% thresholds, so I'm asking of any way to achieve similar effect. notice excessive GC, and preferably cause OOM, or kill the JVM or such.</p>

答: Oracle's GC ergonomics guide covers options for both thresholds.  GCTimeLimit and GCHeapFreeLimit. Lowering the former and increasing the latter should result in OOMs occuring sooner.

Title: How can I OOM sooner in excessive GC?


答:
I think you meant to do something like this:

package main

```<code>import (
    "encoding/json"
    "fmt"
)

func main() {
    var dat interface{}
    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
}
</code>```

What you were trying to do makes no sense, since you're trying to unmarshal two JSON objects one into another.

Title: Cannot unmarshal object into Go value of type []uint8

Body:
I think you meant to do something like this:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var dat interface{}
    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
}

What you were trying to do makes no sense, since you're trying to unmarshal two JSON objects one into another.


问:
how to use image from dll
i have a customized grid view.
it has a property "Theme".
this property has some item (enum) that change apperacne of my gridview such as hedar background image,rowstyle,rowcolor,etc... .
this property work fine.but i must add a folder (contained image) to show background image of header.
i must prepare this folder for users (that use my gridview in their website) .
i want just users(programmers) add my dll(gridview) and change theme of my grid without any additional work.
if you see in my code i must add backgroundimage style refrencde by a floder in web site(ThemeResource/HeaderSoftGamer.png).and naturally users(programmers) must copy this folder of page that use my gridview

```<code> public class MTGridView : GridView
{
    public enum ThemeCollection { HardBlue, Black, Girly , Sky , Samta };
    private ThemeCollection currentTheme;
    public ThemeCollection Theme
    {
        get
        {
            return currentTheme;
        }
        set
        {
            currentTheme = value;
        }

    }
     public MTGridView()
    {
          this.RowCreated += new GridViewRowEventHandler(MTGridView_RowCreated);
    }
     void MTGridView_RowCreated(object sender, GridViewRowEventArgs e)
    {

        switch (Theme)
        {
            case ThemeCollection.Sky:
                {

                    switch (e.Row.RowType)
                    {
                        case DataControlRowType.Header:
                            e.Row.Style.Add("background-color", "blue");
                            e.Row.Style.Add("font-family", "Tahoma");
                            e.Row.Style.Add("font-size", hs.ToString());
                            e.Row.Style.Add("color", "Black");
                            e.Row.Style.Add("background-image", "url(ThemeResource/HeaderSoftGamer.png)");
                         break;
                     }
                   }
              }
     }}
</code>```

thank all

答: You can either keep your images on your server and use them from your code or give the complete image folder and ask them to include it with their project. I don't see a workaround for this..</p>

Title: how to use image from dll

Body:
i have a customized grid view.
it has a property "Theme".
this property has some item (enum) that change apperacne of my gridview such as hedar background image,rowstyle,rowcolor,etc... .
this property work fine.but i must add a folder (contained image) to show background image of header.
i must prepare this folder for users (that use my gridview in their website) .
i want just users(programmers) add my dll(gridview) and change theme of my grid without any additional work.
if you see in my code i must add backgroundimage style refrencde by a floder in web site(ThemeResource/HeaderSoftGamer.png).and naturally users(programmers) must copy this folder of page that use my gridview

 public class MTGridView : GridView
{
    public enum ThemeCollection { HardBlue, Black, Girly , Sky , Samta };
    private ThemeCollection currentTheme;
    public ThemeCollection Theme
    {
        get
        {
            return currentTheme;
        }
        set
        {
            currentTheme = value;
        }

    }
     public MTGridView()
    {
          this.RowCreated += new GridViewRowEventHandler(MTGridView_RowCreated);
    }
     void MTGridView_RowCreated(object sender, GridViewRowEventArgs e)
    {

        switch (Theme)
        {
            case ThemeCollection.Sky:
                {

                    switch (e.Row.RowType)
                    {
                        case DataControlRowType.Header:
                            e.Row.Style.Add("background-color", "blue");
                            e.Row.Style.Add("font-family", "Tahoma");
                            e.Row.Style.Add("font-size", hs.ToString());
                            e.Row.Style.Add("color", "Black");
                            e.Row.Style.Add("background-image", "url(ThemeResource/HeaderSoftGamer.png)");
                         break;
                     }
                   }
              }
     }}

thank all


问:
How to set sync interval of 15 minutes for sync adapter.?
Below is the updated code

```<code>public class MainActivityNew extends AppCompatActivity  {

    private static final String Tag = "MainActivity";
    // Instance fields
    Account mAccount;

    public static final long SECONDS_PER_MINUTE = 60L;
    public static final long SYNC_INTERVAL_IN_MINUTES = 15L;
    public static final long SYNC_INTERVAL =
            SYNC_INTERVAL_IN_MINUTES *
                    SECONDS_PER_MINUTE;

    private static final int NOTIFICATION_EX = 1;

    ContentResolver resolver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       // Create the dummy account
        mAccount = CreateSyncAccount(this);
        resolver = getContentResolver();
        resolver.setIsSyncable(mAccount, CommonUtilities.AUTHORITY, 1);
        resolver.setSyncAutomatically(mAccount, CommonUtilities.AUTHORITY, true);
        resolver.addPeriodicSync(
                mAccount,
                CommonUtilities.AUTHORITY,
                Bundle.EMPTY,
                SYNC_INTERVAL);}

    public static Account CreateSyncAccount(Context context) {
        // Create the mAccount call_type and default mAccount
        Account newAccount = new Account(
                ACCOUNT, ACCOUNT_TYPE);
        // Get an instance of the Android mAccount manager
        AccountManager accountManager =
                (AccountManager) context.getSystemService(
                        ACCOUNT_SERVICE);
        /*
         * Add the mAccount and mAccount call_type, no password or user data
         * If successful, return the Account object, otherwise report an error.
         */
        if (accountManager.addAccountExplicitly(newAccount, null, null)) {
            /*
             * If you don't set android:syncable="true" in
             * in your <provider> element in the manifest,
             * then call context.setIsSyncable(mAccount, AUTHORITY, 1)
             * here.
             */
            ContentResolver.setIsSyncable(newAccount, AUTHORITY, 1);
            ContentResolver.setMasterSyncAutomatically(true);
            ContentResolver.setSyncAutomatically(newAccount, AUTHORITY, true);
        } else {
            /*
             * The mAccount exists or some other error occurred. Log this, report it,
             * or handle it internally.
             */
            Log.d(Tag, "Error occured in creating mAccount");
        }
        return newAccount;
    }
</code>```

and also I am sending sync interval time like 1*60*1000

How to set sync interval of 15 minutes for sync adapter ?

What is the difference between 1*60*1000L and 1*60*1000 ?

答:
1*60*1000 = 60 000 = 1 minute,

use 15*60*1000 to set your sync interval to 15 minutes.

1*60*1000L returns a long where as 1*60*1000 returns an int(not good for large numbers)

Body:
Below is the updated code

public class MainActivityNew extends AppCompatActivity  {

    private static final String Tag = "MainActivity";
    // Instance fields
    Account mAccount;

    public static final long SECONDS_PER_MINUTE = 60L;
    public static final long SYNC_INTERVAL_IN_MINUTES = 15L;
    public static final long SYNC_INTERVAL =
            SYNC_INTERVAL_IN_MINUTES *
                    SECONDS_PER_MINUTE;

    private static final int NOTIFICATION_EX = 1;

    ContentResolver resolver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       // Create the dummy account
        mAccount = CreateSyncAccount(this);
        resolver = getContentResolver();
        resolver.setIsSyncable(mAccount, CommonUtilities.AUTHORITY, 1);
        resolver.setSyncAutomatically(mAccount, CommonUtilities.AUTHORITY, true);
        resolver.addPeriodicSync(
                mAccount,
                CommonUtilities.AUTHORITY,
                Bundle.EMPTY,
                SYNC_INTERVAL);}

    public static Account CreateSyncAccount(Context context) {
        // Create the mAccount call_type and default mAccount
        Account newAccount = new Account(
                ACCOUNT, ACCOUNT_TYPE);
        // Get an instance of the Android mAccount manager
        AccountManager accountManager =
                (AccountManager) context.getSystemService(
                        ACCOUNT_SERVICE);
        /*
         * Add the mAccount and mAccount call_type, no password or user data
         * If successful, return the Account object, otherwise report an error.
         */
        if (accountManager.addAccountExplicitly(newAccount, null, null)) {
            /*
             * If you don't set android:syncable="true" in
             * in your <provider> element in the manifest,
             * then call context.setIsSyncable(mAccount, AUTHORITY, 1)
             * here.
             */
            ContentResolver.setIsSyncable(newAccount, AUTHORITY, 1);
            ContentResolver.setMasterSyncAutomatically(true);
            ContentResolver.setSyncAutomatically(newAccount, AUTHORITY, true);
        } else {
            /*
             * The mAccount exists or some other error occurred. Log this, report it,
             * or handle it internally.
             */
            Log.d(Tag, "Error occured in creating mAccount");
        }
        return newAccount;
    }

and also I am sending sync interval time like 1*60*1000

How to set sync interval of 15 minutes for sync adapter ?

What is the difference between 1*60*1000L and 1*60*1000 ?


问:
rails: using collection_check_boxes in each category
Using

```<code><%= collection_check_boxes(:employee, :skill_ids, Skill.all, :id, :name) %>
</code>```

on its own works just fine in my project. This way, each employee shows all skills and if they are checked or not.

Additionally to that, I have some categories, which the skills are related, to (Category has many Skills).

Can anyone recommend a proper way, to use the collection_check_boxes correctly for each category so only the skills related to the category are displayed?
I think I am just missing the correct limitation for the "Skill.all" parameter.

Finally it should look like this, but instead of Submit buttons (by using jquery-ujs, method: put), I want those skills to be checkboxes.

http://d.pr/i/CYHaGH

Edit1: Skills and Categories model

```<code>class Category < ApplicationRecord

  has_many :subcategories, class_name: "Category", foreign_key: "parent_id"
  belongs_to :topcategory, class_name: "Category"

  has_many :skills
end

class Skill < ApplicationRecord
  has_many :employeeskillsets, foreign_key: "skill_id"
  has_many :employees, through: :employeeskillsets
  has_many :projectskillsets
  has_many :projects, through: :projectskillsets
  has_many :tagsets, dependent: :destroy
  has_many :tags, through: :tagsets

  belongs_to :category
end
</code>```

Edit2: Still no progress. Does anybody have an idea how this could be done?

SOLUTION:

Ok, the solution was pretty simple. I just had to declare the collection on each category, which already was for a previous version of that app. <%= collection_check_boxes :employee, :skill_ids, category.skills, :id, :name%> (category.skills was set for each instance of categories).

Thanks for the help.

答:
Using collection_check_boxes, you can pass a block like that :

```<code>collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
  b.label { b.check_box }
end
</code>```

And you can access value, text and more :

```<code>collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
   b.label(:"data-value" => b.value) { b.check_box + b.text }
end
</code>```

You should read the documentation here :

https://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes

You will find all you need to solve your issue,
Hope that help

Body:
Using

<%= collection_check_boxes(:employee, :skill_ids, Skill.all, :id, :name) %>

on its own works just fine in my project. This way, each employee shows all skills and if they are checked or not.

Additionally to that, I have some categories, which the skills are related, to (Category has many Skills).

Can anyone recommend a proper way, to use the collection_check_boxes correctly for each category so only the skills related to the category are displayed?
I think I am just missing the correct limitation for the "Skill.all" parameter.

Finally it should look like this, but instead of Submit buttons (by using jquery-ujs, method: put), I want those skills to be checkboxes.

http://d.pr/i/CYHaGH

Edit1: Skills and Categories model

class Category < ApplicationRecord

  has_many :subcategories, class_name: "Category", foreign_key: "parent_id"
  belongs_to :topcategory, class_name: "Category"

  has_many :skills
end

class Skill < ApplicationRecord
  has_many :employeeskillsets, foreign_key: "skill_id"
  has_many :employees, through: :employeeskillsets
  has_many :projectskillsets
  has_many :projects, through: :projectskillsets
  has_many :tagsets, dependent: :destroy
  has_many :tags, through: :tagsets

  belongs_to :category
end

Edit2: Still no progress. Does anybody have an idea how this could be done?

SOLUTION:

Ok, the solution was pretty simple. I just had to declare the collection on each category, which already was for a previous version of that app. <%= collection_check_boxes :employee, :skill_ids, category.skills, :id, :name%> (category.skills was set for each instance of categories).

Thanks for the help.

Body:
Using collection_check_boxes, you can pass a block like that :

collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
  b.label { b.check_box }
end

And you can access value, text and more :

collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
   b.label(:"data-value" => b.value) { b.check_box + b.text }
end

You should read the documentation here :

https://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes

You will find all you need to solve your issue,
Hope that help


问:
Is there an Android app exposing the Tango API via websockets?
Is there an Android app exposing the Tango API via websockets? Would be perfect to explore via JavaScript&more without heavy deploy! cf e.g. https://goocreate.com/blog/1137/it-takes-goo-to-tango/

I'd rather avoid having to (re) learn C# with Unity or C/C++ with the Android SDK as I solely want to focus on the Tango API. I understand the performance will be TERRIBLY downgraded but compared to the time to compile and upload, at first during the exploration phase at least, I believe it's still the better path for my needs.

Suggestions welcomed.

PS: checked alternative e.g. termux + node.js + node-ffi or Mobile App - Using both Project Tango and Ionic and/or angular but that doesn't seem much better.

答: Since Google I/O 2017 Google provides Chromium-WebAR https://github.com/googlevr/chromium-webar , a build of Chromium providing access to getPointCloud(), getPickingPointAndPlaneInPointCloud() and for websockets since it is a web browser.


问:
Android Studio 2.3.2 and Kotlin 1.1.2-4 + Data Binding
I have issue in Android Studio 2.3.2 when trying to use Kotlin 1.1.2-4 and Data Binding.

Here is my gradle files:

```<code>buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "my.app.kotlin.databinding"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {

    // Data binding compiler for kotlin
    kapt 'com.android.databinding:compiler:2.3.2'

    //support libraries
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // std lib for Kotlin
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    testCompile 'junit:junit:4.12'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}
repositories {
    mavenCentral()
}
</code>```

When I try to compile the project it gives me this error:

```<code>* Exception is:
org.gradle.api.CircularReferenceException: Circular dependency between the following tasks:
:app:compileReleaseKotlin
\--- :app:kaptReleaseKotlin
     \--- :app:compileReleaseKotlin (*)

(*) - details omitted (listed previously)

        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.onOrderingCycle(DefaultTaskExecutionPlan.java:445)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.determineExecutionPlan(DefaultTaskExecutionPlan.java:287)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.ensurePopulated(DefaultTaskGraphExecuter.java:202)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:109)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)

BUILD FAILED
</code>```

If I switch back to version 1.1.2-3 everything works well and compiling without any issue.

What I missed? Why it doesn't work with version 1.1.2-4?

答:
Unfortunately this is a known bug,

https://youtrack.jetbrains.com/issue/KT-18279
https://issuetracker.google.com/issues/62324689

the work around, as you found out, is to downgrade to kotlin 1.1.2-3

Body:
I have issue in Android Studio 2.3.2 when trying to use Kotlin 1.1.2-4 and Data Binding.

Here is my gradle files:

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "my.app.kotlin.databinding"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {

    // Data binding compiler for kotlin
    kapt 'com.android.databinding:compiler:2.3.2'

    //support libraries
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // std lib for Kotlin
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    testCompile 'junit:junit:4.12'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}
repositories {
    mavenCentral()
}

When I try to compile the project it gives me this error:

* Exception is:
org.gradle.api.CircularReferenceException: Circular dependency between the following tasks:
:app:compileReleaseKotlin
\--- :app:kaptReleaseKotlin
     \--- :app:compileReleaseKotlin (*)

(*) - details omitted (listed previously)

        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.onOrderingCycle(DefaultTaskExecutionPlan.java:445)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.determineExecutionPlan(DefaultTaskExecutionPlan.java:287)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.ensurePopulated(DefaultTaskGraphExecuter.java:202)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:109)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)

BUILD FAILED

If I switch back to version 1.1.2-3 everything works well and compiling without any issue.

What I missed? Why it doesn't work with version 1.1.2-4?


问:
Difference between geckodriver and marionette
I don't fully understand the difference between geckodriver and marionette.

Can anyone clarify the difference between them?

For example, when I use Selenium WebDriver to control a Firefox browser, I need a geckodriver binary to listen the WebDriver protocol from Selenium.

Is Marionette the Firefox extension that actually drives Firefox?

答:
Selenium uses W3C Webdriver protocol to send requests to Geckodriver, which translates them and uses Marionette protocol to send them to Firefox

Selenium<--(W3C Webdriver)-->Geckodriver<---(Marionette)--->Firefox