问:
How to handle request in node.js?
I have a problem with requests in node js. All time i get 404 error.

router:

```<code>router.get('/within', function (req, res){
    var lat1 = parseFloat(req.query.lat1);
    var lon1 = parseFloat(req.query.lon1);
    var lat2 = parseFloat(req.query.lat2);
    var lon2 = parseFloat(req.query.lon2);
    var db = req.db;

    db.collection('parks').find({"pos" : { $geoWithin : { $box: [[lon2,lat2], [lon1,lat1]]}}}).toArray(function(err,names){
        res.header("Content-Type:","application/json");
        res.end(JSON.stringify(names));
    });
});
</code>```

And request url:

```<code>http://localhost:3012/within?lat1=77.31251993823143&lon1=139.92187500000003&lat2=-44.59046718130884&lon2=-190.54687500000003
</code>```

What can be wrong?

答:
Check three points:
Your server is running on 3012?
you have included router file where this code is written?
your server is working ?</p>

Title: How to handle request in node.js?

Body:
I have a problem with requests in node js. All time i get 404 error.

router:

router.get('/within', function (req, res){
    var lat1 = parseFloat(req.query.lat1);
    var lon1 = parseFloat(req.query.lon1);
    var lat2 = parseFloat(req.query.lat2);
    var lon2 = parseFloat(req.query.lon2);
    var db = req.db;

    db.collection('parks').find({"pos" : { $geoWithin : { $box: [[lon2,lat2], [lon1,lat1]]}}}).toArray(function(err,names){
        res.header("Content-Type:","application/json");
        res.end(JSON.stringify(names));
    });
});

And request url:

http://localhost:3012/within?lat1=77.31251993823143&lon1=139.92187500000003&lat2=-44.59046718130884&lon2=-190.54687500000003

What can be wrong?


来源: stackexchange

问:
Using htaccess to redirect all but ONE PAGE to https
I have a new website and am trying to make it https.  I am embedding a forum on one page.  The forum does not come in https !  Thus I need that one page to be served over HTTP, and not HTTPS.  I am using the standard htaccess code to force all pages to go to HTTPS.

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

I read up on syntax a bit, but it is very complex.  I think I want to do something with the RewriteCond , because from what I read that will create an exception to the rule right below it.

My forum is on http://www.xxxx.xxx/forum.html

How to write the rule to make an exception for that page?

答:
You can use the following rules in your .htaccess file. What this does is first check if HTTPs is not on, if not, then it will forward everything to HTTPs except for the directory forum. The second rule checks if HTTPs is on, if so then it will redirect forum back to HTTP.

```<code>RewriteEngine On

RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteCond %{REQUEST_URI} !^\/(forum)
RewriteRule (.*) https://%{HTTP_HOST}/$1 [L,R=301]

RewriteCond %{HTTP:X-Forwarded-SSL} =on
RewriteCond %{REQUEST_URI} ^\/(forum)
RewriteRule (.*) http://%{HTTP_HOST}/$1 [L,R=301]
</code>```

Make sure you clear your cache before testing this. If you have problems with the above rule, then you can also try the following:

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/forum
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} ^/forum
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a new website and am trying to make it https.  I am embedding a forum on one page.  The forum does not come in https !  Thus I need that one page to be served over HTTP, and not HTTPS.  I am using the standard htaccess code to force all pages to go to HTTPS.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I read up on syntax a bit, but it is very complex.  I think I want to do something with the RewriteCond , because from what I read that will create an exception to the rule right below it.

My forum is on http://www.xxxx.xxx/forum.html

How to write the rule to make an exception for that page?

Body:
You can use the following rules in your .htaccess file. What this does is first check if HTTPs is not on, if not, then it will forward everything to HTTPs except for the directory forum. The second rule checks if HTTPs is on, if so then it will redirect forum back to HTTP.

RewriteEngine On

RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteCond %{REQUEST_URI} !^\/(forum)
RewriteRule (.*) https://%{HTTP_HOST}/$1 [L,R=301]

RewriteCond %{HTTP:X-Forwarded-SSL} =on
RewriteCond %{REQUEST_URI} ^\/(forum)
RewriteRule (.*) http://%{HTTP_HOST}/$1 [L,R=301]

Make sure you clear your cache before testing this. If you have problems with the above rule, then you can also try the following:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/forum
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} ^/forum
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]


问:
bing speech to text error in Android
I have gone through documentation of bing speech to text api, i implemented a simple app which just starts speech to text on button click. I have hard coded the key values provided in Cognitive Services console. Now when I start the function as shown in sample app it throws following error. I have searched on google but i can not trace the root of the issue.

```<code>    09-16 11:39:09.799 25615 25655 I NLPLAT  : originating error 0x80070057
    09-16 11:39:09.809 25615 25655 I NLPLAT  : Application Name:
    09-16 11:39:09.819 25615 25655 I NLPLAT  : originating error 0x80070057
    09-16 11:39:09.819 25615 25655 I NLPLAT  : originating error 0x80070057
    09-16 11:39:09.819  3676  4433 D EnterpriseController: netId is 0
    09-16 11:39:09.819  3676  4433 D Netd    : getNetworkForDns: using netid 0 for uid 10068
    09-16 11:39:09.824 25615 26122 I NLPLAT  : originating error 0x8e200005
    09-16 11:39:09.824 25615 25655 I NLPLAT  : Refreshing token S
    09-16 11:39:09.824  3676  4433 D EnterpriseController: netId is 0
    09-16 11:39:09.824  3676  4433 D Netd    : getNetworkForDns: using netid 0 for uid 10068
    09-16 11:39:09.829 25615 26124 I NLPLAT  : originating error 0x8e200005
    09-16 11:39:09.829 25615 25655 I NLPLAT  : Initializing Audio Services
    09-16 11:39:09.829 25615 25655 W libOpenSLES: class OutputMix interface 0 requested but unavailable MPH=43
    09-16 11:39:09.834 25615 25655 W AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client; transfer 1, track 16000 Hz, output 48000 Hz
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Initializing Speech Services
    09-16 11:39:09.834 25615 25655 I NLPLAT  : No application id provided to controller
    09-16 11:39:09.834 25615 25655 I NLPLAT  : GetIdentityPropertyValue 3
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Useragent Value Android Assistant (Android; Unknown;Unknown;ProcessName/AppName=Unknown;DeviceType=Near;SpeechClient=1.0.160511)
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Url: 'https://websockets.platform.bing.com/ws/speech/recognize/continuous'
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Locale: 'en-us'
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Application Id: ''
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Version: 4.0.150429
    09-16 11:39:09.834 25615 25655 I NLPLAT  : UserAuthorizationToken:
    09-16 11:39:09.834 25615 25655 I NLPLAT  : ServerLoggingLevel: 1
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Initiating websocket connection. m_connection=0x0 host=websockets.platform.bing.com port=443
</code>```

Bing OnError function says :

```<code>NameNotFound -1910505467
</code>```

答:
I am having the same issue because of network connection.Check your network connection before calling "this.micClient.startMicAndRecognition();" like</p>

```<code> if(isNetworkAvailable()){
                this.micClient.startMicAndRecognition();
            }else{
                Log.i("Error","No network available");
            }

 public boolean isNetworkAvailable() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }
</code>```

Title: bing speech to text error in Android

Body:
I have gone through documentation of bing speech to text api, i implemented a simple app which just starts speech to text on button click. I have hard coded the key values provided in Cognitive Services console. Now when I start the function as shown in sample app it throws following error. I have searched on google but i can not trace the root of the issue.

    09-16 11:39:09.799 25615 25655 I NLPLAT  : originating error 0x80070057
    09-16 11:39:09.809 25615 25655 I NLPLAT  : Application Name:
    09-16 11:39:09.819 25615 25655 I NLPLAT  : originating error 0x80070057
    09-16 11:39:09.819 25615 25655 I NLPLAT  : originating error 0x80070057
    09-16 11:39:09.819  3676  4433 D EnterpriseController: netId is 0
    09-16 11:39:09.819  3676  4433 D Netd    : getNetworkForDns: using netid 0 for uid 10068
    09-16 11:39:09.824 25615 26122 I NLPLAT  : originating error 0x8e200005
    09-16 11:39:09.824 25615 25655 I NLPLAT  : Refreshing token S
    09-16 11:39:09.824  3676  4433 D EnterpriseController: netId is 0
    09-16 11:39:09.824  3676  4433 D Netd    : getNetworkForDns: using netid 0 for uid 10068
    09-16 11:39:09.829 25615 26124 I NLPLAT  : originating error 0x8e200005
    09-16 11:39:09.829 25615 25655 I NLPLAT  : Initializing Audio Services
    09-16 11:39:09.829 25615 25655 W libOpenSLES: class OutputMix interface 0 requested but unavailable MPH=43
    09-16 11:39:09.834 25615 25655 W AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client; transfer 1, track 16000 Hz, output 48000 Hz
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Initializing Speech Services
    09-16 11:39:09.834 25615 25655 I NLPLAT  : No application id provided to controller
    09-16 11:39:09.834 25615 25655 I NLPLAT  : GetIdentityPropertyValue 3
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Useragent Value Android Assistant (Android; Unknown;Unknown;ProcessName/AppName=Unknown;DeviceType=Near;SpeechClient=1.0.160511)
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Url: 'https://websockets.platform.bing.com/ws/speech/recognize/continuous'
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Locale: 'en-us'
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Application Id: ''
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Version: 4.0.150429
    09-16 11:39:09.834 25615 25655 I NLPLAT  : UserAuthorizationToken:
    09-16 11:39:09.834 25615 25655 I NLPLAT  : ServerLoggingLevel: 1
    09-16 11:39:09.834 25615 25655 I NLPLAT  : Initiating websocket connection. m_connection=0x0 host=websockets.platform.bing.com port=443

