问:
jQuery: Pause function on mousemove or click
I've created a function that autoscrolls up and down the page on repeat, I'm now looking to extend this slightly as I want to have to ability to pause the autoscrolling when the user moves the mouse.

Basically the idea is that the page will autoscroll if the user isn't moving their mouse, as soon as they do this function will pause and they'll take over the interaction...until they stop again.

I have a jsFiddle.
This scrolls up and down as it should but now I need to pause as soon as an interaction is made, or pause and restart the animation upon clicking the .start and .stop respectively. My markup as follows:

```<code>//run instantly and then goes after (setTimeout interval)
function autoScroll() {

    $("html, body").animate({
        scrollTop: $(document).height()
    }, 4000);
    setTimeout(function() {
        $('html, body').animate({
            scrollTop: 0
        }, 4000);
    }, 4000);
    setInterval(function() {
        // 4000 - it will take 4 secound in total from the top of the page to the bottom
        $("html, body").animate({
            scrollTop: $(document).height()
        }, 4000);
        setTimeout(function() {
            $('html, body').animate({
                scrollTop: 0
            }, 4000);
        }, 4000);

    }, 8000);

}

autoScroll();
</code>```

Any suggestions on this would be greatly appreciated!

答:
This is a DEMO fork of your fiddle.

HTML

```<code><div style="height:2000px; float:left; width:100%;">
  Text text Text text Text text Text text Text text Text text Text text Text text Text textv Text text Text text Text text Text textText text

</div>

<div class="start">
  START
</div>
<div class="stop">
  STOP
</div>
</code>```

JS

```<code>var autoScrollInterval;
var autoScrollTimeout;
var mouseMoveTimeout = null

function startAutoScroll() {
    autoScroll();
  autoScrollInterval = setInterval(autoScroll, 8000);
}

function autoScroll() {
  $("html, body").animate({
    scrollTop: $(document).height()
  }, 4000);
  setTimeout(function() {
    $('html, body').animate({
      scrollTop: 0
    }, 4000);
  }, 4000);
}

$(document).on('mousemove', function() {
    // Stop animation
        $("html, body").stop();

    // clear timeouts and intervals
    clearTimeout(mouseMoveTimeout);
    clearTimeout(autoScrollTimeout);
        clearInterval(autoScrollInterval);

    mouseMoveTimeout = setTimeout(function() {
        // restore auto scrolling
        startAutoScroll();
    }, 1000);
});

$(document).ready(function() {
  startAutoScroll();
});
</code>```

In short I used jQuery's mousemove to detect if mouse is moving and then clear intervals and timeouts.

If you want to change the time when autoscroll should start again change it here, now is set to 1 second:

```<code>mouseMoveTimeout = setTimeout(function() {
        // restore auto scrolling
        startAutoScroll();
}, 1000); // change time when autoscroll starts here
</code>```

EDIT

Your statement is good that autoscroll should be disabled when user is scrolling and I made such version of the code HERE

Now we take care for DOMMouseScroll(when browser is Firefox) and mousewheel events because $().on('scroll') will disable the whole code snippet to work(we should detect if scroll is made by the user).

UPDATED JS

```<code>var autoScrollInterval;
var autoScrollTimeout;
var restoreTimeout = null

function autoScroll() {
  $("html, body").animate({
    scrollTop: $(document).height()
  }, 4000);
  setTimeout(function() {
    $('html, body').animate({
      scrollTop: 0
    }, 4000);
  }, 4000);
}

function startAutoScroll() {
  autoScroll();
  autoScrollInterval = setInterval(autoScroll, 8000);
}

function stopAutoScroll() {
  // Stop animation
  $("html, body").stop();

  // clear timeouts and intervals
  clearTimeout(restoreTimeout);
  clearTimeout(autoScrollTimeout);
  clearInterval(autoScrollInterval);

  restoreTimeout = setTimeout(function() {
    // restore auto scrolling
    startAutoScroll();
  }, 1000);
}

//Firefox
$(document).bind('DOMMouseScroll', function(e) {
  stopAutoScroll()
});

//IE, Opera, Safari
$(document).bind('mousewheel', function(e) {
  stopAutoScroll()
});

$(document).on('mousemove', function() {
    stopAutoScroll();
});

$(document).ready(function() {
  startAutoScroll();
});
</code>```

Body:
I've created a function that autoscrolls up and down the page on repeat, I'm now looking to extend this slightly as I want to have to ability to pause the autoscrolling when the user moves the mouse.

Basically the idea is that the page will autoscroll if the user isn't moving their mouse, as soon as they do this function will pause and they'll take over the interaction...until they stop again.

I have a jsFiddle.
This scrolls up and down as it should but now I need to pause as soon as an interaction is made, or pause and restart the animation upon clicking the .start and .stop respectively. My markup as follows:

//run instantly and then goes after (setTimeout interval)
function autoScroll() {

    $("html, body").animate({
        scrollTop: $(document).height()
    }, 4000);
    setTimeout(function() {
        $('html, body').animate({
            scrollTop: 0
        }, 4000);
    }, 4000);
    setInterval(function() {
        // 4000 - it will take 4 secound in total from the top of the page to the bottom
        $("html, body").animate({
            scrollTop: $(document).height()
        }, 4000);
        setTimeout(function() {
            $('html, body').animate({
                scrollTop: 0
            }, 4000);
        }, 4000);

    }, 8000);

}

autoScroll();

Any suggestions on this would be greatly appreciated!

Body:
This is a DEMO fork of your fiddle.

HTML

<div style="height:2000px; float:left; width:100%;">
  Text text Text text Text text Text text Text text Text text Text text Text text Text textv Text text Text text Text text Text textText text

</div>

<div class="start">
  START
</div>
<div class="stop">
  STOP
</div>

JS

var autoScrollInterval;
var autoScrollTimeout;
var mouseMoveTimeout = null

function startAutoScroll() {
    autoScroll();
  autoScrollInterval = setInterval(autoScroll, 8000);
}

function autoScroll() {
  $("html, body").animate({
    scrollTop: $(document).height()
  }, 4000);
  setTimeout(function() {
    $('html, body').animate({
      scrollTop: 0
    }, 4000);
  }, 4000);
}

$(document).on('mousemove', function() {
    // Stop animation
        $("html, body").stop();

    // clear timeouts and intervals
    clearTimeout(mouseMoveTimeout);
    clearTimeout(autoScrollTimeout);
        clearInterval(autoScrollInterval);

    mouseMoveTimeout = setTimeout(function() {
        // restore auto scrolling
        startAutoScroll();
    }, 1000);
});

$(document).ready(function() {
  startAutoScroll();
});

In short I used jQuery's mousemove to detect if mouse is moving and then clear intervals and timeouts.

If you want to change the time when autoscroll should start again change it here, now is set to 1 second:

mouseMoveTimeout = setTimeout(function() {
        // restore auto scrolling
        startAutoScroll();
}, 1000); // change time when autoscroll starts here

EDIT

Your statement is good that autoscroll should be disabled when user is scrolling and I made such version of the code HERE

Now we take care for DOMMouseScroll(when browser is Firefox) and mousewheel events because $().on('scroll') will disable the whole code snippet to work(we should detect if scroll is made by the user).

UPDATED JS

var autoScrollInterval;
var autoScrollTimeout;
var restoreTimeout = null

function autoScroll() {
  $("html, body").animate({
    scrollTop: $(document).height()
  }, 4000);
  setTimeout(function() {
    $('html, body').animate({
      scrollTop: 0
    }, 4000);
  }, 4000);
}

function startAutoScroll() {
  autoScroll();
  autoScrollInterval = setInterval(autoScroll, 8000);
}

function stopAutoScroll() {
  // Stop animation
  $("html, body").stop();

  // clear timeouts and intervals
  clearTimeout(restoreTimeout);
  clearTimeout(autoScrollTimeout);
  clearInterval(autoScrollInterval);

  restoreTimeout = setTimeout(function() {
    // restore auto scrolling
    startAutoScroll();
  }, 1000);
}

//Firefox
$(document).bind('DOMMouseScroll', function(e) {
  stopAutoScroll()
});

//IE, Opera, Safari
$(document).bind('mousewheel', function(e) {
  stopAutoScroll()
});

$(document).on('mousemove', function() {
    stopAutoScroll();
});

$(document).ready(function() {
  startAutoScroll();
});


来源: stackexchange

问:
Using bind(this) in React
Can I use any of these options? Do they all work the same way? I'm using ES6.</p>

```<code>onChange={this.makeChange.bind(this)}

onChange={() => this.makeChange()}

constructor(props) {
  super(props);
  this.makeChange = this.makeChange.bind(this);
}
</code>```

答:
Yes, you can use all three. Even though they behave the same, they have different performance implications.

Binding the function in the constructor is the best option performance-wise, because the function is only created once when the component is instantiated. While with the other solutions a new function is created whenever the component (re-)renders. This will cause child components to also re-render, because their props have changed.

You can read more about this in the official React docs: https://facebook.github.io/react/docs/handling-events.html

