问:
Jquery dynamic text effect / class problem
I have a html file containing a table with some rows n columns. each row contain a button, which has some functions. First, it has to submit the data in a row to a php file, which is not printing anything. Then the button have to change its text and text in column 5 of its corresponding row. The change text effect of button is working well. But the change text effect of column 5 is buggy. Only the text of column5 in first row is changing, no matter which button you click.. Can anyone fix the problem for me??

Thanks in advance :)

blasteralfred

```<code><head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style>
.style1 {
    background-color: #c3d9ff;
    font-family:arial,sans-serif;
}
.style2 {
    text-align: center;
    font-weight: bold;
}
.style3 {
    background-color: #FFFFFF;
    font-family:arial,sans-serif;
    text-align: center;
    font-weight: bold;
}
body {
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:15px;
background-color: ;
}
.delete_button {
font-weight:bold;
float:right;
}
</style>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function()
{
    $(".delete_button").click(function()
    {
    var id = $(this).attr("id");
    var dataString = 'id='+ id ;
    var parent = $(this).parent().parent();
    $.ajax({
        type: "POST",
        url: "del.php",
        data: dataString,
        cache: false,
        success: function()
        {
            if(id % 2)
            {
                parent.fadeOut('fast', function() {$(this).fadeOut();$(this).fadeIn();});
            }
            else
            {
                parent.fadeOut('fast', function()   {$(this).fadeOut();$(this).fadeIn();});
            }
        }
    });
    return false;
    }
);});
$(document).ready(function() {
  $('.delete_button').click(function() {
    $(this).text($(this).text() == 'Inactivate' ? 'Activate' : 'Inactivate');
    $("#clickme2").text($("#clickme2").text() == 'Inactive' ? 'Active' : 'Inactive');
    return false;
});
});
</script>
</head>
<body>
<table style="width: 90%" align="center" class="style1">
<tr>
        <td colspan="7" class="style2">MANAGER</td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">column1</td>
        <td class="style3" style="width: 139px">column2</td>
        <td class="style3" style="width: 139px">column3</td>
        <td class="style3" style="width: 139px">column4</td>
        <td class="style3" style="width: 139px">column5</td>
        <td class="style3" style="width: 144px">column6</td>
        <td class="style3" style="">Action</td>
    </tr>
        <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
</table>
</body>
</code>```

答:
You are using an id multiple times (this is invalid, and not allowed in the HTML specs). When you target this you always get the first one only.

Use the clickme2 as a class instead of an id and target it from the click handler like this

```<code>$(this).closest('tr').find('.clickme2').text(...);
</code>```

Also, remove the div attribute from the td tags as that does not exists either.

Example at http://www.jsfiddle.net/gaby/23KEW/

Body:
I have a html file containing a table with some rows n columns. each row contain a button, which has some functions. First, it has to submit the data in a row to a php file, which is not printing anything. Then the button have to change its text and text in column 5 of its corresponding row. The change text effect of button is working well. But the change text effect of column 5 is buggy. Only the text of column5 in first row is changing, no matter which button you click.. Can anyone fix the problem for me??

Thanks in advance :)

blasteralfred

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

        MANAGER

        column1
        column2
        column3
        column4
        column5
        column6
        Action

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

Body:
You are using an id multiple times (this is invalid, and not allowed in the HTML specs). When you target this you always get the first one only.

Use the clickme2 as a class instead of an id and target it from the click handler like this

$(this).closest('tr').find('.clickme2').text(...);

Also, remove the div attribute from the td tags as that does not exists either.

Example at http://www.jsfiddle.net/gaby/23KEW/


来源: stackexchange

问:
Real-time video stabilization
I got a Google Pixel and tried recording a video with the official app, I found out there is a remarkable built-in stabilization mechanism happening on the recording, so if I shake my hand a bit this movement is only slightly transferred to the recording (even the video preview is impressively stable).

However I tried with my own Video recording app and this stabilization is not happening.

I of course tried with the setVideoStabilization() method over at the official docs but the result is not as good as with the builtin Camera app.

Is there anything else I am missing?

答:
If you don't want to wait, an alternative is to read this amazing article on content unshaking using the accelerometer (with sourcecode here).

This was done to unshake the phone's content (to ease reading in moving transport for example), but it's the same logic you can apply to video feeds from the camera.

However, don't expect to get the same results as Google's approach. Indeed, this can only do software stabilization, which will move around your image, and thus crop it. To avoid cropping and luminance change, Google's uses Optical Image Stabilization, which mechanically moves the lens, and thus avoids any cropping. However, OIS is not yet supported on all phones, so take this into account if you use Google's API in your app.

ContentLicense: CC BY-SA 3.0

Title: Real-time video stabilization


问:
I want to give multiple conditions in ng-disabled
```<code><button type="button" class="btn-submit upload smooth-hover" data-prod-idx="{{index}}" data-prod-id="{{prod.ProductId}}"
ng-click="vm.onUpload($event, index, prod.ProductId)"
ngf-select="vm.uploadAttachments($event, $files, $invalidFiles)" multiple accept="image/*,.pdf,*.doc,*.docx" ngf-capture="'camera'"
ngf-max-size="5MB"
ng-disabled="prod.Product_Status === 'Approved||Not Approved'">
Upload Documents</button>
</code>```

I have different product status condition depending on that I want to disable the button. I am having a problem with or condition in ng-disable. Its not disabling the button if i give to conditions.

2.IF clicked on disabled button it should pop-up the alert message (Not using Jquery)
Every condition have different error msg (Conditions in ng-disabled)

Thanks for Help!

答:
Your condition code is wrong

```<code>ng-disabled="prod.Product_Status === 'Approved'|| prod.Product_Status === 'Not Approved'"
</code>```

In case 2, you can remove ng-disable and, on click function, you could made with this way:

```<code>function onUpload($event, $files, prod.ProductId){
    if(prod.Product_Status === 'Approved'|| prod.Product_Status === 'Not Approved'){
        alert("Message")
        return;
    }
    // your code
}
</code>```

Body:
<button type="button" class="btn-submit upload smooth-hover" data-prod-idx="{{index}}" data-prod-id="{{prod.ProductId}}"
ng-click="vm.onUpload($event, index, prod.ProductId)"
ngf-select="vm.uploadAttachments($event, $files, $invalidFiles)" multiple accept="image/*,.pdf,*.doc,*.docx" ngf-capture="'camera'"
ngf-max-size="5MB"
ng-disabled="prod.Product_Status === 'Approved||Not Approved'">
Upload Documents</button>

I have different product status condition depending on that I want to disable the button. I am having a problem with or condition in ng-disable. Its not disabling the button if i give to conditions.

2.IF clicked on disabled button it should pop-up the alert message (Not using Jquery)
Every condition have different error msg (Conditions in ng-disabled)

Thanks for Help!

Body:
Your condition code is wrong

ng-disabled="prod.Product_Status === 'Approved'|| prod.Product_Status === 'Not Approved'"

In case 2, you can remove ng-disable and, on click function, you could made with this way:

function onUpload($event, $files, prod.ProductId){
    if(prod.Product_Status === 'Approved'|| prod.Product_Status === 'Not Approved'){
        alert("Message")
        return;
    }
    // your code
}


问:
Click anchor element using javascript function
I know this has been covered elsewhere on this site, as well as many others, but I just can't seem to figure it out.

I have an anchor tag that I use to show a lightbox form:

```<code><a id="aNoData" href="#divNoData" class="fancybox">No Data</a>
</code>```

I want to click it using a javascript function:

```<code>function fnNoData()
{
    //  This line works
    alert("this line works");
    //  Neither of these lines work
    $('#aNoData').click();
     document.getElementById('aNoData').click();
}
</code>```

I'm calling the function from my code behind, like this:

```<code>ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "fnNoData()", true);
</code>```

When I do this, the first line (the alert box) shows fine. However, the other two lines (to click the anchor tag) do not. The non-working lines work great if I put them in my $(document).ready block (the anchor clicks on page load). So it seems that the lines to click my anchor work fine, just not in my function.

Can anyone see what I'm doing wrong?

答:
jquery click event is expecting a function
(not tested)

```<code>$('#aNoData').on("click", function() {
  console.log( "clicked the element with id aNoData );
});
</code>```

in case you want to trigger the click(without the actual click), jquery has a function for that too:
http://api.jquery.com/trigger/

Body:
I know this has been covered elsewhere on this site, as well as many others, but I just can't seem to figure it out.

I have an anchor tag that I use to show a lightbox form:

No Data

I want to click it using a javascript function:

function fnNoData()
{
    //  This line works
    alert("this line works");
    //  Neither of these lines work
    $('#aNoData').click();
     document.getElementById('aNoData').click();
}

I'm calling the function from my code behind, like this:

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "fnNoData()", true);

When I do this, the first line (the alert box) shows fine. However, the other two lines (to click the anchor tag) do not. The non-working lines work great if I put them in my $(document).ready block (the anchor clicks on page load). So it seems that the lines to click my anchor work fine, just not in my function.

Can anyone see what I'm doing wrong?