Bing OnError function says :

NameNotFound -1910505467

Body:
I am having the same issue because of network connection.Check your network connection before calling "this.micClient.startMicAndRecognition();" like

 if(isNetworkAvailable()){
                this.micClient.startMicAndRecognition();
            }else{
                Log.i("Error","No network available");
            }

 public boolean isNetworkAvailable() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }


问:
if c3p0 is configured, will connection.pool_size be ignored
I am using hibernate with c3p0 for connection management. In my hibernate configuration I have both connection.pool_size and hibernate.c3p0.max_size configured (with different numbers).

As per my knowledge when I am using c3p0, my default hibernate connection management will not be in use.
But I am not sure whether hibernate.c3p0.max_size is the c3p0 replacement of connection.pool_size of default hibernate pool size setting variable.

So, my query is - Can I remove connection.pool_size from the configuration?
If I have both in my configuration file, will connection.pool_size be completely ignored or will it be used for any other purpose ?

答:
Once you defined configuration for c3po with session factory.
No need of hibernate default settings. You should remove it to avoid confusion.

Your session factory configuration looks like :

```<code>   <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ABCXYZ</property>
  <property name="hibernate.connection.username">myuser</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">SCHEMA_A</property>
  <property name="show_sql">true</property>

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

  <mapping class="com.ABCXYZ.user.DBUser"></mapping>
</session-factory>
</hibernate-configuration>
</code>```

Better you remove that connection.pool_size to make configuration settings clear to understand.

ContentLicense: CC BY-SA 4.0

Body:
Once you defined configuration for c3po with session factory.
No need of hibernate default settings. You should remove it to avoid confusion.

Your session factory configuration looks like :

   <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ABCXYZ</property>
  <property name="hibernate.connection.username">myuser</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">SCHEMA_A</property>
  <property name="show_sql">true</property>

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

  <mapping class="com.ABCXYZ.user.DBUser"></mapping>
</session-factory>
</hibernate-configuration>

Better you remove that connection.pool_size to make configuration settings clear to understand.


问:
Express body-parser req not shown
I am using Express with body-parser as follows:

// Import all required library

var express = require('express')
var app = express()
var bodyParser = require('body-parser')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true, limit: '500mb'}))

var port = 3000

// Route for the API
var router = new express.Router()

router.get('/videos', (req, res, next) => {
    console.log('GET /' + req)
    return res.json({
      "Your videos"
    })
})

// Using Router
app.use('/', router)

app.listen(port, function(err){
 if (!err) {
  console.log("API started running at port 3000")
 }
})```
</div>
</div>
</p>

<p>Versions of Library used are</p>

```    "dependencies": {
      "body-parser": "1.16.1",
      "express": "4.14.1"
    }
```

<p>This is not showing any query parameters in <code>req</code>. Resulting following </p>

```   GET /[object Object]
```

When I used POSTMAN to GET localhost:3000/videos?type=popularity.
This kind of api setup has been working for me until now. Can anyone explain me what I did wrong?

Thanks

答:
Instead of console.log('GET /' + req), do:

```<code>console.log('GET /', req);
</code>```

You'll get the full object.

Title: Express body-parser req not shown

Body:
I am using Express with body-parser as follows:

// Import all required library

var express = require('express')
var app = express()
var bodyParser = require('body-parser')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true, limit: '500mb'}))

var port = 3000

// Route for the API
var router = new express.Router()

router.get('/videos', (req, res, next) => {
    console.log('GET /' + req)
    return res.json({
      "Your videos"
    })
})

// Using Router
app.use('/', router)

app.listen(port, function(err){
 if (!err) {
  console.log("API started running at port 3000")
 }
})

Versions of Library used are

    "dependencies": {
      "body-parser": "1.16.1",
      "express": "4.14.1"
    }

This is not showing any query parameters in req. Resulting following

   GET /[object Object]

When I used POSTMAN to GET localhost:3000/videos?type=popularity.
This kind of api setup has been working for me until now. Can anyone explain me what I did wrong?

Thanks

Body:
Instead of console.log('GET /' + req), do:

console.log('GET /', req);

You'll get the full object.


问:
Drawer not covering header in react-navigation
Hi friends I am scratching my head with react-navigation from last 2 days, I tried many things(documentation doesn't seems that clear for a beginner), so right now I am facing few problem that seems little complex to me and hence I seek advice and help to proceed further.following are the cases/problem/scenario I seek help for -

react-navigation does not cover the header and statusbar, I wanted to achieve something like gmail but I ended up with like this

I used following code blocks to reach to this point

```<code>import React, {Component} from 'react';
import { AppRegistry, View, BackAndroid, StatusBar,} from 'react-native';
import {
  NavigationActions,
  addNavigationHelpers,
  StackNavigator,
  DrawerNavigator
} from 'react-navigation';

import LandingScreen from 'src/screens/landingScreen';
import Login from 'src/screens/login'
import SignUp from 'src/screens/signUp'
import ForgotPassword from 'src/screens/forgotPassword'
import Dashboard from 'src/screens/dashboard'
import UserProfile from 'src/screens/userProfile'

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen:Dashboard,
  },
  UserProfile:{
    path:'/'
    screen:UserProfile
  },
}, {
  initialRouteName: 'Dashboard',
  contentOptions: {
    activeTintColor: '#e91e63',
  },
  headerMode: 'screen',
});

const routesConfig = {
  Landing:{screen:LandingScreen},
  Login: { screen: Login },
  SignUp: { screen: SignUp },
  ForgotPassword: { screen: ForgotPassword },
  Drawer:{screen:Drawer}
};

export const AppNavigator = StackNavigator(routesConfig, {
  initialRouteName: 'Drawer'
});
AppRegistry.registerComponent('Riduk', () => AppNavigator);
</code>```

Other problem is how should I add 2 drawers in my app at the same screen

答:
There is an issue for Header in DrawerNavigator.

But you can fix by using StackNavigator inside DrawerNavigator

```<code>export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen: StackNavigator( { Screen1: {
                screen: Dashboard
            }})
  },
  UserProfile:{
    path:'/',
    screen: StackNavigator( { Screen1: {
                screen: UserProfile
            }})
  },
}});
</code>```

Then set headerMode: 'none' to root StackNavigator

```<code>export const AppNavigator = StackNavigator(routesConfig, {
    headerMode: 'none'
});
</code>```

Here, AppNavigator is root StackNavigator and routesConfig has above DrawerNavigator and other screens.

Body:
Hi friends I am scratching my head with react-navigation from last 2 days, I tried many things(documentation doesn't seems that clear for a beginner), so right now I am facing few problem that seems little complex to me and hence I seek advice and help to proceed further.following are the cases/problem/scenario I seek help for -

react-navigation does not cover the header and statusbar, I wanted to achieve something like gmail but I ended up with like this

I used following code blocks to reach to this point

import React, {Component} from 'react';
import { AppRegistry, View, BackAndroid, StatusBar,} from 'react-native';
import {
  NavigationActions,
  addNavigationHelpers,
  StackNavigator,
  DrawerNavigator
} from 'react-navigation';

import LandingScreen from 'src/screens/landingScreen';
import Login from 'src/screens/login'
import SignUp from 'src/screens/signUp'
import ForgotPassword from 'src/screens/forgotPassword'
import Dashboard from 'src/screens/dashboard'
import UserProfile from 'src/screens/userProfile'

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen:Dashboard,
  },
  UserProfile:{
    path:'/'
    screen:UserProfile
  },
}, {
  initialRouteName: 'Dashboard',
  contentOptions: {
    activeTintColor: '#e91e63',
  },
  headerMode: 'screen',
});

const routesConfig = {
  Landing:{screen:LandingScreen},
  Login: { screen: Login },
  SignUp: { screen: SignUp },
  ForgotPassword: { screen: ForgotPassword },
  Drawer:{screen:Drawer}
};

export const AppNavigator = StackNavigator(routesConfig, {
  initialRouteName: 'Drawer'
});
AppRegistry.registerComponent('Riduk', () => AppNavigator);

Other problem is how should I add 2 drawers in my app at the same screen

Body:
There is an issue for Header in DrawerNavigator.

But you can fix by using StackNavigator inside DrawerNavigator

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen: StackNavigator( { Screen1: {
                screen: Dashboard
            }})
  },
  UserProfile:{
    path:'/',
    screen: StackNavigator( { Screen1: {
                screen: UserProfile
            }})
  },
}});

Then set headerMode: 'none' to root StackNavigator

export const AppNavigator = StackNavigator(routesConfig, {
    headerMode: 'none'
});

Here, AppNavigator is root StackNavigator and routesConfig has above DrawerNavigator and other screens.


问:
S3 connectors to connect with Kafka for streaming data from on-premise to cloud
I want to stream data from on-premise to Cloud(S3) using Kafka. For which I need to intsall kafka on source machine and also on cloud. But I don't want to intsall it on cloud. I need some S3 connector through which I can connect with kafka and stream data from on-premise to cloud. </p>

答:
If your data is in Avro or Json format (or can be converted to those formates), you can use the S3 connector for Kafka Connect. See Confluent's docs on that

Should you want to move actual (bigger) files via Kafka, be aware that Kafka is designed for small messages and not for file transfers.


问:
Jqgrid Date sorting issue with day name and date column
In my Jqgrid table I have a column which has dayName, Date as value,
like, Wed, 01-03-217,

But when I add complete data having days as Tue or Thu, jqgrid shows undefined, NaN-NaN-NaN as column values for both days,

I am using Jqgrid versoin 4.6.0

I have also prepare demo at fiddle. http://jsfiddle.net/alpeshjikadra/jss5b43j/1/

Let me know if anyone knows how to solve this

Thanks

答:
I think there's something with the formatting.

Try removing the ',' from your invdate property strings in mydata eg.: {id:"1", invdate:"Wed 01-03-2017"}

It works for some reason.


问:
add a link on a div displayed on input's focus
I show a tooltip when an input gains focus. This tooltip is a span: hidden, but shown (via CSS) when input has focus.

input + .k-comments {
      display: none;
      max-width: 25em;
      color: #FFF;
      background: #283135;
      padding: 0.3rem;
      margin-top: 0.3rem;
      animation: appearance 2s forwards;
    }

    input:focus + .k-comments {
      display: block;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="myid" type="text"/>
<span class="k-comments">foo a link</span></code>```

