问:
Couldnt find solution for - Error:Execution failed for task
I have tried everything what i found while googling but still have a mistake.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzbut.class

My gradle

```<code>apply plugin: 'com.android.application'

repositories {
    mavenLocal()
    flatDir {
        dirs 'libs'
    }
}

android {
    compileSdkVersion 25
    buildToolsVersion "24.0.3"

    defaultConfig {
        applicationId "com.google.firebase.udacity.friendlychat"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    // Displaying images
    compile 'com.github.bumptech.glide:glide:3.6.1'

    compile 'com.firebaseui:firebase-ui-database:1.2.0'

    // FirebaseUI Auth only
    compile 'com.firebaseui:firebase-ui-auth:1.2.0'

    // FirebaseUI Storage only
    compile 'com.firebaseui:firebase-ui-storage:1.2.0'
    compile 'com.google.firebase:firebase-storage:10.2.6'

    // Single target that includes all FirebaseUI libraries above
    compile 'com.firebaseui:firebase-ui:1.2.0'

    compile 'com.android.support:multidex:1.0.1'

}

apply plugin: 'com.google.gms.google-services'
</code>```

答: This is because of your "multidex" dependency and "multiDexEnabled true" in debug flavor.</p>

Body:
I have tried everything what i found while googling but still have a mistake.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzbut.class

My gradle

apply plugin: 'com.android.application'

repositories {
    mavenLocal()
    flatDir {
        dirs 'libs'
    }
}

android {
    compileSdkVersion 25
    buildToolsVersion "24.0.3"

    defaultConfig {
        applicationId "com.google.firebase.udacity.friendlychat"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    // Displaying images
    compile 'com.github.bumptech.glide:glide:3.6.1'

    compile 'com.firebaseui:firebase-ui-database:1.2.0'

    // FirebaseUI Auth only
    compile 'com.firebaseui:firebase-ui-auth:1.2.0'

    // FirebaseUI Storage only
    compile 'com.firebaseui:firebase-ui-storage:1.2.0'
    compile 'com.google.firebase:firebase-storage:10.2.6'

    // Single target that includes all FirebaseUI libraries above
    compile 'com.firebaseui:firebase-ui:1.2.0'

    compile 'com.android.support:multidex:1.0.1'

}

apply plugin: 'com.google.gms.google-services'


来源: stackexchange

问:
How do I get properties that ONLY have populated values?
How do I get properties that ONLY have populated values?

So for example if I run

```<code>Get-QADUser -Identity "SomeOne" -IncludeAllProperties
</code>```

the output would of course include.. all properties, including those with and those without values. I want a listing of properties with values only. How is it done generally speaking?

This wouldn't be restricted to Quest Cmdlets, I only use Get-QADUser as an example.

答:
You could try using the built-in (hidden) property of PowerShell objects called PSObject, which includes a property called Properties, i.e. a list of all properties on the parent object.

Maybe easier with an example. Take Get-Process... a process can have many attributes (properties) with or without values. In order to get just the ones with values you do this:

```<code>(Get-Process | Select -First 1).PSObject.Properties | ?{$_.Value -ne $null} | FT Name,Value
</code>```

Note that I limited this to just the first process returned by Get-Process. We then get all the properties defined on that object, filtering where Value is not null and then displaying just the Name and Value for those properties.

ContentLicense: CC BY-SA 3.0

Body:
How do I get properties that ONLY have populated values?

So for example if I run

Get-QADUser -Identity "SomeOne" -IncludeAllProperties

the output would of course include.. all properties, including those with and those without values. I want a listing of properties with values only. How is it done generally speaking?

This wouldn't be restricted to Quest Cmdlets, I only use Get-QADUser as an example.

Body:
You could try using the built-in (hidden) property of PowerShell objects called PSObject, which includes a property called Properties, i.e. a list of all properties on the parent object.

Maybe easier with an example. Take Get-Process... a process can have many attributes (properties) with or without values. In order to get just the ones with values you do this:

(Get-Process | Select -First 1).PSObject.Properties | ?{$_.Value -ne $null} | FT Name,Value

Note that I limited this to just the first process returned by Get-Process. We then get all the properties defined on that object, filtering where Value is not null and then displaying just the Name and Value for those properties.


问:
UITabBarController's 'More' navigation controller disappears under UINavigationController
I am using a UITabBarController as well as a UINavigationController on my app.

In my UITabBarController I am using more than 5 items so I automatically get the 'More' item.
I've managed to add a saving procedure so the order of those items will be kept in case somebody changes the order etc.

With 'More' active I get the More navigation controller with the 'Edit' item positioned under my UINavigationController. Both navigation controller are visible. When I click on 'Edit though the More navigation controller disappears and seem to be hiding under my UINavigationController and therefore I can't see/use the 'Done' function to save my new order

What did I miss?

Cheers

答:
I believe iOS does use both navigation controller and tab controller at the same time in their iPod app. The navigation controller takes you to the playing song and back and at the same time you have the tab controller when you select songs/albums/playlists etc. However, the navigation controller (or tab bar controller) seems to be custom made as it handles the More->Edit case by hiding the navigation bar underneath the Edit bar, which is not what the default UITabBarController does.

All in all, I see Apple is rather "creative" when it comes to UI design. For example, in the email app, "New" button is in the lower right corner (bottom bar) while in the SMS app the "New" button is in the upper right corner (navigation bar). I think they pretty much make custom UI to fit the individual needs of the app instead or rigidly following some consistent design.

ContentLicense: CC BY-SA 2.5


问:
Nesting columns good practice?
I am unable to find any rules as to whether or not this is something that should be done. Bootstrap clearly outlines amongst its rules the following:

Rows must be placed within a .container (fixed-width) or
.container-fluid (full-width) for proper alignment and padding

Use rows to create horizontal groups of columns

Content should be placed within columns, and only columns may be

immediate children of rows

So from this I conclude that each section of the website that I do want self-contained would have a container class. Within this we'd have a row and within that we'd have a column. Like so:

```<code><div class="container">
    <div class="row">
        <div class="col">COL 1 of 2</div>
        <div class="col">COL 2 of 2</div>
    </div>
</div>
</code>```

Now my question is, the rules specify that only columns may be immediate children of rows but it doesn't say what the children of columns should be. If I was to want to "nest" another set of double columns within another column, would I write it like in case one or case two?

```<code><div class="container">
    <div class="row">
        <div class="col">  <!--Columns within columns without a row-->
            <div class="col">
            <div class="col">
        </div>
        <div class="col">  <!--Row nested before nesting columns-->
            <div class="row">
                <div class="col">
                <div class="col">
            </div>
        </div>
    </div>
</div>
</code>```

Both work in terms of actually making the page, but I do not know what is considered "good practice". There are obviously limitations to both ways of writing things. In my case, I'd want the "column" to be filled with a dynamically generated amount of elements, which on different screen resolutions/responsive sizes would be aligned, so a row wrapper is not an option. I do not know how many elements per row I'd have, which would make the following rows break and wrap when it is not needed.

So, is it okay to nest columns within columns without a row to hold the children?

答:
Nested rows are better semantically and in some edge cases to maintain the design. This is however opinion but opinion that's based on best practice.

I'd put the row before for the column just to be clear on your intent and to make it more modular.

It's best to think about it as a module and ask yourself "Can I lift this section of markup out of its position and put it anywhere else on the page and it still hold its form?" By encapsulating it within a row, you can answer yes to that question. Of course its always a battle between only putting in mark-up that is necessary and being modular but with concepts such as SMACSS, Object Oriented CSS etc... taking the lead in how we think about structuring our markup and CSS its seems consensus is with a bit of extra markup in order to maintain modularization.

Title: Nesting columns good practice?

Body:
I am unable to find any rules as to whether or not this is something that should be done. Bootstrap clearly outlines amongst its rules the following:

Rows must be placed within a .container (fixed-width) or
.container-fluid (full-width) for proper alignment and padding

Use rows to create horizontal groups of columns

Content should be placed within columns, and only columns may be

immediate children of rows

So from this I conclude that each section of the website that I do want self-contained would have a container class. Within this we'd have a row and within that we'd have a column. Like so:

COL 1 of 2

COL 2 of 2

Now my question is, the rules specify that only columns may be immediate children of rows but it doesn't say what the children of columns should be. If I was to want to "nest" another set of double columns within another column, would I write it like in case one or case two?

Both work in terms of actually making the page, but I do not know what is considered "good practice". There are obviously limitations to both ways of writing things. In my case, I'd want the "column" to be filled with a dynamically generated amount of elements, which on different screen resolutions/responsive sizes would be aligned, so a row wrapper is not an option. I do not know how many elements per row I'd have, which would make the following rows break and wrap when it is not needed.

So, is it okay to nest columns within columns without a row to hold the children?


问:
Setting jython interpreter to PyDev
We are developing an RCP application that is supposed to debug/run jython scripts. These scripts contain our specific annotations so we needed to create our own PythonInterpreter instance and configure it to support our modules and handlers.
We are trying to integrate PyDev into our application in order to get the debugger, editor and what not, but are having problems when trying to set our own jython interpreter object to PyDev.

How is this supposed to be done?

From some investigation we can see that interpreter manager requires executable (jython or python). Is it possible somehow to set our object to the PyDev or somehow to extend PyDev's interpreter object and add our handlers and modules?

EDIT:

So, the problems we had are that when we tried to set jython jar as a jython interpreter programmatically, we got errors that it didn't have main class and could not be treated as an interpreter. What we did is, we found appropriate jython standalone jar that did not cause us those problems.
By setting our modules and handlers means that we kind of extended jython script capabilities programmatically to have some annotations that the interpreter is aware of. For example if we have python code:

```<code>@valueChangeHandler(context.controls.Blank.button_0)
def ASP1_configurePanelSettings(event):
    print "Stuff happend"
</code>```

the interpreter is aware that the @ annotated function will be executed when some event happens. We also need to add libraries with some jar files when the interpreter is being instantiated. For instance:

```<code>interpreter.exec("import sys");
if (modulePaths != null && modulePaths.length > 0)
{
    final StringBuilder imports = new StringBuilder();
    for (final String modulePath : modulePaths)
        imports.append("\nsys.path.append('" + modulePath + "')");
    interpreter.exec(imports.toString());
}
</code>```

So, to do this we need to have interpreter object at our disposal at any time. We noticed that when .py file is opened in pydev editor, a new instance of interpreter is created. Is there any way we can get this interpreter object in our code and manipulate it?

答: You should be able to configure your own jython interpreter through org.python.pydev.ui.interpreters.JythonInterpreterManager and configure it as needed through the org.python.pydev.ui.interpreters.AbstractInterpreterManager.setInfos(IInterpreterInfo[], Set<String>, IProgressMonitor) method.

Title: Setting jython interpreter to PyDev

Body:
We are developing an RCP application that is supposed to debug/run jython scripts. These scripts contain our specific annotations so we needed to create our own PythonInterpreter instance and configure it to support our modules and handlers.
We are trying to integrate PyDev into our application in order to get the debugger, editor and what not, but are having problems when trying to set our own jython interpreter object to PyDev.

How is this supposed to be done?

From some investigation we can see that interpreter manager requires executable (jython or python). Is it possible somehow to set our object to the PyDev or somehow to extend PyDev's interpreter object and add our handlers and modules?

EDIT:

So, the problems we had are that when we tried to set jython jar as a jython interpreter programmatically, we got errors that it didn't have main class and could not be treated as an interpreter. What we did is, we found appropriate jython standalone jar that did not cause us those problems.
By setting our modules and handlers means that we kind of extended jython script capabilities programmatically to have some annotations that the interpreter is aware of. For example if we have python code:

@valueChangeHandler(context.controls.Blank.button_0)
def ASP1_configurePanelSettings(event):
    print "Stuff happend"

the interpreter is aware that the @ annotated function will be executed when some event happens. We also need to add libraries with some jar files when the interpreter is being instantiated. For instance:

interpreter.exec("import sys");
if (modulePaths != null && modulePaths.length > 0)
{
    final StringBuilder imports = new StringBuilder();
    for (final String modulePath : modulePaths)
        imports.append("\nsys.path.append('" + modulePath + "')");
    interpreter.exec(imports.toString());
}

So, to do this we need to have interpreter object at our disposal at any time. We noticed that when .py file is opened in pydev editor, a new instance of interpreter is created. Is there any way we can get this interpreter object in our code and manipulate it?


问:
MouseListener doesn't work the first time
I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

```<code>private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }
    });
</code>```

Does anyone know how to fix it in order to work from the first click and hide the current frame?

答:
Java Labels are not capable of receiving ActionListener event, you should replace the label with a button. You don't click on labels you click on button, what could work for the label probably would be a property change listeners.

Run and analysis this code it will clearly guide you... and good luck you chose the best language in the world, am a java guy two

```<code>class MainFrame extends JFrame {

JButton button2 = new JButton("Go to Frame 2");

public MainFrame() {
    setSize(500, 500);
    getContentPane().setBackground(Color.RED);
    setLayout(new FlowLayout());

    add(button2);

    button2.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            setVisible(false);
            new Sample2().setVisible(true);
        }
    });
}}

public class Sample2 extends JFrame {

JButton button4;

public Sample2() {

    setSize(500, 600);
    setLayout(new FlowLayout());
    getContentPane().setBackground(Color.YELLOW);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MainFrame mf = new MainFrame();
    button4 = new JButton("Button 4");
    add(button4);

    button4.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("It works.");
            mf.setVisible(true);
            setVisible(false);
        }
    });
}
public static void main(String[] args) {
    Sample2 sample2 = new Sample2();
    sample2.setVisible(true);
}}
</code>```

Body:
I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }
    });