Personally, I prefer the following syntax using class properties (this is only available if you're using TypeScript or a Babel plugin):

```<code>class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
</code>```

This option is also explained in the React docs.

ContentLicense: CC BY-SA 3.0

Title: Using bind(this) in React

Body:
Can I use any of these options? Do they all work the same way? I'm using ES6.

onChange={this.makeChange.bind(this)}

onChange={() => this.makeChange()}

constructor(props) {
  super(props);
  this.makeChange = this.makeChange.bind(this);
}

Body:
Yes, you can use all three. Even though they behave the same, they have different performance implications.

Binding the function in the constructor is the best option performance-wise, because the function is only created once when the component is instantiated. While with the other solutions a new function is created whenever the component (re-)renders. This will cause child components to also re-render, because their props have changed.

You can read more about this in the official React docs: https://facebook.github.io/react/docs/handling-events.html

Personally, I prefer the following syntax using class properties (this is only available if you're using TypeScript or a Babel plugin):

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

This option is also explained in the React docs.


问:
GridView in asp.net
I am bit new to Asp.net GridView, and I am facing the following problem.
I have a gridview placed in an ascx. This ascx is loaded dynamically within an aspx, in its Page_Init method
Control control = LoadControl("~/grid.ascx");
PlaceHolder1.Controls.Add(control);

The grid is bound to a IList (which is populated from the data access layer). I have a button field in the grid, which is used to call the delete function in DA layer for the row (performs this call in GridView1_RowCommand()).

My question is, I dont see the grid view getting refreshed after I perform the delete. I placed the code to re-read and bind data to gridview in many places, but none seems to work.

Notes:
1. The loading of ascx is done in an ajax call for the aspx
2. Delete function actually modifies the 'Status' column of 'User' to 'Deleted' which I need to see in the gridview after I do so

Can you please help me?

Edit:
It seems that RowDataBound event is fired (for each row of course) after page load, and then only the button command event fire. Though I set the modified DS and DataBind on the gridview, it never fires the RowDataBound afterwards. Any idea why?
Thanks in advance.

Anuruddha

答: you need to rebind the grid in GridView1_RowCommand() with the new datasource once again</p>

ContentLicense: CC BY-SA 2.5

Title: GridView in asp.net


问:
Injecting mocks into Spring test Mockito + Spring + TestNG
I want to write a test for a printing service. I am using Spring with TestNG and Mockito.

So far I've created a test configuration class for my spring context and the needed test class.

The PrintingService class that i want to test depends on several services, so I've decided to mock them. My problem is that I can't get it working with Spring. Everytime I start the test, spring is throwing an exception

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.printservice.server.message.MessageService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

I thought using the @InjectMocks annotation would solve my problem, but it did not. Maybe I am missunderstanding some aspects, or my idea of testing the service is completly wrong.

PrintingTestConfig

```<code>package com.example.printservice;

import com.example.printservice.server.print.PrintingService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan(basePackageClasses = {PrintingService.class}, scopedProxy = ScopedProxyMode.TARGET_CLASS)
public class PrintingTestConfig {

  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
    return new PropertySourcesPlaceholderConfigurer();
  }

}
</code>```

PrintingServiceTest

```<code>@ContextConfiguration(classes = PrintingTestConfig.class, loader = AnnotationConfigContextLoader.class)
public class PrintingServiceTest extends AbstractTestNGSpringContextTests {

  @Mock
  private MessageService _messageService;

  @Mock
  private ClientCache_clientCache;

  @Mock
  private PrinterCache _printerCache;

  @Value("classpath:example.pdf")
  private Resource _examplePdf;

  @InjectMocks
  private PrintingService _printingService;

  @BeforeMethod
  public void setup() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void printPdf() {
    ...
  }

}
</code>```

答:
You can create mock spring beans with the @MockBean annotation. Although I cant see whats under test with Spring you should have your constructors open to keep unit tests simple i.e. constructor DI so it is not tied directly to spring to inject mocks or other implementations.

in the case of more verbose/large tests @MockBean is useful.

Body:
I want to write a test for a printing service. I am using Spring with TestNG and Mockito.

So far I've created a test configuration class for my spring context and the needed test class.

The PrintingService class that i want to test depends on several services, so I've decided to mock them. My problem is that I can't get it working with Spring. Everytime I start the test, spring is throwing an exception

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.printservice.server.message.MessageService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I thought using the @InjectMocks annotation would solve my problem, but it did not. Maybe I am missunderstanding some aspects, or my idea of testing the service is completly wrong.

PrintingTestConfig

package com.example.printservice;

import com.example.printservice.server.print.PrintingService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan(basePackageClasses = {PrintingService.class}, scopedProxy = ScopedProxyMode.TARGET_CLASS)
public class PrintingTestConfig {

  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
    return new PropertySourcesPlaceholderConfigurer();
  }

}

PrintingServiceTest

@ContextConfiguration(classes = PrintingTestConfig.class, loader = AnnotationConfigContextLoader.class)
public class PrintingServiceTest extends AbstractTestNGSpringContextTests {

  @Mock
  private MessageService _messageService;

  @Mock
  private ClientCache_clientCache;

  @Mock
  private PrinterCache _printerCache;

  @Value("classpath:example.pdf")
  private Resource _examplePdf;

  @InjectMocks
  private PrintingService _printingService;

  @BeforeMethod
  public void setup() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void printPdf() {
    ...
  }

}


问:
Eclipse JAX-RS (REST Web Services) 2.0 requires Java 1.6 or newer
i'm new to web service and i'm trying to do a project using jax-rs rest and spring in eclipse.
I use java 1.8 but eclipse shows me an error that jax-rs 2.0 requires java 1.6 or newer error and my project won't work

This is the project explorer and error's screenshot. I tried to google it but can't get any english solutions

Edit : It seems like the screenshot's quality is low if i try to display it so here is the imgur link for the screenshot for better quality
http://i.imgur.com/YYyoeUX.png

答:
I know the topic is old but I had the same problem and it's hard to find informations on it.
So set the properties wasn't enough for me, I had also to delete the project from Eclipse, then delete the .project file and reimport the project as a Maven project (even if I created it as a Maven project already) like it is answer on this topic.</p>


问:
Android: takePicture hangs
I am trying to take a photo but it hangs when takePicture is called. No exception is generated. My code runs in an AsyncTask which is launced from a service. No activity is used and none MUST be used. I'm running this on Android 2.3.6. I can wait minutes and the onPictureTaken is never called.

Code:

```<code>import android.annotation.SuppressLint;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.AsyncTask;
import android.os.Build;

public class CameraAsyncTask extends AsyncTask<Void, Void, Boolean> implements Camera.PictureCallback
{
  private Camera camera;

  @Override
  protected Boolean doInBackground(Void... params)
  {
    this.camera = Camera.open();
    this.camera.takePicture(null, null, (PictureCallback) this);
    this.camera.release();
  }

  @Override
  protected void onPostExecute(Boolean succeeded)
  {
  }

  public void onPictureTaken(byte[] data, Camera camera)
  {
  }
}
</code>```

Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest>

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />

</manifest>
</code>```

答: camera.takePicture cannot be called through background thread is must be through main thread</p>

Title: Android: takePicture hangs

Body:
I am trying to take a photo but it hangs when takePicture is called. No exception is generated. My code runs in an AsyncTask which is launced from a service. No activity is used and none MUST be used. I'm running this on Android 2.3.6. I can wait minutes and the onPictureTaken is never called.

Code:

import android.annotation.SuppressLint;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.AsyncTask;
import android.os.Build;

public class CameraAsyncTask extends AsyncTask<Void, Void, Boolean> implements Camera.PictureCallback
{
  private Camera camera;

  @Override
  protected Boolean doInBackground(Void... params)
  {
    this.camera = Camera.open();
    this.camera.takePicture(null, null, (PictureCallback) this);
    this.camera.release();
  }

  @Override
  protected void onPostExecute(Boolean succeeded)
  {
  }

  public void onPictureTaken(byte[] data, Camera camera)
  {
  }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest>

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />

</manifest>


问:
What's the equivalent of mysql RLIKE operator in Hibernate Query?
I have the following query which runs perfectly in mysql.

```<code>SELECT * FROM Orders as o, Products as p  where o.productinfo RLIKE p.code;
</code>```

Here I am joining two tables Orders and Products with RLIKE.

I am trying to implement the same in Hibernate.

```<code>Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo RLIKE p.code");
List<Object[]> results = query.getResultList();
</code>```

When I used RLIKE, the following error is thrown in run time.

```<code>{"errormessage":"org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: RLIKE
</code>```

I tried to implement the same with LIKE query and matched it with '%p.code%'.

```<code>Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo LIKE '%p.code%'");
</code>```

But it matches with the string "p.code" rather then the value.

What is the equivalent of RLIKE in HQL?
Is there a different way to join two tables with LIKE in HQL?

Thanks.

Answer by @YCF_L:
For any one trying to join two tables with like operator in Hibernate (mysql) can do it the following way.

```<code>SELECT * FROM Orders as o, Products as p  where o.productinfo LIKE CONCAT('%',p.code,'%');
</code>```

答:
What's the equivalent of mysql RLIKE operator in Hibernate Query?

RLIKE is the synonym for REGEXP so you can implement it in hibernate using REGEXP_LIKE, you can take a look about this here : How to search in multiple columns using one like operator in HQL (hibernate sql)

I tried to implement the same with LIKE query and matched it with
  '%p.code%'.

```<code>..., Products as p  where o.productinfo LIKE '%p.code%'");
</code>```

But it matches with the string "p.code" rather then the value.

This is true, because you don't pass the correct value of p.code, you pass it like a String, instead you have two ways :

```<code>Query query = session.createQuery("....Products as p  where o.productinfo LIKE '%:code%'");
//------------------------------------------------------------------------------^^^^^^^
query.setParameter("code", p.code);
</code>```

Or you can concatenate your code with your Query, but the first solution is better.

```<code>Query query = session.createQuery("....  where o.productinfo LIKE '%" + p.code + "%'");
</code>```

EDIT

You can use like with CONCAT without specify the '' like this :

```<code>SELECT * FROM Orders as o, Products as p  where o.productinfo LIKE CONCAT('%',p.code,'%');
</code>```

Body:
I have the following query which runs perfectly in mysql.

SELECT * FROM Orders as o, Products as p  where o.productinfo RLIKE p.code;

Here I am joining two tables Orders and Products with RLIKE.

I am trying to implement the same in Hibernate.

Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo RLIKE p.code");
List<Object[]> results = query.getResultList();

When I used RLIKE, the following error is thrown in run time.

{"errormessage":"org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: RLIKE

I tried to implement the same with LIKE query and matched it with '%p.code%'.

Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo LIKE '%p.code%'");

But it matches with the string "p.code" rather then the value.

What is the equivalent of RLIKE in HQL?
Is there a different way to join two tables with LIKE in HQL?

Thanks.

Answer by @YCF_L:
For any one trying to join two tables with like operator in Hibernate (mysql) can do it the following way.

SELECT * FROM Orders as o, Products as p  where o.productinfo LIKE CONCAT('%',p.code,'%');

Body:
What's the equivalent of mysql RLIKE operator in Hibernate Query?

RLIKE is the synonym for REGEXP so you can implement it in hibernate using REGEXP_LIKE, you can take a look about this here : How to search in multiple columns using one like operator in HQL (hibernate sql)

I tried to implement the same with LIKE query and matched it with
  '%p.code%'.

..., Products as p  where o.productinfo LIKE '%p.code%'");

But it matches with the string "p.code" rather then the value.

This is true, because you don't pass the correct value of p.code, you pass it like a String, instead you have two ways :

Query query = session.createQuery("....Products as p  where o.productinfo LIKE '%:code%'");
//------------------------------------------------------------------------------^^^^^^^
query.setParameter("code", p.code);

Or you can concatenate your code with your Query, but the first solution is better.

Query query = session.createQuery("....  where o.productinfo LIKE '%" + p.code + "%'");

EDIT

You can use like with CONCAT without specify the '' like this :

SELECT * FROM Orders as o, Products as p  where o.productinfo LIKE CONCAT('%',p.code,'%');


问:
Offline sync with Dropbox API v2
With the Dropbox Sync API there was a method [DBFile writeContentsOfFile] which would sync the file at a later time if the internet connection was offline.

Is there a similar function in the new Dropbox API v2?

I've found a method on DBFilesRoutes -uploadData:inputData:, which works fine for normal upload, but fails with an error if there's no internet connection...and unfortunately it doesn't sync later when the connection is restored.

Perhaps using DBFilesRoutes -uploadSessionStartData: is the solution (which I'll attempt shortly).

答:
No, unfortunately the official Dropbox API v2 SDKs don't offer offline support like that. We'll consider it a feature request.

The difference between uploadData and uploadSessionStartData is that uploadData is for uploading files in one call, whereas uploadSessionStartData is used along with uploadSessionAppendV2Data and uploadSessionFinishData to upload larger files in multiple pieces.

Title: Offline sync with Dropbox API v2


问:
Angular 2 Child route module display the correct url but displays another component
I cleaned up my root route file, by creating a child custom module for routes, and here is the script:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';

const childRoutes: Routes = [

    {path: 'signin', component: SigninComponent},

    {path: 'signup', component: SignupComponent}

];

@NgModule({
  imports: [
    RouterModule.forChild(childRoutes)
  ],
  exports:[RouterModule]
})
export class ChildRoutingModule { }
</code>```

The root route module now is:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './auth/signin/signin.component';
import { SignupComponent } from './auth/signup/signup.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { ChildRoutingModule } from './auth/auth.route'

const appRoutes: Routes = [
    {path: '', redirectTo:'/signup', pathMatch:'full'},

    {path: '**', component: NotfoundComponent}
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports:[RouterModule]
})
export class AppRoutingModule { }
</code>```

I imported the 2 route modules into the app.module.ts:

```<code>import ...
import ...
import { AppRoutingModule } from './routes'
import { ChildRoutingModule } from './auth/auth.route'
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    AppRoutingModule,
    ChildRoutingModule,
    BrowserModule,
    AuthModule,
    RouterModule
  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

The problem now is on the startup component of the app that is the signup component, the url is correct: http://localhost:4200/signup but the displayed component is the 404 component which is defined in the root route component by {path: '**', component: NotfoundComponent}

To mention that no errors are displayed at the console at all

答:
Change this as:

```<code>imports: [
    BrowserModule,
    AuthModule,
    RouterModule,
    ChildRoutingModule,
    AppRoutingModule,
  ],
</code>```

You need to load AppRoutingModule at last , because before that route routes needs to know all the child routes , to make routing deep level on init time.

Or it will redirect to the Error Component as you have defined.

Body:
I cleaned up my root route file, by creating a child custom module for routes, and here is the script:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';

const childRoutes: Routes = [

    {path: 'signin', component: SigninComponent},

    {path: 'signup', component: SignupComponent}

];

@NgModule({
  imports: [
    RouterModule.forChild(childRoutes)
  ],
  exports:[RouterModule]
})
export class ChildRoutingModule { }

The root route module now is:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './auth/signin/signin.component';
import { SignupComponent } from './auth/signup/signup.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { ChildRoutingModule } from './auth/auth.route'

const appRoutes: Routes = [
    {path: '', redirectTo:'/signup', pathMatch:'full'},

    {path: '**', component: NotfoundComponent}
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports:[RouterModule]
})
export class AppRoutingModule { }