If I click on the tooltip (or everywhere else), it disappears: ok.

The problem: my tooltip contains text and a link -> I can't click on the link because the tooltip disappears first.

答:
Probably not the best solution but at least it makes the link clickable:</p>

```<code>input:focus + .k-comments,
.k-comments:active {
    display: block;
}
</code>```

Body:
I show a tooltip when an input gains focus. This tooltip is a span: hidden, but shown (via CSS) when input has focus.

input + .k-comments {
      display: none;
      max-width: 25em;
      color: #FFF;
      background: #283135;
      padding: 0.3rem;
      margin-top: 0.3rem;
      animation: appearance 2s forwards;
    }

    input:focus + .k-comments {
      display: block;
    }

<input id="myid" type="text"/>
foo a link

If I click on the tooltip (or everywhere else), it disappears: ok.

The problem: my tooltip contains text and a link -> I can't click on the link because the tooltip disappears first.

Body:
Probably not the best solution but at least it makes the link clickable:

input:focus + .k-comments,
.k-comments:active {
    display: block;
}


问:
Does InfoPath 2013 support Visual Studio 2013?
I am trying to develop custom code for an InfoPath 2013 form. I have Visual Studio 2013 Professional installed, but when trying to edit code I get the following message:

```<code>The following external components are required to edit your form code. Please install them and try again.

Microsoft Visual Studio 2012
Visual Studio C# Support
Microsoft Visual Studio Tools for Applications 2012
</code>```

C# support is installed, along with Visual Studio Tools for Applications 2012.

Does InfoPath 2013 just not support VS2013?

答:
As you have found, adding code to an InfoPath 2013 form requires Visual Studio 2012. I am not aware of a way to use it with any other version of Visual Studio.

Depending on what you plan to use the custom code for, you may be able to get by with the qRules library (full disclosure: I am one of the developers of this library). It contains many of the most common features for which people tend to use code within InfoPath, and you can use them simply by executing rules within your form, eliminating the need for any version of Visual Studio.

If there is a specific thing you are looking to do with code, I can tell you whether it's possible to do so with qRules, but you should open a separate question for that (and let me know here).

Body:
I am trying to develop custom code for an InfoPath 2013 form. I have Visual Studio 2013 Professional installed, but when trying to edit code I get the following message:

The following external components are required to edit your form code. Please install them and try again.

Microsoft Visual Studio 2012
Visual Studio C# Support
Microsoft Visual Studio Tools for Applications 2012

C# support is installed, along with Visual Studio Tools for Applications 2012.

Does InfoPath 2013 just not support VS2013?


问:
how to pipe a python script to a command (boost::program::options)
I am trying to redirect(in windows) the output of a python file to the stdin of a command created with boost::program::options like this:

```<code>python test.py | command.exe -s
</code>```

test.py just prints the content of a file:

```<code>f = open('test.xml', 'r')
print f.read()
f.close()
</code>```

If i execute just the python file it works but if i try to pipe it to the other command it fails with the following error:

```<code>close failed in the file object destructor:
sys.excepthook is missin
lost sys.stderr
</code>```

If i try to execute this command.exe -s < test.xml it works fine so i guess is a problem with pipe.

Does anyone have an idea what is happening?

答:
You get this error because when CMD is creating pipe, it's closing STDERR. And somehow method close() of file obejct in python need to use this descriptor which is missing.

And possible solution could be like this :
https://superuser.com/questions/452763/how-to-pipleline-stderr-in-cmd-exe

Body:
I am trying to redirect(in windows) the output of a python file to the stdin of a command created with boost::program::options like this:

python test.py | command.exe -s

test.py just prints the content of a file:

f = open('test.xml', 'r')
print f.read()
f.close()

If i execute just the python file it works but if i try to pipe it to the other command it fails with the following error:

close failed in the file object destructor:
sys.excepthook is missin
lost sys.stderr

If i try to execute this command.exe -s < test.xml it works fine so i guess is a problem with pipe.

Does anyone have an idea what is happening?


问:
Issue while scrubbing video using AVPlayer
I am reading video from local using AVPlayer. When I scrub through the video, sometimes I am getting pixelated video for few second or green screen appears for a while.

Following is my code for scrubbing:

```<code> - (void)playerControlView:(PlayerControlView *)playerControlView beganScrubbingAtPercent:(float)timePercent
{
    if (_avPlayer.rate > 0) {
        _resumePlayAfterScrub = YES;
    } else {
        _resumePlayAfterScrub = NO;
    }
}

- (void)playerControlView:(PlayerControlView *)playerControlView scrubbedToPercent:(float)timePercent
{
    if (_avPlayer.rate > 0) {
        [_avPlayer pause];
        [_loadingView startAnimating];
    }

    float durationSeconds = CMTimeGetSeconds(_avPlayerItem.duration);
    CMTime cmTime = CMTimeMakeWithSeconds(durationSeconds * timePercent, NSEC_PER_SEC);
    [_avPlayer seekToTime:cmTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];

    [_hideControlsTimer invalidate];
}

- (void)playerControlView:(PlayerControlView *)playerControlView finishedScrubbingAtPercent:(float)timePercent
{
    if (_resumePlayAfterScrub) {
        [_avPlayer play];
    }
    [self resetCurrentEventWithCopy:YES];
}
</code>```

what can I optimize on above code?

答: It could be a case wherein the gap between consecutive IDR frames is high so when you seek, it takes a while to hit the closest IDR frame and clear picture buffer. Till the player hits an IDR frame, it will not be able to decode the stream properly which will result in you seeing green screens and pixelations.</p>

Body:
I am reading video from local using AVPlayer. When I scrub through the video, sometimes I am getting pixelated video for few second or green screen appears for a while.

Following is my code for scrubbing:

 - (void)playerControlView:(PlayerControlView *)playerControlView beganScrubbingAtPercent:(float)timePercent
{
    if (_avPlayer.rate > 0) {
        _resumePlayAfterScrub = YES;
    } else {
        _resumePlayAfterScrub = NO;
    }
}

- (void)playerControlView:(PlayerControlView *)playerControlView scrubbedToPercent:(float)timePercent
{
    if (_avPlayer.rate > 0) {
        [_avPlayer pause];
        [_loadingView startAnimating];
    }

    float durationSeconds = CMTimeGetSeconds(_avPlayerItem.duration);
    CMTime cmTime = CMTimeMakeWithSeconds(durationSeconds * timePercent, NSEC_PER_SEC);
    [_avPlayer seekToTime:cmTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];

    [_hideControlsTimer invalidate];
}

- (void)playerControlView:(PlayerControlView *)playerControlView finishedScrubbingAtPercent:(float)timePercent
{
    if (_resumePlayAfterScrub) {
        [_avPlayer play];
    }
    [self resetCurrentEventWithCopy:YES];
}

what can I optimize on above code?


问:
Generating Icon Files
I'm looking for an online solution for generating .ICO files.  I'd like the ICO files to have the ability to have transparency as well.

What software or web site do you use to create them?

[Update]

To clarify, I have an existing image in PNG format, 32 x 32 pixels.  I want to generate the icon from this existing file, not create a brand new one online.  Sorry for the confusion.