Body:
jquery click event is expecting a function
(not tested)

$('#aNoData').on("click", function() {
  console.log( "clicked the element with id aNoData );
});

in case you want to trigger the click(without the actual click), jquery has a function for that too:
http://api.jquery.com/trigger/


问:
Dynamic SQL output of a query to a variable
I would like to output the result of the dynamic SQL into a variable called @Count but not sure what the syntax or even the code should like to accomplish this.

The code looks as follows:

```<code>declare @tab nvarchar(255) = 'Person.person'

declare @Count int
declare @SQL nvarchar(max) = 'select  count(*) from '+ @tab

exec(@SQl)

select @Count
</code>```

thank you

答:
The below question is pretty much identical to what you are asking here.

sp_executeSql with output parameter

```<code>DECLARE @retval int
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

DECLARE @tablename nvarchar(50)
SELECT @tablename = N'products'

SELECT @sSQL = N'SELECT @retvalOUT = MAX(ID) FROM ' + @tablename;
SET @ParmDefinition = N'@retvalOUT int OUTPUT';

EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;

SELECT @retval;
</code>```

Body:
I would like to output the result of the dynamic SQL into a variable called @Count but not sure what the syntax or even the code should like to accomplish this.

The code looks as follows:

declare @tab nvarchar(255) = 'Person.person'

declare @Count int
declare @SQL nvarchar(max) = 'select  count(*) from '+ @tab

exec(@SQl)

select @Count

thank you

Body:
The below question is pretty much identical to what you are asking here.

sp_executeSql with output parameter

DECLARE @retval int
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

DECLARE @tablename nvarchar(50)
SELECT @tablename = N'products'

SELECT @sSQL = N'SELECT @retvalOUT = MAX(ID) FROM ' + @tablename;
SET @ParmDefinition = N'@retvalOUT int OUTPUT';

EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;

SELECT @retval;


答:
It should be:

```<code>ng-disabled="prod.Product_Status === 'Approved' || prod.Product_Status === 'Not Approved'"
</code>```

Putting the || inside the string simply makes it part of the string, not a logical operator.

Title: I want to give multiple conditions in ng-disabled

Body:
It should be:

ng-disabled="prod.Product_Status === 'Approved' || prod.Product_Status === 'Not Approved'"

Putting the || inside the string simply makes it part of the string, not a logical operator.


问:
Python3 tkinter set image size
I have looked everywhere to find a way to set the size of an image. The image is set to a url. I have found other questions on the site but none of them have worked.

```<code>import urllib.request, base64

u = urllib.request.urlopen(currentWeatherIconURL)
raw_data = u.read()
u.close()

b64_data = base64.encodestring(raw_data)
image = PhotoImage(data=b64_data)

label = Label(image=image, bg="White")
label.pack()
</code>```

That is the code that creates the image, how would I set the size of the image

答:
As mentioned by several others, you should use PIL to resize your image before attaching it to a tkinter label:</p>

```<code>from tkinter import Tk, Label
from PIL import Image, ImageTk

root = Tk()

img = ImageTk.PhotoImage(Image.open('img-path.png').resize(pixels_x, pixels_y)) # the one-liner I used in my app
label = Label(root, image=img, ...)
label.image = img # this feels redundant but the image didn't show up without it in my app
label.pack()

root.mainloop()
</code>```

Title: Python3 tkinter set image size

Body:
I have looked everywhere to find a way to set the size of an image. The image is set to a url. I have found other questions on the site but none of them have worked.

import urllib.request, base64

u = urllib.request.urlopen(currentWeatherIconURL)
raw_data = u.read()
u.close()

b64_data = base64.encodestring(raw_data)
image = PhotoImage(data=b64_data)

label = Label(image=image, bg="White")
label.pack()

That is the code that creates the image, how would I set the size of the image

Body:
As mentioned by several others, you should use PIL to resize your image before attaching it to a tkinter label:

from tkinter import Tk, Label
from PIL import Image, ImageTk

root = Tk()

img = ImageTk.PhotoImage(Image.open('img-path.png').resize(pixels_x, pixels_y)) # the one-liner I used in my app
label = Label(root, image=img, ...)
label.image = img # this feels redundant but the image didn't show up without it in my app
label.pack()

root.mainloop()


问:
Reduce the number of operations on a simple expression
Lets say I take a computation that involves only addition and multiplication:

```<code>(a+b)*(c+d)
</code>```

which can be done in many other ways, eg.

```<code>a*(c+d) + b*(c+d)
a*c + a*d + b*c + b*d
</code>```

In terms of additions and multiplications the number of operations required for each of the three examples shown are (2,1) (3,2) (3,4) respectively. Clearly, if the goal is to reduce the total number of operations the first is superior. Is there a way, given an arbitrary expression to find the computation order that requires the least number of operations?

Note: This question is being re-asked from SE.math for the insight and perspective of the CS crowd.

答:
One idea - let's consider the variables as boolean values and write the maxterm form
link text</p>

ContentLicense: CC BY-SA 2.5

Body:
Lets say I take a computation that involves only addition and multiplication:

(a+b)*(c+d)

which can be done in many other ways, eg.

a*(c+d) + b*(c+d)
a*c + a*d + b*c + b*d

In terms of additions and multiplications the number of operations required for each of the three examples shown are (2,1) (3,2) (3,4) respectively. Clearly, if the goal is to reduce the total number of operations the first is superior. Is there a way, given an arbitrary expression to find the computation order that requires the least number of operations?

Note: This question is being re-asked from SE.math for the insight and perspective of the CS crowd.


问:
WebService Client Generation Error with JDK8
I need to consume a web service in my project. I use NetBeans so I right-clicked on my project and tried to add a new "Web Service Client". Last time I checked, this was the way to create a web service client. But it resulted in an AssertionError, saying:

java.lang.AssertionError: org.xml.sax.SAXParseException; systemId: jar:file:/path/to/glassfish/modules/jaxb-osgi.jar!/com/sun/tools/xjc/reader/xmlschema/bindinfo/binding.xsd; lineNumber: 52; columnNumber: 88; schema_reference: Failed to read schema document 'xjc.xsd', because 'file' access is not allowed due to restriction set by the accessExternalSchema property.

The default Java platform for NetBeans was JDK8 (Oracle's official version), so when I changed my netbeans.conf file and made JDK7 (from Oracle, as well) as my default, everything worked fine. So I think the problem is with JDK8. Here is my java -version output:

java version "1.8.0"

  Java(TM) SE Runtime Environment (build 1.8.0-b132)

  Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)

For now, I'm keeping JDK7 as my default Java platform. If there is a way to make JDK8 work please share.

答:
A very simple portable solution would be, to place the following line of code somewhere in a crucial part of your code, a part of which you are sure that it will be run (for example right in the main method): </p>

```<code>System.setProperty("javax.xml.accessExternalDTD", "all");
</code>```

<p>This sets the needed system property programmatically, without having to do tricky maven pom.xml changes (which for some reason didn't work for me). </p>

Body:
A very simple portable solution would be, to place the following line of code somewhere in a crucial part of your code, a part of which you are sure that it will be run (for example right in the main method):

System.setProperty("javax.xml.accessExternalDTD", "all");

This sets the needed system property programmatically, without having to do tricky maven pom.xml changes (which for some reason didn't work for me).


问:
Initialize static function pointer in constructor
I am trying to declare a class-member function pointer as static so it can be called by a static member function, and assign the pointer to a function passed to the constructor.

So far I haven't been able to get it working, is this somehow possible?

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

//external callback function
static void innerFunc(int i, float f){
    printf("running inner function : %i %f\n", i, f);
}

class A{
// member function pointer
typedef void (A::*cbPtr)(int, float);
static cbPtr cbptr;

public:

//constructor
A(void(*func)(int, float))
{
   A::cbptr = func; // < this doesn't work
}

void run()
{
   memberFunc(5, 4.4, NULL, NULL);
}

private:
// static member function
static void memberFunc(int i, float f, void* a, const void* aa)
{
    printf("running outer function.\n");
  //  cbptr(i, f);  // << I want to be able to call the function here

}

};

int main() {

    A a(innerFunc);
    a.run();
    return 0;
}
</code>```

答:
The A::cbPtr type expects a pointer to a non-static member function of the A class.  But you are trying to assign a pointer to a non-member function to your static cbptr variable.  They are two different types, that is why the code does not compile.

Drop the A:: from your cbPtr typedef, eg:

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

//external callback function
static void innerFunc(int i, float f)
{
    printf("running inner function : %i %f\n", i, f);
}

class A
{
public:
    // non-member function pointer
    typedef void (*cbPtr)(int, float);

    //constructor
    A(cbPtr func)
    {
        m_cbptr = func;
    }

    void run()
    {
        memberFunc(5, 4.4, NULL, NULL);
    }

private:
    static cbPtr m_cbptr;

    // static member function
    static void memberFunc(int i, float f, void* a, const void* aa)
    {
        printf("running outer function.\n");
        m_cbptr(i, f);
    }
};

A::cbPtr A::m_cbptr = NULL;

int main()
{
    A a(innerFunc);
    a.run();
    return 0;
}
</code>```

When you learn how to separate your declarations and definitions into .h and .cpp files, it would look more like this instead:

A.h:

```<code>#ifndef A_H
#define A_H

class A
{
public:
    // non-member function pointer
    typedef void (*cbPtr)(int, float);

    //constructor
    A(cbPtr func);

    void run();

private:
    static cbPtr m_cbptr;

    // static member function
    static void memberFunc(int i, float f, void* a, const void* aa);
};

#endif
</code>```

A.cpp:

```<code>#include "A.h"
#include <stdio.h>

A::cbPtr A::m_cbptr = NULL;

A::A(A::cbPtr func)
{
    m_cbptr = func;
}

void A::run()
{
    memberFunc(5, 4.4, NULL, NULL);
}

void A::memberFunc(int i, float f, void* a, const void* aa)
{
    printf("running outer function.\n");
    m_cbptr(i, f);
}
</code>```

main.cpp:

```<code>#include "A.h"
#include <stdio.h>

//external callback function
static void innerFunc(int i, float f)
{
    printf("running inner function : %i %f\n", i, f);
}

int main()
{
    A a(innerFunc);
    a.run();
    return 0;
}
</code>```

Either way, just know that because m_cbptr is static, multiple instances of A will share the same variable, so you won't be able to have separate callbacks for different A objects.  If memberFunc() were not static, or if its a or aa parameter is a user-defined value that can be set to point at the A object's this pointer, then you can have a separate callback per object.

Body:
I am trying to declare a class-member function pointer as static so it can be called by a static member function, and assign the pointer to a function passed to the constructor.

So far I haven't been able to get it working, is this somehow possible?

#include <stdio.h>

//external callback function
static void innerFunc(int i, float f){
    printf("running inner function : %i %f\n", i, f);
}

class A{
// member function pointer
typedef void (A::*cbPtr)(int, float);
static cbPtr cbptr;

public:

//constructor
A(void(*func)(int, float))
{
   A::cbptr = func; // < this doesn't work
}

void run()
{
   memberFunc(5, 4.4, NULL, NULL);
}

private:
// static member function
static void memberFunc(int i, float f, void* a, const void* aa)
{
    printf("running outer function.\n");
  //  cbptr(i, f);  // << I want to be able to call the function here

}

};

int main() {

    A a(innerFunc);
    a.run();
    return 0;
}

Body:
The A::cbPtr type expects a pointer to a non-static member function of the A class.  But you are trying to assign a pointer to a non-member function to your static cbptr variable.  They are two different types, that is why the code does not compile.

Drop the A:: from your cbPtr typedef, eg:

#include <stdio.h>

//external callback function
static void innerFunc(int i, float f)
{
    printf("running inner function : %i %f\n", i, f);
}

class A
{
public:
    // non-member function pointer
    typedef void (*cbPtr)(int, float);

    //constructor
    A(cbPtr func)
    {
        m_cbptr = func;
    }

    void run()
    {
        memberFunc(5, 4.4, NULL, NULL);
    }

private:
    static cbPtr m_cbptr;

    // static member function
    static void memberFunc(int i, float f, void* a, const void* aa)
    {
        printf("running outer function.\n");
        m_cbptr(i, f);
    }
};

A::cbPtr A::m_cbptr = NULL;

int main()
{
    A a(innerFunc);
    a.run();
    return 0;
}

When you learn how to separate your declarations and definitions into .h and .cpp files, it would look more like this instead:

A.h:

#ifndef A_H
#define A_H

class A
{
public:
    // non-member function pointer
    typedef void (*cbPtr)(int, float);

    //constructor
    A(cbPtr func);

    void run();

private:
    static cbPtr m_cbptr;

    // static member function
    static void memberFunc(int i, float f, void* a, const void* aa);
};

#endif

A.cpp:

#include "A.h"
#include <stdio.h>

A::cbPtr A::m_cbptr = NULL;

A::A(A::cbPtr func)
{
    m_cbptr = func;
}

void A::run()
{
    memberFunc(5, 4.4, NULL, NULL);
}

void A::memberFunc(int i, float f, void* a, const void* aa)
{
    printf("running outer function.\n");
    m_cbptr(i, f);
}

main.cpp:

#include "A.h"
#include <stdio.h>

//external callback function
static void innerFunc(int i, float f)
{
    printf("running inner function : %i %f\n", i, f);
}

int main()
{
    A a(innerFunc);
    a.run();
    return 0;
}

Either way, just know that because m_cbptr is static, multiple instances of A will share the same variable, so you won't be able to have separate callbacks for different A objects.  If memberFunc() were not static, or if its a or aa parameter is a user-defined value that can be set to point at the A object's this pointer, then you can have a separate callback per object.


答:
You had wrong expression, it is basically comparing with Approved||Not Approved as string check. Better you could make use indexOf valid statuses array to make your implementation more compact.

```<code>ng-disabled="prod.Product_Status === isDisabled(prod.Product_Status)"
</code>```

Code

```<code>//later you can add more status here in this array.
var validStatus = ['Approved', 'Not Approved'];
$scope.isDisabled = function isDisabled(product_Status){
  return validStatus.indexOf(product_Status) > -1
}
</code>```

Body:
You had wrong expression, it is basically comparing with Approved||Not Approved as string check. Better you could make use indexOf valid statuses array to make your implementation more compact.

ng-disabled="prod.Product_Status === isDisabled(prod.Product_Status)"

Code

//later you can add more status here in this array.
var validStatus = ['Approved', 'Not Approved'];
$scope.isDisabled = function isDisabled(product_Status){
  return validStatus.indexOf(product_Status) > -1
}


问:
Duplicate files copied in APK when building with gradle in Android Studio
I'm getting the following error while trying to build my project:

```<code>Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK org/bytedeco/javacpp/windows-x86/msvcp120.dll
    File1: C:\Users\yuh5\.gradle\caches\modules-2\files-2.1\org.bytedeco.javacpp-presets\opencv\3.1.0-1.3\3d455d0c218e90072827d5b22b4163b1eea323e9\opencv-3.1.0-1.3-windows-x86.jar
    File2: C:\Users\yuh5\.gradle\caches\modules-2\files-2.1\org.bytedeco.javacpp-presets\hdf5\1.10.0-patch1-1.3\76b579910f51cd628bed8f6cbb245670483b9eeb\hdf5-1.10.0-patch1-1.3-windows-x86.jar
</code>```

Here is my gradle build script:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.1"

```<code>defaultConfig {
    applicationId "com.yuh5.nih.testall"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/INDEX.LIST'
    }
}
dependencies {
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile project(':libraries:opencv')
    compile 'org.deeplearning4j:deeplearning4j-core:0.8.0'
    compile 'org.nd4j:nd4j-native:0.8.0'
    compile 'org.nd4j:nd4j-native:0.8.0:android-x86'
    compile 'org.nd4j:nd4j-native:0.8.0:android-arm'
}
</code>```

答:
try this :</p>

```<code>packagingOptions {

   exclude 'META-INF/DEPENDENCIES.txt'
   exclude 'META-INF/LICENSE.txt'
   exclude 'META-INF/NOTICE.txt'
   exclude 'META-INF/NOTICE'
   exclude 'META-INF/LICENSE'
   exclude 'META-INF/DEPENDENCIES'
   exclude 'META-INF/notice.txt'
   exclude 'META-INF/license.txt'
   exclude 'META-INF/dependencies.txt'
   exclude 'META-INF/LGPL2.1'

   }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting the following error while trying to build my project:

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK org/bytedeco/javacpp/windows-x86/msvcp120.dll
    File1: C:\Users\yuh5\.gradle\caches\modules-2\files-2.1\org.bytedeco.javacpp-presets\opencv\3.1.0-1.3\3d455d0c218e90072827d5b22b4163b1eea323e9\opencv-3.1.0-1.3-windows-x86.jar
    File2: C:\Users\yuh5\.gradle\caches\modules-2\files-2.1\org.bytedeco.javacpp-presets\hdf5\1.10.0-patch1-1.3\76b579910f51cd628bed8f6cbb245670483b9eeb\hdf5-1.10.0-patch1-1.3-windows-x86.jar

Here is my gradle build script:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.1"

defaultConfig {
    applicationId "com.yuh5.nih.testall"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/INDEX.LIST'
    }
}
dependencies {
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile project(':libraries:opencv')
    compile 'org.deeplearning4j:deeplearning4j-core:0.8.0'
    compile 'org.nd4j:nd4j-native:0.8.0'
    compile 'org.nd4j:nd4j-native:0.8.0:android-x86'
    compile 'org.nd4j:nd4j-native:0.8.0:android-arm'
}

Body:
try this :

packagingOptions {

   exclude 'META-INF/DEPENDENCIES.txt'
   exclude 'META-INF/LICENSE.txt'
   exclude 'META-INF/NOTICE.txt'
   exclude 'META-INF/NOTICE'
   exclude 'META-INF/LICENSE'
   exclude 'META-INF/DEPENDENCIES'
   exclude 'META-INF/notice.txt'
   exclude 'META-INF/license.txt'
   exclude 'META-INF/dependencies.txt'
   exclude 'META-INF/LGPL2.1'

   }


问:
Corelocation automatically drops pin when Current Location is found
I am making a map view with CoreLocation.
the problem I'm facing right now is that whenever I found a location.
It sometimes pops back to my current Location.
i haven't tested this bug thoroughly but is it possible to turn this off?
so I can add the pin myself?

Thanks in advance

答:
If you are adding mapview via XIB then in the map view properties panel uncheck the

Shows User Location

or if you are adding it programmatically then do

```<code>[mapView setShowsUserLocation:NO];
</code>```

But then you have to find the location yourself and then add the pin.

Body:
If you are adding mapview via XIB then in the map view properties panel uncheck the

Shows User Location

or if you are adding it programmatically then do

[mapView setShowsUserLocation:NO];

But then you have to find the location yourself and then add the pin.


问:
jQuery select matching text within element
I need a way to pass an element id and a string to a function which selects any occurrences of that string in the element text, which is not already wrapped in a sub element.

I have an existing event handler which performs some actions, including wrapping the text in an element, when a user highlights a section of text. However some strings can be matched automatically without needing to be selected by a user, which is what I am trying to accomplish here. A different event will sometimes produce an element id and a string, and all instances of the string in the element text which are not all ready tagged, should be passed to the event handler as if a user had selected them.

Example:

```<code>var selectionString = 'word';
<p id="1">select this word, but not this <span>word</span>, but yes to this word.</p>

// My approach so far which may not be on the right track.
function selectStringInElement(selectionString, elementId){
    var el = document.getElementById(elementId);
    var selections = el.innerHTML.split(/<.+>/);
    for(var i=0; i < selections.length; i++){
        // if the selection contains the selectionString, find its range, select it, and pass to existing handler.
    }
}
</code>```

Any help would be much appreciated.

答:
Here is JQuery implementation:

JSFiddle

```<code>     selectStringInElement('word','1');

function selectStringInElement(selectionString, elementId)
{

    var $el =  $("#"+elementId);

    $el.contents()
    .filter(function(){
            return this.nodeType === 3 // Only text nodes
     })
    .each(function(){
        this.textContent = this.textContent.replace(new RegExp(selectionString,'g'),"<span class='highlight'>"+selectionString+"</span>");
     });

      // Decoding lt/gt
      var html = $("<textarea/>").html($("#1").html()).val()

      // Replacing original content
      $el.html(html);

     // Attaching onMouseOver events
      console.log($el.find("span.highlight"));
      $el.find("span.highlight").on("mouseover",function(){
            alert($(this).text());
        });
}
</code>```

Result: "word" is surrounded with span tag, and onMouseOver event attached to  that tags.

HTML resulting code:

```<code><p id="1">select this <span class="highlight">word</span>, but not this <span>word</span>, but yes to this <span class="highlight">word</span>.</p>
</code>```

Body:
I need a way to pass an element id and a string to a function which selects any occurrences of that string in the element text, which is not already wrapped in a sub element.

I have an existing event handler which performs some actions, including wrapping the text in an element, when a user highlights a section of text. However some strings can be matched automatically without needing to be selected by a user, which is what I am trying to accomplish here. A different event will sometimes produce an element id and a string, and all instances of the string in the element text which are not all ready tagged, should be passed to the event handler as if a user had selected them.

Example:

var selectionString = 'word';

select this word, but not this word, but yes to this word.

// My approach so far which may not be on the right track.
function selectStringInElement(selectionString, elementId){
    var el = document.getElementById(elementId);
    var selections = el.innerHTML.split(/<.+>/);
    for(var i=0; i < selections.length; i++){
        // if the selection contains the selectionString, find its range, select it, and pass to existing handler.
    }
}

Any help would be much appreciated.

Body:
Here is JQuery implementation:

JSFiddle

     selectStringInElement('word','1');

function selectStringInElement(selectionString, elementId)
{

    var $el =  $("#"+elementId);

    $el.contents()
    .filter(function(){
            return this.nodeType === 3 // Only text nodes
     })
    .each(function(){
        this.textContent = this.textContent.replace(new RegExp(selectionString,'g'),"<span class='highlight'>"+selectionString+"</span>");
     });

      // Decoding lt/gt
      var html = $("<textarea/>").html($("#1").html()).val()

      // Replacing original content
      $el.html(html);

     // Attaching onMouseOver events
      console.log($el.find("span.highlight"));
      $el.find("span.highlight").on("mouseover",function(){
            alert($(this).text());
        });
}

Result: "word" is surrounded with span tag, and onMouseOver event attached to  that tags.

HTML resulting code:

<p id="1">select this <span class="highlight">word</span>, but not this <span>word</span>, but yes to this <span class="highlight">word</span>.</p>


问:
Prevent auto choose which sharing application use
I'm develop an application in Android.

I have a ListView with some image, when I click a row I open ContextMenu and I have two Choise, eliminate the image or sharing with other application.

```<code>    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    Uri r = Util.getImageUri(getActivity().getApplication(), image);
    intent.putExtra(Intent.EXTRA_STREAM, r);
    startActivity(intent);
</code>```

I use this code to sharing the image, but after the first time, every time that I try to share image, the application choose always the first application with wich I send the first image.

How can I prevent it?
I want that user choose every time sharing application.
Thanks.
t

答:
In your phone go to settings-->Apps then select the app which get opens by default then there you will find an option "Open by default" open that option, in there press "Clear Defaults".

Then in your app again you will get the list of application to share with

Body:
I'm develop an application in Android.

I have a ListView with some image, when I click a row I open ContextMenu and I have two Choise, eliminate the image or sharing with other application.

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    Uri r = Util.getImageUri(getActivity().getApplication(), image);
    intent.putExtra(Intent.EXTRA_STREAM, r);
    startActivity(intent);

I use this code to sharing the image, but after the first time, every time that I try to share image, the application choose always the first application with wich I send the first image.

How can I prevent it?
I want that user choose every time sharing application.
Thanks.
t


问:
Alternative to multiple if else statements in JavaScript?
I have an input which contains a dropdown list of 8 items. Depending on the option the user picks, I want to change the value of their input into a a different string value. In order to do this, I am using a ton of if else statements, which make this look very bulky and I would like to condense this if at all possible. I have the following code:

```<code>if (inputFive == "Corporation"){
    inputFive = "534"
} else if (inputFive == "LLC"){
    inputFive = "535"
} else if(inputFive == "LLP"){
    inputFive = "536"
} else if(inputFive == "Partnership"){
    inputFive = "537"
} else if(inputFive == "Sole Proprietorship"){
    inputFive = "538"
} else if(inputFive == "Limited Partnership"){
    inputFive = "539"
} else {
    inputFive = "540"
}
</code>```

As you can see, this looks a little old-school, and I would like to see if there is a better/simpler way to make this happen. Just looking to condense this code if at all possible. I believe that their might be a way to create a dictionary by assigning key/value objects, but I don't know how to do this correctly... All options/hints will be appreciated!

答:
```<code>   // just another way but not faster than others at all
   // so then order is important
   var inputMap = [
          "Corporation","LLC","LLP",
          "Partnership","Sole Proprietorship",
          "Limited Partnership"
        ];
    var res = inputMap.indexOf(input);
    res = res > -1 ? 534 + res : 540;
</code>```

Body:
I have an input which contains a dropdown list of 8 items. Depending on the option the user picks, I want to change the value of their input into a a different string value. In order to do this, I am using a ton of if else statements, which make this look very bulky and I would like to condense this if at all possible. I have the following code:

if (inputFive == "Corporation"){
    inputFive = "534"
} else if (inputFive == "LLC"){
    inputFive = "535"
} else if(inputFive == "LLP"){
    inputFive = "536"
} else if(inputFive == "Partnership"){
    inputFive = "537"
} else if(inputFive == "Sole Proprietorship"){
    inputFive = "538"
} else if(inputFive == "Limited Partnership"){
    inputFive = "539"
} else {
    inputFive = "540"
}

As you can see, this looks a little old-school, and I would like to see if there is a better/simpler way to make this happen. Just looking to condense this code if at all possible. I believe that their might be a way to create a dictionary by assigning key/value objects, but I don't know how to do this correctly... All options/hints will be appreciated!


问:
How to connect Elastic search 5.4 to tcp in java?
Here is my java code to connect with tcp when I am using Elasticsearch version 1.7.2 and it works well but when I am using same code with Elasticsearch 5.4-3 it shows no definition of ImmutableSettings.

```<code>  Client client = null;
    try {
        Settings settings = ImmutableSettings.settingsBuilder()
                .put("client.transport.ignore_cluster_name", true)
                .put("client.transport.sniff", false)
                 .build();
   System.out.print("true");
         client = new TransportClient(settings)
         .addTransportAddress(new InetSocketTransportAddress("10.196.2.215", 9300));
 }
</code>```

There is also no tcp settings in Elasticsearch 5.4-3/config/elasticserch.yml file

答:
There are major changes between the versions that you have specified in the question. If you want to create a connection successfully in the 5.4.3 version, refer the following code snippet.

```<code>import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ElasticSearchClientTest {
    public void clientConnectionTest() throws UnknownHostException {

        // Use any settings here (As you mentioned in the code)
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .put("sniffOnConnectionFault", true).build();

        TransportClient client = new PreBuiltTransportClient(settings);

        // Change the ip address or the host name accordingly.
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
    }
}
</code>```

Use following dependencies in the pom.xml file.

```<code><dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.4.3</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.4.3</version>
</dependency>
</code>```

Body:
Here is my java code to connect with tcp when I am using Elasticsearch version 1.7.2 and it works well but when I am using same code with Elasticsearch 5.4-3 it shows no definition of ImmutableSettings.

  Client client = null;
    try {
        Settings settings = ImmutableSettings.settingsBuilder()
                .put("client.transport.ignore_cluster_name", true)
                .put("client.transport.sniff", false)
                 .build();
   System.out.print("true");
         client = new TransportClient(settings)
         .addTransportAddress(new InetSocketTransportAddress("10.196.2.215", 9300));
 }

There is also no tcp settings in Elasticsearch 5.4-3/config/elasticserch.yml file

Body:
There are major changes between the versions that you have specified in the question. If you want to create a connection successfully in the 5.4.3 version, refer the following code snippet.

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ElasticSearchClientTest {
    public void clientConnectionTest() throws UnknownHostException {

        // Use any settings here (As you mentioned in the code)
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .put("sniffOnConnectionFault", true).build();

        TransportClient client = new PreBuiltTransportClient(settings);

        // Change the ip address or the host name accordingly.
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
    }
}

Use following dependencies in the pom.xml file.

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.4.3</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.4.3</version>
</dependency>


问:
DirectLineJS Client Library
I am trying to use DirectLineJS library in my Web App (HTML5 and Javascript).

I followed the instruction from the following site.

https://github.com/Microsoft/BotFramework-DirectLineJS

Are these instruction applied to Html/Javascript project too. Or, they are the instruction related to nodejs.

Actually I used following unpkg CDN file as written in the instruction.

>> Use the unpkg CDN, e.g.

答:
The namespace has changed. Now you can use DirectLine like this:</p>

```<code>var directLine = new DirectLine.DirectLine({
                        secret: this.secret,
                        webSocket: false,
                        pollingInterval: 1000
                    });
</code>```

Title: DirectLineJS Client Library

Body:
The namespace has changed. Now you can use DirectLine like this:

var directLine = new DirectLine.DirectLine({
                        secret: this.secret,
                        webSocket: false,
                        pollingInterval: 1000
                    });


问:
How to concatenate QuerySets from a list of QuerySet
I come across this syntax on stackoverflow

```<code>from itertools import chain
result_list = list(chain(page_list, article_list, post_list))
</code>```

I need to concatenate a bunch of QuerySets with something like this:

```<code>    prjExpList = list(chain(lvl for lvl in prjlvl))
    prjEnvList = list(chain(env for env in prjEnv))
</code>```

This gives me an error of

```<code>AttributeError: 'QuerySet' object has no attribute '_meta'
</code>```

My goal is to concatenate a bunch of QuerySets that's stored inside a list prjlvl and prjEnv
How do I do that?

答:
Try:

```<code>prjExpList = list(chain.from_iterable(prjlvl))
</code>```

Note that itertools.chain() takes a *args list of iterables, and that you can get the same unpacking behavior from the chain.from_iterable() class method.

See: https://docs.python.org/2/library/itertools.html#itertools.chain

Body:
I come across this syntax on stackoverflow

from itertools import chain
result_list = list(chain(page_list, article_list, post_list))

I need to concatenate a bunch of QuerySets with something like this:

    prjExpList = list(chain(lvl for lvl in prjlvl))
    prjEnvList = list(chain(env for env in prjEnv))

This gives me an error of

AttributeError: 'QuerySet' object has no attribute '_meta'

My goal is to concatenate a bunch of QuerySets that's stored inside a list prjlvl and prjEnv
How do I do that?

Body:
Try:

prjExpList = list(chain.from_iterable(prjlvl))

Note that itertools.chain() takes a *args list of iterables, and that you can get the same unpacking behavior from the chain.from_iterable() class method.

See: https://docs.python.org/2/library/itertools.html#itertools.chain


问:
Fabric.js group/ungroup - individual objects disappear while ungrouping
I have this functions in my angularJS controller:

```<code>    function group(){
    var activegroup = canvas.getActiveGroup();
    var objectsInGroup = activegroup.getObjects();

    activegroup.clone(function(newgroup) {
        canvas.discardActiveGroup();
        objectsInGroup.forEach(function(object) {
            canvas.remove(object);
        });
        canvas.add(newgroup);

    });
}

function ungroup(){
   var activeObject = canvas.getActiveObject();
    if(activeObject.type=="group"){
        var items = activeObject._objects;
        activeObject._restoreObjectsState();
        canvas.remove(activeObject);
        for(var i = 0; i < items.length; i++) {
          canvas.add(items[i]);
          canvas.item(canvas.size()-1).hasControls = true;
        }
    }
        canvas.renderAll();
}
</code>```

Working almost perfectly - jus when I ungroup the objects are not rendered (they are still in the canvas, but not visible). I can select the objects individually even if they are invisible. Selectin multiple object will show them while they are selected – deselecting one will let the other disappear. In short: ungrouping objects will not show as individual objects again.

This applys only to primitives like, box, circle, triangle. Text an images are not affected.

Help is appreciated!

答:
```<code>function ungroup(){
 var activeObject = canvas.getActiveObject();
if(activeObject.type=="group"){
    var items = activeObject._objects;
    alert(items);
    activeObject._restoreObjectsState();
    canvas.remove(activeObject);
    for(var i = 0; i < items.length; i++) {
      canvas.add(items[i]);
      items[i].dirty = true; //set object dirty true
      canvas.item(canvas.size()-1).hasControls = true;
    }

    canvas.renderAll();
 }
}
</code>```

If you set object dirty true, it will render in renderAll() call and redraw again.

Body:
I have this functions in my angularJS controller:

    function group(){
    var activegroup = canvas.getActiveGroup();
    var objectsInGroup = activegroup.getObjects();

    activegroup.clone(function(newgroup) {
        canvas.discardActiveGroup();
        objectsInGroup.forEach(function(object) {
            canvas.remove(object);
        });
        canvas.add(newgroup);

    });
}

function ungroup(){
   var activeObject = canvas.getActiveObject();
    if(activeObject.type=="group"){
        var items = activeObject._objects;
        activeObject._restoreObjectsState();
        canvas.remove(activeObject);
        for(var i = 0; i < items.length; i++) {
          canvas.add(items[i]);
          canvas.item(canvas.size()-1).hasControls = true;
        }
    }
        canvas.renderAll();
}

Working almost perfectly - jus when I ungroup the objects are not rendered (they are still in the canvas, but not visible). I can select the objects individually even if they are invisible. Selectin multiple object will show them while they are selected – deselecting one will let the other disappear. In short: ungrouping objects will not show as individual objects again.

This applys only to primitives like, box, circle, triangle. Text an images are not affected.

Help is appreciated!

Body:
function ungroup(){
 var activeObject = canvas.getActiveObject();
if(activeObject.type=="group"){
    var items = activeObject._objects;
    alert(items);
    activeObject._restoreObjectsState();
    canvas.remove(activeObject);
    for(var i = 0; i < items.length; i++) {
      canvas.add(items[i]);
      items[i].dirty = true; //set object dirty true
      canvas.item(canvas.size()-1).hasControls = true;
    }

    canvas.renderAll();
 }
}

If you set object dirty true, it will render in renderAll() call and redraw again.


问:
How to disable autoplay for Flickity slider after initialization?
I would like to start with the image sliders I have made with Flickity having the autoPlay option set to true. After a period of time I would then like to disable the setting. The reason for this is because the configuration I have with the sliders is quite complicated and I would just like to ensure the user knows how they work and then allow them to use them as they please. I know that the slider stops autoPlay on hover but that is not exactly what I am looking for. I tried to use a setTimeout() function to handle this but was not successful.

LINK TO SIMILAR ISSUE ON FLICKITY GIT REPOSITORY

HTML:

```<code><div class="top-carousel top-carousel-food">
  <div class="carousel-cell">
        {{ 'food--1.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--2.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--3.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--4.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--5.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--6.jpg' | asset_url | img_tag }}
  </div>
</div>
<div class="bottom-carousel bottom-carousel-food">
  <div class="carousel-cell">
        {{ 'food--1.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--2.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--3.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--4.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--5.jpg' | asset_url | img_tag }}
  </div>
  <div class="carousel-cell">
        {{ 'food--6.jpg' | asset_url | img_tag }}
  </div>
</div>
</code>```

jQuery:

```<code>$( document ).ready(function() {

        $('.top-carousel-food').flickity({
            // options
            cellAlign: 'left',
            contain: true,
            lazyLoad: true,
            sync: '.bottom-carousel-food'
        });

        $('.bottom-carousel').flickity({
            // options
            cellAlign: 'left',
            contain: true,
            lazyLoad: true,
            pageDots: false,
            wrapAround: true,
            autoPlay: true
        });

        if ($(window).width() > 767) {

            $('.top-carousel-food').flickity({
                draggable: false,
                pageDots: false,
                prevNextButtons: false
            });

        }

        var $gallery = $('.bottom-carousel-food').flickity();

        $gallery.on( 'staticClick.flickity', function( event, pointer, cellElem, cellIndex ) {
            if ( cellIndex !== undefined ) {
                $gallery.flickity( 'select', cellIndex );
            }
        });

        $('.bottom-carousel').flickity( options );

        setTimeout(function() {
            options.autoPlay = false;
        }, 5000);

    });
</code>```

答:
```<code>// external js: flickity.pkgd.js

var $carousel = $('.carousel').flickity({
  autoPlay: true,
});

var flkty = $carousel.data('flickity');
var autoplayCount = 0;

$carousel.on( 'select.flickity', onSelect );

function onSelect() {
  if ( flkty.player.state != 'playing' ) {
    disableAutoplay()
    return;
  }
  // stop after 2 advances
  autoplayCount++;
  if ( autoplayCount >= 2 ) {
    disableAutoplay();
  }
}

function disableAutoplay() {
  $carouse.flickity('stopPlayer');
  $carousel.off( 'select.flickity', onSelect );
}
</code>```

Body:
I would like to start with the image sliders I have made with Flickity having the autoPlay option set to true. After a period of time I would then like to disable the setting. The reason for this is because the configuration I have with the sliders is quite complicated and I would just like to ensure the user knows how they work and then allow them to use them as they please. I know that the slider stops autoPlay on hover but that is not exactly what I am looking for. I tried to use a setTimeout() function to handle this but was not successful.

LINK TO SIMILAR ISSUE ON FLICKITY GIT REPOSITORY

HTML:

        {{ 'food--1.jpg' | asset_url | img_tag }}

        {{ 'food--2.jpg' | asset_url | img_tag }}

        {{ 'food--3.jpg' | asset_url | img_tag }}

        {{ 'food--4.jpg' | asset_url | img_tag }}

        {{ 'food--5.jpg' | asset_url | img_tag }}

        {{ 'food--6.jpg' | asset_url | img_tag }}

        {{ 'food--1.jpg' | asset_url | img_tag }}

        {{ 'food--2.jpg' | asset_url | img_tag }}

        {{ 'food--3.jpg' | asset_url | img_tag }}

        {{ 'food--4.jpg' | asset_url | img_tag }}

        {{ 'food--5.jpg' | asset_url | img_tag }}

        {{ 'food--6.jpg' | asset_url | img_tag }}

jQuery:

$( document ).ready(function() {

        $('.top-carousel-food').flickity({
            // options
            cellAlign: 'left',
            contain: true,
            lazyLoad: true,
            sync: '.bottom-carousel-food'
        });

        $('.bottom-carousel').flickity({
            // options
            cellAlign: 'left',
            contain: true,
            lazyLoad: true,
            pageDots: false,
            wrapAround: true,
            autoPlay: true
        });

        if ($(window).width() > 767) {

            $('.top-carousel-food').flickity({
                draggable: false,
                pageDots: false,
                prevNextButtons: false
            });

        }

        var $gallery = $('.bottom-carousel-food').flickity();

        $gallery.on( 'staticClick.flickity', function( event, pointer, cellElem, cellIndex ) {
            if ( cellIndex !== undefined ) {
                $gallery.flickity( 'select', cellIndex );
            }
        });

        $('.bottom-carousel').flickity( options );

        setTimeout(function() {
            options.autoPlay = false;
        }, 5000);

    });


问:
VBA Code for Filtering up through the current month
I have a sheet of work orders that have a column of complete by dates. I am trying to filter it down to show all orders with dates in the past going through to the end of the current month (EX: all past orders-End of July 2017).

The current code I'm am using works, but for some reason will not return 7/31/2017. It will return all prior date up to 7/30/2017. Can someone please help.

```<code>Sub Macro3()
Dim dtStart As Date
Dim dtFinal As Date

dtStart = CDate(Evaluate("DATE(YEAR(NOW()),-1,1)"))
dtFinal = CDate(Evaluate("EOMONTH(NOW(),0)"))

ActiveSheet.Range("$A$1:$N$709").AutoFilter 13, ">=" & dtStart, xlAnd, "<=" &
dtFinal, Operator:=xlFilterDynamic
End Sub
</code>```

答:
You can use the WorksheetFunction.EoMonth function, and the DateSerial, and replace your Now with Date, since you don't need to mess with the hours.

Try the line below instead your entire code:

```<code>ActiveSheet.Range("A1:N709").AutoFilter 13, ">=" & DateSerial(Year(Date), -1, 1), _
                              xlAnd, "<=" & WorksheetFunction.EoMonth(Date, 0), _
                              Operator:=xlFilterDynamic
</code>```

Body:
I have a sheet of work orders that have a column of complete by dates. I am trying to filter it down to show all orders with dates in the past going through to the end of the current month (EX: all past orders-End of July 2017).

The current code I'm am using works, but for some reason will not return 7/31/2017. It will return all prior date up to 7/30/2017. Can someone please help.

Sub Macro3()
Dim dtStart As Date
Dim dtFinal As Date

dtStart = CDate(Evaluate("DATE(YEAR(NOW()),-1,1)"))
dtFinal = CDate(Evaluate("EOMONTH(NOW(),0)"))

ActiveSheet.Range("$A$1:$N$709").AutoFilter 13, ">=" & dtStart, xlAnd, "<=" &
dtFinal, Operator:=xlFilterDynamic
End Sub

Body:
You can use the WorksheetFunction.EoMonth function, and the DateSerial, and replace your Now with Date, since you don't need to mess with the hours.

Try the line below instead your entire code:

ActiveSheet.Range("A1:N709").AutoFilter 13, ">=" & DateSerial(Year(Date), -1, 1), _
                              xlAnd, "<=" & WorksheetFunction.EoMonth(Date, 0), _
                              Operator:=xlFilterDynamic


问:
In JPA Query, can I pass the order by property and DESC/ASC order as parameters in the method signature?
I am using spring framework and working repository level implementations.

I have a class:

@Repository
public interface MyClassReadRepository extends ReadRepository<MyClass, Integer>

In this class there is a method that looks like this:

@Query("SELECT a FROM MyClass a WHERE a.type IN :myType ORDER BY :someProperty :someOrder")
Page<MyClass> findByTypeAndOrder(@Param("myType") List<MyType> myType, @Param("someProperty")String someProperty, @Param("someOrder")String someOrder, Pageable pageable)

But apparently the Query structure is wrong: ":someProperty" should be an identifier...

My question is: how to pass order and sort parameters in the example above?

Thanks in advance!

答:
Use:

```<code>PageRequest(page, size, direction, properties)
</code>```

Creates a new PageRequest with sort parameters applied.
Parameters:

page: zero-based page index. (like 5 or 10 etc)

size: the size of the page to be returned. (like 50 or 100 etc)

direction: the direction of the Sort to be specified, can be null. (like Sort.Direction.ASC)

properties: the properties to sort by, must not be null or empty. (like "my column name")

Body:
Use:

PageRequest(page, size, direction, properties)

Creates a new PageRequest with sort parameters applied.
Parameters:

page: zero-based page index. (like 5 or 10 etc)

size: the size of the page to be returned. (like 50 or 100 etc)

direction: the direction of the Sort to be specified, can be null. (like Sort.Direction.ASC)

properties: the properties to sort by, must not be null or empty. (like "my column name")


问:
Null pointer detection in tcc
I created a very simple linked list and noticed a difference in output for tcc filename.c vs tcc filename.c -run for my code:

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

struct llist {
    struct llist *next;
    struct llist *last;
    struct llist *first;
    int value;
    int item;
    int *length;
};

struct llist *newList(int v){

    struct llist *l1 = malloc(sizeof(struct llist));
    l1 -> length = malloc(sizeof(int));
    *l1 -> length = 1;

    l1 -> value = v;
    l1 -> item = 0;
    l1 -> first = l1;

    return l1;
}

struct llist *appendList(struct llist *l1, int v){

    struct llist *l2 = malloc(sizeof(struct llist));

    l2 -> value = v;
    l2 -> last = l1;
    l2 -> first = l1 -> first;
    l2 -> length = l1 -> length;
    *l2 -> length += 1;
    l2 -> item = l1 -> item + 1;

    l1 -> next = l2;

    return l2;
};

int main(){
    struct llist *list = newList(4);
    list = appendList(list, 6);
    list = appendList(list, 8);
    list = appendList(list, 10);

    list = list -> first;

    int end = 0;
    while(end==0){

        printf("VAL: %d\n", list -> value);

        if(list -> next == NULL){
            printf("END\n");
            end = 1;
        }else{

            list = list -> next;
        }
    }

    return 0;
}
</code>```

For compiling with tcc filename.c and then running it produces the output I expected:

```<code>VAL: 4
VAL: 6
VAL: 8
VAL: 10
END
</code>```

It's also the output I get in GCC and clang.

When I use tcc filename.c -run I get:

```<code>VAL: 4
VAL: 6
VAL: 8
VAL: 10
VAL: 27092544
VAL: 1489483720
VAL: 0
END
</code>```

With the last number always being zero and the other two extra values being different every time I run.

I figured out the solution which was adding l1 -> next = NULL; in the newList function and l2 -> next = NULL; in the appendList function.

But I was wondering why there was a difference in output. Is there a bug in the compiler or was I wrong for not initialising the pointer to NULL even though it works in most compilers?

答:
The function calloc() returns a pointer to a sequence of bytes that are initialized to zero; malloc(), by comparison, returns a pointer to a sequence of bytes that may or may not happen to initially contain zero.  On some platforms, those bytes will always contain zero after a malloc(); on others, at least some of them never will.  Generally, it's unpredictable which bytes will hold zero and which won't.

On most platforms, including nearly all that have been created in the last couple decades, clearing all of the bytes of a pointer object will set the pointer to NULL.  On platforms that document such behavior, using "calloc" rather than "malloc" to create space for a structure containing pointers would be a reliable way of initializing to NULL all pointers therein.  If one creates storage with "malloc" or "realloc" rather than "calloc", however, it will be necessary to either use "memset" to set all the bytes to zero, or else expressly set pointers contained therein to NULL.

Title: Null pointer detection in tcc

Body:
I created a very simple linked list and noticed a difference in output for tcc filename.c vs tcc filename.c -run for my code:

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

struct llist {
    struct llist *next;
    struct llist *last;
    struct llist *first;
    int value;
    int item;
    int *length;
};

struct llist *newList(int v){

    struct llist *l1 = malloc(sizeof(struct llist));
    l1 -> length = malloc(sizeof(int));
    *l1 -> length = 1;

    l1 -> value = v;
    l1 -> item = 0;
    l1 -> first = l1;

    return l1;
}

struct llist *appendList(struct llist *l1, int v){

    struct llist *l2 = malloc(sizeof(struct llist));

    l2 -> value = v;
    l2 -> last = l1;
    l2 -> first = l1 -> first;
    l2 -> length = l1 -> length;
    *l2 -> length += 1;
    l2 -> item = l1 -> item + 1;

    l1 -> next = l2;

    return l2;
};

int main(){
    struct llist *list = newList(4);
    list = appendList(list, 6);
    list = appendList(list, 8);
    list = appendList(list, 10);

    list = list -> first;

    int end = 0;
    while(end==0){

        printf("VAL: %d\n", list -> value);

        if(list -> next == NULL){
            printf("END\n");
            end = 1;
        }else{

            list = list -> next;
        }
    }

    return 0;
}

For compiling with tcc filename.c and then running it produces the output I expected:

VAL: 4
VAL: 6
VAL: 8
VAL: 10
END

It's also the output I get in GCC and clang.

When I use tcc filename.c -run I get:

VAL: 4
VAL: 6
VAL: 8
VAL: 10
VAL: 27092544
VAL: 1489483720
VAL: 0
END

With the last number always being zero and the other two extra values being different every time I run.

I figured out the solution which was adding l1 -> next = NULL; in the newList function and l2 -> next = NULL; in the appendList function.

But I was wondering why there was a difference in output. Is there a bug in the compiler or was I wrong for not initialising the pointer to NULL even though it works in most compilers?


问:
Datepart Calculation in Where clause
I am having problem with the datepart calculation in the Where clause of a query. The query returns result without the calculation but nothing if i add the condition.</p>

```<code>DECLARE @StatusId INT;
SELECT @StatusId = Id FROM company.Status WHERE Name = 'Signed' AND CompanyId = 1;

SELECT FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd') AS newDate,
    SUM(CASE WHEN cont.UpdatedDate IS NOT NULL THEN 1 ELSE 0 END) AS TotalSignedLeads
FROM client.testw cont
WHERE cont.CompanyId = 1
    AND cont.AffiliateId = 1
    AND cont.CreatedDate BETWEEN '7-01-2017' AND '7-09-2017'
    AND DATEPART(dw, cont.CreatedDate) NOT IN (1, 7) //This causes problem.
    AND cont.StatusId = @StatusId
GROUP BY CAST(cont.CreatedDate AS DATE)
ORDER BY newDate ;

This is the data above query gives without the datepart condition.
newDate  TotalSignedLeads
07/08    7
</code>```

答:
I suspect that you want a query more like this:

```<code>SELECT FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd') AS newDate,
       COUNT(cont.UpdatedDate) AS TotalSignedLeads
FROM client.testw cont
WHERE cont.CompanyId = 1 AND
      cont.AffiliateId = 1 AND
      cont.CreatedDate BETWEEN '2017-07-01' AND '2017-09-01' AND
      DATEPART(dw, CAST(cont.CreatedDate AS DATE)) NOT IN (1, 7) AND //This causes problem.
      cont.StatusId = @StatusId
GROUP BY FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd')
ORDER BY newDate ;
</code>```

Changes:

The dates for comparison are in a standard format, so they should be interpreted correctly.

The GROUP BY uses the same structure as the SELECT for the columns.

The SUM(CASE) is replaced by the much simpler COUNT().

The value for CreatedDate is cast as a DATE.  To be honest, I'm not sure that will fix any problem, because that should be happening anyway.

Title: Datepart Calculation in Where clause

Body:
I am having problem with the datepart calculation in the Where clause of a query. The query returns result without the calculation but nothing if i add the condition.

DECLARE @StatusId INT;
SELECT @StatusId = Id FROM company.Status WHERE Name = 'Signed' AND CompanyId = 1;

SELECT FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd') AS newDate,
    SUM(CASE WHEN cont.UpdatedDate IS NOT NULL THEN 1 ELSE 0 END) AS TotalSignedLeads
FROM client.testw cont
WHERE cont.CompanyId = 1
    AND cont.AffiliateId = 1
    AND cont.CreatedDate BETWEEN '7-01-2017' AND '7-09-2017'
    AND DATEPART(dw, cont.CreatedDate) NOT IN (1, 7) //This causes problem.
    AND cont.StatusId = @StatusId
GROUP BY CAST(cont.CreatedDate AS DATE)
ORDER BY newDate ;

This is the data above query gives without the datepart condition.
newDate  TotalSignedLeads
07/08    7

Body:
I suspect that you want a query more like this:

SELECT FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd') AS newDate,
       COUNT(cont.UpdatedDate) AS TotalSignedLeads
FROM client.testw cont
WHERE cont.CompanyId = 1 AND
      cont.AffiliateId = 1 AND
      cont.CreatedDate BETWEEN '2017-07-01' AND '2017-09-01' AND
      DATEPART(dw, CAST(cont.CreatedDate AS DATE)) NOT IN (1, 7) AND //This causes problem.
      cont.StatusId = @StatusId
GROUP BY FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd')
ORDER BY newDate ;

Changes:

The dates for comparison are in a standard format, so they should be interpreted correctly.

The GROUP BY uses the same structure as the SELECT for the columns.

The SUM(CASE) is replaced by the much simpler COUNT().

The value for CreatedDate is cast as a DATE.  To be honest, I'm not sure that will fix any problem, because that should be happening anyway.


问:
Python3 - Pyqt5 how to end loops in threads by exception or pressing the exit button
Im new to python and pyqt and have a problem I was not able to solve yet:
The following program has 3 while loops in its GUI, running from a value to zero. Ive put those loops in seperate QThreads to execute them at the same time.
Problem: if I press the exit button of the window, loops go on and still run in the console, putting out the threadcount (which is why I know they`re still running). How can I stop this by exiting the program?

Sorry for the messy code. As I said, python is new to me...

Main class:

```<code>class Application(QtWidgets.QMainWindow):
    counter = pyqtSignal(int)
    counting = False
    #QtWidgets.QWidget

    def __init__(self, name):
        super(Application, self).__init__()
        self.setupUi(self)
</code>```

One of the loops put in a thread:

```<code>#Start des Reinigungsprozesses Becken 1
def becken1start(self):
    self.sekunden1 = value1 * 60
    if self.pushButton1.isChecked():
        if  value1 == 0:
            self.pushButton1.setChecked(False)
            self.showMessageBox('Bitte Laufzeit der Reinigung wählen')
        else:
            thread = threading.Thread(target=self.run1)
            thread.start()
            print("Active Threads :", threading.activeCount())
    else:
        pass

#Ausführen des Threads für den Countdown Becken 1
def run1(self):
    while self.sekunden1 > -1:
        sleep(1)
        GPIO.setup(2, GPIO.OUT)
        GPIO.output(2, GPIO.LOW)
        self.dial1.setDisabled(True)
        self.lcdNumber1.display(self.sekunden1)
        self.pushButton1.setText("läuft")
        #QtWidgets.qApp.processEvents()
        print("Active Threads :", threading.activeCount())
        self.sekunden1-=1
        if self.pushButton1.isChecked():
            continue
        else:
            break
    self.dial1.setDisabled(False)
    self.pushButton1.setText("BECKEN 1")
    self.lcdNumber1.display(value1)
    self.pushButton1.setChecked(False)
    GPIO.output(2, GPIO.HIGH)
</code>```

Exit part:

```<code>if __name__ == "__main__":
    import sys
    sys._excepthook = sys.excepthook
    def my_exception_hook(exctype, value, traceback):
        print(exctype, value, traceback)
        sys._excepthook(exctype, value, traceback)
        sys.exit()

    sys.excepthook = my_exception_hook
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Application(threading.Thread)
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
</code>```

答:
```<code>#Start des Reinigungsprozesses Becken 1
def becken1start(self):
    self.sekunden1 = value1 * 60
    if self.pushButton1.isChecked():
        if  value1 == 0:
            self.pushButton1.setChecked(False)
            self.showMessageBox('Bitte Laufzeit der Reinigung wählen')
        else:
            thread = threading.Thread(target=self.run1)
            thread.daemon = True
            thread.start()
            print("Active Threads :", threading.activeCount())
    else:
        pass
</code>```

Making the thread a daemon means the thread won't stay up if the main thread dies.

Body:
Im new to python and pyqt and have a problem I was not able to solve yet:
The following program has 3 while loops in its GUI, running from a value to zero. Ive put those loops in seperate QThreads to execute them at the same time.
Problem: if I press the exit button of the window, loops go on and still run in the console, putting out the threadcount (which is why I know they`re still running). How can I stop this by exiting the program?

Sorry for the messy code. As I said, python is new to me...

Main class:

class Application(QtWidgets.QMainWindow):
    counter = pyqtSignal(int)
    counting = False
    #QtWidgets.QWidget

    def __init__(self, name):
        super(Application, self).__init__()
        self.setupUi(self)

One of the loops put in a thread:

#Start des Reinigungsprozesses Becken 1
def becken1start(self):
    self.sekunden1 = value1 * 60
    if self.pushButton1.isChecked():
        if  value1 == 0:
            self.pushButton1.setChecked(False)
            self.showMessageBox('Bitte Laufzeit der Reinigung wählen')
        else:
            thread = threading.Thread(target=self.run1)
            thread.start()
            print("Active Threads :", threading.activeCount())
    else:
        pass

#Ausführen des Threads für den Countdown Becken 1
def run1(self):
    while self.sekunden1 > -1:
        sleep(1)
        GPIO.setup(2, GPIO.OUT)
        GPIO.output(2, GPIO.LOW)
        self.dial1.setDisabled(True)
        self.lcdNumber1.display(self.sekunden1)
        self.pushButton1.setText("läuft")
        #QtWidgets.qApp.processEvents()
        print("Active Threads :", threading.activeCount())
        self.sekunden1-=1
        if self.pushButton1.isChecked():
            continue
        else:
            break
    self.dial1.setDisabled(False)
    self.pushButton1.setText("BECKEN 1")
    self.lcdNumber1.display(value1)
    self.pushButton1.setChecked(False)
    GPIO.output(2, GPIO.HIGH)

Exit part:

if __name__ == "__main__":
    import sys
    sys._excepthook = sys.excepthook
    def my_exception_hook(exctype, value, traceback):
        print(exctype, value, traceback)
        sys._excepthook(exctype, value, traceback)
        sys.exit()

    sys.excepthook = my_exception_hook
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Application(threading.Thread)
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

Body:
#Start des Reinigungsprozesses Becken 1
def becken1start(self):
    self.sekunden1 = value1 * 60
    if self.pushButton1.isChecked():
        if  value1 == 0:
            self.pushButton1.setChecked(False)
            self.showMessageBox('Bitte Laufzeit der Reinigung wählen')
        else:
            thread = threading.Thread(target=self.run1)
            thread.daemon = True
            thread.start()
            print("Active Threads :", threading.activeCount())
    else:
        pass

Making the thread a daemon means the thread won't stay up if the main thread dies.


问:
make html.checkboxfor enable true false
I have a kendo combobox and i have a keno html.checkboxfor control. I need to make that checkbox enable true or false base on the selected text value from the combox i am using the following code but its not working for me. I need some suggestions.</p>

```<code><tr>
    <td>Status Reason</td>
    <td>
        <div id="options">
            @(Html.Kendo().ComboBox()
                .Name("StatusReasons")
                .Placeholder("Select Status...")
                .BindTo(Model.StatusReason)
                .DataTextField("statusName")
                .DataValueField("statusIndex")
                .SelectedIndex(Convert.ToInt32(Model.StatusReasonID) - 1)
                .Events(e => e.Select("enableButton"))
                .DataSource(source =>
                {
                    source.Read(read =>
                    {
                        read.Action("GetStatusReasons", "Home");
                    });
                })
                .Suggest(true)
                .HtmlAttributes(Model.Editable ? new { tabindex = "2" } : (object)new { style = "width:200px", /*disabled = "disabled",*/ tabindex = "2" })
            )

        </div>
    </td>
    <td>
        Name: @Html.CheckBoxFor(model => model.Name, new { disabled = true, value = "false" })
    </td>
    <td>
        Name 2: @Html.CheckBoxFor(model => model.ReissueDeduction, new { disabled = true, value = "false" })
    </td>
</tr>

function enableButton(e)
{
    if (e.item) {
        var dataItem = this.dataItem(e.item.index());

        if (dataItem.statusName == 'Reissue')
        {
            //make check box enable
        } else {
            //make check box disable
        }
    }
}
</code>```

答:
Using jquery:

To disable:

```<code>$("#ReissueDeduction").attr("disabled", true);
</code>```

To enable:

```<code>$("#ReissueDeduction").removeAttr("disabled");
</code>```

Title: make html.checkboxfor enable true false

Body:
I have a kendo combobox and i have a keno html.checkboxfor control. I need to make that checkbox enable true or false base on the selected text value from the combox i am using the following code but its not working for me. I need some suggestions.

    Status Reason

            @(Html.Kendo().ComboBox()
                .Name("StatusReasons")
                .Placeholder("Select Status...")
                .BindTo(Model.StatusReason)
                .DataTextField("statusName")
                .DataValueField("statusIndex")
                .SelectedIndex(Convert.ToInt32(Model.StatusReasonID) - 1)
                .Events(e => e.Select("enableButton"))
                .DataSource(source =>
                {
                    source.Read(read =>
                    {
                        read.Action("GetStatusReasons", "Home");
                    });
                })
                .Suggest(true)
                .HtmlAttributes(Model.Editable ? new { tabindex = "2" } : (object)new { style = "width:200px", /*disabled = "disabled",*/ tabindex = "2" })
            )

        Name: @Html.CheckBoxFor(model => model.Name, new { disabled = true, value = "false" })

        Name 2: @Html.CheckBoxFor(model => model.ReissueDeduction, new { disabled = true, value = "false" })

function enableButton(e)
{
    if (e.item) {
        var dataItem = this.dataItem(e.item.index());

        if (dataItem.statusName == 'Reissue')
        {
            //make check box enable
        } else {
            //make check box disable
        }
    }
}

Body:
Using jquery:

To disable:

$("#ReissueDeduction").attr("disabled", true);

To enable:

$("#ReissueDeduction").removeAttr("disabled");


问:
getbounds on google api v2 is not working
getbounds() return error on firebug. May I know what is the problem? Thanks.

```<code>map=new GMap2(document.getElementbyId('map'));
map.setCenter(new GLatLng(la,lo),15);
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
map.enableScrollWheelZoom();
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var southEast = bounds.getSouthEast();
var northWest = bounds.getNorthWest();
</code>```

Firebug states that getSouthWest() is not a functions. Thank you.

答: Maybe you should wait until the map fires load event.

Body:
getbounds() return error on firebug. May I know what is the problem? Thanks.

map=new GMap2(document.getElementbyId('map'));
map.setCenter(new GLatLng(la,lo),15);
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
map.enableScrollWheelZoom();
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var southEast = bounds.getSouthEast();
var northWest = bounds.getNorthWest();

Firebug states that getSouthWest() is not a functions. Thank you.


问:
signin user upon clicking the link in email automatically in rails application?
I have a User model in my rails application. which is a "devise" model. i have one form called "user-info" form this form can be available once the user logs into the system.

i have one admin login in which an admin can send the link to the user email like fill the "user info" by clicking a button. once the user clicks the button i want the user to login into the system automatically without redirecting to the login page. and should be navigated to the user-info form.

i have an idea of sending query string parameters in the url like email = "x@gmail.com "&& form = "user_info". but once the user clicks on this what needs to be implemented to achieve my requirement.

答: You can use this Simple Token Authentication gem, it is well known to generate the authentication token and to be sent by email to the users you would like to have this authentication. please follow the setup instruction.</p>