I imported the 2 route modules into the app.module.ts:

import ...
import ...
import { AppRoutingModule } from './routes'
import { ChildRoutingModule } from './auth/auth.route'
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    AppRoutingModule,
    ChildRoutingModule,
    BrowserModule,
    AuthModule,
    RouterModule
  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule { }

The problem now is on the startup component of the app that is the signup component, the url is correct: http://localhost:4200/signup but the displayed component is the 404 component which is defined in the root route component by {path: '**', component: NotfoundComponent}

To mention that no errors are displayed at the console at all

Body:
Change this as:

imports: [
    BrowserModule,
    AuthModule,
    RouterModule,
    ChildRoutingModule,
    AppRoutingModule,
  ],

You need to load AppRoutingModule at last , because before that route routes needs to know all the child routes , to make routing deep level on init time.

Or it will redirect to the Error Component as you have defined.


问:
QueryRow().Scan() returns error if row doesn't exist
I want to fetch one row from an sql database. I use the following code:

```<code>var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil {
    // log the error
}
</code>```

For example: if a user with id=2 doesn't exist, then the method Scan returns an error.

Question:

Is there a way to avoid this error when a row doesn't exist? Because it's absolutely normal and I don't want to log such errors.

The only way I found is to use Query instead of QueryRow, but it is not convenient because I have to add for rows.Next() { .. every time when I want to fetch single row.

答:
Simply check for the error you don't want to log before logging: </p>

```<code>var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil && err != sql.ErrNoRows {
    // log the error
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to fetch one row from an sql database. I use the following code:

var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil {
    // log the error
}

For example: if a user with id=2 doesn't exist, then the method Scan returns an error.

Question:

Is there a way to avoid this error when a row doesn't exist? Because it's absolutely normal and I don't want to log such errors.

The only way I found is to use Query instead of QueryRow, but it is not convenient because I have to add for rows.Next() { .. every time when I want to fetch single row.

Body:
Simply check for the error you don't want to log before logging:

var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil && err != sql.ErrNoRows {
    // log the error
}


问:
Mailing script is mixing mail recipients
I have a mailing script that is sending a large mailing.

In this mailing is a unsubscribe button witch fills in the mailaddress from the recipients.

But for some reason when a mails goes to recipients A the mailaddress from recipients B is filled in.

A snippet of my script:

```<code><?php
//First get 500 mailaddressess to send the mail to
$sql = mysql_query( "select mail_id, customers_email_address from " . TABLE_NIEUWSBRIEVEN_MAILING_LIST . " where nieuwsbrief_id = '" . mysql_real_escape_string( $nID ) . "' and send = 0 order by mail_id limit " . $aantal_verzenden ) or die ( mysql_error() );

while ( $mail = mysql_fetch_array( $sql ) )
{
    $sendmail = new PHPMailer();
    $sendmail->AddReplyTo( $data['afzender_email'], ucfirst( $data['afzender_naam'] ) );
    $sendmail->AddAddress( $mail['customers_email_address'] );
    $sendmail->SetFrom( $data['afzender_email'], ucfirst( $data['afzender_naam'] ) );

    // This part is filling in the mailadress at the subscribe button.
    $layout = str_replace( '{EMAIL}', $mail['customers_email_address'], $layout );

    $mbEnc = mb_internal_encoding();
    mb_internal_encoding('UTF-8');
    $sendmail->Subject    = str_replace( '€', mb_encode_mimeheader('€', 'UTF-8'), $data['nieuwsbrief_titel'] );
    mb_internal_encoding($mbEnc);

    $sendmail->AltBody = str_replace( '{ONLINE_WEERGAVE}', 'http://myssite.nl/p-' . $data['url'],  str_replace( '{AFZENDER_ID}', $data['afzenderid'], $data['alt_mail'] ) );
    $sendmail->MsgHTML($layout);

    if(!$sendmail->Send()) {
      echo "Mailer Error: " . $sendmail->ErrorInfo . "\r\n";
      mysql_query( "insert into nieuwsbrief_zender_errors ( email, error ) values ( '" . mysql_real_escape_string( $mail['customers_email_address'] ) . "', '" . mysql_real_escape_string( $sendmail->ErrorInfo ) . "' )" );
      mysql_query( "update " . TABLE_NIEUWSBRIEVEN_MAILING_LIST . " set send = 2 where mail_id = '" . mysql_real_escape_string( $mail['mail_id'] ) . "'"  ) or die ( mysql_error() );
    } else {
      echo "Bericht succesvol verzonden!";
      echo $mail['customers_email_address'] . "\r\n";
      mysql_query( "update " . TABLE_NIEUWSBRIEVEN_MAILING_LIST . " set send = 1 where mail_id = '" . mysql_real_escape_string( $mail['mail_id'] ) . "'"  ) or die ( mysql_error() );
    }

    $sendmail->ClearAddresses();
    $sendmail->ClearAttachments();

}
?>
</code>```

$layout is containing the mail template with variables.

The unsubscribe button has a {EMAIL} variable.

As you can see in the script the $mail['customers_email_address'] is used for the AddAddress and for the {EMAIL} variable.

So how is it possible that those values are different from each other?

答:
The first time you change the {EMAIL} with $mail['customers_email_address'] in  $layout and when the second time you call $layout you don't have {EMAIL}.
You should fill $layout2 = str_replace( '{EMAIL}', $mail['customers_email_address'], $layout );
and send $sendmail->MsgHTML($layout2);

Then the original $layout should stay the same

Body:
I have a mailing script that is sending a large mailing.

In this mailing is a unsubscribe button witch fills in the mailaddress from the recipients.

But for some reason when a mails goes to recipients A the mailaddress from recipients B is filled in.

A snippet of my script:

<?php
//First get 500 mailaddressess to send the mail to
$sql = mysql_query( "select mail_id, customers_email_address from " . TABLE_NIEUWSBRIEVEN_MAILING_LIST . " where nieuwsbrief_id = '" . mysql_real_escape_string( $nID ) . "' and send = 0 order by mail_id limit " . $aantal_verzenden ) or die ( mysql_error() );

while ( $mail = mysql_fetch_array( $sql ) )
{
    $sendmail = new PHPMailer();
    $sendmail->AddReplyTo( $data['afzender_email'], ucfirst( $data['afzender_naam'] ) );
    $sendmail->AddAddress( $mail['customers_email_address'] );
    $sendmail->SetFrom( $data['afzender_email'], ucfirst( $data['afzender_naam'] ) );

    // This part is filling in the mailadress at the subscribe button.
    $layout = str_replace( '{EMAIL}', $mail['customers_email_address'], $layout );

    $mbEnc = mb_internal_encoding();
    mb_internal_encoding('UTF-8');
    $sendmail->Subject    = str_replace( '€', mb_encode_mimeheader('€', 'UTF-8'), $data['nieuwsbrief_titel'] );
    mb_internal_encoding($mbEnc);

    $sendmail->AltBody = str_replace( '{ONLINE_WEERGAVE}', 'http://myssite.nl/p-' . $data['url'],  str_replace( '{AFZENDER_ID}', $data['afzenderid'], $data['alt_mail'] ) );
    $sendmail->MsgHTML($layout);

    if(!$sendmail->Send()) {
      echo "Mailer Error: " . $sendmail->ErrorInfo . "\r\n";
      mysql_query( "insert into nieuwsbrief_zender_errors ( email, error ) values ( '" . mysql_real_escape_string( $mail['customers_email_address'] ) . "', '" . mysql_real_escape_string( $sendmail->ErrorInfo ) . "' )" );
      mysql_query( "update " . TABLE_NIEUWSBRIEVEN_MAILING_LIST . " set send = 2 where mail_id = '" . mysql_real_escape_string( $mail['mail_id'] ) . "'"  ) or die ( mysql_error() );
    } else {
      echo "Bericht succesvol verzonden!";
      echo $mail['customers_email_address'] . "\r\n";
      mysql_query( "update " . TABLE_NIEUWSBRIEVEN_MAILING_LIST . " set send = 1 where mail_id = '" . mysql_real_escape_string( $mail['mail_id'] ) . "'"  ) or die ( mysql_error() );
    }

    $sendmail->ClearAddresses();
    $sendmail->ClearAttachments();

}
?>

$layout is containing the mail template with variables.

The unsubscribe button has a {EMAIL} variable.

As you can see in the script the $mail['customers_email_address'] is used for the AddAddress and for the {EMAIL} variable.

So how is it possible that those values are different from each other?


问:
Angular2 JSON return
I'm new to angular2. I have question about get data from two API's. From first get ID's and from another get data by ID and print it on frontend.

I can't understand how to iterate JSON data from getPlayers() API

Iterating is working, but it doesn't print any data.

My service looks like this:

```<code>import {Injectable} from '@angular/core';
import { Http } from "@angular/http";
import "rxjs/Rx";
import {Observable} from 'rxjs/Rx';

@Injectable()
export class PlayersService {
    roster:any[];
    players:any[];

    constructor(private http: Http){
    }

   getPlayers(roster) {
    let url = "http://php.esports.cz/phone_app_roman_api/api.php/hrac?filter=id,eq,";
    return Observable.combineLatest(
      ...roster["soupiska"].map(player => this.http.get(url+ player['id_hrac'])
        .map(res => res.json()))
    ).do(players=>console.log(JSON.stringify(players)));
  }

  getRoster() {
    let url = "http://php.esports.cz/phone_app_roman_api/api.php/soupiska?filter[]=kategorie,eq,MUZ&filter[]=sezona,eq,2017&order=id_polozka&page=1,10"
    return this.http.get(url)
      .map(res => res.json())
  }

}
</code>```

and my component like this:

```<code>import {Component} from "@angular/core";
import {Location} from "@angular/common";
import {Page} from "../page";
import {OnInit} from '@angular/core';

import{PlayersService} from '../../services/players.service';

@Component({
    selector: 'roster-page',
    templateUrl: 'pages/roster/roster.page.html',
    styleUrls:  ['pages/roster/roster.page.css'],
    providers: [PlayersService]
})
export class RosterPage extends Page implements OnInit {

    roster:any[];
    players:any[];

    constructor(private location: Location, private playersService: PlayersService) {
        super(location);
    }

     ngOnInit() {
        this.playersService.getRoster()
        .do(roster=>this.roster=roster)
        .switchMap(roster=>this.playersService.getPlayers(roster))
        .do(players=>this.players=players)
        .subscribe();

    }

}
</code>```

Template looks like this:

```<code><StackLayout class="players">
    <StackLayout *ngFor="let player of players" orientation="horizontal" [nsRouterLink]="['/player']" pageTransition="slideTop" class="player-box">
        <Label text="{{player.hrac.jmeno}}" class="player-bane"></Label>
    </StackLayout>
</StackLayout>
</code>```

答:
There are many things that are wrong here:

First, http calls are asynchrnous, so you cannot access the value they compute until they have completed.

If there is no .subscribe(), no Observable will do anything.

You shouldn't rely on state when dealing with observables in services, that's counter-productive.

PlayerService:

```<code>export class PlayersService {
  constructor(private http: Http) {}

  getPlayers(roster) {
    let url = "http://php.esports.cz/phone_app_roman_api/api.php/hrac?filter=id,eq," ;
    return Observable.combineLatest(
      ...roster[0]["soupiska"].map(player => this.http.get(url+ player['id_hrac'])
        .map(res => res.json()))
    ).do(players=>console.log(players));
  }

  getRoster() {
    let url = "http://php.esports.cz/phone_app_roman_api/api.php/soupiska?filter[]=kategorie,eq,MUZ&filter[]=sezona,eq,2017&order=id_polozka&page=1,10"
    return this.http.get(url)
      .map(res => res.json())
  }

}
</code>```

RosterPage:

```<code>export class RosterPage extends Page implements OnInit
{
    roster:any[];
    players:any[];

    constructor(private location: Location, private playersService: PlayersService) {
        super(location);
    }

    ngOnInit() {
        this.playersService.getRoster()
        .do(roster=>this.roster=roster)
        .switchMap(roster=>this.playersService.getPlayers(roster))
        .do(players=>this.players=players)
        .subscribe();
    }
}
</code>```

Title: Angular2 JSON return

Body:
I'm new to angular2. I have question about get data from two API's. From first get ID's and from another get data by ID and print it on frontend.

I can't understand how to iterate JSON data from getPlayers() API

Iterating is working, but it doesn't print any data.

My service looks like this:

import {Injectable} from '@angular/core';
import { Http } from "@angular/http";
import "rxjs/Rx";
import {Observable} from 'rxjs/Rx';

@Injectable()
export class PlayersService {
    roster:any[];
    players:any[];

    constructor(private http: Http){
    }

   getPlayers(roster) {
    let url = "http://php.esports.cz/phone_app_roman_api/api.php/hrac?filter=id,eq,";
    return Observable.combineLatest(
      ...roster["soupiska"].map(player => this.http.get(url+ player['id_hrac'])
        .map(res => res.json()))
    ).do(players=>console.log(JSON.stringify(players)));
  }

  getRoster() {
    let url = "http://php.esports.cz/phone_app_roman_api/api.php/soupiska?filter[]=kategorie,eq,MUZ&filter[]=sezona,eq,2017&order=id_polozka&page=1,10"
    return this.http.get(url)
      .map(res => res.json())
  }

}

and my component like this:

import {Component} from "@angular/core";
import {Location} from "@angular/common";
import {Page} from "../page";
import {OnInit} from '@angular/core';

import{PlayersService} from '../../services/players.service';

@Component({
    selector: 'roster-page',
    templateUrl: 'pages/roster/roster.page.html',
    styleUrls:  ['pages/roster/roster.page.css'],
    providers: [PlayersService]
})
export class RosterPage extends Page implements OnInit {

    roster:any[];
    players:any[];

    constructor(private location: Location, private playersService: PlayersService) {
        super(location);
    }

     ngOnInit() {
        this.playersService.getRoster()
        .do(roster=>this.roster=roster)
        .switchMap(roster=>this.playersService.getPlayers(roster))
        .do(players=>this.players=players)
        .subscribe();

    }

}

Template looks like this:

<StackLayout class="players">
    <StackLayout *ngFor="let player of players" orientation="horizontal" [nsRouterLink]="['/player']" pageTransition="slideTop" class="player-box">

    </StackLayout>
</StackLayout>

Body:
There are many things that are wrong here:

First, http calls are asynchrnous, so you cannot access the value they compute until they have completed.

If there is no .subscribe(), no Observable will do anything.

You shouldn't rely on state when dealing with observables in services, that's counter-productive.

PlayerService:

export class PlayersService {
  constructor(private http: Http) {}

  getPlayers(roster) {
    let url = "http://php.esports.cz/phone_app_roman_api/api.php/hrac?filter=id,eq," ;
    return Observable.combineLatest(
      ...roster[0]["soupiska"].map(player => this.http.get(url+ player['id_hrac'])
        .map(res => res.json()))
    ).do(players=>console.log(players));
  }

  getRoster() {
    let url = "http://php.esports.cz/phone_app_roman_api/api.php/soupiska?filter[]=kategorie,eq,MUZ&filter[]=sezona,eq,2017&order=id_polozka&page=1,10"
    return this.http.get(url)
      .map(res => res.json())
  }

}

RosterPage:

export class RosterPage extends Page implements OnInit
{
    roster:any[];
    players:any[];

    constructor(private location: Location, private playersService: PlayersService) {
        super(location);
    }

    ngOnInit() {
        this.playersService.getRoster()
        .do(roster=>this.roster=roster)
        .switchMap(roster=>this.playersService.getPlayers(roster))
        .do(players=>this.players=players)
        .subscribe();
    }
}


问:
Delay ajax request for 3 seconds before processing
I have an ajax script to send data. I want to display .coin-flip for 3 seconds before the data is sent/processed. Once this 3 seconds are over the data will be sent to flip-process.php normally and then the return result will be displayed on success. But currently its so fast that I just can see the coin flipping here (the animation I want to display). Therefore, I want a delay of 3 seconds before processing the ajax request. How can I do so?

Here is my ajax script.

```<code><script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#coins").hide();
                $(".coin-flip").show();
      },
            success: function(html){
                $(".message").html(html).fadeIn();
                    $("#coins").show();
                    $(".coin-flip").hide();
            }
        });
        return false;
    });
});
</script>
</code>```

答:
Try this</p>

```<code>setTimeout(function(){ callAjax(); }, 3000);