答: With http://www.favicon.cc/ you can either draw your own, or upload a jpg, jpeg, gif, png, bmp, or ico. And it's a web app, so there's nothing to install. Works very nicely.</p>

ContentLicense: CC BY-SA 2.5

Title: Generating Icon Files

LastEditorDisplayName: Mark Biek


问:
Using Type instead of specific class
I have this code:

```<code>if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
   return true;
else
   return false;
</code>```

Now I want not to specify the part Classes.ProductGroup. I want to make it universal.

How can I replace the part Classes.ProductGroup with a Type object?

```<code>Type type = typeof(Classes.ProductGroup);
</code>```

Something similar to this:

```<code>if (((type)o).ToString().Contains(comboBox.Text))
</code>```

Is this possible?

Here is the complete method code:

```<code>private void FilterPGsinComboBox(object obj)
{
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.Invoke(new FilterPGsinComboBoxDelegate(this.FilterPGsinComboBox),obj);
        return;
    }
    Type type = ((Dictionary<ComboBox, Type>)obj).First().Value;
    ComboBox comboBox = ((Dictionary<ComboBox, Type>)obj).First().Key;
    comboBox.IsDropDownOpen = true;
    CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(comboBox.ItemsSource);

    itemsViewOriginal.Filter = ((o) =>
    {
        if (String.IsNullOrEmpty(comboBox.Text))
            return true;
        else
        {
            if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
                return true;
            else
                return false;
        }
    });

    itemsViewOriginal.Refresh();
}
</code>```

答:
string ToString() method is defined in the base Object class. cast to concrete type is redundant.

```<code>string filter = comboBox.Text;

itemsViewOriginal.Filter = o => String.IsNullOrEmpty(filter) ||
                                o != null && o.ToString().Contains(filter);
</code>```

Title: Using Type instead of specific class

Body:
I have this code:

if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
   return true;
else
   return false;

Now I want not to specify the part Classes.ProductGroup. I want to make it universal.

How can I replace the part Classes.ProductGroup with a Type object?

Type type = typeof(Classes.ProductGroup);

Something similar to this:

if (((type)o).ToString().Contains(comboBox.Text))

Is this possible?

Here is the complete method code:

private void FilterPGsinComboBox(object obj)
{
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.Invoke(new FilterPGsinComboBoxDelegate(this.FilterPGsinComboBox),obj);
        return;
    }
    Type type = ((Dictionary<ComboBox, Type>)obj).First().Value;
    ComboBox comboBox = ((Dictionary<ComboBox, Type>)obj).First().Key;
    comboBox.IsDropDownOpen = true;
    CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(comboBox.ItemsSource);

    itemsViewOriginal.Filter = ((o) =>
    {
        if (String.IsNullOrEmpty(comboBox.Text))
            return true;
        else
        {
            if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
                return true;
            else
                return false;
        }
    });

    itemsViewOriginal.Refresh();
}

Body:
string ToString() method is defined in the base Object class. cast to concrete type is redundant.

string filter = comboBox.Text;

itemsViewOriginal.Filter = o => String.IsNullOrEmpty(filter) ||
                                o != null && o.ToString().Contains(filter);


问:
How do I change my delimiter from comma to a semicolon?
```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Reflection;
using CsvHelper.Configuration;

namespace ReadCsvFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public DataTable ReadCsv(string filename)
        {
            DataTable dt = new DataTable("Data");
            using (OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
                Path.GetDirectoryName(filename) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(;)';"))
            {
                using (OleDbCommand cmd = new OleDbCommand(string.Format("select *from [{0}]", new FileInfo(filename).Name), cn))
                {
                    cn.Open();
                    using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                    }
                }
            }

            return dt;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV| *.csv", ValidateNames = true, Multiselect = true })
                {
                    if (ofd.ShowDialog() == DialogResult.OK)
                        dataGridView.DataSource = ReadCsv(ofd.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
</code>```

It turned out that the csv files I tried to read had semicolons (;) as separators, instead of the usual commas (,).

I tried to change the delimiter, but for some reason was not able to.

I would appreciate any help I could get!

答:
I would guess that you just need to change this:

```<code>using (OleDbConnection cn = new
          OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
               Path.GetDirectoryName(filename) +
               "\";Extended Properties='text;HDR=yes;FMT=Delimited(;)';"))
</code>```

to this:

```<code>using (OleDbConnection cn = new
          OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
               Path.GetDirectoryName(filename) +
               "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)',"))
</code>```

Change the FMT=Delimited(;)'; in the OleDb connection string to be FMT=Delimited(,)',

UPDATE: Sorry, I misunderstood your original question - you've already changed the delimiter to ; in your OleDbConnection - missed that one.