Does anyone know how to fix it in order to work from the first click and hide the current frame?

Body:
Java Labels are not capable of receiving ActionListener event, you should replace the label with a button. You don't click on labels you click on button, what could work for the label probably would be a property change listeners.

Run and analysis this code it will clearly guide you... and good luck you chose the best language in the world, am a java guy two

class MainFrame extends JFrame {

JButton button2 = new JButton("Go to Frame 2");

public MainFrame() {
    setSize(500, 500);
    getContentPane().setBackground(Color.RED);
    setLayout(new FlowLayout());

    add(button2);

    button2.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            setVisible(false);
            new Sample2().setVisible(true);
        }
    });
}}

public class Sample2 extends JFrame {

JButton button4;

public Sample2() {

    setSize(500, 600);
    setLayout(new FlowLayout());
    getContentPane().setBackground(Color.YELLOW);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MainFrame mf = new MainFrame();
    button4 = new JButton("Button 4");
    add(button4);

    button4.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("It works.");
            mf.setVisible(true);
            setVisible(false);
        }
    });
}
public static void main(String[] args) {
    Sample2 sample2 = new Sample2();
    sample2.setVisible(true);
}}


问:
Why my 2 same titan x have different memory size?
Why my 2 same titan x have different memory size? They differ by 1mb. Is it normal? Also, why the memory usage is different when running on caffe, which supposedly assign same number of images to the 2 gpus?

答: Your first GPU (GPU 0) is running some extra processes. When multiple NVIDIA GPUs are connected via SLI, only one of the GPUs performs the PhysX while the rest of the processes are distributed. So there is a slight extra load on one of the GPUs. A small portion of your primary device will always be reserved for some default processes.</p>


问:
Restricting posts to a specifc category and subcategory
On this site: http://www.palmbeachwoman.com/stories/ I used a programmer to customize the template. His code for this page is:

```<code><?php

$args = array( 'numberposts' => 18,   'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");

$postslist = get_posts( $args );

echo '<ul id="latest_stories">';

foreach ($postslist as $post) :  setup_postdata($post); ?>

<li><a href="<?php the_permalink(); ?>" title="<?php the_title();?>">

<span class="s_thumb"> <?php the_post_thumbnail( 'full' ); ?> </span>

<span class="s_title"> <?php the_title(); ?> </span></a>

<span class="s_cotegories">More Stories from <?php the_category( ', ' ); ?></span></li>

<?php endforeach; ?>
</code>```