function callAjax(){
     $.ajax({
        type: "POST",
        url: "flip-process.php",
        data: dataString,
        cache: true,
        beforeSend: function(){
            $("#coins").hide();
            $(".coin-flip").show();
        },
        success: function(html){
            $(".message").html(html).fadeIn();
                $("#coins").show();
                $(".coin-flip").hide();
        }
    });
    return false;
}
</code>```

Body:
Try this

setTimeout(function(){ callAjax(); }, 3000);

function callAjax(){
     $.ajax({
        type: "POST",
        url: "flip-process.php",
        data: dataString,
        cache: true,
        beforeSend: function(){
            $("#coins").hide();
            $(".coin-flip").show();
        },
        success: function(html){
            $(".message").html(html).fadeIn();
                $("#coins").show();
                $(".coin-flip").hide();
        }
    });
    return false;
}


问:
How to create the instance of custom element on Polymer
I face a problem on creating an instance of Polymer custom element.
I create a custom element using paper-button and paper-toggle-button.
I want to create an instance of it using Javascript(createElement).
However its style is not kept.
I need your help.

button-status.html

```<code><!-- button-status.html -->
<link rel="import" href="/bower_components/polymer/polymer.html">
<link rel="import" href="/bower_components/paper-button/paper-button.html">
<link rel="import" href="/bower_components/paper-toggle-button/paper-toggle-button.html">

