问:
Java applets - is it a wrong choice today?
I have some non-trivial computational code that need to be applied on data already downloaded into the browser DOM and captured from user interactions. I do not wish to expose this code. I am wondering if:

Write a webservice and communicate with the browser over websocket or HTTP. The trade-off is speed of interaction (from slick to poor) and higher traffic costs.

Write a Java applet (signed to hide the code) that encapsulates logic within the page and let JavaScript interact with the Java API. I read elsewhere that the Java and JavaScript engine can deadlock in certain scenarios. However, since I am only computing, this is a non-issue. Maybe, on multi-core machines I could divvy up my work using a few more threads.

Write in JavaScript. But JavaScript is difficult to test, and it's all in public eye.

Q&A such as Usability of Java applets on the web and several others are also discouraging.

Are Java applets a dead technology? There aren't even Q&A on this topic these days! Additionally, Java may not always be bundled with all browsers (desktop, tablet or mobile)?

Are there better ways to accomplish the same like hide code, utilize client CPU/RAM, minimize data traffic?

The web pages are on JavaScript, HTML5, and CSS. The server only dishes out JSON and XML. The data packets are 10-20 KB and updated frequently. The computations are expensive and client-specific, so I would really like to use the client to do all that.

答:
John Demetriou presented very good information.

Additionally now (July 2017) only Firefox and Internet Explorer (and maybe Safari not sure) is allowing the usage of applets. You can use them if you meet the following three requirements:

You allow the HTML site which accessing the .class applet file as an exception in the Java control panel

Java is updated to the version the browser supports (most likely latest version)

The .class file is located in the same location as your HTML file!

You access the java applet, by typing the HTML content's location in your browser. You still may receive a prompt, requesting whether to run Java, so just accept.

I only presented this information just to let people that there is a way to run applets. However, applets were disabled for a reason. They allow many security leaks. Use them only to learn their technology and gain some insight. They are not recommended elsewhere.


来源: stackexchange

问:
How to turn off comment notifications for document?
Using Google Script, I'm creating a document monthly in a shared directory by copying an existing document (method File.makeCopy()). The problem is I get email notifications every time someone leaves a comment in the newly created document even though notifications are disabled for the source document. How can I turn the notifications off for a copied document?

The code of the function that performs copying is below:

```<code>function createNewLogFile() {
  var rootDir = DriveApp.getFolderById('0B-gPh8Bs5aLhY2g2QXRFX2hycUU');
  var curDate = new Date();
  var curYear = curDate.getFullYear();
  var nextMonth = curDate.getMonth() + 2;
  nextMonth = (nextMonth < 10) ? '0' + nextMonth : (nextMonth > 12) ? '1' : nextMonth;

  var folderIter = rootDir.getFoldersByName((nextMonth > 12) ? curYear + 1 : curYear);
  var curYearFolder = folderIter.hasNext() ? folderIter.next() : rootDir.createFolder(curYear);
  var fileIter = curYearFolder.getFilesByName(nextMonth);

  if (!fileIter.hasNext()) {
    var gmLogTemplate = DriveApp.getFileById('1Vyd15DDiKqha9zlU_1Q8gRiqDY4Oqgl0VJ1uUYiBnCQ');
    var monthlyLogFile = gmLogTemplate.makeCopy(curYearFolder);
    monthlyLogFile.setName(nextMonth);
  }
}
</code>```

答:
AFAIK, there's already a filed feature request which you can star or you may want to regularly check Release Notes for any updates on this.

Currently, Script Service still doesn't have method that supports this. Also, based from this thread, there's still no way to turn off notifications globally in Docs even in UI.

You may want to check this related SO post and see if it will help you.

ContentLicense: CC BY-SA 4.0

Body:
Using Google Script, I'm creating a document monthly in a shared directory by copying an existing document (method File.makeCopy()). The problem is I get email notifications every time someone leaves a comment in the newly created document even though notifications are disabled for the source document. How can I turn the notifications off for a copied document?

The code of the function that performs copying is below:

function createNewLogFile() {
  var rootDir = DriveApp.getFolderById('0B-gPh8Bs5aLhY2g2QXRFX2hycUU');
  var curDate = new Date();
  var curYear = curDate.getFullYear();
  var nextMonth = curDate.getMonth() + 2;
  nextMonth = (nextMonth < 10) ? '0' + nextMonth : (nextMonth > 12) ? '1' : nextMonth;

  var folderIter = rootDir.getFoldersByName((nextMonth > 12) ? curYear + 1 : curYear);
  var curYearFolder = folderIter.hasNext() ? folderIter.next() : rootDir.createFolder(curYear);
  var fileIter = curYearFolder.getFilesByName(nextMonth);

  if (!fileIter.hasNext()) {
    var gmLogTemplate = DriveApp.getFileById('1Vyd15DDiKqha9zlU_1Q8gRiqDY4Oqgl0VJ1uUYiBnCQ');
    var monthlyLogFile = gmLogTemplate.makeCopy(curYearFolder);
    monthlyLogFile.setName(nextMonth);
  }
}

ContentLicense: CC BY-SA 3.0


问:
Multi line and style Android button with image
My goal is to make button with a rounded image on the left without padding and a multi line text on the right where the 2 lines have different style(color/font). Like this:

My problems are:

I don't know how to implement the multi line button text

The image corners are not rounded on the left

The image is bigger than requested

See my result:

My code is the following:

buttonshape.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <corners android:radius="5dp" />
    <solid android:color="#F7F7F7" />
    <padding
        android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp" />
    <size android:width="270dp"
          android:height="60dp" />
</shape>
</code>```

myActivity.xml:

```<code><Button
    android:id="@+id/parkingBtn"
    android:layout_width="0dp"
    android:layout_height="82dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:background="@drawable/buttonshape"
    android:drawableStart="@drawable/parking"
    android:drawablePadding="20dp"
    android:text="Parking"
    android:textAlignment="viewStart"
    android:textAllCaps="false"
    android:textColor="@color/colorPrimary"
    android:textDirection="ltr"
    android:textSize="18sp"
    android:cropToPadding="true"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/otherBtn" />
</code>```

Update:
I changed to CardView and the result is almost fine. Thanks the tip for @pouya. The problem is that the rounded corners are not visible on the image.

card_layout.xml:

```<code><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    card_view:cardCornerRadius="15dp"
    card_view:cardElevation="2dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/buttonshape15"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="24dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="@drawable/parking" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical"
            android:paddingStart="16dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif"
                android:paddingTop="8dp"
                android:text="Parking"
                android:textColor="@color/colorPrimary"
                android:textSize="24sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8dp"
                android:text="Pay without coins" />
        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>
</code>```

And the result is:

(I have changed the border color and radius for better visibility)

Update 2:
Even closer to the final result. Now border is present, only the shadow is missing:

layout.xml:

```<code><LinearLayout xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/buttonshape15" >

    <android.support.v7.widget.CardView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="15dp"
        card_view:cardElevation="0dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:scaleType="fitXY"
                android:background="@drawable/parking" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="6"
                android:orientation="vertical"
                android:paddingStart="16dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="sans-serif"
                    android:paddingTop="6dp"
                    android:text="Parking"
                    android:textColor="@color/colorPrimary"
                    android:textSize="22sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingTop="3dp"
                    android:text="Pay without coins"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

To solve the shadow problem I have tried to use layer-list in the background.xml but it gives ugly shadows. Wrapping everything again inside a CardView and set the elevation gives better result but not as perfect as the reference layout has.

答:
I would use LinearLayout so that I could have the text right of the rounded image.
The text is actually two different texts.
So use Weight and then you can put them wherever you want.</p>

Body:
My goal is to make button with a rounded image on the left without padding and a multi line text on the right where the 2 lines have different style(color/font). Like this:

My problems are:

I don't know how to implement the multi line button text

The image corners are not rounded on the left

The image is bigger than requested

See my result:

My code is the following:

buttonshape.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <corners android:radius="5dp" />
    <solid android:color="#F7F7F7" />
    <padding
        android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp" />
    <size android:width="270dp"
          android:height="60dp" />
</shape>

myActivity.xml:

<Button
    android:id="@+id/parkingBtn"
    android:layout_width="0dp"
    android:layout_height="82dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:background="@drawable/buttonshape"
    android:drawableStart="@drawable/parking"
    android:drawablePadding="20dp"
    android:text="Parking"
    android:textAlignment="viewStart"
    android:textAllCaps="false"
    android:textColor="@color/colorPrimary"
    android:textDirection="ltr"
    android:textSize="18sp"
    android:cropToPadding="true"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/otherBtn" />

Update:
I changed to CardView and the result is almost fine. Thanks the tip for @pouya. The problem is that the rounded corners are not visible on the image.

card_layout.xml:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    card_view:cardCornerRadius="15dp"
    card_view:cardElevation="2dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/buttonshape15"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="24dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="@drawable/parking" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical"
            android:paddingStart="16dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif"
                android:paddingTop="8dp"
                android:text="Parking"
                android:textColor="@color/colorPrimary"
                android:textSize="24sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8dp"
                android:text="Pay without coins" />
        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>