The posts were supposed to be restricted to a specific category (#82) and any subcategories within it. I know how to do this with the traditional post display: http://alijafarian.com/how-to-display-wordpress-posts-for-a-specific-category/ but since I didn't write this code, I'm not sure how to modify it.

答:
You can set the category in the array past to get_posts</p>

```<code>$args = array( 'numberposts' => 18, 'post_status'=>"publish",'post_type'=>"post",
'orderby'=>"post_date", category=>82);
</code>```

Body:
On this site: http://www.palmbeachwoman.com/stories/ I used a programmer to customize the template. His code for this page is:

<?php

$args = array( 'numberposts' => 18,   'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");

$postslist = get_posts( $args );

echo '
';

foreach ($postslist as $post) :  setup_postdata($post); ?>

<a href="<?php the_permalink(); ?>" title="<?php the_title();?>">

 <?php the_post_thumbnail( 'full' ); ?>

 <?php the_title(); ?>

More Stories from <?php the_category( ', ' ); ?>

<?php endforeach; ?>

The posts were supposed to be restricted to a specific category (#82) and any subcategories within it. I know how to do this with the traditional post display: http://alijafarian.com/how-to-display-wordpress-posts-for-a-specific-category/ but since I didn't write this code, I'm not sure how to modify it.

Body:
You can set the category in the array past to get_posts

$args = array( 'numberposts' => 18, 'post_status'=>"publish",'post_type'=>"post",
'orderby'=>"post_date", category=>82);


问:
Second argument to std::vector
Looking at vector, I realized that I have never used the second argument when creating vectors.

```<code>std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?
</code>```

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?

答: Hi you can find example of custom allocator http://www.codeproject.com/KB/cpp/allocator.aspx</p>

Title: Second argument to std::vector

Body:
Looking at vector, I realized that I have never used the second argument when creating vectors.

std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?


问:
Best way to cancel task with functions that don't implement InterruptedException
I would like to cancel the following task

```<code>fooFuture = executor.submit(() ->  {
    bar1();
    bar2();
    bar3();
});
</code>```

The bar functions don't implement InterruptedException.

Is there a way I can catch an interrupt without checking Thread.currentThread().isInterruped(); after every instruction?

答: In a word, no. You don’t have to check after every line, of course, but methods which can take a long time to execute are responsible for properly handling interrupts. If they don’t, you’re out of luck, unfortunately.

Body:
I would like to cancel the following task

fooFuture = executor.submit(() ->  {
    bar1();
    bar2();
    bar3();
});

The bar functions don't implement InterruptedException.

Is there a way I can catch an interrupt without checking Thread.currentThread().isInterruped(); after every instruction?


问:
Unable to use RadioButton with JQuery - Alert doesn't pop up
I have two radio buttons and I want to display an alert when one of them is checked, it seems that the problem is that it doesn't recognize the element because the alert doesn't pop up!

This code used to work but it doesn't anymore (I think I changed the Id of one of the elements and that's what caused the issue)

JS:

```<code>/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
});
/*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

$("form input:radio").change(function() {
    if ($(this).val() == "Yes") {
        document.getElementById("recordType").value = "01220000000FdvyAAC";
        alert("Yes");

    } else {
        document.getElementById("recordType").value = "01220000000FffjAAC";
        console.log(document.getElementById("recordType").value);
        alert("No");
    }
});
</code>```

HTML

```<code>    <form method='post' id='prechatForm' autocomplete="on">
        <div id="bankEmployeeYesNoRadioButtonDiv">
          <label>{!$Label.Bank_Employee}</label><br/>
          <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
          <label for="radio-2" class="radioLabel">{!$Label.No}</label>
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>
        </div>
</form>
</code>```

Result: When I click on a radio button nothing happens, no alert.
No Console Errors
Notes: Please note that I'm using Salesforce (Visualforce) syntax.

答:
Your have a lot of mistake... You try to find "form" in your js but you don't have any form tag in your HTML, you don't have also tag with this id : "recordType".
However, your alert is good :)

Next time, just F12 (open your browser console) and read the errors.

EDIT : Add JQuery UI

$("document").ready(function () {
    $(".r1").checkboxradio({
        icon: false
    });

    $(".r1").change(function () {
        if ($(this).val() == "Yes") {
            alert("Yes");
        } else {
            alert("No");
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
    <title>Test</title>
</head>

<body>
    <!-- Modal Register -->
    <div id="bankEmployeeYesNoRadioButtonDiv">
        <label>{!$Label.Bank_Employee}</label><br/>
        <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
        <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes" />
        <label for="radio-2" class="radioLabel">{!$Label.No}</label>
        <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No" />
    </div>
    <!--/ Modal Register -->
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="./script.js"></script>
</body>

</html></code>```

Body:
I have two radio buttons and I want to display an alert when one of them is checked, it seems that the problem is that it doesn't recognize the element because the alert doesn't pop up!

This code used to work but it doesn't anymore (I think I changed the Id of one of the elements and that's what caused the issue)

JS:

/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
});
/*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

$("form input:radio").change(function() {
    if ($(this).val() == "Yes") {
        document.getElementById("recordType").value = "01220000000FdvyAAC";
        alert("Yes");

    } else {
        document.getElementById("recordType").value = "01220000000FffjAAC";
        console.log(document.getElementById("recordType").value);
        alert("No");
    }
});

HTML

    <form method='post' id='prechatForm' autocomplete="on">

          {!$Label.Bank_Employee}

          {!$Label.Yes}
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
          {!$Label.No}
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>

</form>

Result: When I click on a radio button nothing happens, no alert.
No Console Errors
Notes: Please note that I'm using Salesforce (Visualforce) syntax.

Body:
Your have a lot of mistake... You try to find "form" in your js but you don't have any form tag in your HTML, you don't have also tag with this id : "recordType".
However, your alert is good :)

Next time, just F12 (open your browser console) and read the errors.

EDIT : Add JQuery UI

$("document").ready(function () {
    $(".r1").checkboxradio({
        icon: false
    });

    $(".r1").change(function () {
        if ($(this).val() == "Yes") {
            alert("Yes");
        } else {
            alert("No");
        }
    });
});

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
    <title>Test</title>
</head>

<body>
    <!-- Modal Register -->
    <div id="bankEmployeeYesNoRadioButtonDiv">
        <label>{!$Label.Bank_Employee}</label><br/>
        <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
        <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes" />
        <label for="radio-2" class="radioLabel">{!$Label.No}</label>
        <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No" />
    </div>
    <!--/ Modal Register -->
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="./script.js"></script>
</body>

</html>


问:
Product is not displaying in listing in Magento after import?

I have created csv file and import that using System -> Import/Export -> Dataflow-Profile

I found that in Catalog -> Manage Categories in Category Products, product is displaying
but in Manage Products product is not displaying.

and in database catalog_product_flat_1 table has not entry for that product and in other tables there is entry for that product

I have Re-index data and cleared cache but no solution..

Please help some one..

答: It happened to me because of a special character in the product name. In my case the word "Crème" was creating all the trouble.</p>


问:
How to disable text selection highlighting
For anchors that act like buttons (for example, the buttons on the sidebar of this Stack Overflow page titled Questions, Tags, and Users) or tabs, is there a CSS standard way to disable the highlighting effect if the user accidentally selects the text?

I realize that this could be done with JavaScript and a little googling yielded the Mozilla-only -moz-user-select option.

Is there a standard-compliant way to accomplish this with CSS, and if not, what is the "best practice" approach?

答:
You can use CSS or JavaScript for that.

The JavaScript way is supported in older browsers, like old versions of Internet Explorer as well, but if it's not your case, use the CSS way then:

HTML/JavaScript:

This is the Heading!

And I'm the text, I won't be selected if you select me.

```
</div>
</div>
</p>

<p><strong>HTML/CSS:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.not-selectable {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}</code>```

This is the Heading!

And I'm the text, I won't be selected if you select me.

```

OwnerDisplayName: anon

LastEditorDisplayName: anon

ContentLicense: CC BY-SA 4.0

Body:
You can use CSS or JavaScript for that.

The JavaScript way is supported in older browsers, like old versions of Internet Explorer as well, but if it's not your case, use the CSS way then:

HTML/JavaScript:

<html onselectstart='return false;'>
  <body>
    <h1>This is the Heading!</h1>
    <p>And I'm the text, I won't be selected if you select me.</p>
  </body>
</html>

HTML/CSS:

.not-selectable {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

<body class="not-selectable">
  <h1>This is the Heading!</h1>
  <p>And I'm the text, I won't be selected if you select me.</p>
</body>


问:
Define Java POJO so Gson does not write value double quoted
Note is this example javascript

```<code><html>
<head>
<script type="text/javascript">
window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title: {
            text: "Using labelFormatter function of axisY"
        },
        axisY:{
            labelFormatter: function(e){
                return  "Y: " + e.value;
            }
        },
        data: [
        {
            type: "spline",
            dataPoints: [
                { y: 5  },
                { y: 9  },
                { y: 17 },
                { y: 32 },
                { y: 22 },
                { y: 14 },
                { y: 25 },
                { y: 18 },
                { y: 20 }
            ]
        }
        ]
    });
    chart.render();
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
</code>```

from http://canvasjs.com/docs/charts/chart-options/axisy/label-formatter/ that the value of labelFormatter field is not double quoted, and if I modify it to be double quoted then the code does not work.

I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

I am trying to generate such code from Java using Gson, how do I create my POJO so that its value is not double quoted when output to json. Currently it is just defined as type String and therefore gets double quoted.

e.g

```<code>public class AxisY
{
    private boolean reversed;
    private int     labelMaxWidth;
    private boolean labelWrap;
    private String  title;
    private int     viewportMinimum = 0;
    private int     viewportMaximum;
    private int     interval;
    private String  labelFormatter;

    public boolean isReversed()
    {
        return reversed;
    }

    public void setReversed(boolean reversed)
    {
        this.reversed = reversed;
    }

    public int getLabelMaxWidth()
    {
        return labelMaxWidth;
    }

    public void setLabelMaxWidth(int labelMaxWidth)
    {
        this.labelMaxWidth = labelMaxWidth;
    }

    public boolean isLabelWrap()
    {
        return labelWrap;
    }

    public void setLabelWrap(boolean labelWrap)
    {
        this.labelWrap = labelWrap;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getViewportMinimum()
    {
        return viewportMinimum;
    }

    public void setViewportMinimum(int viewportMinimum)
    {
        this.viewportMinimum = viewportMinimum;
    }

    public int getViewportMaximum()
    {
        return viewportMaximum;
    }

    public void setViewportMaximum(int viewportMaximum)
    {
        this.viewportMaximum = viewportMaximum;
    }

    public int getInterval()
    {
        return interval;
    }

    public void setInterval(int interval)
    {
        this.interval = interval;
    }

    public String getLabelFormatter()
    {
        return labelFormatter;
    }

    public void setLabelFormatter(String labelFormatter)
    {
        this.labelFormatter = labelFormatter;
    }
}

  <!DOCTYPE HTML>
    <html>
    <head>
    <script type="text/javascript">
    window.onload = function () {
        var chart = new CanvasJS.Chart("chartContainer",
        {
            title: {
                text: "Using labelFormatter function of axisY"
            },
            axisY:{
                labelFormatter: function(e){
                    return  "Y: " + e.value;
                }
            },
            data: [
            {
                type: "spline",
                dataPoints: [
                    { y: 5  },
                    { y: 9  },
                    { y: 17 },
                    { y: 32 },
                    { y: 22 },
                    { y: 14 },
                    { y: 25 },
                    { y: 18 },
                    { y: 20 }
                ]
            }
            ]
        });
        chart.render();
    }
    </script>
    <script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
    </head>
    <body>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
    </body>
    </html>
</code>```

答:
Pass the labelFormatter function as string, and in your js you will need to put an eval in the value like this:</p>

```<code>labelFormatter: eval("("+ <yourFunctionAsString> +")");
</code>```

Body:
Note is this example javascript

from http://canvasjs.com/docs/charts/chart-options/axisy/label-formatter/ that the value of labelFormatter field is not double quoted, and if I modify it to be double quoted then the code does not work.

I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

I am trying to generate such code from Java using Gson, how do I create my POJO so that its value is not double quoted when output to json. Currently it is just defined as type String and therefore gets double quoted.

e.g

public class AxisY
{
    private boolean reversed;
    private int     labelMaxWidth;
    private boolean labelWrap;
    private String  title;
    private int     viewportMinimum = 0;
    private int     viewportMaximum;
    private int     interval;
    private String  labelFormatter;

    public boolean isReversed()
    {
        return reversed;
    }

    public void setReversed(boolean reversed)
    {
        this.reversed = reversed;
    }

    public int getLabelMaxWidth()
    {
        return labelMaxWidth;
    }

    public void setLabelMaxWidth(int labelMaxWidth)
    {
        this.labelMaxWidth = labelMaxWidth;
    }

    public boolean isLabelWrap()
    {
        return labelWrap;
    }

    public void setLabelWrap(boolean labelWrap)
    {
        this.labelWrap = labelWrap;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getViewportMinimum()
    {
        return viewportMinimum;
    }

    public void setViewportMinimum(int viewportMinimum)
    {
        this.viewportMinimum = viewportMinimum;
    }

    public int getViewportMaximum()
    {
        return viewportMaximum;
    }

    public void setViewportMaximum(int viewportMaximum)
    {
        this.viewportMaximum = viewportMaximum;
    }

    public int getInterval()
    {
        return interval;
    }

    public void setInterval(int interval)
    {
        this.interval = interval;
    }

    public String getLabelFormatter()
    {
        return labelFormatter;
    }

    public void setLabelFormatter(String labelFormatter)
    {
        this.labelFormatter = labelFormatter;
    }
}

  <!DOCTYPE HTML>

Body:
Pass the labelFormatter function as string, and in your js you will need to put an eval in the value like this:

labelFormatter: eval("("+ <yourFunctionAsString> +")");


问:
Operate with my line and next line in data frame with R
I've a data frame like this:

```<code>A tibble: 693,748 x 10
   Target Orbit CrossSectionalArea Elevation  RAAN ObsType Observer           StartTime            StopTime  Duration
   <fctr> <int>             <fctr>     <int> <int>  <fctr>   <fctr>              <dttm>              <dttm>     <dbl>
1   Sat1   550                Ama         5     0       A      AV1 2019-09-01 20:47:50 2019-09-01 20:49:14  84.22333
2   Sat1   550                Ama         5     0       A      AV1 2019-09-03 09:54:27 2019-09-03 09:55:49  82.45977
3   Sat1   550                Ama         5     0       A      AV1 2019-09-04 09:45:37 2019-09-04 09:47:41 124.05633
</code>```

I'm trying to create a new column with mutate where newcolumn has StopTime - StartTime(next row). My problem is when I try to get StartTime(next row).

How can I do this operation?

Thank you!

答:
We can use</p>

```<code>df1 %>%
     mutate(newcolumn = StopTime  -  lead(StartTime))
</code>```

Body:
I've a data frame like this:

A tibble: 693,748 x 10
   Target Orbit CrossSectionalArea Elevation  RAAN ObsType Observer           StartTime            StopTime  Duration
   <fctr> <int>             <fctr>     <int> <int>  <fctr>   <fctr>              <dttm>              <dttm>     <dbl>
1   Sat1   550                Ama         5     0       A      AV1 2019-09-01 20:47:50 2019-09-01 20:49:14  84.22333
2   Sat1   550                Ama         5     0       A      AV1 2019-09-03 09:54:27 2019-09-03 09:55:49  82.45977
3   Sat1   550                Ama         5     0       A      AV1 2019-09-04 09:45:37 2019-09-04 09:47:41 124.05633

I'm trying to create a new column with mutate where newcolumn has StopTime - StartTime(next row). My problem is when I try to get StartTime(next row).

How can I do this operation?

Thank you!

Body:
We can use

df1 %>%
     mutate(newcolumn = StopTime  -  lead(StartTime))


问:
Liferay7 : Delete title from FORM
Hello ,

I am working with Liferay 7 and I have no idea how to delete the Title and description from Liferay FORM application.

Thank you

答:
Try those 3 steps :

1- Go to the Look and feel configuration

2- Use Custom Title switch it to : YES

3- Try to make the title empty for all languages

4- Save and refresh you page

Title: Liferay7 : Delete title from FORM


问:
JRuby on Rails does not work with Tomcat running as a service on Windows Server 2008

Problem

It seems like running Tomcat as a service doesn't play well with Rails 3 applications that are packaged up using warble. Looking at the log files, it looks like there is either a circular dependency or a dependency that is being dynamically resolved but cannot be found, so it loops. Eventually, org.jruby.exceptions.RaiseException: stack level too deep is thrown. However, when I use startup.bat to start Tomcat instead, this problem does not occur.

Any help would be appreciated! I've been desperately searching for answer to this. Thanks in advance!

Deployment Platform

Windows Server 2008 (64-bit)

Apache Tomcat 6.29 (64-bit)

JDK 1.6

Rails 3

jruby 1.5.6

warbler (1.2.1)

jruby-jars (>= 1.4.0)

jruby-rack (>= 1.0.0)

Tomcat localhost.log

http://pastie.org/1308566

答:
I would guess your database connection information contains an unexpected null string, which the system is attempting to convert to uppercase somewhere. See this error message as the hint:

at
  ERB.result(C:/bin/apache-tomcat-6.0.29/webapps/rails3app/WEB-INF/gems/gems/railties-3.0.0/lib/rails/application/configuration.rb:86)
    at
  Rails::Application::Configuration.database_configuration(C:/bin/apache-tomcat-6.0.29/webapps/rails3app/WEB-INF/gems/gems/activerecord-3.0.0/lib/active_record/railtie.rb:58)

This may be correctable with a configuration edit.


问:
How to use Snapchat in swift, Does an API exist?
I'm looking an iOS / Swift API to publish photo directly in user story. I can't find any information. Is it possible ? Somebody already do it ?

Regards

答:
Snapchat does not allow third party apps, and does not allow third parties to connect to its private API, and does not provide developers with a public API.

MORE INFO:- https://www.snap.com/en-US/news/post/third-party-applications-and-the-snapchat-api/


问:
How to map EXIT CODE 2 in spring batch when input file is not located at the source folder
I have to map exit code 2 whenever input file is not located in the source folder in spring batch.I have tried by implementing listener but batch terminate before starting and return exit code 1. It doesn't reach to the listener to map it with exit code 2. So can someone help me in that.Thanks in advance.</p>

答:
I'm assuming you mean the EXIT_CODE in the BATCH_STEP_EXECUTION table, not the exit code from like System.exit(int x).

In that case, it's probably easier to just change the reader not to throw the Exception (and instead just return null when the read() method executes. The FlatFileItemReader makes this easy by just setting the strict property to false.

If you meant the actual JVM exit code (which is pretty gross), then you'd basically have to register a StepExecutionListener and then inform the calling class that the failure occurred... please note: I don't recommend this pattern

```<code>// In MainClass
private static final AtomicBoolean fileNotFound = new AtomicBoolean(false);

public static void main(String[] args) {
    // launch job

    if (fileNotFound.get()) {
        System.exit(2);
    }
}

public static void setFileNotFound(boolean bool) {
    fileNotFound.set(bool);
}

// In StepExecutionListener
public void afterStep(StepExecution stepExecution) {
    for (Throwable error : stepExecution.getFailureExceptions()) {
        if (error instanceof IllegalArgumentException && "source cannot be null".equals(error.getMessage())) {
            MainClass.setFileNotFound(true);
        }
    }
}
</code>```

Body:
I'm assuming you mean the EXIT_CODE in the BATCH_STEP_EXECUTION table, not the exit code from like System.exit(int x).

In that case, it's probably easier to just change the reader not to throw the Exception (and instead just return null when the read() method executes. The FlatFileItemReader makes this easy by just setting the strict property to false.

If you meant the actual JVM exit code (which is pretty gross), then you'd basically have to register a StepExecutionListener and then inform the calling class that the failure occurred... please note: I don't recommend this pattern

// In MainClass
private static final AtomicBoolean fileNotFound = new AtomicBoolean(false);

public static void main(String[] args) {
    // launch job

    if (fileNotFound.get()) {
        System.exit(2);
    }
}

public static void setFileNotFound(boolean bool) {
    fileNotFound.set(bool);
}

// In StepExecutionListener
public void afterStep(StepExecution stepExecution) {
    for (Throwable error : stepExecution.getFailureExceptions()) {
        if (error instanceof IllegalArgumentException && "source cannot be null".equals(error.getMessage())) {
            MainClass.setFileNotFound(true);
        }
    }
}


问:
How do I get properties that ONLY have populated values?
How do I get properties that ONLY have populated values?

So for example if I run

```<code>Get-QADUser -Identity "SomeOne" -IncludeAllProperties
</code>```

the output would of course include.. all properties, including those with and those without values. I want a listing of properties with values only. How is it done generally speaking?

This wouldn't be restricted to Quest Cmdlets, I only use Get-QADUser as an example.

答:
To complement Charlie Joynt's helpful answer:

Below is convenience function Remove-NullProperties, which creates custom-object copies of its input objects populated with only the non-$null properties of the input objects.

Example use:

```<code># Sample input collection, with 2 objects with different $null-valued
# properties.
$coll = [pscustomobject] @{ one = 'r1c1'; two = $null; three = 'r1c3' },
        [pscustomobject] @{ one = 'r2c1'; two = 'r2c2'; three = $null }

# Output copies containing only non-$null-valued properties.
# NOTE: The `ForEach-Object { Out-String -InputObject $_ }` part is solely
#       there to ensure that *all* resulting properties are shown.
#       With the default output, only the properties found on the FIRST
#       input object would be used in the output table.
$coll | Remove-NullProperties |
  ForEach-Object { Out-String -InputObject $_ }
</code>```

This yields the following - note how the respective null-valued properties were removed:

```<code>one  three
---  -----
r1c1 r1c3

one  two
---  ---
r2c1 r2c2
</code>```

Remove-NullProperties source code:

```<code><#
.SYNOPSIS
Removes properties with $null values from custom-object copies of
the input objects.

.DESCRIPTION
Note that output objects are custom objects that are copies of the input
objects with copies of only those input-object properties that are not $null.

CAVEAT: If you pipe multiple objects to this function, and these objects
        differ in what properties are non-$null-valued, the default output
        format will show only the non-$null-valued properties of the FIRST object.
        Use ... | ForEach-Object { Out-String -InputObject $_ } to avoid
        this problem.

.NOTES
Since the output objects are generally of a distinct type - [pscustomobject] -
and have only NoteProperty members, use of this function only makes sense
with plain-old data objects as input.

.EXAMPLE
> [pscustomobject] @{ one = 1; two = $null; three = 3 } | Remove-NullProperties

one three
--- -----
  1     3

#>
function Remove-NullProperties {

  param(
    [parameter(Mandatory,ValueFromPipeline)]
    [psobject] $InputObject
  )

  process {
    # Create the initially empty output object
    $obj = [pscustomobject]::new()
    # Loop over all input-object properties.
    foreach($prop in $InputObject.psobject.properties) {
      # If a property is non-$null, add it to the output object.
      if ($null -ne $InputObject.$($prop.Name)) {
        Add-Member -InputObject $obj -NotePropertyName $prop.Name -NotePropertyValue $prop.Value
      }
    }
    # Give the output object a type name that reflects the type of the input
    # object prefixed with 'NonNull.' - note that this is purely informational, unless
    # you define a custom output format for this type name.
    $obj.pstypenames.Insert(0, 'NonNull.' + $InputObject.GetType().FullName)
    # Output the output object.
    $obj
  }

}
</code>```

Body:
How do I get properties that ONLY have populated values?

So for example if I run

Get-QADUser -Identity "SomeOne" -IncludeAllProperties

the output would of course include.. all properties, including those with and those without values. I want a listing of properties with values only. How is it done generally speaking?

This wouldn't be restricted to Quest Cmdlets, I only use Get-QADUser as an example.

Body:
To complement Charlie Joynt's helpful answer:

Below is convenience function Remove-NullProperties, which creates custom-object copies of its input objects populated with only the non-$null properties of the input objects.

Example use:

# Sample input collection, with 2 objects with different $null-valued
# properties.
$coll = [pscustomobject] @{ one = 'r1c1'; two = $null; three = 'r1c3' },
        [pscustomobject] @{ one = 'r2c1'; two = 'r2c2'; three = $null }

# Output copies containing only non-$null-valued properties.
# NOTE: The `ForEach-Object { Out-String -InputObject $_ }` part is solely
#       there to ensure that *all* resulting properties are shown.
#       With the default output, only the properties found on the FIRST
#       input object would be used in the output table.
$coll | Remove-NullProperties |
  ForEach-Object { Out-String -InputObject $_ }

This yields the following - note how the respective null-valued properties were removed:

one  three
---  -----
r1c1 r1c3

one  two
---  ---
r2c1 r2c2

Remove-NullProperties source code:

<#
.SYNOPSIS
Removes properties with $null values from custom-object copies of
the input objects.

.DESCRIPTION
Note that output objects are custom objects that are copies of the input
objects with copies of only those input-object properties that are not $null.

CAVEAT: If you pipe multiple objects to this function, and these objects
        differ in what properties are non-$null-valued, the default output
        format will show only the non-$null-valued properties of the FIRST object.
        Use ... | ForEach-Object { Out-String -InputObject $_ } to avoid
        this problem.

.NOTES
Since the output objects are generally of a distinct type - [pscustomobject] -
and have only NoteProperty members, use of this function only makes sense
with plain-old data objects as input.

.EXAMPLE
> [pscustomobject] @{ one = 1; two = $null; three = 3 } | Remove-NullProperties

one three
--- -----
  1     3

#>
function Remove-NullProperties {

  param(
    [parameter(Mandatory,ValueFromPipeline)]
    [psobject] $InputObject
  )

  process {
    # Create the initially empty output object
    $obj = [pscustomobject]::new()
    # Loop over all input-object properties.
    foreach($prop in $InputObject.psobject.properties) {
      # If a property is non-$null, add it to the output object.
      if ($null -ne $InputObject.$($prop.Name)) {
        Add-Member -InputObject $obj -NotePropertyName $prop.Name -NotePropertyValue $prop.Value
      }
    }
    # Give the output object a type name that reflects the type of the input
    # object prefixed with 'NonNull.' - note that this is purely informational, unless
    # you define a custom output format for this type name.
    $obj.pstypenames.Insert(0, 'NonNull.' + $InputObject.GetType().FullName)
    # Output the output object.
    $obj
  }

}


问:
How to extend d3 with related library in typescript/webpack environment?
I'm trying to use the d3.tip extension with d3v4 inside a typescript/webpack build.

I've tried to implement this with two different d3.tip forks which have modified the library to be up to date with d3v4. These can be found here and here.

I've then installed @types/d3-tip which can be found here

After installing the types, and then requiring the code inside my main index file like;

```<code>import * as d3 from 'd3';

require('./d3-tip.js');

var tip = d3.tip()
</code>```

I keep getting a compile error -

error TS2339: Property 'tip' does not exist on type 'typeof "/node_modules/@types/d3/index"'.

One thing I have tried is to export the d3 tip typings from inside the main d3 typings file, so that the original d3 typings file includes;

export * from 'd3-tip';

This however has not worked, so I'm not sure how else I could fix it?

I've looked around for similar questions but none offer a definitive answer, and any of the solutions posted did not work for me.

答:
If you look at the source for the plugin, it correctly registers itself as an AMD module when required. To correctly import and use, you simply need to name it,</p>

```<code>import d3tip from 'd3-tip';

d3tip().attr...
</code>```

Body:
I'm trying to use the d3.tip extension with d3v4 inside a typescript/webpack build.

I've tried to implement this with two different d3.tip forks which have modified the library to be up to date with d3v4. These can be found here and here.

I've then installed @types/d3-tip which can be found here

After installing the types, and then requiring the code inside my main index file like;

import * as d3 from 'd3';

require('./d3-tip.js');

var tip = d3.tip()

I keep getting a compile error -

error TS2339: Property 'tip' does not exist on type 'typeof "/node_modules/@types/d3/index"'.

One thing I have tried is to export the d3 tip typings from inside the main d3 typings file, so that the original d3 typings file includes;

export * from 'd3-tip';

This however has not worked, so I'm not sure how else I could fix it?

I've looked around for similar questions but none offer a definitive answer, and any of the solutions posted did not work for me.

Body:
If you look at the source for the plugin, it correctly registers itself as an AMD module when required. To correctly import and use, you simply need to name it,

import d3tip from 'd3-tip';

d3tip().attr...


问:
Nginx automated /tmp cleanup?
I've installed Nginx on my vps

i found this message inside Nginx Admin

```<code>To automated /tmp cleanup add bellow cron
0 */1 * * * /usr/sbin/tmpwatch -am 1 /tmp/nginx_client
via crontab -e command
</code>```

where i should execute this line ?

```<code> 0 */1 * * * /usr/sbin/tmpwatch -am 1 /tmp/nginx_client
</code>```

my vps centos 5 32 cpanel

答:
another way...</p>

```<code>0 * * * * find /tmp/nginx_client/ -type f -mtime +8 -delete > /dev/null 2>&1
</code>```

Title: Nginx automated /tmp cleanup?

Body:
I've installed Nginx on my vps

i found this message inside Nginx Admin

To automated /tmp cleanup add bellow cron
0 */1 * * * /usr/sbin/tmpwatch -am 1 /tmp/nginx_client
via crontab -e command

where i should execute this line ?

 0 */1 * * * /usr/sbin/tmpwatch -am 1 /tmp/nginx_client

my vps centos 5 32 cpanel

Body:
another way...

0 * * * * find /tmp/nginx_client/ -type f -mtime +8 -delete > /dev/null 2>&1


问:
C# - Capturing user clicks on other application
I need to create a program that can record user clicks for another Windows application. Essentially my program should read a data file and automatically run another application and enter the data. I understand that there are process automation tools but they are prohibitively expensive for one-time use. For refernce of this forum a simimar question was asked in past but was not answered so recreating it.

Capturing user events (button clicks etc) from another Windows application

Thanks

答:
I think you need global mouse event listener.
Something like this:
https://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C</p>


问:
How to show login/logout links the rails way?
I have a property that is exposed in my view @is_logged_in

if its true, then I want to show the 'logout' link, otherwise I want to show the 'login' link.

Is there a fancy rails way to do this?

答:
```<code><%= link_to_if(@is_logged_in, "Logout", logout_path) do
       link_to("Login", login_path)
    end
%>
</code>```


问:
how to speed up my macro?
I faced an interesting problem with my macro that parses log files (1GB).

Of course there are some settings as follows:

```<code>Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
Application.DisplayAlerts = False
Application.CutCopyMode = False
</code>```

And also there is one general loop by log file lines with DoEvents within (to prevent excel screen from freezes).

The problem is the macro is very slow when my mouse pointer hovers over cells. Once the pointer moves away from the excel cells, the macro starts working 30 times faster! Any ideas why this happens and how to resolve the problem?

One proposed way is

application.visible=false

but it looks like excel crashes while the macro is running.

答:
Something you can definitely add is:

Application.Cursor = xlWait

Then switch it back at the end

Application.Cursor = xlDefault

This will get rid of the cursor flickering

Title: how to speed up my macro?

Body:
I faced an interesting problem with my macro that parses log files (1GB).

Of course there are some settings as follows:

Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
Application.DisplayAlerts = False
Application.CutCopyMode = False

And also there is one general loop by log file lines with DoEvents within (to prevent excel screen from freezes).

The problem is the macro is very slow when my mouse pointer hovers over cells. Once the pointer moves away from the excel cells, the macro starts working 30 times faster! Any ideas why this happens and how to resolve the problem?

One proposed way is

application.visible=false

but it looks like excel crashes while the macro is running.


问:
Material-ui: How to stop propagation of click event in nested components
I have an IconMenu component inside a Paper component.
I would like to prevent the propagation of the click event on the inner component (the IconMenu).
That's what I came up with, without significant results (I also tried substituting onClick with onTouchTap, onMouseUp with same effects): the _iconMenuClick method is never called.

```<code>render() {
     return (
         <Paper onClick={this._onClick}>
             <IconMenu iconButtonElement={iconButtonElement} onClick={this._iconMenuClick}>
                 {menuItems}
             </IconMenu>
         </Paper>
     );
}

_iconMenuClick(event) {
    MenuItem.onClick(event);
    event.stopPropagation();
}
</code>```

答:
For stopping top node bubble events :-)

event.stopPropagation();
event.preventDefault();

Body:
I have an IconMenu component inside a Paper component.
I would like to prevent the propagation of the click event on the inner component (the IconMenu).
That's what I came up with, without significant results (I also tried substituting onClick with onTouchTap, onMouseUp with same effects): the _iconMenuClick method is never called.

render() {
     return (
         <Paper onClick={this._onClick}>
             <IconMenu iconButtonElement={iconButtonElement} onClick={this._iconMenuClick}>
                 {menuItems}
             </IconMenu>
         </Paper>
     );
}

_iconMenuClick(event) {
    MenuItem.onClick(event);
    event.stopPropagation();
}


问:
Tools used for programming in Linux
I would like to start programming using the Linux operating system and all the free stuff out there.

What is the most common and the best language to use with Linux, C or C++ or C#?

What tools are similar to Turbo C, or Visual Studio in Windows?

答: vim + gcc/g++ +make. Language choice is task dependent/personal, but I'm not sure C# can be considered for Linux (Mono fans are welcome to downvote :) ).

Title: Tools used for programming in Linux


问:
Mixing UTF-8 with UTF-16
I'm currently working on a korean program, which should be translated into chinese language. What I found strange, is that application is mixing UTF-8 and UTF-16 characters.

Let's say we've a string which goes as:

```<code>"게임을 정말로 종료하시겠습니까"
8C AC 84 C7 44 C7 20 00 15 C8 D0 B9 5C B8 20 00
85 C8 CC B8 58 D5 DC C2 A0 AC B5 C2 C8 B2 4C AE 00
</code>```

But it's stored as

```<code>B0 D4 C0 D3 C0 BB 20 C1 A4 B8 BB B7 CE 20 C1 BE
B7 E1 C7 CF BD C3 B0 DA BD C0 B4 CF B1 EE 3F 00
</code>```

just to prevent zeros. I'd like to know, if it's some kind of encryption, or is it just a normal method used by compilers to prevent end of the string somewhere in the middle of the string? Because, the final result is the first string, that I've mentioned. Any reading would be strongly appreciated.

答:
A string must be either uft-8 or utf-16 (or some other encoding). If you mix encodings in a string it is an error. However it is very common to pass string about as utf-8, and only convert them to utf-16 when needed by a Windows function. There are several reasons for this, Basile Starynkevitch has provided a link.

If you need routines to read UFT-8, I've got some here.

https://github.com/MalcolmMcLean/babyx/blob/master/src/common/BBX_Font.c

Title: Mixing UTF-8 with UTF-16

Body:
I'm currently working on a korean program, which should be translated into chinese language. What I found strange, is that application is mixing UTF-8 and UTF-16 characters.

Let's say we've a string which goes as:

"게임을 정말로 종료하시겠습니까"
8C AC 84 C7 44 C7 20 00 15 C8 D0 B9 5C B8 20 00
85 C8 CC B8 58 D5 DC C2 A0 AC B5 C2 C8 B2 4C AE 00

But it's stored as

B0 D4 C0 D3 C0 BB 20 C1 A4 B8 BB B7 CE 20 C1 BE
B7 E1 C7 CF BD C3 B0 DA BD C0 B4 CF B1 EE 3F 00

just to prevent zeros. I'd like to know, if it's some kind of encryption, or is it just a normal method used by compilers to prevent end of the string somewhere in the middle of the string? Because, the final result is the first string, that I've mentioned. Any reading would be strongly appreciated.


问:
Cannot get a joined Kafka stream to run or output anything
For the below code, both stream1 and stream2 run fine individually and I can see output, but the joined stream just doesn't log anything at all. I have a feeling it has something to do with the join window, but the data from both streams comes in at almost exactly the same time.</p>

```<code>val stream = builder.stream(stringSerde, byteArraySerde, "topic")

val stream1 = stream
  .filter((key, value) => somefilter(key, value))
  .through(stringSerde, byteArraySerde, "topic1")

val stream2 = stream
  .filter((key, value) => someotherfilter(key, value))
  .through(stringSerde, byteArraySerde, "topic2")

val joinedStream = stream1
  .join(stream2, (value1: Array[Byte], value2: Array[Byte]) => {
    println("wont print anything")
    return somerandomdata
  },
  JoinWindows.of("othertopic").within(10000L),
  stringSerde, byteArraySerde, byteArraySerde)
</code>```

答:
Shouldn't the keys of both topic be te same in order to join them?

I think the Javadoc explains this :
https://kafka.apache.org/0102/javadoc/org/apache/kafka/streams/kstream/JoinWindows.html

This might also be an interesting read :
https://cwiki.apache.org/confluence/display/KAFKA/Kafka+Streams+Join+Semantics

Body:
For the below code, both stream1 and stream2 run fine individually and I can see output, but the joined stream just doesn't log anything at all. I have a feeling it has something to do with the join window, but the data from both streams comes in at almost exactly the same time.

val stream = builder.stream(stringSerde, byteArraySerde, "topic")

val stream1 = stream
  .filter((key, value) => somefilter(key, value))
  .through(stringSerde, byteArraySerde, "topic1")

val stream2 = stream
  .filter((key, value) => someotherfilter(key, value))
  .through(stringSerde, byteArraySerde, "topic2")

val joinedStream = stream1
  .join(stream2, (value1: Array[Byte], value2: Array[Byte]) => {
    println("wont print anything")
    return somerandomdata
  },
  JoinWindows.of("othertopic").within(10000L),
  stringSerde, byteArraySerde, byteArraySerde)


问:
Passing arguments to a Scala udf
I am calling a udf on a specific column of my dataframe, in which I check if all values are valid as per a specified date format.

```<code>sourcefile = sourcefile.withColumn(column, DateConversion(col(column)))
</code>```

Here DateConversion is my udf. My question here is that, is there a way  by which I can pass the valid date format "yyyy/MM/dd" as a string to this udf which can be used internally in the udf for validation purposes.

I was trying

```<code>sourcefile = sourcefile.withColumn(column, DateConversion(col(column),"yyyy/MM/dd"))
</code>```

But this gives and error.

答:
You can use lit function to create a literal column and pass to the udf.

```<code>def udfName = udf((name: String, value:String) => {
      name + value
    })
</code>```

Use lit() function while calling udf:

```<code>dataframe.withColumn("colName", udfName($"firstName", lit("xyz")))
</code>```

Title: Passing arguments to a Scala udf

Body:
I am calling a udf on a specific column of my dataframe, in which I check if all values are valid as per a specified date format.

sourcefile = sourcefile.withColumn(column, DateConversion(col(column)))

Here DateConversion is my udf. My question here is that, is there a way  by which I can pass the valid date format "yyyy/MM/dd" as a string to this udf which can be used internally in the udf for validation purposes.

I was trying

sourcefile = sourcefile.withColumn(column, DateConversion(col(column),"yyyy/MM/dd"))

But this gives and error.

Body:
You can use lit function to create a literal column and pass to the udf.

def udfName = udf((name: String, value:String) => {
      name + value
    })

Use lit() function while calling udf:

dataframe.withColumn("colName", udfName($"firstName", lit("xyz")))


问:
Uploading screenshots error to the developer console
I get the following error when trying to upload an image as a screenshot to my developer console:

"You need to check that your screenshot image is a valid image."

I took a screenshot from my cell and uploaded it as a screenshot to the developer console and it worked.

Then I just added a line on top of the image using paint.

Tried to upload the modified image to the developer console but it failed.

My images are480wx800h PNG formatted images so it should be okay. (both the original and the modified bitmap).

Could any1 tell me how to solve this?
I want to upload a sample image from my app and add some instructions written on top of the image.
But i can't do it.

答:
It gave me error when i tried to upload IDE generated screen shot of wrong aspect ratio

i.e, i have taken Pixel screen shot from Android Studio IDE, and tried to upload directly to Playstore Store listing , it gave me error because the screen shot dimensions were of 1226 X 2502, It began to upload when i changed them to 1226 X 2452 (aspect ratio 1:2)

I hope Android Studio IDE will fix this in future.


问:
How to write linq query for sample xml
How to get the collection of values of elements from such an xml, using linq
(root/doc/files/file):

```<code><root>

  <doc>
    <files>
      <file>1</file>
      <file>2</file>
      <file>3</file>
    </files>
  </doc>

  <doc>
    <files>
      <file>4</file>
      <file>5</file>
      <file>6</file>
    </files>
  </doc>

</root>
</code>```

From that query I would like to have:

```<code>1
2
3
4
5
6
</code>```

Here is the beginning of the code I have written so far.

```<code>    string xmlIn = "<root> "+
                   "   <doc>"+
                   "     <files>"+
                   "       <file>1</file>"+
                   "       <file>2</file>"+
                   "       <file>3</file>  "+
                   "     </files>   "+
                   "   </doc>"+

                   " <doc>"+
                   "     <files>"+
                   "       <file>4</file>"+
                   "       <file>5</file>"+
                   "       <file>6</file>  "+
                   "     </files>   "+
                   "   </doc>"+

                   " </root>";

    var xml = XDocument.Parse(xmlin);
</code>```

答:
C#/.NET has an XML deserializer/parser:

```<code>using System.Xml;
</code>```

you can use it to load the XML:

```<code>  //using a previously created stream that holds an XML document
     XDocument xdoc =  XDocument.Load(xmlstream);
</code>```

You can then use LINQ to select what you want:

```<code> // this example looks for a tag called 'object' and then collects all
 // the objects of type 'cluster'
 var clusters = from cluster in _XDoc.Descendants("object")
                       where cluster.Attribute("type").Value == "cluster"
                       select cluster;
</code>```

Title: How to write linq query for sample xml

Body:
How to get the collection of values of elements from such an xml, using linq
(root/doc/files/file):

<root>

  <doc>
    <files>
      <file>1</file>
      <file>2</file>
      <file>3</file>
    </files>
  </doc>

  <doc>
    <files>
      <file>4</file>
      <file>5</file>
      <file>6</file>
    </files>
  </doc>

</root>

From that query I would like to have:

1
2
3
4
5
6

Here is the beginning of the code I have written so far.

    string xmlIn = "<root> "+
                   "   <doc>"+
                   "     <files>"+
                   "       <file>1</file>"+
                   "       <file>2</file>"+
                   "       <file>3</file>  "+
                   "     </files>   "+
                   "   </doc>"+

                   " <doc>"+
                   "     <files>"+
                   "       <file>4</file>"+
                   "       <file>5</file>"+
                   "       <file>6</file>  "+
                   "     </files>   "+
                   "   </doc>"+

                   " </root>";

    var xml = XDocument.Parse(xmlin);

Body:
C#/.NET has an XML deserializer/parser:

using System.Xml;

you can use it to load the XML:

  //using a previously created stream that holds an XML document
     XDocument xdoc =  XDocument.Load(xmlstream);

You can then use LINQ to select what you want:

 // this example looks for a tag called 'object' and then collects all
 // the objects of type 'cluster'
 var clusters = from cluster in _XDoc.Descendants("object")
                       where cluster.Attribute("type").Value == "cluster"
                       select cluster;


问:
Running the same query causing error the second time
I have a Data-table with all the mandatory fields which is required by select query in it. Now i am fetching data from 1st row of the data-table and running a select query (as given below). For the first time its working fine.
Now I am taking the 2nd row and giving all the mandatory fields (as i did for the first) and running the select query its giving error "insufficient permissions". When i am running both the select query (which are actually same but with different parameter) manually in Oracle SQL Developer its working fine.

```<code>Query1: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
Query2: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
</code>```

To fetch data from database

```<code>public OracleDataReader ExecuteReader(string SelectQuery, string conString)
        {
        try
        {
            OpenDbConnection(conString);

            OracleCommand cmd = new OracleCommand();
            cmd.Connection = con;
            cmd.CommandText = SelectQuery;
            cmd.CommandType = System.Data.CommandType.Text;
            OracleDataReader ora_dataReader = cmd.ExecuteReader();

            return ora_dataReader;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
        }
    }
</code>```

EDIT:
Forgot to mention that i am calling this funtion in another function as given below

```<code>public DataTable GetDataFromDB(string SelectQuery, string conString)
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Load(ExecuteReader(SelectQuery,conString));

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CloseDbConnection();
            }
        }
</code>```

答:
You need to open and close the connection after each query execution.

And also return the OracleDataReader after you have closed the connection or else it would lead to memory leak. If you return the OracleDataReader before you close connection, you would get the same error.

Try something like this:

```<code>public OracleDataReader ExecuteReader(string SelectQuery, string conString)
        {
        try
        {
        OpenDbConnection(conString);
        OracleCommand cmd = new OracleCommand();
        con.Open();
        cmd.Connection = con;
        cmd.CommandText = SelectQuery;
        cmd.CommandType = System.Data.CommandType.Text;
        OracleDataReader ora_dataReader = cmd.ExecuteReader();
    }
    catch (Exception ex)
    {
        Logging.LogMessage(Logging.LogLevel.Error, 0, "DAL", this.GetType().Name, ex.Message + " : " + ex.StackTrace);
        throw ex;
    }
    finally
    {
     con.close();
     con.Dispose();
    }

        return ora_dataReader;
}
</code>```

More info in this reference: https://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledatareader(v=vs.110).aspx

Body:
I have a Data-table with all the mandatory fields which is required by select query in it. Now i am fetching data from 1st row of the data-table and running a select query (as given below). For the first time its working fine.
Now I am taking the 2nd row and giving all the mandatory fields (as i did for the first) and running the select query its giving error "insufficient permissions". When i am running both the select query (which are actually same but with different parameter) manually in Oracle SQL Developer its working fine.

Query1: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
Query2: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'

To fetch data from database

public OracleDataReader ExecuteReader(string SelectQuery, string conString)
        {
        try
        {
            OpenDbConnection(conString);

            OracleCommand cmd = new OracleCommand();
            cmd.Connection = con;
            cmd.CommandText = SelectQuery;
            cmd.CommandType = System.Data.CommandType.Text;
            OracleDataReader ora_dataReader = cmd.ExecuteReader();

            return ora_dataReader;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
        }
    }

EDIT:
Forgot to mention that i am calling this funtion in another function as given below

public DataTable GetDataFromDB(string SelectQuery, string conString)
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Load(ExecuteReader(SelectQuery,conString));

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CloseDbConnection();
            }
        }

Body:
You need to open and close the connection after each query execution.

And also return the OracleDataReader after you have closed the connection or else it would lead to memory leak. If you return the OracleDataReader before you close connection, you would get the same error.

Try something like this:

public OracleDataReader ExecuteReader(string SelectQuery, string conString)
        {
        try
        {
        OpenDbConnection(conString);
        OracleCommand cmd = new OracleCommand();
        con.Open();
        cmd.Connection = con;
        cmd.CommandText = SelectQuery;
        cmd.CommandType = System.Data.CommandType.Text;
        OracleDataReader ora_dataReader = cmd.ExecuteReader();
    }
    catch (Exception ex)
    {
        Logging.LogMessage(Logging.LogLevel.Error, 0, "DAL", this.GetType().Name, ex.Message + " : " + ex.StackTrace);
        throw ex;
    }
    finally
    {
     con.close();
     con.Dispose();
    }

        return ora_dataReader;
}

More info in this reference: https://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledatareader(v=vs.110).aspx


问:
ruby requests more memory when there are plenty free heap slots
We have a server running

Sidekiq 4.2.9

rails 4.2.8

MRI 2.1.9

This server periodically produce some amount of importing from external API's, perform some calculations on them and save these values to the database.

About 3 weeks ago server started hanging, as I see from NewRelic (and when ssh'ed to it) - it consumes more and more memory over time, eventually occupying all available RAM, then server hangs.

I've read some articles about how ruby GC works, but still can't understand, why at ~5:30 AM  heap size jumps from ~2.3M to 3M , when there's still 1M free heap slots available(GC settings are default)

similar behavior, 3:35PM:

So, the questions are:

how to make Ruby fill free heap slots instead of requesting new slots from OS ?

how to make it release free heap slots to the system ?

答:
how to make Ruby fill free heap slots instead of requesting new slots from OS ?

Your graph does not have "full" fidelity. It is a lot to assume that GC.stat was called by Newrelic or whatnot just at the exact right time.

It is incredibly likely that you ran out of slots, heap grew and since heaps don't shrink in Ruby you are stuck with a somewhat bloated heap.

To alleviate some of the pain you can limit RUBY_GC_HEAP_GROWTH_MAX_SLOTS to a sane number, something like 100,000 will do, I am trying to lobby setting a default here in core.

Also

Create a persistent log of jobs that run and time they ran (duration and so on), gather GC.stat before and after job runs

Split up your jobs by queue, run 1 queue on one server and other queue on another one, see which queue and which job is responsible for the problem

Profile various jobs you have using flamegraph or other profiling tools

Reduce the amount of concurrent jobs you run as an experiment, or place a mutex between certain job types. It is possible that 1 "job a" at a time is OKish, and 20 concurrent "job a"s at a time will bloat memory.


答:
You need to close the database connection and open it again before firing up your second query.

something like:

```<code>SqlConnection.Open();
</code>```

And

```<code>SqlConnection.Close();
</code>```

Title: Running the same query causing error the second time

Body:
You need to close the database connection and open it again before firing up your second query.

something like:

SqlConnection.Open();

And

SqlConnection.Close();


问:
MySQL - Error Code: 1054. Unknown column 'task_log_wip.task_log_task' in 'on clause'
I have having a bit strange issue with a query. This query works:

```<code>SELECT task_log_wip.*
FROM task_log_wip
INNER JOIN tasks ON tasks.task_id = task_log_wip.task_log_task;
</code>```

But this query doesn't work:

```<code>SELECT task_log_wip.*, xmlform.*
FROM task_log_wip, xmlform
INNER JOIN tasks ON tasks.task_id = task_log_wip.task_log_task;
</code>```

Adding any kind of table to SELECT and FROM will produce following error:

Error Code: 1054. Unknown column 'task_log_wip.task_log_task' in 'on clause'

Table task_log_wip structure:

```<code>task_log_id
task_log_task
task_log_name
task_log_description
task_log_creator
task_log_hours
task_log_date
task_log_costcode
task_log_xmlform_id
task_log_xmldoc
task_log_uniqueid
task_log_javascript_executed
task_log_fm_related_date
task_log_draft
task_log_status
task_log_approver
task_log_approval_date
task_log_pre_delete_status
task_log_deletion_approver
task_log_deletion_date
task_log_orig_creator
task_log_wip_auto_save
task_log_orig_created
</code>```

Table tasks structure:

```<code>task_id
task_name
task_parent
task_milestone
task_project
task_owner
task_start_date
task_duration
task_duration_type
task_hours_worked
task_end_date
task_status
task_priority
task_percent_complete
task_description
task_target_budget
task_related_url
task_creator
task_order
task_client_publish
task_dynamic
task_access
task_notify
task_departments
task_contacts
task_custom
task_xmlform_id
task_procedure
task_virtual
task_ypaccess
task_created_ts
</code>```

Table xmlform structure (task_log_wip is connected with xmlform via task_log_wip_xmlform_id):

```<code>xmlform_id
xmlform_project_type
xmlform_project_type_parent
xmlform_type
xmlform_name
xmlform_description
xmlform_dtd
xmlform_edit_rule_value
xmlform_company_id
xmlform_department
xmlform_creator_id
xmlform_shared
xmlform_notify_via_email
xmlform_notify_via_sms
xmlform_notify_via_pager
xmlform_notify_via_instant_messenger
xmlform_report_severity_level
xmlform_hidden
xmlform_released
xmlform_restricted
created_by
created_timestamp
last_updated_by
last_updated_timestamp
</code>```

答:
So you need to either JOIN or LEFT JOIN with the xmlform table like this:

```<code>SELECT task_log_wip.*,
       xmlform.*
 FROM task_log_wip
       INNER JOIN tasks
          ON tasks.task_id = task_log_wip.task_log_task
       INNER JOIN xmlform
          ON xmlform.id = task_log_wip.task_log_wip_xmlform_id;
</code>```

The JOIN or LEFT JOIN choice will depends on your data and requirement.

Body:
I have having a bit strange issue with a query. This query works:

SELECT task_log_wip.*
FROM task_log_wip
INNER JOIN tasks ON tasks.task_id = task_log_wip.task_log_task;

But this query doesn't work:

SELECT task_log_wip.*, xmlform.*
FROM task_log_wip, xmlform
INNER JOIN tasks ON tasks.task_id = task_log_wip.task_log_task;

Adding any kind of table to SELECT and FROM will produce following error:

Error Code: 1054. Unknown column 'task_log_wip.task_log_task' in 'on clause'

Table task_log_wip structure:

task_log_id
task_log_task
task_log_name
task_log_description
task_log_creator
task_log_hours
task_log_date
task_log_costcode
task_log_xmlform_id
task_log_xmldoc
task_log_uniqueid
task_log_javascript_executed
task_log_fm_related_date
task_log_draft
task_log_status
task_log_approver
task_log_approval_date
task_log_pre_delete_status
task_log_deletion_approver
task_log_deletion_date
task_log_orig_creator
task_log_wip_auto_save
task_log_orig_created

Table tasks structure:

task_id
task_name
task_parent
task_milestone
task_project
task_owner
task_start_date
task_duration
task_duration_type
task_hours_worked
task_end_date
task_status
task_priority
task_percent_complete
task_description
task_target_budget
task_related_url
task_creator
task_order
task_client_publish
task_dynamic
task_access
task_notify
task_departments
task_contacts
task_custom
task_xmlform_id
task_procedure
task_virtual
task_ypaccess
task_created_ts

Table xmlform structure (task_log_wip is connected with xmlform via task_log_wip_xmlform_id):

xmlform_id
xmlform_project_type
xmlform_project_type_parent
xmlform_type
xmlform_name
xmlform_description
xmlform_dtd
xmlform_edit_rule_value
xmlform_company_id
xmlform_department
xmlform_creator_id
xmlform_shared
xmlform_notify_via_email
xmlform_notify_via_sms
xmlform_notify_via_pager
xmlform_notify_via_instant_messenger
xmlform_report_severity_level
xmlform_hidden
xmlform_released
xmlform_restricted
created_by
created_timestamp
last_updated_by
last_updated_timestamp

Body:
So you need to either JOIN or LEFT JOIN with the xmlform table like this:

SELECT task_log_wip.*,
       xmlform.*
 FROM task_log_wip
       INNER JOIN tasks
          ON tasks.task_id = task_log_wip.task_log_task
       INNER JOIN xmlform
          ON xmlform.id = task_log_wip.task_log_wip_xmlform_id;

The JOIN or LEFT JOIN choice will depends on your data and requirement.


问:
Zero downtime deployment with Puma
The documentation for puma indicates that a phased restart can be initiated with the USR1 signal. But I am unclear as to how to do a rolling restart using this. If I have directories /home/abc/rails_app and /home/abc/rails_app_updated containing a copy of my code with the new changes, is there suppose to be a way to tell puma where my new code is when doing a restart? I couldn't find anything definitive on this.</p>

答:
Puma loads your code when it starts, after that you could delete the rails app and things would still keep working (basically). So you can update the code, and Puma wouldn't even notice. What sending the USR1 signal does is make puma reload the (new) code, while gracefully handling existing connections. So there is no need to have two separate directories, you can update the code in place.

If you do need to separate directories, you can just have a single symlinked directory that points at the code that you want to be current and which is used by Puma (capistrano uses this strategy, it has a symlink 'current' pointing at the latest release). Then send puma USR1 and it will reload the code from the given dir.

please let me know if you need more pointers.

Edit: Probabaly I was not very precise. Puma doesn't actually handle the (re)loading of files, that's handled by Rails (Puma just starts a Rack application, or on a USR1 signal, will restart an application). In development mode, Rails will reload files on every request, which is handy when changing code. On production these settings typically apply (from config/environments/production.rb):

```<code>  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both thread web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true
</code>```

More details in the rails guides.

If you really want to go down the rabbithole could have a look at what the cache_classes does exactly in the rails source, but I'm not familiar with that.

Niels

Title: Zero downtime deployment with Puma

Body:
Puma loads your code when it starts, after that you could delete the rails app and things would still keep working (basically). So you can update the code, and Puma wouldn't even notice. What sending the USR1 signal does is make puma reload the (new) code, while gracefully handling existing connections. So there is no need to have two separate directories, you can update the code in place.

If you do need to separate directories, you can just have a single symlinked directory that points at the code that you want to be current and which is used by Puma (capistrano uses this strategy, it has a symlink 'current' pointing at the latest release). Then send puma USR1 and it will reload the code from the given dir.

please let me know if you need more pointers.

Edit: Probabaly I was not very precise. Puma doesn't actually handle the (re)loading of files, that's handled by Rails (Puma just starts a Rack application, or on a USR1 signal, will restart an application). In development mode, Rails will reload files on every request, which is handy when changing code. On production these settings typically apply (from config/environments/production.rb):

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both thread web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

More details in the rails guides.

If you really want to go down the rabbithole could have a look at what the cache_classes does exactly in the rails source, but I'm not familiar with that.

Niels


问:
Open Chrome and Close Activity (But let Chrome Open)
I have a simple APP then opens up chrome on a page. However, if the user presses  'back' button, chrome closes and my blank activity comes up. I wish i could open chrome and close the blank activity.

Here's my code, as simple as that.

```<code>        Intent i = new Intent("android.intent.action.MAIN");
        i.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));
        i.addCategory("android.intent.category.LAUNCHER");
        i.setData(Uri.parse(url));
        startActivity(i);
</code>```

If i call this.finish() after opening the chrome activity, the chrome closes as well.

Would apreciate any help. Thanks for the attention.

答: just call the finish(); method after your intent.

Body:
I have a simple APP then opens up chrome on a page. However, if the user presses  'back' button, chrome closes and my blank activity comes up. I wish i could open chrome and close the blank activity.

Here's my code, as simple as that.

        Intent i = new Intent("android.intent.action.MAIN");
        i.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));
        i.addCategory("android.intent.category.LAUNCHER");
        i.setData(Uri.parse(url));
        startActivity(i);

If i call this.finish() after opening the chrome activity, the chrome closes as well.

Would apreciate any help. Thanks for the attention.


问:
Meteor-React Pass function with createContainer
Is it possible to a pass a function with createContainer in Meteor with React and react-meteor-data?

For example:

```<code>import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import App from 'App.jsx';
export default AppContainer = createContainer(({ }) => {
    const do = () => {
        console.log("do");
    }
    return {
        do
    };
}, App);
</code>```

And then in App:

```<code>const App = ({ do }) => (
    <button onClick={do}>Do something</button>

);

export default App;
</code>```

答:
I solved my question by my own. I do not know why this was working then, but if I call the passed function like this

```<code> <button onClick={do()}>Do something</button>
</code>```

Then my code is working. I thought I could also invoke passed function without parenthesis, but this seems to be not the case.

But thanks so for the help :)

Body:
Is it possible to a pass a function with createContainer in Meteor with React and react-meteor-data?

For example:

import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import App from 'App.jsx';
export default AppContainer = createContainer(({ }) => {
    const do = () => {
        console.log("do");
    }
    return {
        do
    };
}, App);

And then in App:

const App = ({ do }) => (
    <button onClick={do}>Do something</button>

);

export default App;

Body:
I solved my question by my own. I do not know why this was working then, but if I call the passed function like this

 <button onClick={do()}>Do something</button>

Then my code is working. I thought I could also invoke passed function without parenthesis, but this seems to be not the case.

But thanks so for the help :)