<dom-module id="button-status">
<template>
    <style>
        .dname {
            margin-top: 15px;
            margin-left: 5px;
            margin-right: 5px;
            min-height: 50px;
            max-height: 50px;
            min-width: 300px;
            width: 100%;
            height: 50px;
            position: relative;
            display: block;
            color: #000;
            border: 1px solid rgba(0, 0, 0, 0.2);
            box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.4);
        }
        .toggle {
            width: 15%;
            height: 100%;
            position: absolute;
            top: 0;
            right: 0;
        }
        paper-button {
            width: 80%;
            height: 100%;
        }
        paper-toggle-button {
            position: absolute;
            width: 100%;
            height: 100%;
            right: 0;
            left: 0;
        }
        #yourButton {
            position: absolute;
            top: 100px;
        }
    </style>
<div class="dname">
    <paper-button>
        <content></content>
    </paper-button>
    <div class="toggle">
        <paper-toggle-button id="myButton"></paper-toggle-button>
    </div>
</div>
</template>
<script>
    Polymer({
        is: 'button-status',
        properties : {
            deviceId: {
                type: String,
                notify: true
            }
        }
    });
</script>
</dom-module>
</code>```

index.html

```<code><!-- index.html -->

<!DOCTYPE html>

<html lang="ja">

<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <meta charset="UTF-8">
    <link rel="import" href="/bower_components/polymer/polymer.html">
    <link rel="import" href="/bower_components/paper-input/paper-input.html">
    <link rel="import" href="/bower_components/gold-email-input/gold-email-input.html">
    <link rel="import" href="/bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
    <link rel="import" href="/bower_components/paper-listbox/paper-listbox.html">
    <link rel="import" href="/bower_components/paper-item/paper-item.html">
    <link rel="import" href="/bower_components/paper-dialog-scrollable/paper-dialog-scrollable.html">
    <link rel="import" href="/bower_components/paper-dialog/paper-dialog.html">
    <link rel="import" href="/bower_components/paper-button/paper-button.html">
    <link rel="import" href="/bower_components/paper-toolbar/paper-toolbar.html">
    <link rel="import" href="/bower_components/iron-icons/iron-icons.html">
    <link rel="import" href="/bower_components/paper-icon-button/paper-icon-button.html">
    <link rel="import" href="/bower_components/paper-toggle-button/paper-toggle-button.html">
    <link rel="import" href="/cre_components/button-status/button-status.html">
    <link rel="import" href="/cre_components/device-add-input/device-add-input.html">
    <link rel="stylesheet" type="text/css" href="/css/dashboard.css">
    <title>Create new account</title>
</head>

<body>
    <paper-toolbar>
        <paper-icon-button icon="menu"></paper-icon-button>
        <span class="title">Test</span>
        <a href="help.html">
            <paper-button class="help">Button</paper-button>
        </a>
    </paper-toolbar>
    <section>
        <div id="statusList">
            <button-status device-id = "A01" id="A01">status1</button-status>
            <button-status device-id = "A02" id="A02">status2</button-status>
        </div>
        <div class="edit">
            <paper-button raised onclick="dialog.open()">Add</paper-button>
            <paper-button raised>Delet</paper-button>
            <paper-dialog id="dialog">
                <device-add-input></device-add-input>
            </paper-dialog>
        </div>
    </section>
</body>
<script>
    var newEl = document.createElement('button-status');
    newEl.innerHTML = "status3";
    newEl.id = "S03";
    var l = document.getElementById('deviceList');
    l.appendChild(newEl);
</script>
</html>
</code>```

答:
I don't know if I understood your question, but this newEl.innerHTML = "status3"; will override all html of your element.

Jsbin with added element working -->
https://jsbin.com/qeyareqemi/1/edit?html,console,output

Body:
I face a problem on creating an instance of Polymer custom element.
I create a custom element using paper-button and paper-toggle-button.
I want to create an instance of it using Javascript(createElement).
However its style is not kept.
I need your help.

button-status.html

<link rel="import" href="/bower_components/polymer/polymer.html">
<link rel="import" href="/bower_components/paper-button/paper-button.html">
<link rel="import" href="/bower_components/paper-toggle-button/paper-toggle-button.html">

<dom-module id="button-status">
<template>

    <paper-button>
        <content></content>
    </paper-button>

        <paper-toggle-button id="myButton"></paper-toggle-button>

</template>

</dom-module>

index.html

<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <meta charset="UTF-8">
    <link rel="import" href="/bower_components/polymer/polymer.html">
    <link rel="import" href="/bower_components/paper-input/paper-input.html">
    <link rel="import" href="/bower_components/gold-email-input/gold-email-input.html">
    <link rel="import" href="/bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
    <link rel="import" href="/bower_components/paper-listbox/paper-listbox.html">
    <link rel="import" href="/bower_components/paper-item/paper-item.html">
    <link rel="import" href="/bower_components/paper-dialog-scrollable/paper-dialog-scrollable.html">
    <link rel="import" href="/bower_components/paper-dialog/paper-dialog.html">
    <link rel="import" href="/bower_components/paper-button/paper-button.html">
    <link rel="import" href="/bower_components/paper-toolbar/paper-toolbar.html">
    <link rel="import" href="/bower_components/iron-icons/iron-icons.html">
    <link rel="import" href="/bower_components/paper-icon-button/paper-icon-button.html">
    <link rel="import" href="/bower_components/paper-toggle-button/paper-toggle-button.html">
    <link rel="import" href="/cre_components/button-status/button-status.html">
    <link rel="import" href="/cre_components/device-add-input/device-add-input.html">
    <link rel="stylesheet" type="text/css" href="/css/dashboard.css">
    <title>Create new account</title>

    <paper-toolbar>
        <paper-icon-button icon="menu"></paper-icon-button>
        Test

            <paper-button class="help">Button</paper-button>

    </paper-toolbar>

            <button-status device-id = "A01" id="A01">status1</button-status>
            <button-status device-id = "A02" id="A02">status2</button-status>

            <paper-button raised onclick="dialog.open()">Add</paper-button>
            <paper-button raised>Delet</paper-button>
            <paper-dialog id="dialog">
                <device-add-input></device-add-input>
            </paper-dialog>


问:
Sending a list of java objects to an SQL stored procedure via mybatis?
I've asked this question before - didn't really end up with a working solution, and that might have been somewhat my own problem for not really knowing at the time, what the hell I wanted to do.

Please don't flag this as a duplicate, as I intend including better information on it.

Here is my mapper xml :

```<code><select id="deleteItems" resultMap="BaseResultMap">
    exec [dbo].[PR_ItemsForDeletion_Delete]