And the result is:

(I have changed the border color and radius for better visibility)

Update 2:
Even closer to the final result. Now border is present, only the shadow is missing:

layout.xml:

<LinearLayout xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/buttonshape15" >

    <android.support.v7.widget.CardView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="15dp"
        card_view:cardElevation="0dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:scaleType="fitXY"
                android:background="@drawable/parking" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="6"
                android:orientation="vertical"
                android:paddingStart="16dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="sans-serif"
                    android:paddingTop="6dp"
                    android:text="Parking"
                    android:textColor="@color/colorPrimary"
                    android:textSize="22sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingTop="3dp"
                    android:text="Pay without coins"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

To solve the shadow problem I have tried to use layer-list in the background.xml but it gives ugly shadows. Wrapping everything again inside a CardView and set the elevation gives better result but not as perfect as the reference layout has.


问:
Assembly.LoadFrom(...) is relative from first executable
So I have made an updater for my application. It downloads my application (a .dll file) tp %appdata%/Folder and opens it via reflection like this:

```<code>var appdataFolder =
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\[ApplicationName]\";

var mainAssembly = Assembly.LoadFrom(appdataFolder + @"TF2Callout.dll");
mainAssembly.GetType("TF2Callout.App").GetMethod("Main").Invoke(null, null);
</code>```

This opens the .dll and executes the static void Main. But in my application I have this:

```<code>Assembly.LoadFrom("SomeOtherDll.dll");
</code>```

I would expect the application to search for the .dll in the %appdata%/[application name] folder because it is saved there, however, it tries to find the file in the folder of the installer, which is in my program files.

How would I go about fixing this? I would rather not make the SomeOtherDll.dll get loaded from an absolute path, because it might change.

答:
Assembly.LoadFrom behaves as specified at https://msdn.microsoft.com/en-us/library/1009fa28(v=vs.110).aspx :

assemblyFile may be absolute or relative to the current directory, and
  the assembly is loaded into the domain of the caller.

https://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory(v=vs.110).aspx has details about what current directory means.

If you wish to load from a specific location, you must use an absolute path. You may be able to construct that absolute path by using appdataFolder or checking the path of an existing DLL (e.g. How to get the location of the DLL currently executing? ). But fundamentally, if you want the DLL to load reliably, you need to use an absolute path.

Body:
So I have made an updater for my application. It downloads my application (a .dll file) tp %appdata%/Folder and opens it via reflection like this:

var appdataFolder =
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\[ApplicationName]\";

var mainAssembly = Assembly.LoadFrom(appdataFolder + @"TF2Callout.dll");
mainAssembly.GetType("TF2Callout.App").GetMethod("Main").Invoke(null, null);

This opens the .dll and executes the static void Main. But in my application I have this:

Assembly.LoadFrom("SomeOtherDll.dll");

I would expect the application to search for the .dll in the %appdata%/[application name] folder because it is saved there, however, it tries to find the file in the folder of the installer, which is in my program files.

How would I go about fixing this? I would rather not make the SomeOtherDll.dll get loaded from an absolute path, because it might change.


问:
Gtk3 keys bindings in css files
Where can I find an exhaustive list of available keybindings that a user can define in a CSS file for GTK+ 3?

I have already checked those resources:

https://developer.gnome.org/gtk3/stable/GtkCssProvider.html

https://developer.gnome.org/gtk3/stable/gtk3-Bindings.html

/usr/share/themes/Default/gtk-3.0/gtk-keys.css (which is empty)

/usr/share/themes/Emacs/gtk-3.0/gtk-keys.css

For example, how can a user make <Control>Space move the cursor to the end of the text in a GtkTextView?

答:
I think ultimately ntd has the most correct idea, but here is a more browsable solution, rather than grepping through the GIR file.

You should (assuming comprehensive documentation) be able to find this info by going to the documentation page for the widget of interest, then search that page for the term keybinding signal.

The available signals are documented along with the others on each widget's page and then qualified as whether or not they are for key bindings in the description.

Usually you can also identify them by the fact that their value in the 2nd column of the summary table of signals, i.e. signal type flags, is Action, as also pointed out by ntd.

For example, GtkComboBox:move-active:

[handler function signature]

The ::move-active signal is a keybinding signal which gets emitted to move the active selection.

[description of arguments]

As ntd indicated, this can probably be automated to a large extent. Like the GIR, the documentation is generated from the C source files, so if you lack a GIR file or just prefer this way, you can presumably do some clever use of grep, sed, et al. through those to pull out the info.

Title: Gtk3 keys bindings in css files


问:
Mongoose search for element in utmost sub array
My schema is as follows

```<code>{
  product:[{
    structure :[{
      version:[{
        type:[{
          values:[{}]
        }]
      }]
    }]
  }]
}
</code>```

Need to search fields in values array.
Actually I need to update the fields in values array. I'm unable to write query to get sub array values. How can I do that.  Kindly let me know, as soon as possible.

答:
You can use this types of query:

```<code>// match a one name
db.getCollection('test').find({"product.structure.version.type.values.name":'test'})
// match some value from an array
db.getCollection('test').find({"product.structure.version.type.values.name": {$in: [1, 'test']}})
</code>```

Last query will find 3 items in the next collection:

```<code>/* 1 */
{
    "_id" : ObjectId("595b9e17c482ca1b99db23a6"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : 1
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("595b9e68f9f2fe8d79ca4c82"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : 3
                                        },
                                        {
                                            "name" : 4
                                        },
                                        {
                                            "name" : 1
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 3 */
{
    "_id" : ObjectId("595b9e71f9f2fe8d79ca4c84"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : 5
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 4 */
{
    "_id" : ObjectId("595ba08af9f2fe8d79ca4cd9"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : 6
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 5 */
{
    "_id" : ObjectId("595ba0f1f9f2fe8d79ca4d00"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : "test"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}
</code>```

UPDATE:
To do an update query, you need to do something like this:

```<code>db.getCollection('test').update({"product.structure.version.type.values.name": {$in: [1, 'test']}}, {$set: {"product.$.testProp": 'some test string'}}, {multi: true})
</code>```

Body:
My schema is as follows

{
  product:[{
    structure :[{
      version:[{
        type:[{
          values:[{}]
        }]
      }]
    }]
  }]
}

Need to search fields in values array.
Actually I need to update the fields in values array. I'm unable to write query to get sub array values. How can I do that.  Kindly let me know, as soon as possible.

Body:
You can use this types of query:

// match a one name
db.getCollection('test').find({"product.structure.version.type.values.name":'test'})
// match some value from an array
db.getCollection('test').find({"product.structure.version.type.values.name": {$in: [1, 'test']}})

Last query will find 3 items in the next collection:

/* 1 */
{
    "_id" : ObjectId("595b9e17c482ca1b99db23a6"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : 1
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("595b9e68f9f2fe8d79ca4c82"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : 3
                                        },
                                        {
                                            "name" : 4
                                        },
                                        {
                                            "name" : 1
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 3 */
{
    "_id" : ObjectId("595b9e71f9f2fe8d79ca4c84"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : 5
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 4 */
{
    "_id" : ObjectId("595ba08af9f2fe8d79ca4cd9"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : 6
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 5 */
{
    "_id" : ObjectId("595ba0f1f9f2fe8d79ca4d00"),
    "product" : [
        {
            "structure" : [
                {
                    "version" : [
                        {
                            "type" : [
                                {
                                    "values" : [
                                        {
                                            "name" : "test"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

UPDATE:
To do an update query, you need to do something like this:

db.getCollection('test').update({"product.structure.version.type.values.name": {$in: [1, 'test']}}, {$set: {"product.$.testProp": 'some test string'}}, {multi: true})


问:
Javascript force recalculate value of object property
I would like to re-use an "object", however, one of the object's properties values should be recalculated every time the object is accessed.

In my code I have a library which can basically make a list of card views from a data url. This list of card views is added to a page. There are two types of lists: Active Buildings list and Archived Buildings list. Switching between these two lists is done by pressing a button, which triggers the "rerender" function of the repeater shown below.

Archived Buildings should not be clickable. I pass along some configuration options to my library where I handle the relevant parts. However, because of the way I invoke the card view library, the value of the enableClick configuration option is always set to what the state was like at the load of the page.

Example of how the code looks:

```<code>$(function () {
    var buildingsContainer = $('#buildings');
    buildingsContainer.repeater({
        url: function () {
            var activeFilter = buildingFilter.find('.btn-primary').data('status');
            return '/Building/All?status=' + activeFilter;
        },
        renderItem: cardTemplates(buildingsContainer).building({
            activateBuildingUrl: '@(Url.Action("ActivateBuilding", "Building"))/{Id}',
            editUrl: '@(Url.Action("Edit", "Building"))/{Id}',
            deleteBuildingUrl: '@(Url.Action("SoftDeleteBuilding", "Building"))/{Id}',
            enableClick: getActiveFilter() === 'Active'
        })
    })
});

function getActiveFilter() {
    var buildingFilter = $('#buildingFilter');
    return buildingFilter.find('.btn-primary').data('status');
}
</code>```

No matter what the currently pressed button is, enableClick is always set to what it was when the page opened.

To better demonstrate my problem, I have created a JSFiddle:
https://jsfiddle.net/e3xnbxov/

In this JSFiddle, you see I have a options object with a value property. In the button's click listeners I print this value. However, it always remains on Active, even though I switch between Active and Archived. How can I make it so the value of the property is recalculated?

答:
The problem is that the object (options) is created once, and the property is set once.

At the moment that the creation (and property setting) occurs, the 'active' button matches the jQuery selector ($('#container').find('.btn-primary')).

Javascript, like many languages, uses references.  When you set the object's property, it received a reference to the result of the jQuery selector, not the selector (as a method) itself.

You could change it to behave more as you're expecting by creating a method on your object:

```<code>$(function() {
    var options = {
        value: function () {
         return $('#container').find('.btn-primary').data('status')
      }
    };
    var container = $('#container');
    container.find('.btn').click(function() {
        container.find('.btn').removeClass('btn-primary').addClass('btn-default');
        $(this).addClass('btn-primary');
        console.log(options.value());
    });
});
</code>```

Thus your options object now has a callable method which dynamically returns what you were expecting.

Otherwise I'd update the property when the selected button changes:

```<code>$(function() {
    var options = {
        value: $('#container').find('.btn-primary').data('status')
    };
    var container = $('#container');
    container.find('.btn').click(function() {
        container.find('.btn').removeClass('btn-primary').addClass('btn-default');
        $(this).addClass('btn-primary');
    options.value = $('#container').find('.btn-primary').data('status');
        console.log(options.value);
    });
});
</code>```

Body:
I would like to re-use an "object", however, one of the object's properties values should be recalculated every time the object is accessed.

In my code I have a library which can basically make a list of card views from a data url. This list of card views is added to a page. There are two types of lists: Active Buildings list and Archived Buildings list. Switching between these two lists is done by pressing a button, which triggers the "rerender" function of the repeater shown below.

Archived Buildings should not be clickable. I pass along some configuration options to my library where I handle the relevant parts. However, because of the way I invoke the card view library, the value of the enableClick configuration option is always set to what the state was like at the load of the page.

Example of how the code looks:

$(function () {
    var buildingsContainer = $('#buildings');
    buildingsContainer.repeater({
        url: function () {
            var activeFilter = buildingFilter.find('.btn-primary').data('status');
            return '/Building/All?status=' + activeFilter;
        },
        renderItem: cardTemplates(buildingsContainer).building({
            activateBuildingUrl: '@(Url.Action("ActivateBuilding", "Building"))/{Id}',
            editUrl: '@(Url.Action("Edit", "Building"))/{Id}',
            deleteBuildingUrl: '@(Url.Action("SoftDeleteBuilding", "Building"))/{Id}',
            enableClick: getActiveFilter() === 'Active'
        })
    })
});

function getActiveFilter() {
    var buildingFilter = $('#buildingFilter');
    return buildingFilter.find('.btn-primary').data('status');
}

No matter what the currently pressed button is, enableClick is always set to what it was when the page opened.

To better demonstrate my problem, I have created a JSFiddle:
https://jsfiddle.net/e3xnbxov/

In this JSFiddle, you see I have a options object with a value property. In the button's click listeners I print this value. However, it always remains on Active, even though I switch between Active and Archived. How can I make it so the value of the property is recalculated?

Body:
The problem is that the object (options) is created once, and the property is set once.

At the moment that the creation (and property setting) occurs, the 'active' button matches the jQuery selector ($('#container').find('.btn-primary')).

Javascript, like many languages, uses references.  When you set the object's property, it received a reference to the result of the jQuery selector, not the selector (as a method) itself.

You could change it to behave more as you're expecting by creating a method on your object:

$(function() {
    var options = {
        value: function () {
         return $('#container').find('.btn-primary').data('status')
      }
    };
    var container = $('#container');
    container.find('.btn').click(function() {
        container.find('.btn').removeClass('btn-primary').addClass('btn-default');
        $(this).addClass('btn-primary');
        console.log(options.value());
    });
});

Thus your options object now has a callable method which dynamically returns what you were expecting.

Otherwise I'd update the property when the selected button changes:

$(function() {
    var options = {
        value: $('#container').find('.btn-primary').data('status')
    };
    var container = $('#container');
    container.find('.btn').click(function() {
        container.find('.btn').removeClass('btn-primary').addClass('btn-default');
        $(this).addClass('btn-primary');
    options.value = $('#container').find('.btn-primary').data('status');
        console.log(options.value);
    });
});


问:
Configuring and running PHPWord
I'm trying to generate a word template out based on the sample example of PHPWord example. But there is no word template being generated or unable to display the page successfully. I have already filtered out the sample code and only add one section of hello world!

```<code>Code:
<?php
  require_once 'PHPWord.php';
  $PHPWord = new PHPWord();
  $section = $PHPWord->createSection();
  $section->addText('Hello world!');
  header("Cache-Control: public");
  header("Content-Description: File Transfer");
  header("Content-Disposition: attachment; filename=helloWorld.docx");
  header("Content-Type: application/docx");
  header("Content-Transfer-Encoding: binary");
  $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
  $objWriter->save('helloWorld.docx');
  ?>
</code>```

Kindly advise and if i use objwriter->save that helloworld.docx. Would it automatically be in the my web server? Or temp folder?

Thanks!

答:
If you want your web page to force the generated document to be downloaded, just use the following:</p>

```<code>$PHPWord->save('helloWorld.docx', 'Word2007', true);
</code>```

Title: Configuring and running PHPWord

Body:
I'm trying to generate a word template out based on the sample example of PHPWord example. But there is no word template being generated or unable to display the page successfully. I have already filtered out the sample code and only add one section of hello world!

Code:
<?php
  require_once 'PHPWord.php';
  $PHPWord = new PHPWord();
  $section = $PHPWord->createSection();
  $section->addText('Hello world!');
  header("Cache-Control: public");
  header("Content-Description: File Transfer");
  header("Content-Disposition: attachment; filename=helloWorld.docx");
  header("Content-Type: application/docx");
  header("Content-Transfer-Encoding: binary");
  $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
  $objWriter->save('helloWorld.docx');
  ?>

Kindly advise and if i use objwriter->save that helloworld.docx. Would it automatically be in the my web server? Or temp folder?

Thanks!

Body:
If you want your web page to force the generated document to be downloaded, just use the following:

$PHPWord->save('helloWorld.docx', 'Word2007', true);


问:
How to define an array with conditional elements?
How can I define conditional array elements?
I want to do something like this:

```<code>const cond = true;
const myArr = ["foo", cond && "bar"];
</code>```

This works as expected and results in ["foo", "bar"] but if I set cond to false, I get the following result: ["foo", false]

How can I define an array with a conditional element?

答:
You can try with a simple if :</p>

```<code>if(cond) {
    myArr.push("bar");
}
</code>```

Body:
How can I define conditional array elements?
I want to do something like this:

const cond = true;
const myArr = ["foo", cond && "bar"];

This works as expected and results in ["foo", "bar"] but if I set cond to false, I get the following result: ["foo", false]

How can I define an array with a conditional element?

Body:
You can try with a simple if :

if(cond) {
    myArr.push("bar");
}


问:
Please explain use of Option's orNull method
Scala's Option class has an orNull method, whose signature is shown below.

```<code>orNull [A1 >: A](implicit ev : <:<[Null, A1]) : A1
</code>```

I'm bewildered by the implicit thing. Would somebody please explain how it can be used, ideally with an example?

答:
To understand why it is useful, IttayD provided a nice explanation:

So what we would have liked is def
  orNull[A >: Null] = ..... But A is
  already set and we don't want to
  restrict it in the definition of the
  trait. Therefore, orNull expects an
  evidence that A is a nullable type.
  This evidence is in the form of an
  implicit variable (hence the name
  'ev')

In summary, type constraints are useful when you want have methods (eg orNull) on a generic class (eg Option) with more specific constraints (eg Null <: A <: Any) than on the class itself (eg A <: Any).

This is another "feature" that is not built into the language but comes for free thanks to implicit parameters and variance annotations of type parameters. To understand this, look at the definition of <:<:

```<code>// from Predef
sealed abstract class <:<[-From, +To] extends (From => To)
implicit def conforms[A]: A <:< A = new (A <:< A) {def apply(x: A) = x}
</code>```

For

```<code>scala> Some(1).orNull
<console>:10: error: could not find implicit value for parameter ev: <:<[Null,Int]
       Some(1).orNull
</code>```

the compiler looks for an implicit value of type <:<[Null, Int] and will find the method def conforms[A]: A <:< A. So there has to be an A for which <:<[A, A] conforms to <:<[Null, Int]. There is no A for which this holds and as a result the compiler will complain about the missing implicit value.

However, for

```<code>scala> Some("hi").orNull
res21: java.lang.String = hi
</code>```

we are lucky. Now, the compiler tries to find an A for which <:<[A, A] conforms to <:<[Null, String]. This works for A = String, because Null is a subtype of String and the From type parameter of the class <:< is defined as contravariant).

As mentioned, the most intuitive way to think about type constraints is reading it like a type bound (i.e. reading it as Null <: Int). Null does not conform to Int and there is no implicit value for <:<[Null, Int]. On the other hand, Null does conform to String and the compiler will find the implicit parameter.

By the way, here is another related answer.

ContentLicense: CC BY-SA 2.5

Body:
Scala's Option class has an orNull method, whose signature is shown below.

orNull [A1 >: A](implicit ev : <:<[Null, A1]) : A1

I'm bewildered by the implicit thing. Would somebody please explain how it can be used, ideally with an example?

Body:
To understand why it is useful, IttayD provided a nice explanation:

So what we would have liked is def
  orNull[A >: Null] = ..... But A is
  already set and we don't want to
  restrict it in the definition of the
  trait. Therefore, orNull expects an
  evidence that A is a nullable type.
  This evidence is in the form of an
  implicit variable (hence the name
  'ev')

In summary, type constraints are useful when you want have methods (eg orNull) on a generic class (eg Option) with more specific constraints (eg Null <: A <: Any) than on the class itself (eg A <: Any).

This is another "feature" that is not built into the language but comes for free thanks to implicit parameters and variance annotations of type parameters. To understand this, look at the definition of <:<:

// from Predef
sealed abstract class <:<[-From, +To] extends (From => To)
implicit def conforms[A]: A <:< A = new (A <:< A) {def apply(x: A) = x}

For

scala> Some(1).orNull
<console>:10: error: could not find implicit value for parameter ev: <:<[Null,Int]
       Some(1).orNull

the compiler looks for an implicit value of type <:<[Null, Int] and will find the method def conforms[A]: A <:< A. So there has to be an A for which <:<[A, A] conforms to <:<[Null, Int]. There is no A for which this holds and as a result the compiler will complain about the missing implicit value.

However, for

scala> Some("hi").orNull
res21: java.lang.String = hi

we are lucky. Now, the compiler tries to find an A for which <:<[A, A] conforms to <:<[Null, String]. This works for A = String, because Null is a subtype of String and the From type parameter of the class <:< is defined as contravariant).

As mentioned, the most intuitive way to think about type constraints is reading it like a type bound (i.e. reading it as Null <: Int). Null does not conform to Int and there is no implicit value for <:<[Null, Int]. On the other hand, Null does conform to String and the compiler will find the implicit parameter.

By the way, here is another related answer.


问:
Bind to property of a control in another view
I have set up in a view the height of a control using dockpanels and alignments.
I want to use the computed size of this control as an input for another control in another view.

MainWindow

```<code><StackPanel>
    <local:View1 />
    <local:View2 />
</StackPanel>
</code>```

View1

```<code><DockPanel>
    ...
        <Button x:Name="myButton" />
    ...
</DockPanel>
</code>```

View2 (where I want to bind the button's height to the first view)

```<code><Button Height="{Binding Path=Button.Height, RelativeSource={RelativeSource AncestorType={x:Type local:View1}}}" />
</code>```

But it does not work...

I am looking if possible for a xaml-only solution with binding...

答:
You may want to try using dependency properties in order to achieve this. Here is a sample based on your case:

View1:

```<code><DockPanel>
        <Button x:Name="myButton" Content="Button in view1" FontSize="32"/>
    </DockPanel>
</code>```

View1 codebehind. Notice that we handle loaded event in order to get the actual height of the button and to assign its value to the DependencyProperty we created:

```<code>public static readonly DependencyProperty ButtonHeightProperty = DependencyProperty.Register(
            "ButtonHeight", typeof (double), typeof (View1), new PropertyMetadata(default(double)));

        public double ButtonHeight
        {
            get { return (double) GetValue(ButtonHeightProperty); }
            set { SetValue(ButtonHeightProperty, value); }
        }
        public View1()
        {
            InitializeComponent();
        }

        private void View1_OnLoaded(object sender, RoutedEventArgs e)
        {
            ButtonHeight = myButton.ActualHeight;
        }
</code>```

Then in view2 we bind the button height to another dependency property in that user control:

And in view2 codebehind:

```<code>public static readonly DependencyProperty ButtonHeightProperty = DependencyProperty.Register(
    "ButtonHeight", typeof (double), typeof (View2), new PropertyMetadata(default(double)));

public double ButtonHeight
{
    get { return (double) GetValue(ButtonHeightProperty); }
    set { SetValue(ButtonHeightProperty, value); }
}

public View2()
{
    InitializeComponent();
}
</code>```

Finally the mainWindow xaml looks like this:

```<code><StackPanel>
    <local:View1 x:Name="View1"/>
    <local:View2 ButtonHeight="{Binding ElementName=View1,Path=ButtonHeight}"/>
</StackPanel>
</code>```

And the output:

Hope this helps

Body:
I have set up in a view the height of a control using dockpanels and alignments.
I want to use the computed size of this control as an input for another control in another view.

MainWindow

<StackPanel>
    <local:View1 />
    <local:View2 />
</StackPanel>

View1

<DockPanel>
    ...
        <Button x:Name="myButton" />
    ...
</DockPanel>

View2 (where I want to bind the button's height to the first view)

<Button Height="{Binding Path=Button.Height, RelativeSource={RelativeSource AncestorType={x:Type local:View1}}}" />

But it does not work...

I am looking if possible for a xaml-only solution with binding...

Body:
You may want to try using dependency properties in order to achieve this. Here is a sample based on your case:

View1:

<DockPanel>
        <Button x:Name="myButton" Content="Button in view1" FontSize="32"/>
    </DockPanel>

View1 codebehind. Notice that we handle loaded event in order to get the actual height of the button and to assign its value to the DependencyProperty we created:

public static readonly DependencyProperty ButtonHeightProperty = DependencyProperty.Register(
            "ButtonHeight", typeof (double), typeof (View1), new PropertyMetadata(default(double)));

        public double ButtonHeight
        {
            get { return (double) GetValue(ButtonHeightProperty); }
            set { SetValue(ButtonHeightProperty, value); }
        }
        public View1()
        {
            InitializeComponent();
        }

        private void View1_OnLoaded(object sender, RoutedEventArgs e)
        {
            ButtonHeight = myButton.ActualHeight;
        }

Then in view2 we bind the button height to another dependency property in that user control:

And in view2 codebehind:

public static readonly DependencyProperty ButtonHeightProperty = DependencyProperty.Register(
    "ButtonHeight", typeof (double), typeof (View2), new PropertyMetadata(default(double)));

public double ButtonHeight
{
    get { return (double) GetValue(ButtonHeightProperty); }
    set { SetValue(ButtonHeightProperty, value); }
}

public View2()
{
    InitializeComponent();
}

Finally the mainWindow xaml looks like this:

<StackPanel>
    <local:View1 x:Name="View1"/>
    <local:View2 ButtonHeight="{Binding ElementName=View1,Path=ButtonHeight}"/>
</StackPanel>

And the output:

Hope this helps


答:
You don't have so many options other than using push:

```<code>const cond = true;
const myArr = ["foo"];

if (cond) myArr.push("bar");
</code>```

Another idea is potentially adding null's and filtering them out:

```<code>const cond = true;
const myArr = ["foo", cond ? "bar" : null];

myArr = myArr.filter((item) => item !== null);
</code>```

Title: How to define an array with conditional elements?

Body:
You don't have so many options other than using push:

const cond = true;
const myArr = ["foo"];

if (cond) myArr.push("bar");

Another idea is potentially adding null's and filtering them out:

const cond = true;
const myArr = ["foo", cond ? "bar" : null];

myArr = myArr.filter((item) => item !== null);


问:
How do we account for exception throws in static code analysis?
I wrote an utility to create a CFG (Control Flow Graph) for a java method whose nodes are basic blocks instead of instructions.

I could not consider exception throws to be edges in CFG. The reasons are that:

Every instruction in try block can potentially throw exceptions / errors which can be handled by any of the nesting try-catch blocks. If we consider exception throws as edges, the number of paths to process increases drastically, and so will the number of nodes in CFG.

We need to know the inheritance hierarchy for exceptions before we can decide what jumps are possible.

How do static code analyzers solve this problem?

I am stuck at this point. If I have to proceed, how should I go about it?

Edit: in my case, I can limit support to those use cases which can specify where and which exceptions are thrown. This solved my second problem. I would still like to know how generic static code analysers manage this.

答:
Here's how I dealt with the issue in the Krakatau decompiler:

We need to know the inheritance hierarchy for exceptions before we can
  decide what jumps are possible.

Krakatau requires the class definitions of any referenced classes to be available, so it knows the inheritance hierarchy. However, if I was doing it over, I wouldn't do this. Requiring class definitions makes the decompiler difficult for users to operate because finding and adding the dependencies is a huge pain. You don't actually need this if you're ok with the analysis being a little less precise. You can instead just assume that all exceptions can reach all handlers. In practice, I expect that it would lead to nearly the same results.

Every instruction in try block can potentially throw exceptions /
  errors which can be handled by any of the nesting try-catch blocks. If
  we consider exception throws as edges, the number of paths to process
  increases drastically, and so will the number of nodes in CFG.

Krakatau does include exceptions as edges in the CFG, which leads to the problems you identified. In order to reduce the number of edges, I pretended that only certain instructions can throw (method calls, array accesses, division, etc.). This isn't technically correct, but it does the right thing for real world code. I've never seen anything that actually cares about the exceptions being thrown from a link error, Thread.Stop or the like. I did later add an option to disable this behavior though.

Anyway, this worked well enough for most code, but it sometimes caused performance problems. In particular, really large methods with lots of field accesses or method calls would result in huge CFGs that made decompilation really slow. I tried some tricks to optimize this, but ultimately, the solution was to move from basic blocks to extended basic blocks.

Extended Basic Blocks are similar to Basic Blocks, except that exception edges are represented semi-implicitly, resulting in a much smaller CFG. An EBB consists of straight line code with no entry points or exit points in the middle apart from exception edges, and where every instruction in the block is covered by the same set of exception handlers. That way, instead of having an exception edge per instruction, you have one per block, making things much more efficient.

Even Java methods with thousands of methods calls will typically only have a few try/catches and hence only a few EBBs.


问:
Chronometer: I want to make a button reset to "00.00" not restart the chronometer
I want the start button to start the time, the stop button to completely stop it at that time, and the reset button to start the clock back at "00.00". Everytime I click reset it restarts the time. I just want it to reset back to "00.00". Thanks for your help. Heres my code:</p>

```<code>import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class TimeLogActivity extends ActionBarActivity {Chronometer focus;
Button start, stop, reset;

private Toolbar toolbar;
private DrawerLayout drawerLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_time_log);

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);

    start = (Button) findViewById(R.id.timeLogStartButton);
    stop = (Button) findViewById(R.id.timeLogStopButton);
    reset  = (Button) findViewById(R.id.timeLogResetButton);

    focus = (Chronometer) findViewById(R.id.timeLogChronometer);

    start.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            focus.start();
        }
    });

    stop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            focus.stop();
        }
    });

    reset.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            focus.setBase(SystemClock.elapsedRealtime());
            focus.start();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_time_log, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}
</code>```

答:
These lines you should be able to reset the chronometer back to 00:00</p>

```<code>focus.setBase(SystemClock.elapsedRealtime());
focus.stop();
</code>```

Body:
I want the start button to start the time, the stop button to completely stop it at that time, and the reset button to start the clock back at "00.00". Everytime I click reset it restarts the time. I just want it to reset back to "00.00". Thanks for your help. Heres my code:

import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class TimeLogActivity extends ActionBarActivity {Chronometer focus;
Button start, stop, reset;

private Toolbar toolbar;
private DrawerLayout drawerLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_time_log);

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);

    start = (Button) findViewById(R.id.timeLogStartButton);
    stop = (Button) findViewById(R.id.timeLogStopButton);
    reset  = (Button) findViewById(R.id.timeLogResetButton);

    focus = (Chronometer) findViewById(R.id.timeLogChronometer);

    start.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            focus.start();
        }
    });

    stop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            focus.stop();
        }
    });

    reset.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            focus.setBase(SystemClock.elapsedRealtime());
            focus.start();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_time_log, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Body:
These lines you should be able to reset the chronometer back to 00:00

focus.setBase(SystemClock.elapsedRealtime());
focus.stop();


问:
Storing user input in variables
This is a method to get user input and store it in variables.
How should I create a second method to access these vars and print them to the console ?
String "who" is used to specify who is that person for example: Teacher or Student or Parent.</p>

```<code> static void GetInformation(string who)
  {
    Console.WriteLine("Enter the {0} first name: ",who);
    newStudent.firstName = Console.ReadLine();
    Console.WriteLine("Enter the {0} last name: ",who);
    string lastName = Console.ReadLine();
    Console.WriteLine("Enter the {0} birthdate: ",who);
    string birthdate = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 1: ",who);
    string addressLine1 = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 2: ",who);
    string addressLine2 = Console.ReadLine();
    Console.WriteLine("Enter the {0} city: ",who);
    string city = Console.ReadLine();
    Console.WriteLine("Enter the {0} state: ",who);
    string state = Console.ReadLine();
    Console.WriteLine("Enter the {0} post code: ",who);
    string postCode = Console.ReadLine();
    Console.WriteLine("Enter the {0} country: ",who);
    string country = Console.ReadLine();
}
</code>```

答:
You can create a class called Person, return object of this class filled with the values you collect from GetInformation method, and use it as the parameter of another method. Example of the class:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
    public string Birthdate  { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostCode { get; set; }
    public string Country  { get; set; }
}
</code>```

But I highly suggest you to read some C# tutorial first. This is really basic stuff.

Title: Storing user input in variables

Body:
This is a method to get user input and store it in variables.
How should I create a second method to access these vars and print them to the console ?
String "who" is used to specify who is that person for example: Teacher or Student or Parent.

 static void GetInformation(string who)
  {
    Console.WriteLine("Enter the {0} first name: ",who);
    newStudent.firstName = Console.ReadLine();
    Console.WriteLine("Enter the {0} last name: ",who);
    string lastName = Console.ReadLine();
    Console.WriteLine("Enter the {0} birthdate: ",who);
    string birthdate = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 1: ",who);
    string addressLine1 = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 2: ",who);
    string addressLine2 = Console.ReadLine();
    Console.WriteLine("Enter the {0} city: ",who);
    string city = Console.ReadLine();
    Console.WriteLine("Enter the {0} state: ",who);
    string state = Console.ReadLine();
    Console.WriteLine("Enter the {0} post code: ",who);
    string postCode = Console.ReadLine();
    Console.WriteLine("Enter the {0} country: ",who);
    string country = Console.ReadLine();
}

Body:
You can create a class called Person, return object of this class filled with the values you collect from GetInformation method, and use it as the parameter of another method. Example of the class:

public class Person
{
    public string FirstName { get; set; }
    public string LastName  { get; set; }
    public string Birthdate  { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostCode { get; set; }
    public string Country  { get; set; }
}

But I highly suggest you to read some C# tutorial first. This is really basic stuff.


答:
I think you have 2 options here.

1) Set the property as a function, and evaluate it:

```<code>$(function() {
    var options = {
        value: ()=>$('#container').find('.btn-primary').data('status')
    };
    var container = $('#container');
    container.find('.btn').click(function() {
        container.find('.btn').removeClass('btn-primary').addClass('btn-default');
        $(this).addClass('btn-primary');
        console.log(options.value());
    });
});
</code>```

jsfiddle: https://jsfiddle.net/mw8kuq6L/

2) Just use "this" to directly access the data value you want to check:

```<code>$(function() {
    var container = $('#container');
    container.find('.btn').click(function() {
        container.find('.btn').removeClass('btn-primary').addClass('btn-default');
        $(this).addClass('btn-primary');
        console.log($(this).data('status'));
    });
});
</code>```

Title: Javascript force recalculate value of object property

Body:
I think you have 2 options here.

1) Set the property as a function, and evaluate it:

$(function() {
    var options = {
        value: ()=>$('#container').find('.btn-primary').data('status')
    };
    var container = $('#container');
    container.find('.btn').click(function() {
        container.find('.btn').removeClass('btn-primary').addClass('btn-default');
        $(this).addClass('btn-primary');
        console.log(options.value());
    });
});

jsfiddle: https://jsfiddle.net/mw8kuq6L/

2) Just use "this" to directly access the data value you want to check:

$(function() {
    var container = $('#container');
    container.find('.btn').click(function() {
        container.find('.btn').removeClass('btn-primary').addClass('btn-default');
        $(this).addClass('btn-primary');
        console.log($(this).data('status'));
    });
});


问:
Capturing Mouse and Keyboard Events Simultaneously
I am in a situation where I have to detect that the control key is pressed or not while dragging an object in JavaScript. If the control key is pressed then I need to perform some other action.
Can someone help me out on this?

答: Check event.ctrlKey.

Body: Check event.ctrlKey.


问:
qpainter drawText text direction and size
I have a QGraphicsView/QGraphicsScene pair. I have overriden the QGraphicsView.drawBackgroud method in order to draw a rectangular grid. Everything is fine until that point, but when I try to draw the actual coordinates, using QPainter.drawText method, the resulting text is upside down. Another issue is that I dont want the text for coordinates values resize with zooming, but I havent been able to achieve this.

My view is initially scaled (1,-1).

I'm working on PySide

This is my code for drawBackground:

```<code>pen = QtGui.QPen(QtGui.QColor(0,0,0))
painter.setPen(pen)
gridInterval = 10
#painter.setWorldMatrixEnabled(True)

l, r = rect.left(), rect.right()
t, b = rect.bottom(), rect.top()

dx = (r - l) / gridInterval
dy = (t - b) / gridInterval
left = int(l) + dx / 2
bottom = int(b) + dy / 2
nx = gridInterval
ny = gridInterval
dx = (r - l) / gridInterval
dy = (t - b) / gridInterval
myxrange = [left + i * dx for i in range(nx)]
myyrange = [bottom + j * dy for j in range(ny)]

xlabels = ["{0:.2f}".format(x) for x in myxrange]
ylabels = ["{0:.2f}".format(y) for y in myyrange]

xlines = []
for point in myxrange:
    line = QtCore.QLineF(point, t, point, b)
    xlines.append(line)

ylines = []
for point in myyrange:
    line = QtCore.QLineF(l, point, r, point)
    ylines.append(line)

painter.drawLines(xlines)
painter.drawLines(ylines)

#font = QtGui.QFont()
#font.setPointSize(20)
#painter.setFont(font)

for k, text in enumerate(xlabels):
    #painter.save()
    #painter.rotate(90)
    painter.drawText(myxrange[k], myyrange[0], text)
    #painter.rotate(-90)
    #painter.restore()
</code>```

答:
Ok, so I found a solution that works for the "rotated" text. I had to rescale the painter before drawing the text and actually draw it on the translated location:

So the for loop looks like this:

```<code>for k, text in enumerate(xlabels):
    painter.save()
    painter.scale(1,-1)
    painter.drawText(myxrange[k], -myyrange[0], text)
    painter.restore()
</code>```

I'm still looking for an answer to the fixed size issue.

Body:
I have a QGraphicsView/QGraphicsScene pair. I have overriden the QGraphicsView.drawBackgroud method in order to draw a rectangular grid. Everything is fine until that point, but when I try to draw the actual coordinates, using QPainter.drawText method, the resulting text is upside down. Another issue is that I dont want the text for coordinates values resize with zooming, but I havent been able to achieve this.

My view is initially scaled (1,-1).

I'm working on PySide

This is my code for drawBackground:

pen = QtGui.QPen(QtGui.QColor(0,0,0))
painter.setPen(pen)
gridInterval = 10
#painter.setWorldMatrixEnabled(True)

l, r = rect.left(), rect.right()
t, b = rect.bottom(), rect.top()

dx = (r - l) / gridInterval
dy = (t - b) / gridInterval
left = int(l) + dx / 2
bottom = int(b) + dy / 2
nx = gridInterval
ny = gridInterval
dx = (r - l) / gridInterval
dy = (t - b) / gridInterval
myxrange = [left + i * dx for i in range(nx)]
myyrange = [bottom + j * dy for j in range(ny)]

xlabels = ["{0:.2f}".format(x) for x in myxrange]
ylabels = ["{0:.2f}".format(y) for y in myyrange]

xlines = []
for point in myxrange:
    line = QtCore.QLineF(point, t, point, b)
    xlines.append(line)

ylines = []
for point in myyrange:
    line = QtCore.QLineF(l, point, r, point)
    ylines.append(line)

painter.drawLines(xlines)
painter.drawLines(ylines)

#font = QtGui.QFont()
#font.setPointSize(20)
#painter.setFont(font)

for k, text in enumerate(xlabels):
    #painter.save()
    #painter.rotate(90)
    painter.drawText(myxrange[k], myyrange[0], text)
    #painter.rotate(-90)
    #painter.restore()

Body:
Ok, so I found a solution that works for the "rotated" text. I had to rescale the painter before drawing the text and actually draw it on the translated location:

So the for loop looks like this:

for k, text in enumerate(xlabels):
    painter.save()
    painter.scale(1,-1)
    painter.drawText(myxrange[k], -myyrange[0], text)
    painter.restore()

I'm still looking for an answer to the fixed size issue.


问:
Recover current value in checkBox during gridView Editing - WebForm C#
I have a simple checkBox in Editable gridView :

```<code><asp:TemplateField HeaderText="Editable">
  <ItemTemplate>
      <asp:Label runat="server" Text="<%# Item.IsEditable %>" />
  </ItemTemplate>
  <EditItemTemplate>
      <asp:CheckBox ID="CheckBoxEditable " runat="server" Text="Editable"></asp:CheckBox>
  </EditItemTemplate>
</asp:TemplateField>
</code>```

When I click on edit button in the row, I would like that checkBox is already checked if value is true. (IsEditable is a boolean)
Text Field is easy because I have a BindItem on Text property in EditItemTemplate. But it's not the same for checkBox or dropdownlist

GridView

I use a UpdateItem Method to update my data in database. I tried a small condition to check my checkBox but it does'nt work.

```<code>public void GridViewRisquesAggravants_UpdateItem(IndexViewModel item)
{
 try
   {
    if (ModelState.IsValid)
      {
       CheckBox chbEdit = (CheckBox)GridView.Rows[this.GridView.EditIndex].FindControl("CheckBoxEditable")
          if (item.IsEditable)
              chbEdit.Checked = true;

        new TypeService().Update(new Type
        {
          IsEditable = item.IsEditable,
        });
        this.GridView.DataBind();
      }
    }
    catch
    {
      throw;
    }
}
</code>```

It makes sense because I am not in the right function to declare this. But I just have 3 methods in my webform.

```<code>SelectMethod="GridView_GetData"
UpdateMethod="GridView_UpdateItem"
DeleteMethod="GridView_DeleteItem"
</code>```

Where can I do this?
(And I have the same problem with datas on dropdownList. I don't know where I recover current value during editing)

Thanks in advance
(Sorry I am beginner about webforms and my english is not perfect)

Evy

答:
Where can I do this?

Try it in RowDataBound event:

```<code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chbEdit = (CheckBox)e.Row.FindControl("CheckBoxEditable");

        string value = ((Label)e.Row.FindControl("lblID")).Text;
        if (value=="True")
            chbEdit.Checked = true;
        else
            chbEdit.Checked = false;
    }
}
</code>```

Note: Don't forget to add OnRowDataBound in GrindView <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >

Body:
I have a simple checkBox in Editable gridView :

<asp:TemplateField HeaderText="Editable">
  <ItemTemplate>
      <asp:Label runat="server" Text="<%# Item.IsEditable %>" />
  </ItemTemplate>
  <EditItemTemplate>
      <asp:CheckBox ID="CheckBoxEditable " runat="server" Text="Editable"></asp:CheckBox>
  </EditItemTemplate>
</asp:TemplateField>

When I click on edit button in the row, I would like that checkBox is already checked if value is true. (IsEditable is a boolean)
Text Field is easy because I have a BindItem on Text property in EditItemTemplate. But it's not the same for checkBox or dropdownlist

GridView

I use a UpdateItem Method to update my data in database. I tried a small condition to check my checkBox but it does'nt work.

public void GridViewRisquesAggravants_UpdateItem(IndexViewModel item)
{
 try
   {
    if (ModelState.IsValid)
      {
       CheckBox chbEdit = (CheckBox)GridView.Rows[this.GridView.EditIndex].FindControl("CheckBoxEditable")
          if (item.IsEditable)
              chbEdit.Checked = true;

        new TypeService().Update(new Type
        {
          IsEditable = item.IsEditable,
        });
        this.GridView.DataBind();
      }
    }
    catch
    {
      throw;
    }
}

It makes sense because I am not in the right function to declare this. But I just have 3 methods in my webform.

SelectMethod="GridView_GetData"
UpdateMethod="GridView_UpdateItem"
DeleteMethod="GridView_DeleteItem"

Where can I do this?
(And I have the same problem with datas on dropdownList. I don't know where I recover current value during editing)

Thanks in advance
(Sorry I am beginner about webforms and my english is not perfect)

Evy

Body:
Where can I do this?

Try it in RowDataBound event:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chbEdit = (CheckBox)e.Row.FindControl("CheckBoxEditable");

        string value = ((Label)e.Row.FindControl("lblID")).Text;
        if (value=="True")
            chbEdit.Checked = true;
        else
            chbEdit.Checked = false;
    }
}

Note: Don't forget to add OnRowDataBound in GrindView <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >


问:
How to return 2 values and rounding them? Excel VBA
I am working on a code that should calculate simple foundations, and in order to do that I have to return 2 values with my function -preferably in two different columns.

```<code>Function FundacaoSimples(b, l, carga) As Variant

tensao = Sheets("Tabelas e Constantes").Range("tensao").Value

Dim area As Double
Dim Bs As Single
Dim Ls As Single
Dim Resultado(1 To 2) As String

If b = l Then
    area = (1.1 * carga) / tensao
    Bs = Sqr(area)
    Ls = Bs
ElseIf b <> l Then
    area = (1.1 * carga) / tensao
    Bs = Sqr((2 * area) / 3)
    Ls = (3 * Bs) / 2
End If

Resultado(1) = Round(Bs, 2)
Resultado(2) = Round(Ls, 2)

FundacaoSimples = (Resultado(1) & " / " & Resultado(2))

End Function
</code>```

This rounding I am using it just to get a value rounded with 2 decimals, e.g: 2,73 to 2,75; 0,89 to 0,90.
I tried working with ActiveCells.Offset(0,1), but the statement isn't valid.
Is it possible to to just jump one column to the right?

答:
You could use ActiveCell.Offset(0, 1).value = SomeValue, however - That's when writing a regular Sub. You're writing a Function / User Defined Function.

Within a UDF it is not possible to alter different cells.

However, a workaround is to have the UDF and when it's entered in a cell, you can then use the Worksheet_Change event to alter the cell next to the Target parameter of that event.

Edit:
Some sample code:

In a regular module:

```<code>Public Function MyUDF(param1 as integer, param2 as integer) as Integer
    MyUDF = param1 + param2
End Function
</code>```

In the Worksheet where you want the offset:

```<code>Private Sub Worksheet_Change(Byval Target as Range)
    If Left(Target.Formula, 6) = "=MyUDF" Then
        Target.Offset(0, 1).value = "somevalue at the offset cells"
    End If
End Sub
</code>```

Body:
I am working on a code that should calculate simple foundations, and in order to do that I have to return 2 values with my function -preferably in two different columns.

Function FundacaoSimples(b, l, carga) As Variant

tensao = Sheets("Tabelas e Constantes").Range("tensao").Value

Dim area As Double
Dim Bs As Single
Dim Ls As Single
Dim Resultado(1 To 2) As String

If b = l Then
    area = (1.1 * carga) / tensao
    Bs = Sqr(area)
    Ls = Bs
ElseIf b <> l Then
    area = (1.1 * carga) / tensao
    Bs = Sqr((2 * area) / 3)
    Ls = (3 * Bs) / 2
End If

Resultado(1) = Round(Bs, 2)
Resultado(2) = Round(Ls, 2)

FundacaoSimples = (Resultado(1) & " / " & Resultado(2))

End Function

This rounding I am using it just to get a value rounded with 2 decimals, e.g: 2,73 to 2,75; 0,89 to 0,90.
I tried working with ActiveCells.Offset(0,1), but the statement isn't valid.
Is it possible to to just jump one column to the right?

Body:
You could use ActiveCell.Offset(0, 1).value = SomeValue, however - That's when writing a regular Sub. You're writing a Function / User Defined Function.

Within a UDF it is not possible to alter different cells.

However, a workaround is to have the UDF and when it's entered in a cell, you can then use the Worksheet_Change event to alter the cell next to the Target parameter of that event.

Edit:
Some sample code:

In a regular module:

Public Function MyUDF(param1 as integer, param2 as integer) as Integer
    MyUDF = param1 + param2
End Function

In the Worksheet where you want the offset:

Private Sub Worksheet_Change(Byval Target as Range)
    If Left(Target.Formula, 6) = "=MyUDF" Then
        Target.Offset(0, 1).value = "somevalue at the offset cells"
    End If
End Sub


问:
Javascript in WebView doesn't work
I am trying the examples from here: https://developer.android.com/guide/webapps/webview.html but it just Doesn't Work™.

This is my Activity:

```<code>public class MainActivity extends Activity {
    private static final String TAG = "browser";
    protected WebView wv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wv = (WebView)findViewById(R.id.wvBrowser);
        WebSettings webSettings = wv.getSettings();
        webSettings.setJavaScriptEnabled(true);
        wv.addJavascriptInterface(new WebAppInterface(this), "android");

        wv.loadUrl("http://192.168.3.183");
    }
}
</code>```

This is the WebAppInterface:

```<code>public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}
</code>```

and, finally the Javascript:

```<code><html>
<head>
    <title>Android JavaScript Scan Test</title>
</head>
<body>
<h3>Scan Test</h3>
<input id="barcode">

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    f = 0;
    function showAndroidToast(toast) {
        document.getElementById("barcode").value = typeof(Android) + (f++);

        Android.showToast(toast);
    }
</script>
</body>
</html>
</code>```

And all it gives me is undefined0, undefined1, etc. Apparently, the Android object is not available in my WebView.

Am I missing something?

答:
You registered the callback with android and trying to use it with a capitalized letter Android.

The names need to be identical for Javascript interfaces to work. Currently there is a bug in the Android documentation example

Title: Javascript in WebView doesn't work

Body:
I am trying the examples from here: https://developer.android.com/guide/webapps/webview.html but it just Doesn't Work™.

This is my Activity:

public class MainActivity extends Activity {
    private static final String TAG = "browser";
    protected WebView wv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wv = (WebView)findViewById(R.id.wvBrowser);
        WebSettings webSettings = wv.getSettings();
        webSettings.setJavaScriptEnabled(true);
        wv.addJavascriptInterface(new WebAppInterface(this), "android");

        wv.loadUrl("http://192.168.3.183");
    }
}

This is the WebAppInterface:

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

and, finally the Javascript:

    <title>Android JavaScript Scan Test</title>

Scan Test

<input id="barcode">

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

And all it gives me is undefined0, undefined1, etc. Apparently, the Android object is not available in my WebView.

Am I missing something?


问:
performance with left join and include max in the query with values null
The data of the table exceeds 7 billion.
I want to display the max of entryDate affiliation for each participant and i want to include the null values so i used left join but the query takes long minute. Anyway it gives me the expected results.
Could anyone has a better idea or another better solution to fix the performance?</p>

```<code>Select ParticipantID,MaxDate
    From dbo.Participant Par
    LEFT JOIN dbo.Affiliation Aff
    ON AFF.ParticipantID=Par.ParticipantID
    LEFT JOIN (
                               SELECT              AFF.AffiliationID,
                                                      MAX(EntryDate) as MaxDate
                               FROM                dbo.Affiliation

                               GROUP BY            AFF.AffiliationID

                    )AS AFF1
           ON           AFF1.AffiliationID = AFF.AffiliationID
                        AND AFF1.MaxDate = AFF.EntryDate
</code>```

答:
I think the first join is unnecessary

```<code>SELECT ParticipantID, MaxDate
FROM dbo.Participant Par
OUTER APPLY (
    SELECT MAX(EntryDate) as MaxDate
    FROM dbo.Affiliation Aff
    WHERE Aff.ParticipantID = ParParticipantID
) A
</code>```

Also you need index on Affilation:

```<code>CREATE INDEX IX_Affiliation_ParticipantID_EntryDate ON dbo.Affiliation(ParticipantID, EntryDate)
</code>```

Body:
The data of the table exceeds 7 billion.
I want to display the max of entryDate affiliation for each participant and i want to include the null values so i used left join but the query takes long minute. Anyway it gives me the expected results.
Could anyone has a better idea or another better solution to fix the performance?

Select ParticipantID,MaxDate
    From dbo.Participant Par
    LEFT JOIN dbo.Affiliation Aff
    ON AFF.ParticipantID=Par.ParticipantID
    LEFT JOIN (
                               SELECT              AFF.AffiliationID,
                                                      MAX(EntryDate) as MaxDate
                               FROM                dbo.Affiliation

                               GROUP BY            AFF.AffiliationID

                    )AS AFF1
           ON           AFF1.AffiliationID = AFF.AffiliationID
                        AND AFF1.MaxDate = AFF.EntryDate

Body:
I think the first join is unnecessary

SELECT ParticipantID, MaxDate
FROM dbo.Participant Par
OUTER APPLY (
    SELECT MAX(EntryDate) as MaxDate
    FROM dbo.Affiliation Aff
    WHERE Aff.ParticipantID = ParParticipantID
) A

Also you need index on Affilation:

CREATE INDEX IX_Affiliation_ParticipantID_EntryDate ON dbo.Affiliation(ParticipantID, EntryDate)


问:
ios - How to close open cells in uitableview through code (Objective-C)
I am adding a filter function to my app, but every time a filter is applied a previously opened cell does not close when I change the filter, is there a way to implement this?

I am currently using:

```<code>[self.tableview reloadData];
</code>```

to reload the table every time the filter is applied

To open and close:

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self tableView:tableView canCollapseSection:indexPath.section])
    {
        if (!indexPath.row)
        {
            // only first row toggles exapand/collapse
            [tableView deselectRowAtIndexPath:indexPath animated:YES];

            NSInteger section = indexPath.section;
            BOOL currentlyExpanded = [expandedSections containsIndex:section];
            NSInteger rows;

            NSMutableArray *tmpArray = [NSMutableArray array];

            if (currentlyExpanded)
            {
                rows = [self tableView:tableView numberOfRowsInSection:section];
                [expandedSections removeIndex:section];

            }
            else
            {

                [expandedSections addIndex:section];
                rows = [self tableView:tableView numberOfRowsInSection:section];
                NSLog(@"Section:%d", rows);
            }

            for (int i=1; i<rows; i++)
            {
                NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
                                                               inSection:section];
                NSLog(@"INDEX: %@", tmpIndexPath);
                [tmpArray addObject:tmpIndexPath];
            }

            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (currentlyExpanded)
            {
                dispatch_async(dispatch_get_main_queue(), ^{

                [tableView deleteRowsAtIndexPaths:tmpArray
                                 withRowAnimation:UITableViewRowAnimationTop];
                });
            }
            else
            {
                  dispatch_async(dispatch_get_main_queue(), ^{
                [tableView insertRowsAtIndexPaths:tmpArray
                                 withRowAnimation:UITableViewRowAnimationTop];
                  });

            }
        }
}
</code>```

答:
Before tableview reloadData clear the expandedSections array.

```<code>[expandedSections removeAllIndexes];
[self.tableView reloadData];
</code>```

expandedSections Array maintains the status of the expand section details.Due to that its not collapse the view. So clear the array before reload the table view.

Body:
I am adding a filter function to my app, but every time a filter is applied a previously opened cell does not close when I change the filter, is there a way to implement this?

I am currently using:

[self.tableview reloadData];

to reload the table every time the filter is applied

To open and close:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self tableView:tableView canCollapseSection:indexPath.section])
    {
        if (!indexPath.row)
        {
            // only first row toggles exapand/collapse
            [tableView deselectRowAtIndexPath:indexPath animated:YES];

            NSInteger section = indexPath.section;
            BOOL currentlyExpanded = [expandedSections containsIndex:section];
            NSInteger rows;

            NSMutableArray *tmpArray = [NSMutableArray array];

            if (currentlyExpanded)
            {
                rows = [self tableView:tableView numberOfRowsInSection:section];
                [expandedSections removeIndex:section];

            }
            else
            {

                [expandedSections addIndex:section];
                rows = [self tableView:tableView numberOfRowsInSection:section];
                NSLog(@"Section:%d", rows);
            }

            for (int i=1; i<rows; i++)
            {
                NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
                                                               inSection:section];
                NSLog(@"INDEX: %@", tmpIndexPath);
                [tmpArray addObject:tmpIndexPath];
            }

            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (currentlyExpanded)
            {
                dispatch_async(dispatch_get_main_queue(), ^{

                [tableView deleteRowsAtIndexPaths:tmpArray
                                 withRowAnimation:UITableViewRowAnimationTop];
                });
            }
            else
            {
                  dispatch_async(dispatch_get_main_queue(), ^{
                [tableView insertRowsAtIndexPaths:tmpArray
                                 withRowAnimation:UITableViewRowAnimationTop];
                  });

            }
        }
}

Body:
Before tableview reloadData clear the expandedSections array.

[expandedSections removeAllIndexes];
[self.tableView reloadData];

expandedSections Array maintains the status of the expand section details.Due to that its not collapse the view. So clear the array before reload the table view.


问:
How to add a wallpaper-gallery to an Android application
I have noticed that some Android applications adds a new Wallpaper-gallery to the "Wallpaper-chooser".

I am currently building a theme for Android and I would like to add some wallpapers with this feature.

How is it done?

答:
Figured out, that I have to write the code myself.

Found the code in the Home-sample in the SDK


答:
If you really want to keep it as a one liner, you could use:

```<code>const cond = true;
const myArr = ["foo"].concat(cond ? ["bar"] : []);
</code>```

Body:
How can I define conditional array elements?
I want to do something like this:

const cond = true;
const myArr = ["foo", cond && "bar"];

This works as expected and results in ["foo", "bar"] but if I set cond to false, I get the following result: ["foo", false]

How can I define an array with a conditional element?

Body:
If you really want to keep it as a one liner, you could use:

const cond = true;
const myArr = ["foo"].concat(cond ? ["bar"] : []);


问:
plot 3D polygons in 2D
I search for the correct implementation for this a long time now.

I have a 3D delaunay triangulation and want to plot this in 2D.
In 3D i manage to do so:

I need a 2D plot though. What i get using matplotlib.tripcolor method or the matplotlib.collections.PolyCollection is:

How do i plot this in 2D without the top and back triangles all mixed up? With all methods tried so far, some triangles are hidden by triangles that should be in the back of the structure.

I see, that the methods just do not have the information necessary to plot in the correct order, since i have to provide 2D arrays already. The depth information is lost.

Does anybody know how to do this?
Thanks a lot!

答:
You can mimic a 2D plot with Axes3d by setting an orthographic projection, initialising the view to face the desired plane, and removing unwanted plot elements along the axis orthogonal to the chosen plane of view. In addition, you can plot 2D elements using the zdir keyword argument.

Here's one of the matplotlib 3D plot examples I modified to demonstrate

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

# Enable orthographic projection
# https://stackoverflow.com/questions/23840756/how-to-disable-perspective-in-mplot3d
from mpl_toolkits.mplot3d import proj3d
def orthogonal_proj(zfront, zback):
    a = (zfront+zback)/(zfront-zback)
    b = -2*(zfront*zback)/(zfront-zback)
    return np.array([[1,0,0,0],
                        [0,1,0,0],
                        [0,0,a,b],
                        [0,0,-0.000001,zback]])
proj3d.persp_transformation = orthogonal_proj

fig = plt.figure()
ax = fig.gca(projection='3d')

# Init view to YZ plane
ax.view_init(azim=0, elev=0)

# Hide the X axis
ax.w_xaxis.line.set_lw(0.)
ax.set_xticks([])

# Change YZ plane colour to white
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.1, 1.1)
ax.set_ylabel('y')
ax.set_zlabel('z')

# Plot 2D elements with zdir argument
# https://stackoverflow.com/questions/29549905/pylab-3d-scatter-plots-with-2d-projections-of-plotted-data
stepsize = 0.1
t = np.arange(-4, 4+stepsize, step=stepsize)
ax.plot(t, 0.5*np.sin(t), 'k', zdir='x', linewidth=1.0)
ax.text(0, 0, 1, 'Text', zdir='y', ha='center', va='top')

plt.show()
</code>```

Title: plot 3D polygons in 2D

Body:
You can mimic a 2D plot with Axes3d by setting an orthographic projection, initialising the view to face the desired plane, and removing unwanted plot elements along the axis orthogonal to the chosen plane of view. In addition, you can plot 2D elements using the zdir keyword argument.

Here's one of the matplotlib 3D plot examples I modified to demonstrate

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

# Enable orthographic projection
# https://stackoverflow.com/questions/23840756/how-to-disable-perspective-in-mplot3d
from mpl_toolkits.mplot3d import proj3d
def orthogonal_proj(zfront, zback):
    a = (zfront+zback)/(zfront-zback)
    b = -2*(zfront*zback)/(zfront-zback)
    return np.array([[1,0,0,0],
                        [0,1,0,0],
                        [0,0,a,b],
                        [0,0,-0.000001,zback]])
proj3d.persp_transformation = orthogonal_proj

fig = plt.figure()
ax = fig.gca(projection='3d')

# Init view to YZ plane
ax.view_init(azim=0, elev=0)

# Hide the X axis
ax.w_xaxis.line.set_lw(0.)
ax.set_xticks([])

# Change YZ plane colour to white
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.1, 1.1)
ax.set_ylabel('y')
ax.set_zlabel('z')

# Plot 2D elements with zdir argument
# https://stackoverflow.com/questions/29549905/pylab-3d-scatter-plots-with-2d-projections-of-plotted-data
stepsize = 0.1
t = np.arange(-4, 4+stepsize, step=stepsize)
ax.plot(t, 0.5*np.sin(t), 'k', zdir='x', linewidth=1.0)
ax.text(0, 0, 1, 'Text', zdir='y', ha='center', va='top')

plt.show()


问:
Qt - Download Data from url
I wrote a web service with PHP. I need download content via web service URL. How can I download data from URL?

Which libraries are needed?

答:
Add QT += network in .pro project file

Include below libraries to your code:

```<code>#include <QUrl>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
</code>```

At the end receive URL content via following code:

```<code>QString url = "WEB_SERVICE_URL";
QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop event;
connect(response, SIGNAL(finished()), &event, SLOT(quit()));
event.exec();
QString content = response->readAll();
</code>```

Title: Qt - Download Data from url

Body:
Add QT += network in .pro project file

Include below libraries to your code:

#include <QUrl>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>

At the end receive URL content via following code:

QString url = "WEB_SERVICE_URL";
QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop event;
connect(response, SIGNAL(finished()), &event, SLOT(quit()));
event.exec();
QString content = response->readAll();