Quite honestly: I have no idea how and what you should do (in addition to what you've already done) to get this OleDbConnection and command to work properly...

Personally, I would use the excellent (and free!) CsvHelper component to read any CSV files I might need to import - not that OleDb stuff..... with CsvHelper, it's very easy to define delimiters (and many more properties of your import), and it works like a charm, returning a List<YourEntity> from any .csv file, ready to be used whichever way you want

Body:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Reflection;
using CsvHelper.Configuration;

namespace ReadCsvFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public DataTable ReadCsv(string filename)
        {
            DataTable dt = new DataTable("Data");
            using (OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
                Path.GetDirectoryName(filename) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(;)';"))
            {
                using (OleDbCommand cmd = new OleDbCommand(string.Format("select *from [{0}]", new FileInfo(filename).Name), cn))
                {
                    cn.Open();
                    using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                    }
                }
            }

            return dt;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV| *.csv", ValidateNames = true, Multiselect = true })
                {
                    if (ofd.ShowDialog() == DialogResult.OK)
                        dataGridView.DataSource = ReadCsv(ofd.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

It turned out that the csv files I tried to read had semicolons (;) as separators, instead of the usual commas (,).

I tried to change the delimiter, but for some reason was not able to.

I would appreciate any help I could get!

Body:
I would guess that you just need to change this:

using (OleDbConnection cn = new
          OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
               Path.GetDirectoryName(filename) +
               "\";Extended Properties='text;HDR=yes;FMT=Delimited(;)';"))

to this:

using (OleDbConnection cn = new
          OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
               Path.GetDirectoryName(filename) +
               "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)',"))

Change the FMT=Delimited(;)'; in the OleDb connection string to be FMT=Delimited(,)',

UPDATE: Sorry, I misunderstood your original question - you've already changed the delimiter to ; in your OleDbConnection - missed that one.

Quite honestly: I have no idea how and what you should do (in addition to what you've already done) to get this OleDbConnection and command to work properly...

Personally, I would use the excellent (and free!) CsvHelper component to read any CSV files I might need to import - not that OleDb stuff..... with CsvHelper, it's very easy to define delimiters (and many more properties of your import), and it works like a charm, returning a List<YourEntity> from any .csv file, ready to be used whichever way you want


问:
Protractor: Why cucumber steps shows as executed before the actual execution happened
I am new to protractor-cucumber. I am trying to execute below step definition from protractor conf.js.

```<code>this.Given(/^I go to sparqHomePage$/, function (callback) {

  homepage.goToHomePage()
  homepage.login(data[0].UserName,data[0].Password).then(callback);

});

this.Then(/^I create a process$/, function () {

  homepage.clickDesign();
  homepage.clickFlowDesigner();
  console.log(params.flow.procName + ' '+  params.flow.procDesc);
  designPage.createNewProc(params.flow.procName, params.flow.procDesc);

});

this.Then(/^I should see process is saved in db$/, function (callback) {

    var sql = "select * from process where name = ?";
    sql = mysql.format(sql, params.flow.procName);
    console.log(sql);

    dbConn.query(sql, function(err, rows, fields){

        if(!err) {
            procDbObj = rows;
            console.log(rows);
            expect(procDbObj[0].name).to.eventually.equal( params.flow.procName);
            expect(procDbObj[0].description).to.eventually.equal(params.flow.procDesc).and.notify(callback);
        }
    });
});
</code>```

As soon as I start the execution, the console log shows, feature file execution was completed, but the actual execution is not yet completed.

In my 3rd step I am doing some db validation based on the step 1 and step 2 actions. As cucumber trying to execute all the steps before the completion of real execution with browser, my 3rd test is always failing.

How can I make cucumber to wait for step execution is completed before moving to the next step.

答:
```<code>homepage.goToHomePage()
homepage.login(data[0].UserName,data[0].Password).then(callback);
</code>```

I'm not sure exactly what is happening in the first line but I assume thats going to be doing a click, you will need to make that return a promise and re-write it like

```<code>homepage.goToHomePage().then(()=>{
    homepage.login(data[0].UserName,data[0].Password).then(callback);
})
</code>```

And then follow this pattern for the rest of your code as I can see this same issue throughout

Body:
I am new to protractor-cucumber. I am trying to execute below step definition from protractor conf.js.

this.Given(/^I go to sparqHomePage$/, function (callback) {

  homepage.goToHomePage()
  homepage.login(data[0].UserName,data[0].Password).then(callback);

});

this.Then(/^I create a process$/, function () {

  homepage.clickDesign();
  homepage.clickFlowDesigner();
  console.log(params.flow.procName + ' '+  params.flow.procDesc);
  designPage.createNewProc(params.flow.procName, params.flow.procDesc);

});

this.Then(/^I should see process is saved in db$/, function (callback) {

    var sql = "select * from process where name = ?";
    sql = mysql.format(sql, params.flow.procName);
    console.log(sql);

    dbConn.query(sql, function(err, rows, fields){

        if(!err) {
            procDbObj = rows;
            console.log(rows);
            expect(procDbObj[0].name).to.eventually.equal( params.flow.procName);
            expect(procDbObj[0].description).to.eventually.equal(params.flow.procDesc).and.notify(callback);
        }
    });
});

As soon as I start the execution, the console log shows, feature file execution was completed, but the actual execution is not yet completed.

In my 3rd step I am doing some db validation based on the step 1 and step 2 actions. As cucumber trying to execute all the steps before the completion of real execution with browser, my 3rd test is always failing.

How can I make cucumber to wait for step execution is completed before moving to the next step.

Body:
homepage.goToHomePage()
homepage.login(data[0].UserName,data[0].Password).then(callback);

I'm not sure exactly what is happening in the first line but I assume thats going to be doing a click, you will need to make that return a promise and re-write it like

homepage.goToHomePage().then(()=>{
    homepage.login(data[0].UserName,data[0].Password).then(callback);
})

And then follow this pattern for the rest of your code as I can see this same issue throughout


问:
Why does mAlphabetIndexer.getSectionForPosition crash with NPE?
I have a class called ContactListFragment to get user to select phone number from their contact book. My adapter is a cursor adapter as follows

```<code>private class ContactsAdapter extends CursorAdapter implements SectionIndexer {
…

@Override
        public int getSectionForPosition(int i) {
            if (getCursor() == null) {
                return 0;
            }
            return mAlphabetIndexer.getSectionForPosition(i);
        }
...
}
</code>```

I am getting a NullPointerException at the line return mAlphabetIndexer.getPositionForSection(i). I am not sure what constitutes enough information in this context, so I am including the stack trace below. Does anyone know what I might be doing wrong? My alphabet are all uppercase but I am using API 11 as opposed to API 14, so that I cannot use android:textAllCaps in

```<code><style name="addressHeader" parent="@android:style/TextAppearance.Small">
        <item name="android:textAllCaps">true</item>
        <item name="android:textStyle">bold</item>
    </style>
</code>```

Here is the alphabet

```<code><string name="alphabet">ABCDEFGHIJKLMNOPQRSTUVWXYZ</string>
</code>```

For reference, I am using the ContactListFragment from the Google Tutorial as guide. The only difference to my knowledge is the API levels I mention.

```<code>FATAL EXCEPTION: main
 java.lang.NullPointerException
    at android.widget.AlphabetIndexer.compare(AlphabetIndexer.java:128)
    at android.widget.AlphabetIndexer.getSectionForPosition(AlphabetIndexer.java:265)
    at com.company.app.fragments.ContactsListFragment$ContactsAdapter.getSectionForPosition(ContactsListFragment.java:801)
    at android.widget.FastScroller.getThumbPositionForListPosition(FastScroller.java:648)
    at android.widget.FastScroller.onScroll(FastScroller.java:458)
    at android.widget.AbsListView.invokeOnItemScrollListener(AbsListView.java:1358)
    at android.widget.ListView.layoutChildren(ListView.java:1707)
    at android.widget.AbsListView.onLayout(AbsListView.java:2141)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1003)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:469)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:469)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1535)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1448)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:469)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1535)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1448)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:469)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1895)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1715)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1010)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4255)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
    at android.view.Choreographer.doFrame(Choreographer.java:525)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4849)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I had this error because my cursor data had null into his columnIndex that I passed in second param of AlphabetIndexer.

You can use DatabaseUtils.dumpCursorToString(cursor)) to debug.

Body:
I have a class called ContactListFragment to get user to select phone number from their contact book. My adapter is a cursor adapter as follows

private class ContactsAdapter extends CursorAdapter implements SectionIndexer {
…

@Override
        public int getSectionForPosition(int i) {
            if (getCursor() == null) {
                return 0;
            }
            return mAlphabetIndexer.getSectionForPosition(i);
        }
...
}

I am getting a NullPointerException at the line return mAlphabetIndexer.getPositionForSection(i). I am not sure what constitutes enough information in this context, so I am including the stack trace below. Does anyone know what I might be doing wrong? My alphabet are all uppercase but I am using API 11 as opposed to API 14, so that I cannot use android:textAllCaps in

Here is the alphabet

<string name="alphabet">ABCDEFGHIJKLMNOPQRSTUVWXYZ</string>

For reference, I am using the ContactListFragment from the Google Tutorial as guide. The only difference to my knowledge is the API levels I mention.

FATAL EXCEPTION: main
 java.lang.NullPointerException
    at android.widget.AlphabetIndexer.compare(AlphabetIndexer.java:128)
    at android.widget.AlphabetIndexer.getSectionForPosition(AlphabetIndexer.java:265)
    at com.company.app.fragments.ContactsListFragment$ContactsAdapter.getSectionForPosition(ContactsListFragment.java:801)
    at android.widget.FastScroller.getThumbPositionForListPosition(FastScroller.java:648)
    at android.widget.FastScroller.onScroll(FastScroller.java:458)
    at android.widget.AbsListView.invokeOnItemScrollListener(AbsListView.java:1358)
    at android.widget.ListView.layoutChildren(ListView.java:1707)
    at android.widget.AbsListView.onLayout(AbsListView.java:2141)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1003)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:469)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:469)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1535)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1448)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:469)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1535)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1448)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:469)
    at android.view.View.layout(View.java:13849)
    at android.view.ViewGroup.layout(ViewGroup.java:4364)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1895)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1715)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1010)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4255)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
    at android.view.Choreographer.doFrame(Choreographer.java:525)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4849)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
    at dalvik.system.NativeStart.main(Native Method)


问:
PHP & PDO: Can connect to DB; can't seem to query
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:

```<code> private function connect() {
      try {
           $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
      }
           catch (PDOException $e) {
           die ($e);
      }
      print_r($link);
      $result = $link->query("select * from mt3_users");
      var_dump($result);
      $row = $result->fetch($result);
      die("Your id is: ".$row["id"]);
      //$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
      if (!$link) {
          echo "Failed to connect to $this->sHost!";
          return false;
      }
      return $link;
 }
</code>```

This returns the following:

PDO Object ( ) bool(false)
  Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32

So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?

答:
can you give this a try

```<code> private function connect() {
 try {
   $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
 return $link ;
 }
 catch (PDOException $e) {
 die ($e);
 }
}
$pdolink = $this->connect();
$rows = $pdolink->query("select * from mt3_users");
foreach($rows as $row ){
   echo("Your id is: ".$row["id"]);
 }
</code>```

and if you need to stick with fetchAll function

```<code>  private function connect() {
     try {
       $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
     return $link ;
     }
     catch (PDOException $e) {
     die ($e);
     }
    }
    $pdolink = $this->connect();
    $q = $pdolink->prepare("select * from mt3_users");
    $q->exectue();
    $rows = $q->fetchAll();
    var_dump($rows);
    foreach($rows as $row ){
       echo("Your id is: ".$row["id"]);
     }
</code>```

Body:
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:

 private function connect() {
      try {
           $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
      }
           catch (PDOException $e) {
           die ($e);
      }
      print_r($link);
      $result = $link->query("select * from mt3_users");
      var_dump($result);
      $row = $result->fetch($result);
      die("Your id is: ".$row["id"]);
      //$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
      if (!$link) {
          echo "Failed to connect to $this->sHost!";
          return false;
      }
      return $link;
 }

This returns the following:

PDO Object ( ) bool(false)
  Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32

So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?

Body:
can you give this a try

 private function connect() {
 try {
   $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
 return $link ;
 }
 catch (PDOException $e) {
 die ($e);
 }
}
$pdolink = $this->connect();
$rows = $pdolink->query("select * from mt3_users");
foreach($rows as $row ){
   echo("Your id is: ".$row["id"]);
 }

and if you need to stick with fetchAll function

  private function connect() {
     try {
       $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
     return $link ;
     }
     catch (PDOException $e) {
     die ($e);
     }
    }
    $pdolink = $this->connect();
    $q = $pdolink->prepare("select * from mt3_users");
    $q->exectue();
    $rows = $q->fetchAll();
    var_dump($rows);
    foreach($rows as $row ){
       echo("Your id is: ".$row["id"]);
     }


问:
Pivot table to get data to be displayed like this?
Bit of an SQL newbie here. I have an SQL table which stores data at specific dates for a specific unique identifier.

Example:

```<code>UniqueIdentifier    someData1   Date1         SomeData2     Date2       SomeData3   Date3
1                   1000        01/01/2017    2000          01/02/2017  2000        01/03/2017
2                   2000        21/01/2017    2500          21/02/2017  3540        21/03/2017
3                   3000        05/01/2017    3000          08/07/2016  3000        12/05/2016
</code>```

I would like to somehow convert the data so it ends up like this:

```<code>UniqueIdentifier    Data    Date
1                   1000    01/01/2017
1                   2000    01/02/2017
1                   2000    01/03/2017
2                   2000    21/01/2017
2                   2500    21/02/2017
2                   3540    21/03/2017
3                   3000    05/01/2017
3                   3000    08/07/2016
3                   3000    12/05/2016
</code>```

Basically extracting each date and it's corresponding value into a separate line. I'm guessing I need to use some sort of pivot table to do this, but I'm not quite sure exactly how to do it! Any help would be greatly appreciated!

答:
Using Union</p>

```<code>select UniqueIdentifier, someData1 as 'Data', Date1 as 'Date' from <yourtable>
union
select UniqueIdentifier, someData2 as 'Data', Date2 as 'Date' from <yourtable>
union
select UniqueIdentifier, someData3 as 'Data', Date3 as 'Date' from <yourtable>
</code>```

Body:
Bit of an SQL newbie here. I have an SQL table which stores data at specific dates for a specific unique identifier.

Example:

UniqueIdentifier    someData1   Date1         SomeData2     Date2       SomeData3   Date3
1                   1000        01/01/2017    2000          01/02/2017  2000        01/03/2017
2                   2000        21/01/2017    2500          21/02/2017  3540        21/03/2017
3                   3000        05/01/2017    3000          08/07/2016  3000        12/05/2016

I would like to somehow convert the data so it ends up like this:

UniqueIdentifier    Data    Date
1                   1000    01/01/2017
1                   2000    01/02/2017
1                   2000    01/03/2017
2                   2000    21/01/2017
2                   2500    21/02/2017
2                   3540    21/03/2017
3                   3000    05/01/2017
3                   3000    08/07/2016
3                   3000    12/05/2016

Basically extracting each date and it's corresponding value into a separate line. I'm guessing I need to use some sort of pivot table to do this, but I'm not quite sure exactly how to do it! Any help would be greatly appreciated!

Body:
Using Union

select UniqueIdentifier, someData1 as 'Data', Date1 as 'Date' from <yourtable>
union
select UniqueIdentifier, someData2 as 'Data', Date2 as 'Date' from <yourtable>
union
select UniqueIdentifier, someData3 as 'Data', Date3 as 'Date' from <yourtable>


问:
Is html title attribute a toolip?
I have question to know the truth. can some one tell me is HTML title attribute a tool tip.
Someone told me it is not a tooltip.
Can anybody describe what is a tool tip?
and HTML title is it or not?
I need the truth pleas.

答:
It is "Advisory information for the element" according to the specification.

Some browsers render it as a tooltip when you hover the element.

Obviously a screen reader would not, it reads it out.

A touch screen browser would not, it doesn't support a hover state.

Title: Is html title attribute a toolip?


问:
Should I always use -Wall and -pedantic switches with g++ while learning C++?
Being a --novice, I am wondering is it beneficial to always use these flags (with g++) while learning C++ ?

Thanks

答:
As long as you understand that code samples written by others will likely result in warnings with -Wall, then yes, it's a good flag to use because it gets you in the habit of writing code that is free of any potential gray areas the compiler may be able to identify.

-pedantic, on the other hand, is a trickier case. Here's what the GCC 4.4.4 manpage has to say about it:

Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and some other programs that do not
  follow ISO C and ISO C++.  For ISO C, follows the version of the ISO C standard specified by any -std option used.

Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few will require -ansi or a -std option specifying
  the required version of ISO C).  However, without this option, certain GNU extensions and traditional C and C++ features are supported as well.  With
  this option, they are rejected.

-pedantic does not cause warning messages for use of the alternate keywords whose names begin and end with __.  Pedantic warnings are also disabled in
  the expression that follows "__extension__".  However, only system header files should use these escape routes; application programs should avoid
  them.

Some users try to use -pedantic to check programs for strict ISO C conformance.  They soon find that it does not do quite what they want: it finds
  some non-ISO practices, but not all---only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added.

A feature to report any failure to conform to ISO C might be useful in some instances, but would require considerable additional work and would be
  quite different from -pedantic.  We don't have plans to support such a feature in the near future.


问:
How can I connect Xamarin Android app to an existing Sqlite database?
I developed the Xamarin android app. I also created an Sqlite database using Sqlite browser. After that, I inserted my existing data. My database has 5 tables. Now I want to connect to it via my Xamarin Android app. How can I do this? Please help.</p>

答:
You find a nice tutorial to use the SQLite database in your Xamarin.Android project here

Alternatively you can use the SQLite.Net library to connect with the database, you can find the detailed documentation here


问:
Ionic 2 control font size from UI
I am in between a mobile App development and there is a requirement where an end user can click +/- sign to increase or decrease the font size.

I have done it for many time for web using JQuery/JavaScript but not sure how can I manage it here.

My post.html

```<code> <ion-header>
    <ion-navbar>
        <button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-buttons>
          <button (click)="fontSizeChange()" class="details_btn  blicon-text-file-font" ion-button icon-only>
          </button>
        </ion-buttons>
    </ion-navbar>
</ion-header>
<ion-content class="post" *ngIf="post">
    <div class="detail">
        <div class="detail_image">
            <h1>{{post.title.rendered}}</h1>
        </div>
        <div class="page_info">
          <span class="date"><span class="blicon-clock"></span> {{post.date | date: 'mediumDate'}} </span>
          <span class="tag"> News</span>
        </div>
        <ion-item *ngIf="authorData && authorData.avatar_urls">
            <ion-avatar item-left>
                <img [src]="authorData.avatar_urls[96]">
            </ion-avatar>
            <h2>{{authorData.name}}</h2>
        </ion-item>
        <div id="fontControl">
            <p padding [innerHtml]="post.content.rendered"></p>
        </div>
    </div>
<!-- detail -->

</ion-content>
</code>```

and my page.component.ts is:-

```<code>import { Component, ViewChild } from '@angular/core';
import { Content, NavParams, LoadingController, ToastController } from 'ionic-angular';
import { Storage } from '@ionic/storage';

@Component({
    selector: 'post-detail',
    templateUrl: './wordpress-post.html'
})
export class WordpressPost {
    @ViewChild(Content) content: Content;

    post: any;
    authorData: any;
    comments = [];
    favoritePosts: any;
    user: any;

    constructor(
            private navParams: NavParams,
            private loadingController: LoadingController,
            private toastController: ToastController,
            private storage: Storage
        ) {
        if (navParams.get('post')) {
            this.post = navParams.get('post');
            }
        }

    }

    fontSizeChange(){
         var s = document.getElementById('fontControl').style.fontSize;
         console.log(s);
         var p = s.split('px');
         var z = parseInt(p[0]) + 1;
         document.getElementById('fontControl').style.fontSize = z + "px";
         console.log(document.getElementById('fontControl').style.fontSize);
    }
}
</code>```

Please suggest.

Thanks in advance.

答:
You can use document.getElementById('mydiv') for this.

This is what I have done and it works.

Say you have a div like this - with id, pre-given font-size and a button +:

```<code><div id="mydiv" style="font-size: 1px;">This text</div>
<button (click)='clicked()'>+</button>
</code>```

Now, on click:

```<code>clicked(){
    var s = document.getElementById('mydiv').style.fontSize;
    var p = s.split('px');
    var z = parseInt(p[0]) + 1;
    document.getElementById('mydiv').style.fontSize = z + "px";
    console.log(document.getElementById('mydiv').style.fontSize);
}
</code>```

NOTE: I have manipulated the style in px from string. You can do the same for %, em, rem etc.

Title: Ionic 2 control font size from UI

Body:
I am in between a mobile App development and there is a requirement where an end user can click +/- sign to increase or decrease the font size.

I have done it for many time for web using JQuery/JavaScript but not sure how can I manage it here.

My post.html

 <ion-header>
    <ion-navbar>
        <button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-buttons>
          <button (click)="fontSizeChange()" class="details_btn  blicon-text-file-font" ion-button icon-only>
          </button>
        </ion-buttons>
    </ion-navbar>
</ion-header>
<ion-content class="post" *ngIf="post">

{{post.title.rendered}}

           {{post.date | date: 'mediumDate'}}
           News

        <ion-item *ngIf="authorData && authorData.avatar_urls">
            <ion-avatar item-left>

            </ion-avatar>

{{authorData.name}}

        </ion-item>

</ion-content>

and my page.component.ts is:-

import { Component, ViewChild } from '@angular/core';
import { Content, NavParams, LoadingController, ToastController } from 'ionic-angular';
import { Storage } from '@ionic/storage';

@Component({
    selector: 'post-detail',
    templateUrl: './wordpress-post.html'
})
export class WordpressPost {
    @ViewChild(Content) content: Content;

    post: any;
    authorData: any;
    comments = [];
    favoritePosts: any;
    user: any;

    constructor(
            private navParams: NavParams,
            private loadingController: LoadingController,
            private toastController: ToastController,
            private storage: Storage
        ) {
        if (navParams.get('post')) {
            this.post = navParams.get('post');
            }
        }

    }

    fontSizeChange(){
         var s = document.getElementById('fontControl').style.fontSize;
         console.log(s);
         var p = s.split('px');
         var z = parseInt(p[0]) + 1;
         document.getElementById('fontControl').style.fontSize = z + "px";
         console.log(document.getElementById('fontControl').style.fontSize);
    }
}

Please suggest.

Thanks in advance.

Body:
You can use document.getElementById('mydiv') for this.

This is what I have done and it works.

Say you have a div like this - with id, pre-given font-size and a button +:

<div id="mydiv" style="font-size: 1px;">This text</div>
<button (click)='clicked()'>+</button>

Now, on click:

clicked(){
    var s = document.getElementById('mydiv').style.fontSize;
    var p = s.split('px');
    var z = parseInt(p[0]) + 1;
    document.getElementById('mydiv').style.fontSize = z + "px";
    console.log(document.getElementById('mydiv').style.fontSize);
}

NOTE: I have manipulated the style in px from string. You can do the same for %, em, rem etc.


问:
how remove XML Node with java
i need to remove the "Object" tag, but I need to preserve and keep the content. Is that possible?

```<code><ds:KeyInfo>
    <wsse:SecurityTokenReference>
        <wsse:Reference URI="#b3f74c53-b79f-4dec-aa26-ca552f8f8745"/>
    </wsse:SecurityTokenReference>
</ds:KeyInfo>
<ds:Object Id="id1"> // <-Remove this
    <wsu:Timestamp>
        <wsu:Created>2017-03-28T20:21:44Z</wsu:Created>
        <wsu:Expires>2017-03-28T23:08:24Z</wsu:Expires>
    </wsu:Timestamp>
 </ds:Object>  // <-Remove this
</code>```

I tried:

```<code>Node node = xml.getElementById("id1");
xml.getDocumentElement().removeChild(node);
</code>```

but:

```<code>Org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.
</code>```

答:
First of all, only the parent of the node to be removed can remove it:

```<code>Node nodeToBeRemoved = xmlDoc.getElementById("id1");
Node parentNode = nodeToBeRemoved.getParentNode();
Node removedNode = parentNode.removeChild(nodeToBeRemoved);
</code>```

Second, in order to "preserve and keep the content" you will need to attach the children elements of the removed one to its parent:

```<code>NodeList removedChildren = removedNode.getChildNodes();
for (int i = 0 ; i < removedChildren.getLength(); i++) {
    Node child = removedChildren.item(i);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
        parentNode.appendChild(child);
    }
}
</code>```

Title: how remove XML Node with java

Body:
i need to remove the "Object" tag, but I need to preserve and keep the content. Is that possible?

<ds:KeyInfo>
    <wsse:SecurityTokenReference>
        <wsse:Reference URI="#b3f74c53-b79f-4dec-aa26-ca552f8f8745"/>
    </wsse:SecurityTokenReference>
</ds:KeyInfo>
<ds:Object Id="id1"> // <-Remove this
    <wsu:Timestamp>
        <wsu:Created>2017-03-28T20:21:44Z</wsu:Created>
        <wsu:Expires>2017-03-28T23:08:24Z</wsu:Expires>
    </wsu:Timestamp>
 </ds:Object>  // <-Remove this

I tried:

Node node = xml.getElementById("id1");
xml.getDocumentElement().removeChild(node);

but:

Org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

Body:
First of all, only the parent of the node to be removed can remove it:

Node nodeToBeRemoved = xmlDoc.getElementById("id1");
Node parentNode = nodeToBeRemoved.getParentNode();
Node removedNode = parentNode.removeChild(nodeToBeRemoved);

Second, in order to "preserve and keep the content" you will need to attach the children elements of the removed one to its parent:

NodeList removedChildren = removedNode.getChildNodes();
for (int i = 0 ; i < removedChildren.getLength(); i++) {
    Node child = removedChildren.item(i);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
        parentNode.appendChild(child);
    }
}


问:
How to get a sorted subvector out of a sorted vector, fast
I have a data structure like this:

```<code>struct X {
  float value;
  int id;
};
</code>```

a vector of those (size N (think 100000), sorted by value (stays constant during the execution of the program):

```<code>std::vector<X> values;
</code>```

Now, I want to write a function

```<code>void subvector(std::vector<X> const& values,
               std::vector<int> const& ids,
               std::vector<X>& out /*,
               helper data here */);
</code>```

that fills the out parameter with a sorted subset of values, given by the passed ids (size M < N (about 0.8 times N)), fast (memory is not an issue, and this will be done repeatedly, so building lookuptables (the helper data from the function parameters) or something else that is done only once is entirely ok).

My solution so far:

Build lookuptable lut containing id -> offset in values (preparation, so constant runtime)

create std::vector<X> tmp, size N, filled with invalid ids (linear in N)

for each id, copy values[lut[id]] to tmp[lut[id]] (linear in M)

loop over tmp, copying items to out (linear in N)

this is linear in N (as it's bigger than M), but the temporary variable and repeated copying bugs me. Is there a way to do it quicker than this? Note that M will be close to N, so things that are O(M log N) are unfavourable.

Edit: http://ideone.com/xR8Vp is a sample implementation of mentioned algorithm, to make the desired output clear and prove that it's doable in linear time - the question is about the possibility of avoiding the temporary variable or speeding it up in some other way, something that is not linear is not faster :).

答:
Since your vector is sorted, and you want a subset of it sorted the same way, I assume we can just slice out the chunk you want without rearranging it.

Why not just use find_if() twice. Once to find the start of the range you want and once to find the end of the range. This will give you the start and end iterators of the sub vector. Construct a new vector using those iterators. One of the vector constructor overloads takes two iterators.

That or the partition algorithm should work.

Body:
I have a data structure like this:

struct X {
  float value;
  int id;
};

a vector of those (size N (think 100000), sorted by value (stays constant during the execution of the program):

std::vector<X> values;

Now, I want to write a function

void subvector(std::vector<X> const& values,
               std::vector<int> const& ids,
               std::vector<X>& out /*,
               helper data here */);

that fills the out parameter with a sorted subset of values, given by the passed ids (size M < N (about 0.8 times N)), fast (memory is not an issue, and this will be done repeatedly, so building lookuptables (the helper data from the function parameters) or something else that is done only once is entirely ok).

My solution so far:

Build lookuptable lut containing id -> offset in values (preparation, so constant runtime)

create std::vector<X> tmp, size N, filled with invalid ids (linear in N)

for each id, copy values[lut[id]] to tmp[lut[id]] (linear in M)

loop over tmp, copying items to out (linear in N)

this is linear in N (as it's bigger than M), but the temporary variable and repeated copying bugs me. Is there a way to do it quicker than this? Note that M will be close to N, so things that are O(M log N) are unfavourable.

Edit: http://ideone.com/xR8Vp is a sample implementation of mentioned algorithm, to make the desired output clear and prove that it's doable in linear time - the question is about the possibility of avoiding the temporary variable or speeding it up in some other way, something that is not linear is not faster :).


问:
Testing Multiple Calls to input()
I have the following function that I'd like to test:

```<code># Ask user input, returns year
def what_year():
    # Get the first input from the user.
    year = input('\n\tEnter the year you would like to START your range: \n\t')

    # Catch the error if the user doesn't enter a convertable string.
    try:
        year = int(year)
    except ValueError:
        print(error_msg.format(year))
        what_year()

    # We only want years between 2005 and today's year.
    if year not in range(2005, int(datetime.now().year +1)):
        print(error_msg.format(year))
        what_year()

    return year
</code>```

I'd like to test it without having to raise any errors, since ideally the function would continually loop without raising an error until the user inputs an acceptable input.

I'm lost as to how to get pytest to loop through inputs. I'm tried to patch builtins.input with mock, and that works to give a specified input to my function, but ideally the test would be able to successfully loop through a list of inputs.

For example, from my test code below, in the real world a user would go through all of the invalid options first and then finally start putting in valid options and the function would finally start returning "year".

I roughly got around this by make a debug parameter for each of my functions, then raising a value error if debug is on for testing purposes, but this seems rudimentary:

Function:

```<code># Ask user input, returns year
def what_year(debug=False):
    # Get the first input from the user.
    year = input('\n\tEnter the year you would like to START your range: \n\t')

    # Catch the error if the user doesn't enter a convertable string.
    try:
        year = int(year)
    except ValueError:

        # Only raise ValueError if debug is on for testing purposes.
        if debug:
            raise ValueError

        print(error_msg.format(year))
        what_year(debug)

    # We only want years between 2005 and today's year.
    if year not in range(2005, int(datetime.now().year +1)):

        if debug:
            raise ValueError

        print(error_msg.format(year))
        what_year(debug)

    return year
</code>```

Test:

```<code>import mock
import pytest
from redditimagescraper import RedditImageScraper

@pytest.mark.parametrize('invalid_years', ["9999", "0", "", " ", "-2015"])
def test_what_year_invalid(invalid_years):
    # Test invalid years
    with pytest.raises(ValueError):
        with mock.patch('builtins.input', return_value=invalid_years):
            RedditImageScraper.what_year(True)

@pytest.mark.parametrize('valid_years', [str(year) for year in range(2005,2018)])
def test_what_year_valid(valid_years):
    # Test valid years
    with mock.patch('builtins.input', return_value=valid_years):
        assert RedditImageScraper.what_year(True) == int(valid_years)
</code>```

Any ideas how to rewrite this function or test function to more easily test inputs?

答:
Not sure why but Barmar's comment on my question got my noggin joggin.

Anyway, here's an answer for those who have viewed the question. Per Barmar's comment I also updated my function.

what_year() function:

```<code># Ask user input, returns year
def what_year(start_or_end):
    while True:
        try:
            # Catch the error if the user doesn't enter a convertable string.
            # Get input from the user.
            year = int(input('\n\tEnter the year you would like to {} your range: '.format(start_or_end)))

            # We only want years between 2005 and today's year.
            if year in range(2005, int(datetime.now().year + 1)):
                # Success!
                break
            else:
                print(error_msg.format(year))
        except:
            print(error_msg.format('ValueError'))
            pass

    return year
</code>```

Test function:

```<code># Parametrize my valid answers
@pytest.mark.parametrize('valid_year', [str(year) for year in range(2005, datetime.now().year + 1)])
def test_what_year(valid_year):

    # years = a bunch of invalid inputs with a valid input at the end
    years = ["9999", "0", "", " ", "-2015", "-30", str(10^1000), valid_year]

    # side_effect, when given an iterable, iterates through
    # each time the patched function is called (in this case input())
    with mock.patch('builtins.input', side_effect=years):
        assert RedditImageScraper.what_year('start') == int(valid_year)
</code>```

running pytest -v gives me this:

```<code>============================= test session starts ==============================
platform linux -- Python 3.6.0, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /home/ardeaf/Projects/RedditImageScraper/venv/bin/python3
cachedir: .cache
rootdir: /home/ardeaf/Projects/RedditImageScraper, inifile: setup.cfg
collecting ... collected 12 items

tests/RedditImageScraper_test.py::test_what_year[2005] PASSED
tests/RedditImageScraper_test.py::test_what_year[2006] PASSED
tests/RedditImageScraper_test.py::test_what_year[2007] PASSED
tests/RedditImageScraper_test.py::test_what_year[2008] PASSED
tests/RedditImageScraper_test.py::test_what_year[2009] PASSED
tests/RedditImageScraper_test.py::test_what_year[2010] PASSED
tests/RedditImageScraper_test.py::test_what_year[2011] PASSED
tests/RedditImageScraper_test.py::test_what_year[2012] PASSED
tests/RedditImageScraper_test.py::test_what_year[2013] PASSED
tests/RedditImageScraper_test.py::test_what_year[2014] PASSED
tests/RedditImageScraper_test.py::test_what_year[2015] PASSED
tests/RedditImageScraper_test.py::test_what_year[2016] PASSED
tests/RedditImageScraper_test.py::test_what_year[2017] PASSED

========================== 12 passed in 0.31 seconds ===========================
</code>```

Title: Testing Multiple Calls to input()

Body:
I have the following function that I'd like to test:

# Ask user input, returns year
def what_year():
    # Get the first input from the user.
    year = input('\n\tEnter the year you would like to START your range: \n\t')

    # Catch the error if the user doesn't enter a convertable string.
    try:
        year = int(year)
    except ValueError:
        print(error_msg.format(year))
        what_year()

    # We only want years between 2005 and today's year.
    if year not in range(2005, int(datetime.now().year +1)):
        print(error_msg.format(year))
        what_year()

    return year

I'd like to test it without having to raise any errors, since ideally the function would continually loop without raising an error until the user inputs an acceptable input.

I'm lost as to how to get pytest to loop through inputs. I'm tried to patch builtins.input with mock, and that works to give a specified input to my function, but ideally the test would be able to successfully loop through a list of inputs.

For example, from my test code below, in the real world a user would go through all of the invalid options first and then finally start putting in valid options and the function would finally start returning "year".

I roughly got around this by make a debug parameter for each of my functions, then raising a value error if debug is on for testing purposes, but this seems rudimentary:

Function:

# Ask user input, returns year
def what_year(debug=False):
    # Get the first input from the user.
    year = input('\n\tEnter the year you would like to START your range: \n\t')

    # Catch the error if the user doesn't enter a convertable string.
    try:
        year = int(year)
    except ValueError:

        # Only raise ValueError if debug is on for testing purposes.
        if debug:
            raise ValueError

        print(error_msg.format(year))
        what_year(debug)

    # We only want years between 2005 and today's year.
    if year not in range(2005, int(datetime.now().year +1)):

        if debug:
            raise ValueError

        print(error_msg.format(year))
        what_year(debug)

    return year

Test:

import mock
import pytest
from redditimagescraper import RedditImageScraper

@pytest.mark.parametrize('invalid_years', ["9999", "0", "", " ", "-2015"])
def test_what_year_invalid(invalid_years):
    # Test invalid years
    with pytest.raises(ValueError):
        with mock.patch('builtins.input', return_value=invalid_years):
            RedditImageScraper.what_year(True)

@pytest.mark.parametrize('valid_years', [str(year) for year in range(2005,2018)])
def test_what_year_valid(valid_years):
    # Test valid years
    with mock.patch('builtins.input', return_value=valid_years):
        assert RedditImageScraper.what_year(True) == int(valid_years)

Any ideas how to rewrite this function or test function to more easily test inputs?

Body:
Not sure why but Barmar's comment on my question got my noggin joggin.

Anyway, here's an answer for those who have viewed the question. Per Barmar's comment I also updated my function.

what_year() function:

# Ask user input, returns year
def what_year(start_or_end):
    while True:
        try:
            # Catch the error if the user doesn't enter a convertable string.
            # Get input from the user.
            year = int(input('\n\tEnter the year you would like to {} your range: '.format(start_or_end)))

            # We only want years between 2005 and today's year.
            if year in range(2005, int(datetime.now().year + 1)):
                # Success!
                break
            else:
                print(error_msg.format(year))
        except:
            print(error_msg.format('ValueError'))
            pass

    return year

Test function:

# Parametrize my valid answers
@pytest.mark.parametrize('valid_year', [str(year) for year in range(2005, datetime.now().year + 1)])
def test_what_year(valid_year):

    # years = a bunch of invalid inputs with a valid input at the end
    years = ["9999", "0", "", " ", "-2015", "-30", str(10^1000), valid_year]

    # side_effect, when given an iterable, iterates through
    # each time the patched function is called (in this case input())
    with mock.patch('builtins.input', side_effect=years):
        assert RedditImageScraper.what_year('start') == int(valid_year)

running pytest -v gives me this:

============================= test session starts ==============================
platform linux -- Python 3.6.0, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /home/ardeaf/Projects/RedditImageScraper/venv/bin/python3
cachedir: .cache
rootdir: /home/ardeaf/Projects/RedditImageScraper, inifile: setup.cfg
collecting ... collected 12 items

tests/RedditImageScraper_test.py::test_what_year[2005] PASSED
tests/RedditImageScraper_test.py::test_what_year[2006] PASSED
tests/RedditImageScraper_test.py::test_what_year[2007] PASSED
tests/RedditImageScraper_test.py::test_what_year[2008] PASSED
tests/RedditImageScraper_test.py::test_what_year[2009] PASSED
tests/RedditImageScraper_test.py::test_what_year[2010] PASSED
tests/RedditImageScraper_test.py::test_what_year[2011] PASSED
tests/RedditImageScraper_test.py::test_what_year[2012] PASSED
tests/RedditImageScraper_test.py::test_what_year[2013] PASSED
tests/RedditImageScraper_test.py::test_what_year[2014] PASSED
tests/RedditImageScraper_test.py::test_what_year[2015] PASSED
tests/RedditImageScraper_test.py::test_what_year[2016] PASSED
tests/RedditImageScraper_test.py::test_what_year[2017] PASSED

========================== 12 passed in 0.31 seconds ===========================


问:
UIbutton misplaced in simulator
Here I have to implement the UIView for both the screens iPhone 5 and 6. So I used the screeHeight to integrate the UIView. But the button in the view is misplaced in iPhone 5s simulator and works fine in iPhone 6 simulator Here is the code for that. Whatever I changed the values in x and y remains the same top position.

```<code>if screenHeight == 568{

        self.viewFareEstimate.frame = CGRect(x:0, y:150, width:359, height:40)

    }
</code>```

答:
The screen size of Iphone 5 is 320 × 568, but your width is more than 320.
Try this </p>

```<code>if screenHeight == 568{

    self.viewFareEstimate.frame = CGRect(x:0, y:150, width:320, height:40)

}
</code>```

Title: UIbutton misplaced in simulator

Body:
Here I have to implement the UIView for both the screens iPhone 5 and 6. So I used the screeHeight to integrate the UIView. But the button in the view is misplaced in iPhone 5s simulator and works fine in iPhone 6 simulator Here is the code for that. Whatever I changed the values in x and y remains the same top position.

if screenHeight == 568{

        self.viewFareEstimate.frame = CGRect(x:0, y:150, width:359, height:40)

    }

Body:
The screen size of Iphone 5 is 320 × 568, but your width is more than 320.
Try this

if screenHeight == 568{

    self.viewFareEstimate.frame = CGRect(x:0, y:150, width:320, height:40)

}