</select>
</code>```

Now, we can ignore the result map here I believe - because I am not concerned with what I am getting back (yet!)

Now, see that stored procedure? I didn't write it - and I also don't have access to the code for that - but I do know for a fact that it works.

The stored procedure takes a list of items. I need to pass in the following :

```<code>List<CustomDeletableObject>
</code>```

Trusting that the sproc works, and with the mapper I just want to execute that mapping XML - and pass a list to it, but I have ABSOLUTELY no idea where to begin with that.

Massive thankyou in advance, I have been banging my head against this one for hours now.

The custom deletable object type contains two properties :

private long id - which is just an id we use. private Sting token - the data we are actually storing.

the Stored procedure, I don't have access to the query itself - but essentially what it does, is deletes every item in a table which has a match to an item in the list we want to provide to it via myBatis.

This is how I am planning to call the mapper...

```<code>@Override
public boolean deleteItems(List<CustomDeletableObject> tokens){

    // This method handles the deletion.
    jobMapper.deleteItems();

    return false;
}
</code>```

Here is the stored procedure I am trying to use : In the interest of security, the table names have been replaced with nonsense TABLE tags.

```<code>CREATE PROCEDURE [dbo].[PR_ItemsForDeletion_Delete]
    @pTokenList dbo.UDT_TokenDeletion READONLY
AS

BEGIN
    BEGIN TRY
        IF EXISTS (SELECT TOP 1 1 FROM @pTokenList)
            BEGIN
                INSERT INTO <TABLE> (Token)
                SELECT
                    Token
                FROM @pTokenList tl
                WHERE NOT EXISTS
                (
                    SELECT TOP 1 1
                    FROM <TABLE> tp
                    WHERE tp.Token = tl.Token
                )
            END
    END TRY
    BEGIN CATCH
    ;THROW
    END CATCH
END
</code>```

答:
You will need to extend BaseTypeHandler and specially setNonNullParameter method. Here is example, not so bad, but look up for more.

It seems what you need is (close to) Table-Valued Parameter

This is is driver specific JDBC code to put in the type handler method.

Reference the type handler in the parameter binding in call.

```<code><delete id="deleteItems">
    exec dbo.PR_ItemsForDeletion_Delete #{list, typeHandler=com.fully.qualified.name.TokenListTypeHandler}
</delete>
</code>```

Semantically the intention is deleting, better use the keyword even though there is no technical impact. no need for result map if there is no result to map.

Body:
I've asked this question before - didn't really end up with a working solution, and that might have been somewhat my own problem for not really knowing at the time, what the hell I wanted to do.

Please don't flag this as a duplicate, as I intend including better information on it.

Here is my mapper xml :

<select id="deleteItems" resultMap="BaseResultMap">
    exec [dbo].[PR_ItemsForDeletion_Delete]
</select>

Now, we can ignore the result map here I believe - because I am not concerned with what I am getting back (yet!)

Now, see that stored procedure? I didn't write it - and I also don't have access to the code for that - but I do know for a fact that it works.

The stored procedure takes a list of items. I need to pass in the following :

List<CustomDeletableObject>

Trusting that the sproc works, and with the mapper I just want to execute that mapping XML - and pass a list to it, but I have ABSOLUTELY no idea where to begin with that.

Massive thankyou in advance, I have been banging my head against this one for hours now.

The custom deletable object type contains two properties :

private long id - which is just an id we use. private Sting token - the data we are actually storing.

the Stored procedure, I don't have access to the query itself - but essentially what it does, is deletes every item in a table which has a match to an item in the list we want to provide to it via myBatis.

This is how I am planning to call the mapper...

@Override
public boolean deleteItems(List<CustomDeletableObject> tokens){

    // This method handles the deletion.
    jobMapper.deleteItems();

    return false;
}

Here is the stored procedure I am trying to use : In the interest of security, the table names have been replaced with nonsense TABLE tags.

CREATE PROCEDURE [dbo].[PR_ItemsForDeletion_Delete]
    @pTokenList dbo.UDT_TokenDeletion READONLY
AS

BEGIN
    BEGIN TRY
        IF EXISTS (SELECT TOP 1 1 FROM @pTokenList)
            BEGIN
                INSERT INTO
 (Token)
                SELECT
                    Token
                FROM @pTokenList tl
                WHERE NOT EXISTS
                (
                    SELECT TOP 1 1
                    FROM
 tp
                    WHERE tp.Token = tl.Token
                )
            END
    END TRY
    BEGIN CATCH
    ;THROW
    END CATCH
END

Body:
You will need to extend BaseTypeHandler and specially setNonNullParameter method. Here is example, not so bad, but look up for more.

It seems what you need is (close to) Table-Valued Parameter

This is is driver specific JDBC code to put in the type handler method.

Reference the type handler in the parameter binding in call.

<delete id="deleteItems">
    exec dbo.PR_ItemsForDeletion_Delete #{list, typeHandler=com.fully.qualified.name.TokenListTypeHandler}
</delete>

Semantically the intention is deleting, better use the keyword even though there is no technical impact. no need for result map if there is no result to map.


问:
Embedded authentication + LDAP user verification in Django. How to?

Intro

Django version: 1.10

Python version: 3.5.2

I'm trying to implement an authentication based on a LDAP condition and I can't get my head around on how to achieve this.

My project already uses Django's built-in authentication system, which works great and looks like this:

```<code># urls.py

from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views
from coffee_app.forms import LoginForm

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('coffee_app.urls')),

    url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),
    url(r'^logout/$', views.logout, {'next_page': '/login'}, name='logout'),
]
</code>```

```<code># forms.py

from django.contrib.auth.forms import AuthenticationForm
from django import forms

class LoginForm(AuthenticationForm):
    username = forms.CharField(label="Username", max_length=32,
                               widget=forms.TextInput(attrs={
                                   'class': 'form-control',
                                   'name': 'username'
                               }))
    password = forms.CharField(label="Password", max_length=20,
                               widget=forms.PasswordInput(attrs={
                                   'class': 'form-control',
                                   'name': 'password'
                               }))
</code>```

```<code><!--login.html (relevant part)-->

<form class="form-horizontal" action="{% url 'login' %}" method="post" id="contact_form">
    {% csrf_token %}
    <fieldset>
        <div class="form-group">
            <label class="col-md-4 control-label">{{ form.username.label_tag }}</label>
            <div class="col-md-4 inputGroupContainer">
                <div class="input-group">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                    {{ form.username }}
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-md-4 control-label" >{{ form.password.label_tag }}</label>
            <div class="col-md-4 inputGroupContainer">
                <div class="input-group">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                    {{ form.password }}
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-md-4 control-label"></label>
            <div class="col-md-4 text-center">
                <br>
                <button value="login" type="submit" class="btn btn-warning" >
                LOG IN
                <span class="glyphicon glyphicon-send"></span>
                </button>
            </div>
        </div>
    </fieldset>
    <input type="hidden" name="next" value="{{ next }}"/>
</form>
</code>```

Problem

Now, what I'm trying to do, is to verify whether a user exists in LDAP or not, before getting to the initial Django auth:

```<code>from ldap3 import Server, Connection, ALL, NTLM

server = Server('server here', get_info=ALL, use_ssl=True)
conn = Connection(server,
                  user='DOMAIN\\username',
                  password='password',
                  authentication=NTLM)

print(conn.bind())
</code>```

If conn.bind() returns True, I'd like to go further to Django's built-in authentication system and authenticate the user. Unfortunately, I don't know where / how to add this step in order to achieve this.

Some views look like this:

```<code>from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

@login_required(login_url="login/")
def home(request):
    return render(request, "home.html")

@login_required(login_url="login/")
def activity_report_page(request):
    return render(request, "activity_report.html")
...
</code>```

And their urls:

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'report$', views.activity_report_page, name='activity_report')
]
</code>```

Could someone please point out where should I add the LDAP piece of code so that I can first verify if a user exist there?

PS: I didn't consider using django-auth-ldap because I don't really need a pure LDAP authentication-based system. Just a simple verification.

答:
You want to customize authentication in Django, where you more specifically want to write an authentication backend. I assume that your project is called 'coffee_site', and you have the app 'coffee_app'. You first want to change coffee_site/settings.py, and append AUTHENTICATION_BACKENDS = ['coffee_site.auth.LDAP'] to it. After this, you want to make and edit coffee_site/auth.py. As you said in the question you want to use the default authentication, and so you should inherit from django.contrib.auth.backends.ModelBackend, you then want to make it so that if conn.bind() is not True, then you don't use the default authentication, and so you should return None. This can be implemented with:

```<code>from django.contrib.auth.backends import ModelBackend
from ldap3 import Server, Connection, ALL, NTLM

server = Server('server here', get_info=ALL, use_ssl=True)

class LDAP(ModelBackend):
    def authenticate(self, *args, **kwargs):
        username = kwargs.get('username')
        password = kwargs.get('password')
        if username is None or password is None:
            return None
        conn = Connection(server,
                          user='DOMAIN\\{}'.format(username),
                          password=password,
                          authentication=NTLM)
        if not conn.bind():
            return None
        return super().authenticate(*args, **kwargs)
</code>```

Note: I checked this works on Django's side, but I made no effort to check that the LDAP code works.

Body:
Intro

Django version: 1.10

Python version: 3.5.2

I'm trying to implement an authentication based on a LDAP condition and I can't get my head around on how to achieve this.

My project already uses Django's built-in authentication system, which works great and looks like this:

# urls.py

from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views
from coffee_app.forms import LoginForm

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('coffee_app.urls')),

    url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),
    url(r'^logout/$', views.logout, {'next_page': '/login'}, name='logout'),
]

# forms.py

from django.contrib.auth.forms import AuthenticationForm
from django import forms

class LoginForm(AuthenticationForm):
    username = forms.CharField(label="Username", max_length=32,
                               widget=forms.TextInput(attrs={
                                   'class': 'form-control',
                                   'name': 'username'
                               }))
    password = forms.CharField(label="Password", max_length=20,
                               widget=forms.PasswordInput(attrs={
                                   'class': 'form-control',
                                   'name': 'password'
                               }))

<form class="form-horizontal" action="{% url 'login' %}" method="post" id="contact_form">
    {% csrf_token %}
    <fieldset>

            {{ form.username.label_tag }}

                    {{ form.username }}

            {{ form.password.label_tag }}

                    {{ form.password }}

                <button value="login" type="submit" class="btn btn-warning" >
                LOG IN

                </button>

    </fieldset>
    <input type="hidden" name="next" value="{{ next }}"/>
</form>

Problem

Now, what I'm trying to do, is to verify whether a user exists in LDAP or not, before getting to the initial Django auth:

from ldap3 import Server, Connection, ALL, NTLM

server = Server('server here', get_info=ALL, use_ssl=True)
conn = Connection(server,
                  user='DOMAIN\\username',
                  password='password',
                  authentication=NTLM)

print(conn.bind())

If conn.bind() returns True, I'd like to go further to Django's built-in authentication system and authenticate the user. Unfortunately, I don't know where / how to add this step in order to achieve this.

Some views look like this:

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

@login_required(login_url="login/")
def home(request):
    return render(request, "home.html")

@login_required(login_url="login/")
def activity_report_page(request):
    return render(request, "activity_report.html")
...

And their urls:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'report$', views.activity_report_page, name='activity_report')
]

Could someone please point out where should I add the LDAP piece of code so that I can first verify if a user exist there?

PS: I didn't consider using django-auth-ldap because I don't really need a pure LDAP authentication-based system. Just a simple verification.

Body:
You want to customize authentication in Django, where you more specifically want to write an authentication backend. I assume that your project is called 'coffee_site', and you have the app 'coffee_app'. You first want to change coffee_site/settings.py, and append AUTHENTICATION_BACKENDS = ['coffee_site.auth.LDAP'] to it. After this, you want to make and edit coffee_site/auth.py. As you said in the question you want to use the default authentication, and so you should inherit from django.contrib.auth.backends.ModelBackend, you then want to make it so that if conn.bind() is not True, then you don't use the default authentication, and so you should return None. This can be implemented with:

from django.contrib.auth.backends import ModelBackend
from ldap3 import Server, Connection, ALL, NTLM

server = Server('server here', get_info=ALL, use_ssl=True)

class LDAP(ModelBackend):
    def authenticate(self, *args, **kwargs):
        username = kwargs.get('username')
        password = kwargs.get('password')
        if username is None or password is None:
            return None
        conn = Connection(server,
                          user='DOMAIN\\{}'.format(username),
                          password=password,
                          authentication=NTLM)
        if not conn.bind():
            return None
        return super().authenticate(*args, **kwargs)

Note: I checked this works on Django's side, but I made no effort to check that the LDAP code works.


问:
UICollectionView Programmatically
I created my own window in storyboard like below:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        window?.rootViewController = UINavigationController(rootViewController: HomeController())
        return true
    }
</code>```

This actually worked fine when my class is subclassing UIViewController.

```<code>class HomeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = UIColor.red
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

Now when I subclass my class with UICollectionViewController:

```<code>class HomeController: UICollectionViewController {

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            Collectionview.backgroundColor = UIColor.red
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

    }
</code>```

At runtime it gives me an error saying:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'UICollectionView must be
  initialized with a non-nil layout parameter'
  *** First throw call stack:

In my understanding it is asking me to give layout for UICollectionView.Correct me here if I am wrong.So I tried this-:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        let layout = UICollectionViewFlowLayout()
        window?.rootViewController = UINavigationController(rootViewController: HomeController(UICollectionViewLayout: layout))
        return true
    }
</code>```

But Still ending up with an error:

Argument labels 'UICollectionViewLayout' do not match any available
  overloads.

Am I using a wrong swift3 syntax? If yes what is correct to solve out this issue.

答:
You need to use UICollectionViewController's designated intialiser as below.

```<code>let layout = UICollectionViewLayout()
let homeViewController = HomeController(collectionViewLayout: layout)
window?.rootViewController = UINavigationController(rootViewController: homeViewController)
</code>```

Along with that, you will need to modify you HomeViewController to implement UICollectionViewDataSource required methods.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

        // Do any additional setup after loading the view.
    }

// MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 0
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

        // Configure the cell

        return cell
    }
</code>```

Title: UICollectionView Programmatically

Body:
I created my own window in storyboard like below:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        window?.rootViewController = UINavigationController(rootViewController: HomeController())
        return true
    }

This actually worked fine when my class is subclassing UIViewController.

class HomeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = UIColor.red
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Now when I subclass my class with UICollectionViewController:

class HomeController: UICollectionViewController {

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            Collectionview.backgroundColor = UIColor.red
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

    }

At runtime it gives me an error saying:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'UICollectionView must be
  initialized with a non-nil layout parameter'
  *** First throw call stack:

In my understanding it is asking me to give layout for UICollectionView.Correct me here if I am wrong.So I tried this-:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        let layout = UICollectionViewFlowLayout()
        window?.rootViewController = UINavigationController(rootViewController: HomeController(UICollectionViewLayout: layout))
        return true
    }

But Still ending up with an error:

Argument labels 'UICollectionViewLayout' do not match any available
  overloads.

Am I using a wrong swift3 syntax? If yes what is correct to solve out this issue.

Body:
You need to use UICollectionViewController's designated intialiser as below.

let layout = UICollectionViewLayout()
let homeViewController = HomeController(collectionViewLayout: layout)
window?.rootViewController = UINavigationController(rootViewController: homeViewController)

Along with that, you will need to modify you HomeViewController to implement UICollectionViewDataSource required methods.

override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

        // Do any additional setup after loading the view.
    }

// MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 0
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

        // Configure the cell

        return cell
    }


问:
How to use strtok properly to compare versions?
I am trying to write a C program which compares 2 software version numbers (in the format "12.3.2", "2.10", "6.0.0.3" or "2.0") using strtok in C. Also 1.0 is considered bigger than 1. So, basically, compares 2 strings that represent version numbers. Trying to figure out a way for the code to work. I'm stuck at the point that how could I store these tokens? And then how could I compare them later?
So if:

```<code>v1>v2 : return 1,
v1==v2:return 0
v1<v2: return -1.
</code>```

The function signature could be:

```<code>int cmp(char *v1, char *v2){...}
</code>```

(v1 and v2 are the version numbers.)
Any suggestions? I'm practically new to C compared to Python or other object oriented programming languages(C#,java).

Here's what I've tried so far:

```<code>struct version_t {
int major;
int minor;
int build;
</code>```

};

```<code>version_t parse_ver(const char* version_str) {
   version_t res;
   version_t r;
   // Trying to use strtok_r to split the string, and atoi to convert
   //tokens to ints
  char *token;
  char *rest = version_str;
  while((token = strtok_r(rest,".",&rest)))
  {
    res = token;
  }
  r = atoi(res);
  return r;
 }
</code>```

Initially I am just considering that versions are in the format 12.3.4(3 fields). I'm not sure how I could work with other sorts of version numbers like 1.34.2.5 or 1.0

I would then use the parse_ver function twice to parse both the version numbers. If I could get the tokens and return them as integers I would later use a compare function to compare those integers and solve this problem.
I wrote a small program to check how strtok works and I got the idea by writing something as the following:

```<code>void main(void)
{
  char str[] = "1.2.3.4";
  char *token;
  char *rest = str;

  while((token = strtok_r(rest, ".", &rest)))
  {
    printf("token:%s\n", token);

  }
}
</code>```

But I need to store the tokens in the struct somehow. Slightly confused here.

Again, I'm pretty new to the C programming language and any kind of help would be really appreciated.

答:
You could use strtol() for this, taking advantage of the tail pointer and skipping over the decimal points. This would allow comparison of each field.

In the code below, starting from the first field, a positive value is returned if the first version number is greater than the second, or a negative value is returned if the first version number is less than the second. If the two version numbers are equal, the decimal point is skipped, and the next two fields are compared. If the the end of one string is reached and the fields have compared equal, the difference between the values indicated by the tail pointers is returned (so 1.0 is greater than 1).

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

int ver_comp(char *, char *);

int main(void)
{
    char *ver1 = "12.3.2";
    char *ver2 = "2.10";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    ver1 = "2.10";
    ver2 = "6.0.0.3";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    ver1 = "2";
    ver2 = "2.0";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    ver1 = "2.0.0.1.2";
    ver2 = "2.0.0.2.2";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    ver1 = "1.2.3.4";
    ver2 = "1.2.3.4";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    return 0;
}

int ver_comp(char *v1, char *v2)
{
    int res = 0;
    char *next_1 = v1;
    char *next_2 = v2;

    while (*next_1 != '\0' && *next_2 != '\0') {
        long x1 = strtol(v1, &next_1, 10);
        long x2 = strtol(v2, &next_2, 10);

        res = x1 - x2;
        if (res) {
            break;
        }

        if (*next_1 == '\0' || *next_2 == '\0') {
            res = *next_1 - *next_2;
            break;
        }

        v1 = next_1 + 1;
        v2 = next_2 + 1;
    }

    return res;
}
</code>```

Program output:

```<code>12.3.2 - 2.10 = 10
2.10 - 6.0.0.3 = -4
2 - 2.0 = -46
2.0.0.1.2 - 2.0.0.2.2 = -1
1.2.3.4 - 1.2.3.4 = 0
</code>```

Body:
I am trying to write a C program which compares 2 software version numbers (in the format "12.3.2", "2.10", "6.0.0.3" or "2.0") using strtok in C. Also 1.0 is considered bigger than 1. So, basically, compares 2 strings that represent version numbers. Trying to figure out a way for the code to work. I'm stuck at the point that how could I store these tokens? And then how could I compare them later?
So if:

v1>v2 : return 1,
v1==v2:return 0
v1<v2: return -1.

The function signature could be:

int cmp(char *v1, char *v2){...}

(v1 and v2 are the version numbers.)
Any suggestions? I'm practically new to C compared to Python or other object oriented programming languages(C#,java).

Here's what I've tried so far:

struct version_t {
int major;
int minor;
int build;

};

version_t parse_ver(const char* version_str) {
   version_t res;
   version_t r;
   // Trying to use strtok_r to split the string, and atoi to convert
   //tokens to ints
  char *token;
  char *rest = version_str;
  while((token = strtok_r(rest,".",&rest)))
  {
    res = token;
  }
  r = atoi(res);
  return r;
 }

Initially I am just considering that versions are in the format 12.3.4(3 fields). I'm not sure how I could work with other sorts of version numbers like 1.34.2.5 or 1.0

I would then use the parse_ver function twice to parse both the version numbers. If I could get the tokens and return them as integers I would later use a compare function to compare those integers and solve this problem.
I wrote a small program to check how strtok works and I got the idea by writing something as the following:

void main(void)
{
  char str[] = "1.2.3.4";
  char *token;
  char *rest = str;

  while((token = strtok_r(rest, ".", &rest)))
  {
    printf("token:%s\n", token);

  }
}

But I need to store the tokens in the struct somehow. Slightly confused here.

Again, I'm pretty new to the C programming language and any kind of help would be really appreciated.

Body:
You could use strtol() for this, taking advantage of the tail pointer and skipping over the decimal points. This would allow comparison of each field.

In the code below, starting from the first field, a positive value is returned if the first version number is greater than the second, or a negative value is returned if the first version number is less than the second. If the two version numbers are equal, the decimal point is skipped, and the next two fields are compared. If the the end of one string is reached and the fields have compared equal, the difference between the values indicated by the tail pointers is returned (so 1.0 is greater than 1).

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

int ver_comp(char *, char *);

int main(void)
{
    char *ver1 = "12.3.2";
    char *ver2 = "2.10";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    ver1 = "2.10";
    ver2 = "6.0.0.3";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    ver1 = "2";
    ver2 = "2.0";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    ver1 = "2.0.0.1.2";
    ver2 = "2.0.0.2.2";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    ver1 = "1.2.3.4";
    ver2 = "1.2.3.4";
    printf("%s - %s = %d\n", ver1, ver2, ver_comp(ver1, ver2));

    return 0;
}

int ver_comp(char *v1, char *v2)
{
    int res = 0;
    char *next_1 = v1;
    char *next_2 = v2;

    while (*next_1 != '\0' && *next_2 != '\0') {
        long x1 = strtol(v1, &next_1, 10);
        long x2 = strtol(v2, &next_2, 10);

        res = x1 - x2;
        if (res) {
            break;
        }

        if (*next_1 == '\0' || *next_2 == '\0') {
            res = *next_1 - *next_2;
            break;
        }

        v1 = next_1 + 1;
        v2 = next_2 + 1;
    }

    return res;
}

Program output:

12.3.2 - 2.10 = 10
2.10 - 6.0.0.3 = -4
2 - 2.0 = -46
2.0.0.1.2 - 2.0.0.2.2 = -1
1.2.3.4 - 1.2.3.4 = 0


Title: Check whether a value appeared within the last n minutes

Body:
If we have the following data:

timestamp = ['2016-01-09_14-49-18','2016-01-10_09-48-59','2016-01-10_09-50-29','2016-01-10_09-59-08','2016-01-10_10-33-01','2016-01-10_10-35-01','2016-01-10_10-39-05','2016-01-10_10-40-38','2016-01-10_10-50-55','2016-01-10_12-28-35','2016-01-10_15-13-34','2016-01-10_17-02-44','2016-01-10_17-05-48','2016-01-10_17-13-44','2016-01-10_17-15-52']
feature = ['A','A','B','C','B','C','C','A','A','A','B','A','C','C','A']
df = pd.DataFrame({'timestamp':timestamp, 'feature':feature})

How can one create a new column for each feature that represents whether or not that class appeared in, let's say, the last 15 minutes?

Result:

   feature    timestamp              A    B    C
0       A  2016-01-09_14-49-18       1    0    0
1       A  2016-01-10_09-48-59       1    0    0
2       B  2016-01-10_09-50-29       1    1    0
3       C  2016-01-10_09-59-08       1    1    1
4       B  2016-01-10_10-33-01       0    1    0
5       C  2016-01-10_10-35-01       0    1    1
6       C  2016-01-10_10-39-05       0    1    1
7       A  2016-01-10_10-40-38       1    1    1
8       A  2016-01-10_10-50-55       1    0    1
9       A  2016-01-10_12-28-35       1    0    0
10      B  2016-01-10_15-13-34       0    1    0
11      A  2016-01-10_17-02-44       1    0    0
12      C  2016-01-10_17-05-48       1    0    1
13      C  2016-01-10_17-13-44       1    0    1
14      A  2016-01-10_17-15-52       1    0    1

Where 1 = the class appeared in the last 15 minutes, and 0 = the class did not appear.

Body:
You can use:

df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d_%H-%M-%S')

for col in df['feature'].unique():
    df[col] = df['timestamp'] - df['timestamp'].where(df['feature'] == col).ffill()
    df[col] = (df[col] < pd.to_timedelta('15min')).astype(int)
print (df)

   feature           timestamp  A  B  C
0        A 2016-01-09 14:49:18  1  0  0
1        A 2016-01-10 09:48:59  1  0  0
2        B 2016-01-10 09:50:29  1  1  0
3        C 2016-01-10 09:59:08  1  1  1
4        B 2016-01-10 10:33:01  0  1  0
5        C 2016-01-10 10:35:01  0  1  1
6        C 2016-01-10 10:39:05  0  1  1
7        A 2016-01-10 10:40:38  1  1  1
8        A 2016-01-10 10:50:55  1  0  1
9        A 2016-01-10 12:28:35  1  0  0
10       B 2016-01-10 15:13:34  0  1  0
11       A 2016-01-10 17:02:44  1  0  0
12       C 2016-01-10 17:05:48  1  0  1
13       C 2016-01-10 17:13:44  1  0  1
14       A 2016-01-10 17:15:52  1  0  1


问:
Toggle visibility of sibling element of $(this) element | No unique ID [jQuery]
I need div.edit-button to toggle its sibling div.additionalFieldForm.

Note that there's more than one div.edit-button and div.additionalFieldForm on the page, but I would like to target the div.additionalFieldForm that is in the same "family" as the div.edit-button that was clicked.

$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).closest("div").prev().toggle();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm">Content</div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm">Content</div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
</ul></code>```

I've tried other selectors but I couldn't specifically target just the div.additionalFieldForm sibling of the edit button being clicked.

EDIT: I realize that there must be an underlying problem because the selector works on jsFiddle (http://jsfiddle.net/wf7jjoq7/), but not on my site, without any console errors.

答:
Try this solution:

$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).parent().find(".additionalFieldForm").first().toggle();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
</ul></code>```

Body:
I need div.edit-button to toggle its sibling div.additionalFieldForm.

Note that there's more than one div.edit-button and div.additionalFieldForm on the page, but I would like to target the div.additionalFieldForm that is in the same "family" as the div.edit-button that was clicked.

$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).closest("div").prev().toggle();

});

    Additional Field

Content

Edit

Remove

    Additional Field

Content

Edit

Remove

I've tried other selectors but I couldn't specifically target just the div.additionalFieldForm sibling of the edit button being clicked.

EDIT: I realize that there must be an underlying problem because the selector works on jsFiddle (http://jsfiddle.net/wf7jjoq7/), but not on my site, without any console errors.

Body:
Try this solution:

$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).parent().find(".additionalFieldForm").first().toggle();

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
</ul>