问:
My webpack doesn't generate my css file
I have an issue with webpack and my react app. I am developing my app in react, but when I run my bundle script to run webpack, it doesn't generate the output css.

Here is my component

```<code>import React from 'react'
import { Link } from 'react-router'

import styles from './Header.css'

function Header() {
  return (
    <header className={styles.header}>
      <h1>
        Mi first react app
      </h1>

      <nav role="navigation">
        <Link to="/">
          Home
        </Link>
        <a
          href="http://google.com"
          target="_blank"
        >
          Google
        </a>
      </nav>
    </header>
  )
}

export default Header
</code>```

My webpack config:

```<code>const ExtractTextPlugin = require('extract-text-webpack-plugin')
const path = require('path');

module.exports = {
  entry: ['babel-polyfill', path.join(__dirname, '../src/client.js')],
  output: {
    filename: 'app.js',
    path: path.join(__dirname, '../built/statics')
  },
  module: {
    loaders: [
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /(node_modules)/,
        query: {
          presets: ['es2016', 'es2017', 'react'],
          plugins: ['transform-es2015-modules-commonjs']
        }
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader?modules' })
      }
    ]
  },
  target: 'web',
  plugins: [
    new ExtractTextPlugin('../statics/styles.css')
  ],
  watch: true
}
</code>```

If you need, my css is this:

```<code>.header {
  background: linear-gradient(90deg, #1c3643 0, #273b46 25%, #1e5372);
}
</code>```

In advance, thanks for any help to discover what I am missing

答:
Can you please try making changes as mentioned below?

What is "Header.css" ?

What is the use of this code?

```<code>import styles from './Header.css'
</code>```

The filename is styles.css as mentioned in ExtractTextPlugin.

You should directly include "statics/styles.css" file in your HTML.

Also, here

```<code>function Header() {
  return (
    <header className="header">
      <h1>
        Mi first react app
      </h1>

      <nav role="navigation">
        <Link to="/">
          Home
        </Link>
        <a
          href="http://google.com"
          target="_blank"
        >
          Google
        </a>
      </nav>
    </header>
  )
}
</code>```

The goal of ExtractTextplugin is to generate a separate single CSS file which could be used separately as in general case.

Title: My webpack doesn't generate my css file

Body:
I have an issue with webpack and my react app. I am developing my app in react, but when I run my bundle script to run webpack, it doesn't generate the output css.

Here is my component

import React from 'react'
import { Link } from 'react-router'

import styles from './Header.css'

function Header() {
  return (

        Mi first react app

        <Link to="/">
          Home
        </Link>

          Google

  )
}

export default Header

My webpack config:

const ExtractTextPlugin = require('extract-text-webpack-plugin')
const path = require('path');

module.exports = {
  entry: ['babel-polyfill', path.join(__dirname, '../src/client.js')],
  output: {
    filename: 'app.js',
    path: path.join(__dirname, '../built/statics')
  },
  module: {
    loaders: [
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /(node_modules)/,
        query: {
          presets: ['es2016', 'es2017', 'react'],
          plugins: ['transform-es2015-modules-commonjs']
        }
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader?modules' })
      }
    ]
  },
  target: 'web',
  plugins: [
    new ExtractTextPlugin('../statics/styles.css')
  ],
  watch: true
}

If you need, my css is this:

.header {
  background: linear-gradient(90deg, #1c3643 0, #273b46 25%, #1e5372);
}

In advance, thanks for any help to discover what I am missing

Body:
Can you please try making changes as mentioned below?

What is "Header.css" ?

What is the use of this code?

import styles from './Header.css'

The filename is styles.css as mentioned in ExtractTextPlugin.

You should directly include "statics/styles.css" file in your HTML.

Also, here

function Header() {
  return (
    <header className="header">
      <h1>
        Mi first react app
      </h1>

      <nav role="navigation">
        <Link to="/">
          Home
        </Link>
        <a
          href="http://google.com"
          target="_blank"
        >
          Google
        </a>
      </nav>
    </header>
  )
}

The goal of ExtractTextplugin is to generate a separate single CSS file which could be used separately as in general case.


来源: stackexchange

问:
How to execute a CMD /C command with ( round bracket in the path name
I'm trying to execute a command like this:

```<code>CMD /C "C:\Users\Richard(R)D\abc.bat"
</code>```

I get the error message:

```<code>'C:\Users\Richard' is not recognized as an internal or external command
</code>```

How can I execute the command that resides in a folder that uses round brackets?

答:
Try escaping the parentheses with a circumflex ^</p>

```<code>CMD /C "C:\Users\Richard^(R^)D\abc.bat"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to execute a command like this:

CMD /C "C:\Users\Richard(R)D\abc.bat"

I get the error message:

'C:\Users\Richard' is not recognized as an internal or external command

How can I execute the command that resides in a folder that uses round brackets?

Body:
Try escaping the parentheses with a circumflex ^

CMD /C "C:\Users\Richard^(R^)D\abc.bat"


问:
Find number of CPUs in linux kernel
I want detect number of CPUs in linux kernel and write a sys_call that find it.

cpuinfo_x86 gives features of one CPU and cpu_detect fills it but how to find number of CPUs to detect?

答:
Try:

```<code>$lscpu
</code>```

This gives me information about CPUs, as well as architecture,  etc...

Title: Find number of CPUs in linux kernel

Body:
Try:

$lscpu

This gives me information about CPUs, as well as architecture,  etc...


问:
If-statement with changing url
What is wrong with this function? The first if-statement does work. But the else-statement doesn't work.

```<code>function func() {
    if (document.getElementById("pic2").src = "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src == "pause.png";
    }
}
</code>```

HTML:

```<code><div id="all" onclick="func()" onmouseover="func3()">
            <div id="background" onclick="func()" onmouseout="func2()"></div>
            <div id="pic">
                <img id="pic2" src="pause.png">
            </div>
            <video>
                <source src="test.mp4" type="video/mp4">
            </video>
        </div>
</code>```

答:
There were few things which didn't let you toggle your img src.

Improper condition check. if (document.getElementById("pic2").src = "pause.png") must be if (document.getElementById("pic2").src=="pause.png")

document.getElementById("pic2").src would give you the full path to your image. Its better to trim it down to the image name (with extension) using img_url.substr(img_url.lastIndexOf("/")+1);

function func() {
    var img_url = document.getElementById("pic2").src;
    var img = img_url.substr(img_url.lastIndexOf("/")+1);
    if (img  == "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src = "pause.png";
    }
}

function func2(){
 // your func2
}

function func3(){
 // your func3
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="all" onclick="func()" onmouseover="func3()">
            <div id="background" onclick="func()" onmouseout="func2()"></div>
            <div id="pic">
                <img id="pic2" src="pause.png">
            </div>
            <video>
                <source src="test.mp4" type="video/mp4">
            </video>
        </div></code>```

Title: If-statement with changing url

Body:
What is wrong with this function? The first if-statement does work. But the else-statement doesn't work.

function func() {
    if (document.getElementById("pic2").src = "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src == "pause.png";
    }
}

HTML:

            <video>
                <source src="test.mp4" type="video/mp4">
            </video>

Body:
There were few things which didn't let you toggle your img src.

Improper condition check. if (document.getElementById("pic2").src = "pause.png") must be if (document.getElementById("pic2").src=="pause.png")

document.getElementById("pic2").src would give you the full path to your image. Its better to trim it down to the image name (with extension) using img_url.substr(img_url.lastIndexOf("/")+1);

function func() {
    var img_url = document.getElementById("pic2").src;
    var img = img_url.substr(img_url.lastIndexOf("/")+1);
    if (img  == "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src = "pause.png";
    }
}

function func2(){
 // your func2
}

function func3(){
 // your func3
}

<div id="all" onclick="func()" onmouseover="func3()">
            <div id="background" onclick="func()" onmouseout="func2()"></div>
            <div id="pic">
                <img id="pic2" src="pause.png">
            </div>
            <video>
                <source src="test.mp4" type="video/mp4">
            </video>
        </div>


问:
onClick method error & App crashes when I press the button
I have a simple app to increase and decrease a number with button press. but unfortunately my app crashes when I press the button. Here is the MainActivity.java code :

```<code>package com.example.sparker.asafool;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

int quantity = 1;

public void decrement(View view) {
    quantity = quantity - 1;
    displayIt(quantity);
}

public void increment(View view) {
    quantity = quantity + 1;
    displayIt(quantity);
}

public void displayIt(int xyz){
    TextView quantityTextView = (TextView)findViewById(R.id.textView);
    quantityTextView.setText(xyz);
}
</code>```

}

decrement and increment methods are in the xml file.

Here is the logcat:

答:
The problem is that you are trying to .setText() an int while .setText accepts a string (actually, a CharSequence) as a parameter. Try it like this:</p>

```<code>quantityTextView.setText(String.valueOf(xyz));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple app to increase and decrease a number with button press. but unfortunately my app crashes when I press the button. Here is the MainActivity.java code :

package com.example.sparker.asafool;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

int quantity = 1;

public void decrement(View view) {
    quantity = quantity - 1;
    displayIt(quantity);
}

public void increment(View view) {
    quantity = quantity + 1;
    displayIt(quantity);
}

public void displayIt(int xyz){
    TextView quantityTextView = (TextView)findViewById(R.id.textView);
    quantityTextView.setText(xyz);
}

}

decrement and increment methods are in the xml file.

Here is the logcat:

Body:
The problem is that you are trying to .setText() an int while .setText accepts a string (actually, a CharSequence) as a parameter. Try it like this:

quantityTextView.setText(String.valueOf(xyz));


答:
you missed out the ending quotes so the command will be like this

CMD /C "C:\Users\Richard(R)D\abc.bat"

Hope this will help u fix it.

Title: How to execute a CMD /C command with ( round bracket in the path name


问:
Does Azure Active Directory B2C work with Oauth or Open ID?
I successfully implemented Azure Active Directory for user management/authentication/login in a web app, following this example:
Azure Sample AAD with Flask

I decided to try Azure Active Directory B2C because of its integration for the various social apps. However, I could not get the flask app to work using OAuth 2.0, since Azure AD B2C does not seem to be compatible with OAuth 2.0. I found some documentation that states Azure AD B2C requires Open ID Connect.

Could you please confirm whether Azure Active Directory B2C requires Open ID Connect, or whether it works with OAuth 2.0 as well?

Thanks

答:
Based on the documentation here, Azure AD B2C supports both OpenID Connect and OAuth 2.0 protocols.

Azure Active Directory (Azure AD) B2C provides identity as a service
  for your apps by supporting two industry standard protocols: OpenID
  Connect and OAuth 2.0. The service is standards-compliant, but any two
  implementations of these protocols can have subtle differences.


问:
Unable to display category name of post
On my home page, I'm trying to loop through a set number of posts and display the category name of each post. The category that I'm trying to display the name for is a subcategory of a parent (if that makes any difference). Here's my code for it:

```<code>        <?php
            $args = array( 'numberposts' => '15' );
            $recent_posts = wp_get_recent_posts( $args );
            foreach ( $recent_posts as $recent ) {
                $category = get_the_category($recent['ID']);
                echo $category['cat-name'];
        }; ?>
</code>```

When I run that, nothing ends up displaying. That page displays as if the code wasn't there. But when I do a var_dump on $category:

```<code>        <?php
            $args = array( 'numberposts' => '15' );
            $recent_posts = wp_get_recent_posts( $args );
            foreach ( $recent_posts as $recent ) {
                $category = get_the_category($recent['ID']);
                echo var_dump($category);
        }; ?>
</code>```

I can see that everything is there that I need. Each post, with it's keys and values, but for some reason trying to display a specific property of a post (like 'cat-name', or even 'name') doesn't work. Any ideas?

答:
get_the_category() will return an array of WP_Term objects, one for each category assigned to the post.

This means you need to loop through the array, or if you only have 1 array in there fetch it using

```<code>$category[0]->name;
</code>```

Title: Unable to display category name of post

Body:
On my home page, I'm trying to loop through a set number of posts and display the category name of each post. The category that I'm trying to display the name for is a subcategory of a parent (if that makes any difference). Here's my code for it:

        <?php
            $args = array( 'numberposts' => '15' );
            $recent_posts = wp_get_recent_posts( $args );
            foreach ( $recent_posts as $recent ) {
                $category = get_the_category($recent['ID']);
                echo $category['cat-name'];
        }; ?>

When I run that, nothing ends up displaying. That page displays as if the code wasn't there. But when I do a var_dump on $category:

        <?php
            $args = array( 'numberposts' => '15' );
            $recent_posts = wp_get_recent_posts( $args );
            foreach ( $recent_posts as $recent ) {
                $category = get_the_category($recent['ID']);
                echo var_dump($category);
        }; ?>

I can see that everything is there that I need. Each post, with it's keys and values, but for some reason trying to display a specific property of a post (like 'cat-name', or even 'name') doesn't work. Any ideas?

Body:
get_the_category() will return an array of WP_Term objects, one for each category assigned to the post.

This means you need to loop through the array, or if you only have 1 array in there fetch it using

$category[0]->name;


问:
How do I add a horizontal line in a html select control?
How do I add a horizontal line (
 tag) in the dropdown control or in select control in HTML?

答:
If you want to insert a seperator of sorts into a  tag, you can do something like this: http://jsfiddle.net/k4emic/4CfEp/

However, this isn't recommended practice.

ContentLicense: CC BY-SA 2.5


问:
Rewrite to https and www doesn't work for aliases
I read tons of posts about this topic, but still couldn't solve my problem. In my httpd.conf I have an alias like "/folder2" "/home/web/folder1". Also I have these lines in my .htaccess to rewrite all possible URLs to https://www.:

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

This works perfectly except for all URLs with mydomain.com/folder2. They still remain in http:// and in order to acces them with https:// I have to type it explicitly.

答:
Good evening :)

Are both, the alias and the rewrites, within the same context (e.g. vhost)? Because if they are not, the alias could be applied before the rewrite and so the rewrite might never 'hit'.

Read this for further information on processing order and merging rules.

To fix it, put the rewrite rules first, alias second. Alias should still work and rewrite rules have already been applied by then :)

EDIT

The target (or substitution string) in a RewriteRule is assumed to be a file path, by default. The use of the [PT] flag causes it to be treated as a URI instead. That is to say, the use of the [PT] flag causes the result of the RewriteRule to be passed back through URL mapping, so that location-based mappings, such as Alias, Redirect, or ScriptAlias, for example, might have a chance to take effect.

If, for example, you have an Alias for /icons, and have a RewriteRule pointing there, you should use the [PT] flag to ensure that the Alias is evaluated.

Excerpt from here

Body:
I read tons of posts about this topic, but still couldn't solve my problem. In my httpd.conf I have an alias like "/folder2" "/home/web/folder1". Also I have these lines in my .htaccess to rewrite all possible URLs to https://www.:

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

This works perfectly except for all URLs with mydomain.com/folder2. They still remain in http:// and in order to acces them with https:// I have to type it explicitly.


问:
File handling in C programming: What is the difference between below two codes?
CODE #1:

```<code>#include<stdio.h>
void main()
{
    FILE *fp;
    char ch;
    fp=fopen("1.txt","r");
    while((ch=fgetc(fp))!=EOF)
    {
        printf("%c",ch);
    }
    fclose(fp);

}
</code>```

code #2:

```<code>#include<stdio.h>
void main()
{
    FILE *fp;
    int ch;
    fp=fopen("1.txt","r");
    while((ch=fgetc(fp))!=EOF)
    {
        printf("%c",ch);
    }
    fclose(fp);

}
</code>```

Here in CODE #1 variable ch is declared under character data type while in
CODE #2 it's declared under integer data type, My question is how come the output of both codes be same? How can we compare character(stored in ch variable in CODE #1) with integer value(returned by EOF)? And how can integer value stored in ch variable(of interger data type) and printed in CODE #2?

答:
CODE#1 is obviously wrong and it is a common mistake done by programmers. fgetc returns an int precisely so that the value can be compared with EOF.

EOF expands to an integer constant value and it is an implementation dependent negative value, but, most commonly it will be -1. So, when the return value of fgetc is assigned to char it gets truncated to 255 which is a valid char value. This is the reason why fgetc has the return type of int and value returned from fgetc should never be assigned to a char.

And how can integer value stored in ch variable(of interger data type) and printed in CODE #2?

The man page of fgetc clearly states

fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.

So, typecasting it to char to print it is fine as long as the returned value is not EOF.

Body:
CODE #1:

#include<stdio.h>
void main()
{
    FILE *fp;
    char ch;
    fp=fopen("1.txt","r");
    while((ch=fgetc(fp))!=EOF)
    {
        printf("%c",ch);
    }
    fclose(fp);

}

code #2:

#include<stdio.h>
void main()
{
    FILE *fp;
    int ch;
    fp=fopen("1.txt","r");
    while((ch=fgetc(fp))!=EOF)
    {
        printf("%c",ch);
    }
    fclose(fp);

}

Here in CODE #1 variable ch is declared under character data type while in
CODE #2 it's declared under integer data type, My question is how come the output of both codes be same? How can we compare character(stored in ch variable in CODE #1) with integer value(returned by EOF)? And how can integer value stored in ch variable(of interger data type) and printed in CODE #2?


问:
Merge next results into one and display in Angular 2 project
I am trying to get my head around Observables in RxJs. I have a page with Search box and when user start typing then Webservice returns 20 results and then when i press Show More then next 20 results are displayed and so on.

I am able to get first 20 results successfully but next 20, i am not able to merge with earlier ones.

Service

```<code>@Injectable()
export class AppService {

constructor(private http : Http) {}

search(terms : Observable < string >) {

    return terms
      .debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term));

  }

searchEntries(term) {

    const API = "https://jsonplaceholder.typicode.com/posts/";

    return this
      .http
      .get(API)
      .map(res => res.json());
  }

}
</code>```

Component

```<code>export class AppComponent {

resp : Object;
searchTerm = new Subject < string > ();

constructor(private _searchService : AppService) {
this
  ._searchService
  .search(this.searchTerm)
  .subscribe(results => {
    this.resp = results;
  });
 }
}
</code>```

HTML

```<code><span *ngFor="let res of resp | slice:0:10">
      <a href="#" class="lex-column align-items-start">
        <div class="d-flex w-100 justify-content-between">
          <h5 class="mb-1">{{res.title}}</h5>
          <small># {{res.id}}</small>
        </div>
        <p class="mb-1">{{res.body}}</p>
        <small >Donec id elit non mi porta.</small>
      </a>
 </span>
</code>```

I have replaced API URL to general one

Please help in combining next 20 results to previously shown results.

答:
You can use take(n) operator

```<code>return terms
      .debounceTime(400)
      .distinctUntilChanged()
      .take(10)
      .switchMap(term => this.searchEntries(term));
</code>```

By this everytime only 10 items are taken.

Body:
I am trying to get my head around Observables in RxJs. I have a page with Search box and when user start typing then Webservice returns 20 results and then when i press Show More then next 20 results are displayed and so on.

I am able to get first 20 results successfully but next 20, i am not able to merge with earlier ones.

Service

@Injectable()
export class AppService {

constructor(private http : Http) {}

search(terms : Observable < string >) {

    return terms
      .debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term));

  }

searchEntries(term) {

    const API = "https://jsonplaceholder.typicode.com/posts/";

    return this
      .http
      .get(API)
      .map(res => res.json());
  }

}

Component

export class AppComponent {

resp : Object;
searchTerm = new Subject < string > ();

constructor(private _searchService : AppService) {
this
  ._searchService
  .search(this.searchTerm)
  .subscribe(results => {
    this.resp = results;
  });
 }
}

HTML

{{res.title}}

          # {{res.id}}

{{res.body}}

        Donec id elit non mi porta.

I have replaced API URL to general one

Please help in combining next 20 results to previously shown results.

Body:
You can use take(n) operator

return terms
      .debounceTime(400)
      .distinctUntilChanged()
      .take(10)
      .switchMap(term => this.searchEntries(term));

By this everytime only 10 items are taken.


问:
PHP Mysql count distinct reasons given where reason value in another table
I want to create a statistics page where i can count the number of reasons given in a table ...The reasons are created dynamically and stored in another table.

Table1 contains all the reasons which populate a drop down box...
Table2 contains the entries given by the user one of the columns is the reason value.

I would like to count the amount of times each reason appears .

Thankyou for your time and help

答:
Looks like simply group statement:</p>

```<code>select
    reason.name reason,
    count(*) count
from entry, reason
where
    entry.reason = reason.id and
    entry.time > now() - interval 7 day -- you probably need some filter
group by reason.id
</code>```

Body:
Looks like simply group statement:

select
    reason.name reason,
    count(*) count
from entry, reason
where
    entry.reason = reason.id and
    entry.time > now() - interval 7 day -- you probably need some filter
group by reason.id


问:
UIScrollView odd behavior: zoom in, pan, zoom out leaves content view uncentered
I have a custom UIViewController subclass controlling a UISCrollView containing an UIImageView, set up like so:

```<code>UIViewController
+ UIScrollView (delegate: UIViewController, viewForZoomingInView: UIImageView)
  + UIImageView
</code>```

I can use the UIScrollView to zoom in on my image, and pan around -- but if I do so such that the center of the view is not the center of the image, and then zoom out fully, my image is off center; what's more, since I am at the minimum zoom scale at that point, I cannot pan around to re-center my image.

My expectation was that when zooming out, UIScrollView would re-center the contentSize's area under its bounds so that you never see beyond the edge of the content view (or rather, the content view's size plus contentInset). Am I wrong in this assumption?

If so, what should I do to provide this behavior?

Here's my code:

```<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    imageView.image = image;
    [imageView sizeToFit];

    float minimumScale = [imageScrollView frame].size.width  / [imageView frame].size.width;

    imageScrollView.contentSize = [imageView frame].size;
    imageScrollView.maximumZoomScale = 2.0;
    imageScrollView.minimumZoomScale = minimumScale;

    imageScrollView.zoomScale = imageScrollView.minimumZoomScale;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageView;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
    // nothing
}
</code>```

EDIT: Solution!

You have to set clipsToBounds = YES on the UIScrollView to get the desired behavior. I didn't find this initially because it is a property of UIView, not of UIScrollView directly.

答: I saw same on my UIImageView with pinch in and out, in IB I checked on "Clip subviews" and the Image view started behaving better. </p>

Body:
I have a custom UIViewController subclass controlling a UISCrollView containing an UIImageView, set up like so:

UIViewController
+ UIScrollView (delegate: UIViewController, viewForZoomingInView: UIImageView)
  + UIImageView

I can use the UIScrollView to zoom in on my image, and pan around -- but if I do so such that the center of the view is not the center of the image, and then zoom out fully, my image is off center; what's more, since I am at the minimum zoom scale at that point, I cannot pan around to re-center my image.

My expectation was that when zooming out, UIScrollView would re-center the contentSize's area under its bounds so that you never see beyond the edge of the content view (or rather, the content view's size plus contentInset). Am I wrong in this assumption?

If so, what should I do to provide this behavior?

Here's my code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    imageView.image = image;
    [imageView sizeToFit];

    float minimumScale = [imageScrollView frame].size.width  / [imageView frame].size.width;

    imageScrollView.contentSize = [imageView frame].size;
    imageScrollView.maximumZoomScale = 2.0;
    imageScrollView.minimumZoomScale = minimumScale;

    imageScrollView.zoomScale = imageScrollView.minimumZoomScale;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageView;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
    // nothing
}

EDIT: Solution!

You have to set clipsToBounds = YES on the UIScrollView to get the desired behavior. I didn't find this initially because it is a property of UIView, not of UIScrollView directly.


问:
Keyboard interrupt in x86 protected mode causes processor error
I'm working on a simple kernel and I've been trying to implement a keyboard interrupt handler to get rid of port polling. I've been using QEMU in -kernel mode (to reduce compile time, because generating the iso using grub-mkrescue takes quite some time) and it worked just fine, but when I wanted to switch to -cdrom mode it suddenly started crashing. I had no idea why.

Eventually I've realized that when it boots from an iso it also runs a GRUB bootloader before booting the kernel itself. I've figured out GRUB probably switches the processor into protected mode and that causes the problem.

the problem:
Normally I'd simply initialize the interrupt handler and whenever I'd press a key it would be handled. However when I run my kernel using an iso and pressed a key the virtual machine simply crashed. This happened in both qemu and VMWare so I assume there must be something wrong with my interrupts.

Bear in mind that the code work just fine for as long as I don't use GRUB.
interrupts_init()(see below) is one of the first things called in the main() kernel function.

Essentially the question is: Is there a way to make this work in protected mode?.

A complete copy of my kernel can be found in my GitHub repository. Some relevant files:

lowlevel.asm:

```<code>section .text

global keyboard_handler_int
global load_idt

extern keyboard_handler

keyboard_handler_int:
    pushad
    cld
    call keyboard_handler
    popad
    iretd

load_idt:
    mov edx, [esp + 4]
    lidt [edx]
    sti
    ret
</code>```

interrupts.c:

```<code>#include <assembly.h> // defines inb() and outb()

#define IDT_SIZE 256
#define PIC_1_CTRL 0x20
#define PIC_2_CTRL 0xA0
#define PIC_1_DATA 0x21
#define PIC_2_DATA 0xA1

extern void keyboard_handler_int(void);
extern void load_idt(void*);

struct idt_entry
{
    unsigned short int offset_lowerbits;
    unsigned short int selector;
    unsigned char zero;
    unsigned char flags;
    unsigned short int offset_higherbits;
} __attribute__((packed));

struct idt_pointer
{
    unsigned short limit;
    unsigned int base;
} __attribute__((packed));

struct idt_entry idt_table[IDT_SIZE];
struct idt_pointer idt_ptr;

void load_idt_entry(int isr_number, unsigned long base, short int selector, unsigned char flags)
{
    idt_table[isr_number].offset_lowerbits = base & 0xFFFF;
    idt_table[isr_number].offset_higherbits = (base >> 16) & 0xFFFF;
    idt_table[isr_number].selector = selector;
    idt_table[isr_number].flags = flags;
    idt_table[isr_number].zero = 0;
}

static void initialize_idt_pointer()
{
    idt_ptr.limit = (sizeof(struct idt_entry) * IDT_SIZE) - 1;
    idt_ptr.base = (unsigned int)&idt_table;
}

static void initialize_pic()
{
    /* ICW1 - begin initialization */
    outb(PIC_1_CTRL, 0x11);
    outb(PIC_2_CTRL, 0x11);

    /* ICW2 - remap offset address of idt_table */
    /*
    * In x86 protected mode, we have to remap the PICs beyond 0x20 because
    * Intel have designated the first 32 interrupts as "reserved" for cpu exceptions
    */
    outb(PIC_1_DATA, 0x20);
    outb(PIC_2_DATA, 0x28);

    /* ICW3 - setup cascading */
    outb(PIC_1_DATA, 0x00);
    outb(PIC_2_DATA, 0x00);

    /* ICW4 - environment info */
    outb(PIC_1_DATA, 0x01);
    outb(PIC_2_DATA, 0x01);
    /* Initialization finished */

    /* mask interrupts */
    outb(0x21 , 0xFF);
    outb(0xA1 , 0xFF);
}

void idt_init(void)
{
    initialize_pic();
    initialize_idt_pointer();
    load_idt(&idt_ptr);
}

void interrupts_init(void)
{
    idt_init();
    load_idt_entry(0x21, (unsigned long) keyboard_handler_int, 0x08, 0x8E);

    /* 0xFD is 11111101 - enables only IRQ1 (keyboard)*/
    outb(0x21 , 0xFD);
}
</code>```

kernel.c

```<code>#if defined(__linux__)
    #error "You are not using a cross-compiler, you will most certainly run into trouble!"
#endif

#if !defined(__i386__)
    #error "This kernel needs to be compiled with a ix86-elf compiler!"
#endif

#include <kernel.h>

// These _init() functions are not in their respective headers because
// they're supposed to be never called from anywhere else than from here

void term_init(void);
void mem_init(void);
void dev_init(void);

void interrupts_init(void);
void shell_init(void);

void kernel_main(void)
{
    // Initialize basic components
    term_init();
    mem_init();
    dev_init();
    interrupts_init();

    // Start the Shell module
    shell_init();

    // This should be unreachable code
    kernel_panic("End of kernel reached!");
}
</code>```

boot.asm:

```<code>bits 32
section .text
;grub bootloader header
        align 4
        dd 0x1BADB002            ;magic
        dd 0x00                  ;flags
        dd - (0x1BADB002 + 0x00) ;checksum. m+f+c should be zero

global start
extern kernel_main

start:
  mov esp, stack_space  ;set stack pointer
  call kernel_main

; We shouldn't get to here, but just in case do an infinite loop
endloop:
  hlt           ;halt the CPU
  jmp endloop

section .bss
resb 8192       ;8KB for stack
stack_space:
</code>```

答:
I had a hunch last night as to why loading through GRUB and loading through the Multiboot -kernel feature of QEMU might not work as expected. That is captured in the comments. I have managed to confirm the findings based on more of the source code being released by the OP.

In the Mulitboot Specification there is a note about the GDTR and the GDT with regards to modifying selectors that is relevant:

GDTR

Even though the segment registers are set up as described above, the ‘GDTR’ may be invalid, so the OS image must not load any segment registers (even just reloading the same values!) until it sets up its own ‘GDT’.

An interrupt routine could alter the CS selector causing issues.

There is another concern and most likely the root cause of problems. The Multiboot specification also states this about the selectors it creates in its GDT:

```<code>‘CS’
Must be a 32-bit read/execute code segment with an offset of ‘0’ and a
limit of ‘0xFFFFFFFF’. The exact value is undefined.
‘DS’
‘ES’
‘FS’
‘GS’
‘SS’
Must be a 32-bit read/write data segment with an offset of ‘0’ and a limit
of ‘0xFFFFFFFF’. The exact values are all undefined.
</code>```

Although it says what types of descriptors will be set up it doesn't actually specify that a descriptor has to have a particular index. One Multiboot loader may have a Code segment descriptor at index 0x08 and another bootloader may use 0x10. This is of particular relevance when you look at one line of your code:

load_idt_entry(0x21, (unsigned long) keyboard_handler_int, 0x08, 0x8E);

This creates an IDT descriptor for interrupt 0x21. The third parameter 0x08 is the Code selector the CPU needs to use to access the interrupt handler. I discovered this works on QEMU where the code selector is 0x08, but in GRUB it appears to be 0x10. In GRUB the 0x10 selector points at a non-executable Data segment and this will not work.

To get around all these problems the best thing to do is set up your own GDT shortly after starting up your kernel and before setting up an IDT and enabling interrupts. There is a tutorial on the GDT in the OSDev Wiki if you want more information.

To set up a GDT I'll simply create an assembler routine in lowlevel.asm to do it by adding a load_gdt function and data structures:

```<code>global load_gdt

; GDT with a NULL Descriptor, a 32-Bit code Descriptor
; and a 32-bit Data Descriptor
gdt_start:
gdt_null:
    dd 0x0
    dd 0x0

gdt_code:
    dw 0xffff
    dw 0x0
    db 0x0
    db 10011010b
    db 11001111b
    db 0x0

gdt_data:
    dw 0xffff
    dw 0x0
    db 0x0
    db 10010010b
    db 11001111b
    db 0x0
gdt_end:

; GDT descriptor record
gdt_descriptor:
    dw gdt_end - gdt_start - 1
    dd gdt_start

CODE_SEG equ gdt_code - gdt_start
DATA_SEG equ gdt_data - gdt_start

; Load GDT and set selectors for a flat memory model
load_gdt:
    lgdt [gdt_descriptor]
    jmp CODE_SEG:.setcs              ; Set CS selector with far JMP
.setcs:
    mov eax, DATA_SEG                ; Set the Data selectors to defaults
    mov ds, eax
    mov es, eax
    mov fs, eax
    mov gs, eax
    mov ss, eax
    ret
</code>```

This creates and loads a GDT that has a NULL Descriptor at index 0x00, a 32-bit code descriptor at 0x08, and a 32-bit data descriptor at 0x10. Since we are using 0x08 as the code selector this matches what you specify as a code selector in your IDT entry initialization for interrupt 0x21:

load_idt_entry(0x21, (unsigned long) keyboard_handler_int, 0x08, 0x8E);

The only other thing is that you'll need to amend your kernel.c to call load_gdt. One can do that with something like:

```<code>extern void load_gdt(void);

void kernel_main(void)
{
    // Initialize basic components
    load_gdt();
    term_init();
    mem_init();
    dev_init();
    interrupts_init();

    // Start the Shell module
    shell_init();

    // This should be unreachable code
    kernel_panic("End of kernel reached!");
}
</code>```

Body:
I'm working on a simple kernel and I've been trying to implement a keyboard interrupt handler to get rid of port polling. I've been using QEMU in -kernel mode (to reduce compile time, because generating the iso using grub-mkrescue takes quite some time) and it worked just fine, but when I wanted to switch to -cdrom mode it suddenly started crashing. I had no idea why.

Eventually I've realized that when it boots from an iso it also runs a GRUB bootloader before booting the kernel itself. I've figured out GRUB probably switches the processor into protected mode and that causes the problem.

the problem:
Normally I'd simply initialize the interrupt handler and whenever I'd press a key it would be handled. However when I run my kernel using an iso and pressed a key the virtual machine simply crashed. This happened in both qemu and VMWare so I assume there must be something wrong with my interrupts.

Bear in mind that the code work just fine for as long as I don't use GRUB.
interrupts_init()(see below) is one of the first things called in the main() kernel function.

Essentially the question is: Is there a way to make this work in protected mode?.

A complete copy of my kernel can be found in my GitHub repository. Some relevant files:

lowlevel.asm:

section .text

global keyboard_handler_int
global load_idt

extern keyboard_handler

keyboard_handler_int:
    pushad
    cld
    call keyboard_handler
    popad
    iretd

load_idt:
    mov edx, [esp + 4]
    lidt [edx]
    sti
    ret

interrupts.c:

#include <assembly.h> // defines inb() and outb()

#define IDT_SIZE 256
#define PIC_1_CTRL 0x20
#define PIC_2_CTRL 0xA0
#define PIC_1_DATA 0x21
#define PIC_2_DATA 0xA1

extern void keyboard_handler_int(void);
extern void load_idt(void*);

struct idt_entry
{
    unsigned short int offset_lowerbits;
    unsigned short int selector;
    unsigned char zero;
    unsigned char flags;
    unsigned short int offset_higherbits;
} __attribute__((packed));

struct idt_pointer
{
    unsigned short limit;
    unsigned int base;
} __attribute__((packed));

struct idt_entry idt_table[IDT_SIZE];
struct idt_pointer idt_ptr;

void load_idt_entry(int isr_number, unsigned long base, short int selector, unsigned char flags)
{
    idt_table[isr_number].offset_lowerbits = base & 0xFFFF;
    idt_table[isr_number].offset_higherbits = (base >> 16) & 0xFFFF;
    idt_table[isr_number].selector = selector;
    idt_table[isr_number].flags = flags;
    idt_table[isr_number].zero = 0;
}

static void initialize_idt_pointer()
{
    idt_ptr.limit = (sizeof(struct idt_entry) * IDT_SIZE) - 1;
    idt_ptr.base = (unsigned int)&idt_table;
}

static void initialize_pic()
{
    /* ICW1 - begin initialization */
    outb(PIC_1_CTRL, 0x11);
    outb(PIC_2_CTRL, 0x11);

    /* ICW2 - remap offset address of idt_table */
    /*
    * In x86 protected mode, we have to remap the PICs beyond 0x20 because
    * Intel have designated the first 32 interrupts as "reserved" for cpu exceptions
    */
    outb(PIC_1_DATA, 0x20);
    outb(PIC_2_DATA, 0x28);

    /* ICW3 - setup cascading */
    outb(PIC_1_DATA, 0x00);
    outb(PIC_2_DATA, 0x00);

    /* ICW4 - environment info */
    outb(PIC_1_DATA, 0x01);
    outb(PIC_2_DATA, 0x01);
    /* Initialization finished */

    /* mask interrupts */
    outb(0x21 , 0xFF);
    outb(0xA1 , 0xFF);
}

void idt_init(void)
{
    initialize_pic();
    initialize_idt_pointer();
    load_idt(&idt_ptr);
}

void interrupts_init(void)
{
    idt_init();
    load_idt_entry(0x21, (unsigned long) keyboard_handler_int, 0x08, 0x8E);

    /* 0xFD is 11111101 - enables only IRQ1 (keyboard)*/
    outb(0x21 , 0xFD);
}

kernel.c

#if defined(__linux__)
    #error "You are not using a cross-compiler, you will most certainly run into trouble!"
#endif

#if !defined(__i386__)
    #error "This kernel needs to be compiled with a ix86-elf compiler!"
#endif

#include <kernel.h>

// These _init() functions are not in their respective headers because
// they're supposed to be never called from anywhere else than from here

void term_init(void);
void mem_init(void);
void dev_init(void);

void interrupts_init(void);
void shell_init(void);

void kernel_main(void)
{
    // Initialize basic components
    term_init();
    mem_init();
    dev_init();
    interrupts_init();

    // Start the Shell module
    shell_init();

    // This should be unreachable code
    kernel_panic("End of kernel reached!");
}

boot.asm:

bits 32
section .text
;grub bootloader header
        align 4
        dd 0x1BADB002            ;magic
        dd 0x00                  ;flags
        dd - (0x1BADB002 + 0x00) ;checksum. m+f+c should be zero

global start
extern kernel_main

start:
  mov esp, stack_space  ;set stack pointer
  call kernel_main

; We shouldn't get to here, but just in case do an infinite loop
endloop:
  hlt           ;halt the CPU
  jmp endloop

section .bss
resb 8192       ;8KB for stack
stack_space:

Body:
I had a hunch last night as to why loading through GRUB and loading through the Multiboot -kernel feature of QEMU might not work as expected. That is captured in the comments. I have managed to confirm the findings based on more of the source code being released by the OP.

In the Mulitboot Specification there is a note about the GDTR and the GDT with regards to modifying selectors that is relevant:

GDTR

Even though the segment registers are set up as described above, the ‘GDTR’ may be invalid, so the OS image must not load any segment registers (even just reloading the same values!) until it sets up its own ‘GDT’.

An interrupt routine could alter the CS selector causing issues.

There is another concern and most likely the root cause of problems. The Multiboot specification also states this about the selectors it creates in its GDT:

‘CS’
Must be a 32-bit read/execute code segment with an offset of ‘0’ and a
limit of ‘0xFFFFFFFF’. The exact value is undefined.
‘DS’
‘ES’
‘FS’
‘GS’
‘SS’
Must be a 32-bit read/write data segment with an offset of ‘0’ and a limit
of ‘0xFFFFFFFF’. The exact values are all undefined.

Although it says what types of descriptors will be set up it doesn't actually specify that a descriptor has to have a particular index. One Multiboot loader may have a Code segment descriptor at index 0x08 and another bootloader may use 0x10. This is of particular relevance when you look at one line of your code:

load_idt_entry(0x21, (unsigned long) keyboard_handler_int, 0x08, 0x8E);

This creates an IDT descriptor for interrupt 0x21. The third parameter 0x08 is the Code selector the CPU needs to use to access the interrupt handler. I discovered this works on QEMU where the code selector is 0x08, but in GRUB it appears to be 0x10. In GRUB the 0x10 selector points at a non-executable Data segment and this will not work.

To get around all these problems the best thing to do is set up your own GDT shortly after starting up your kernel and before setting up an IDT and enabling interrupts. There is a tutorial on the GDT in the OSDev Wiki if you want more information.

To set up a GDT I'll simply create an assembler routine in lowlevel.asm to do it by adding a load_gdt function and data structures:

global load_gdt

; GDT with a NULL Descriptor, a 32-Bit code Descriptor
; and a 32-bit Data Descriptor
gdt_start:
gdt_null:
    dd 0x0
    dd 0x0

gdt_code:
    dw 0xffff
    dw 0x0
    db 0x0
    db 10011010b
    db 11001111b
    db 0x0

gdt_data:
    dw 0xffff
    dw 0x0
    db 0x0
    db 10010010b
    db 11001111b
    db 0x0
gdt_end:

; GDT descriptor record
gdt_descriptor:
    dw gdt_end - gdt_start - 1
    dd gdt_start

CODE_SEG equ gdt_code - gdt_start
DATA_SEG equ gdt_data - gdt_start

; Load GDT and set selectors for a flat memory model
load_gdt:
    lgdt [gdt_descriptor]
    jmp CODE_SEG:.setcs              ; Set CS selector with far JMP
.setcs:
    mov eax, DATA_SEG                ; Set the Data selectors to defaults
    mov ds, eax
    mov es, eax
    mov fs, eax
    mov gs, eax
    mov ss, eax
    ret

This creates and loads a GDT that has a NULL Descriptor at index 0x00, a 32-bit code descriptor at 0x08, and a 32-bit data descriptor at 0x10. Since we are using 0x08 as the code selector this matches what you specify as a code selector in your IDT entry initialization for interrupt 0x21:

load_idt_entry(0x21, (unsigned long) keyboard_handler_int, 0x08, 0x8E);

The only other thing is that you'll need to amend your kernel.c to call load_gdt. One can do that with something like:

extern void load_gdt(void);

void kernel_main(void)
{
    // Initialize basic components
    load_gdt();
    term_init();
    mem_init();
    dev_init();
    interrupts_init();

    // Start the Shell module
    shell_init();

    // This should be unreachable code
    kernel_panic("End of kernel reached!");
}


问:
Show user statistics using Node.js
I am building a web platform using the MEAN stack intended to be used by different business in the same field. I want to be able to show the businesses using my platform statistics about who visited their pages, how many bookings were made through the website.. etc.

I know of tools such as Facebook or Google Analytics that can collect statistics about my web application. Is it a good idea to use these tools and then query them to display customized statistics to each user? Or are there other better alternatives? I'm using AngularJS 1 for front-end.

I am a beginner so detailed advice would be much appreciated.

答:
You have to be specific about exactly what statistics you need to collect.  What you mentioned seemed to be stats that are application specific. Google Analytics is not appropriate for that.

We are not supposed to recommend tools on Stack Overflow because that is completely subjective.  However, I will say that one very popular tool for collecting stats in Node is statsd.

But basically I think you should make sure your requirements are clear and then tailor a solution for that, rather than trying to select a tool first.

Title: Show user statistics using Node.js


问:
Difference between Static methods and Instance methods
I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?

Could someone please explain to me in really simple terms what Static or Class Methods are?

Also, could I get a simple explanation on what Instance methods are?

This is what they give me in the textbook:

There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.

The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".

答:
Difference between Static methods and Instance methods

Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.

Static method is  declared with static keyword. Instance method is not with static keyword.

Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.

Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.

Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.

Reference : geeksforgeeks


问:
traverse list in scala and group all the first elements and second elements
This might be pretty simple questions. I have a list named "List1" that contain list of integer pairs as below.

List1 = List((1,2), (3,4), (9,8), (9,10))

Output should be:

r1 = (1,3,9,9)      //List((1,2), (3,4), (9,8), (9,10))

    r2 = (2,4,8,10)     //List((1,2), (3,4), (9,8), (9,10))

```<code>array r1(Array[int]) should contains set of all first integers of each pair in the list.
array r2(Array[int]) should contains set of all second integers of each pair
</code>```

Body:
This might be pretty simple questions. I have a list named "List1" that contain list of integer pairs as below.

List1 = List((1,2), (3,4), (9,8), (9,10))

Output should be:

r1 = (1,3,9,9)      //List((1,2), (3,4), (9,8), (9,10))

    r2 = (2,4,8,10)     //List((1,2), (3,4), (9,8), (9,10))

array r1(Array[int]) should contains set of all first integers of each pair in the list.
array r2(Array[int]) should contains set of all second integers of each pair

Body:
Just use unzip:

scala> List((1,2), (3,4), (9,8), (9,10)).unzip
res0: (List[Int], List[Int]) = (List(1, 3, 9, 9),List(2, 4, 8, 10))


问:
Retrieving Points of Polygons created by cvApproxPoly()
I have a CvSeq* containing the polygons created by running cvApproxPoly() on a CvSeq* created from running cvFindContors on a b&w input image.  I want to access the CvPoints of each polygon returned from the CvSeq*.  Code so far as follows (outlines is an IplImage containing the b&w input image):

```<code>//create pointers to store data we're going to be calculating
CvMemStorage* storage = cvCreateMemStorage();
CvSeq* first_contour = NULL;
CvSeq* first_polygon = NULL;

//find the contours (edges) of the silhouette, in terms of pixels.
cvFindContours( &outlines,
                storage,
                &first_contour,
                sizeof(CvContour),
                CV_RETR_LIST );

//convert the pixel contours to line segments in a polygon.
first_polygon = cvApproxPoly(first_contour,
                             sizeof(CvContour),
                             storage,
                             CV_POLY_APPROX_DP,
                             2,
                             1);
</code>```

I can use cvDrawContour to draw the polygon onto an image, but I want to iterate over each 2D point that defines each contour. It looks like each element of the CvSeq* first_polygon contains the set of points for a single polygon (concluded based on the value of first_polygon->total;, but I don't know how to access the individual points. Help please?

答: Resolved this myself:  CvSeq* is multi-dimensional. e.g: cvSeq->total; is the first dimension (each polygon), eg cvSeq->first->total is the second dimension (each point in a polygon).</p>

Body:
I have a CvSeq* containing the polygons created by running cvApproxPoly() on a CvSeq* created from running cvFindContors on a b&w input image.  I want to access the CvPoints of each polygon returned from the CvSeq*.  Code so far as follows (outlines is an IplImage containing the b&w input image):

//create pointers to store data we're going to be calculating
CvMemStorage* storage = cvCreateMemStorage();
CvSeq* first_contour = NULL;
CvSeq* first_polygon = NULL;

//find the contours (edges) of the silhouette, in terms of pixels.
cvFindContours( &outlines,
                storage,
                &first_contour,
                sizeof(CvContour),
                CV_RETR_LIST );

//convert the pixel contours to line segments in a polygon.
first_polygon = cvApproxPoly(first_contour,
                             sizeof(CvContour),
                             storage,
                             CV_POLY_APPROX_DP,
                             2,
                             1);

I can use cvDrawContour to draw the polygon onto an image, but I want to iterate over each 2D point that defines each contour. It looks like each element of the CvSeq* first_polygon contains the set of points for a single polygon (concluded based on the value of first_polygon->total;, but I don't know how to access the individual points. Help please?


问:
(Yii2) the page that you are looking for used information.....?
my simple view file

```<code><?php
 use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<?php ActiveForm::begin()?>

 <?=Html::submitButton('something')?>

 <?php ActiveForm::end()?
</code>```

Clicked the button. After I reload the page and browser shows me
this

So how can I remove this?

答:
This problem happen when  you submit data in a form and then  refresh the page
Browsers should stop this, or at least prompt if you want to resend the data,
but the best way to prevent this from happening is submit the data .. and manage the submit properly.

In you case your submit repeat the index action because you don't manage  proper the action code
(all you're being made does not produce the creation of a new model to be complete so as not prroduce displaying a result.
 or any other action ..
 your code continues to call the same action that produces post calling for action and so on)

try adding a simple die()  or a render for another  view

```<code>public function actionIndex()
{
   if (Yii::$app->request->post('submit')==='my_value') {
      echo "Button my_value Clicked";
      die(); // or render a proper view
   }
   return $this->render('index');
}
</code>```

Body:
my simple view file

<?php
 use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<?php ActiveForm::begin()?>

 <?=Html::submitButton('something')?>

 <?php ActiveForm::end()?

Clicked the button. After I reload the page and browser shows me
this

So how can I remove this?

Body:
This problem happen when  you submit data in a form and then  refresh the page
Browsers should stop this, or at least prompt if you want to resend the data,
but the best way to prevent this from happening is submit the data .. and manage the submit properly.

In you case your submit repeat the index action because you don't manage  proper the action code
(all you're being made does not produce the creation of a new model to be complete so as not prroduce displaying a result.
 or any other action ..
 your code continues to call the same action that produces post calling for action and so on)

try adding a simple die()  or a render for another  view

public function actionIndex()
{
   if (Yii::$app->request->post('submit')==='my_value') {
      echo "Button my_value Clicked";
      die(); // or render a proper view
   }
   return $this->render('index');
}


问:
Why layout is disturbing even using width in dp Android
I have created a demo application in Android using Nexus 9 2048 X 1536
I have added an EditText and assign width as 1000dp it is working fine in Nexus 9 Emulator. But When I change the Emulator as Nexus 5X 1080 X 1920 to test the dp purpose, Then the EditText goes out of the layout and shown about half of it.

Why it is happening even I assign the width in dp. It should adjust the width by screen-resolution.

答:
It should adjust the width by screen-resolution.

No, it does not. dp will adjust the width by screen density, not screen resolution. You asked for it to be 1000dp wide, and so it will be 1000dp wide, regardless of screen resolution or screen size.


问:
Adding a value to a hashmap java
Sorry, new to Java, probably a really simple question.

Let's say I have an outter map, that has a (key, inner map), and in the inner map I have (String, Double).

So it looks something like this.

```<code>    HashMap<String, Double> inner = new HashMap<String, Double>();
    HashMap<Integer, Map<String, Double>> outter = new HashMap<Integer, Map<String, Double>>();
    inner.put("MyVal", 24.5930553450692151964475150);
    inner.put("MyVal2", 48.6514790522118734018261775);
    outter.put(20151205, inner)
</code>```

I end up with and outter map like this:

```<code>{20151205={MyVal=24.593055345069214, MyVal2=48.651479052211876}}
</code>```

Now let's say I no longer have access to the inner map, so I can't put any more values in it. But, I want to add a MyVal3 using only the outter map.

How can this be done?

I want to end up with something like this using code for only the outter map.

```<code>{20151205={MyVal=24.593055345069214, MyVal2=48.651479052211876, MyVal3=48.4846855555555}}
</code>```

Thanks a lot! Couldn't find exactly this question elsewhere on SO.

As always thanks everyone!

答:
You always have access to the inner map, but you need to get the key.

Then you simply put.

```<code>outter.get(20151205).put("MyVal3", 48.4846855555) ;
</code>```

Beware of the Nullpointerexception when you try to get a key that doesn't exist

Title: Adding a value to a hashmap java

Body:
Sorry, new to Java, probably a really simple question.

Let's say I have an outter map, that has a (key, inner map), and in the inner map I have (String, Double).

So it looks something like this.

    HashMap<String, Double> inner = new HashMap<String, Double>();
    HashMap<Integer, Map<String, Double>> outter = new HashMap<Integer, Map<String, Double>>();
    inner.put("MyVal", 24.5930553450692151964475150);
    inner.put("MyVal2", 48.6514790522118734018261775);
    outter.put(20151205, inner)

I end up with and outter map like this:

{20151205={MyVal=24.593055345069214, MyVal2=48.651479052211876}}

Now let's say I no longer have access to the inner map, so I can't put any more values in it. But, I want to add a MyVal3 using only the outter map.

How can this be done?

I want to end up with something like this using code for only the outter map.

{20151205={MyVal=24.593055345069214, MyVal2=48.651479052211876, MyVal3=48.4846855555555}}

Thanks a lot! Couldn't find exactly this question elsewhere on SO.

As always thanks everyone!

Body:
You always have access to the inner map, but you need to get the key.

Then you simply put.

outter.get(20151205).put("MyVal3", 48.4846855555) ;

Beware of the Nullpointerexception when you try to get a key that doesn't exist


问:
Number formatting in SSRS 2008
SSRS 2008 reports are being developed using T-SQL Queries. The requirement is to display the numbers in Indian format. E.g 1234568 should be shown as 12,34,568. SSRS is applying thousand seperator(i.e 1234568 is shown as 1,234,568) only, though number format is set to regional settings for all the report items and the regional settings in report server machine are set to the required format. We tried custom formats also but invain. Is there is any solution for this problem. Thanks in advance.</p>

答:
This may also be helpful:

http://social.msdn.microsoft.com/Forums/en/vscrystalreports/thread/5e2c8681-9d7d-4731-848e-d0e2cc8aa0b7

Title: Number formatting in SSRS 2008


问:
get lines in file via index from another file
i have two files, first my big list:

```<code>123 321 231 412
424 244 bear wolf
512 dinosaur 525
</code>```

second one with the index i want from the first one, so

```<code>1
-1
3
</code>```

Now i want as an output the exact lines from the first file via the specific index of the second one, note: if i have a '-1' i want to just skip it.

So in the example:

```<code>123 321 231 412
512 dinosaur 525
</code>```

i tried this:

```<code>import linecache

i = open('list_wanted', 'w')

with open ('index_list', 'r') as index:
     for line in index:
          int_index = [int(i) for i in line.split()] # this seems necessary since my index list seems to be in strings, not integers

     for line in int_index:
          if line != ('-1'):
               i.write(linecache.getline('big_list' , line))
</code>```

I really dont want the whole big_list in my memory, so the linecache seems fine, but i can't get it to work properly. What am i doing wrong?

:edit:
The first answer was correct, but i have a very weird result now:
the length does not match from what i was expecting, i added a small counter w:

```<code>import linecache

w = 0

a = open('lines_wanted', 'w')

with open ('index_list', 'r') as index:
     int_index = [int(i), for i in index.readlines()]

     for line in int_index:
          a.write(linecache.getline('big_list', line))
          w = w + 1

print(w)
</code>```

the number of times i write (w) is the expected number of lines, but if i check my file i have some lines less (expected 34752 (thats the same as my w) and got in fact only 34308).
i think this might be a problem with duplicates, how can i avoid it and get my expected w lines in my file.
Does someone has an idea?
I NEED exactly as many lines as in my index_list file.

P.s.: the case of -1 is not an issue anymore, i got rid of it, so i have really only the "good" lines that i want in my index_list file.

:edit2:
found it, i had to write line+1 in my write command

答:
```<code>import linecache

i = open('lines_wanted', 'w')

with open('index_list', 'r') as index:
    # this seems necessary since my index list seems to be in strings, not integers
    int_index = [int(i) for i in index.readlines()]

    for line in int_index:
        if line != ('-1'):
            i.write(linecache.getline('big_list', line))
</code>```

The problem was with the int_index list. It was not being formed as expected.

Body:
i have two files, first my big list:

123 321 231 412
424 244 bear wolf
512 dinosaur 525

second one with the index i want from the first one, so

1
-1
3

Now i want as an output the exact lines from the first file via the specific index of the second one, note: if i have a '-1' i want to just skip it.

So in the example:

123 321 231 412
512 dinosaur 525

i tried this:

import linecache

i = open('list_wanted', 'w')

with open ('index_list', 'r') as index:
     for line in index:
          int_index = [int(i) for i in line.split()] # this seems necessary since my index list seems to be in strings, not integers

     for line in int_index:
          if line != ('-1'):
               i.write(linecache.getline('big_list' , line))

I really dont want the whole big_list in my memory, so the linecache seems fine, but i can't get it to work properly. What am i doing wrong?

:edit:
The first answer was correct, but i have a very weird result now:
the length does not match from what i was expecting, i added a small counter w:

import linecache

w = 0

a = open('lines_wanted', 'w')

with open ('index_list', 'r') as index:
     int_index = [int(i), for i in index.readlines()]

     for line in int_index:
          a.write(linecache.getline('big_list', line))
          w = w + 1

print(w)

the number of times i write (w) is the expected number of lines, but if i check my file i have some lines less (expected 34752 (thats the same as my w) and got in fact only 34308).
i think this might be a problem with duplicates, how can i avoid it and get my expected w lines in my file.
Does someone has an idea?
I NEED exactly as many lines as in my index_list file.

P.s.: the case of -1 is not an issue anymore, i got rid of it, so i have really only the "good" lines that i want in my index_list file.

:edit2:
found it, i had to write line+1 in my write command

Body:
import linecache

i = open('lines_wanted', 'w')

with open('index_list', 'r') as index:
    # this seems necessary since my index list seems to be in strings, not integers
    int_index = [int(i) for i in index.readlines()]

    for line in int_index:
        if line != ('-1'):
            i.write(linecache.getline('big_list', line))

The problem was with the int_index list. It was not being formed as expected.


问:
Merge multiple arrays based on their index using javascript
I need to merge two arrays into a single array.  I have code but it is not working as expected-- it is merging them one after another, but I need to interlock the values.

    <title></title>

```

答:
Well actually JavaScript lacks a .zip() functor which would be very handy for exactly what you are trying to do. Lets invent it;

Array.prototype.zip = function(a){
 return this.map((e,i) => typeof e === "object" || typeof a[i] === "object" ? [e,a[i]] : e+a[i]);
};

var arrays = [[1, 2, 3, 4],
              ["a", "b", "c", "d"],
              [9, 8, 7, 6],
              ["z", "y", "x", "w"],
              [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
             ],
result = arrays.reduce((p,c) => p.zip(c));
console.log(result);```


问:
If-statement with changing url
What is wrong with this function? The first if-statement does work. But the else-statement doesn't work.

```<code>function func() {
    if (document.getElementById("pic2").src = "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src == "pause.png";
    }
}
</code>```

HTML:

```<code><div id="all" onclick="func()" onmouseover="func3()">
            <div id="background" onclick="func()" onmouseout="func2()"></div>
            <div id="pic">
                <img id="pic2" src="pause.png">
            </div>
            <video>
                <source src="test.mp4" type="video/mp4">
            </video>
        </div>
</code>```

答:
single equal signs sign is for assign a value. you have to add two equals to compare two variables or values.
 like this:-

```<code>function func() {
    if (document.getElementById("pic2").src == "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src = "pause.png";
    }
}
</code>```

Title: If-statement with changing url

Body:
What is wrong with this function? The first if-statement does work. But the else-statement doesn't work.

function func() {
    if (document.getElementById("pic2").src = "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src == "pause.png";
    }
}

HTML:

            <video>
                <source src="test.mp4" type="video/mp4">
            </video>

Body:
single equal signs sign is for assign a value. you have to add two equals to compare two variables or values.
 like this:-

function func() {
    if (document.getElementById("pic2").src == "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src = "pause.png";
    }
}


问:
Swift - Get data from Alamofire POST request
I'm stuck in Swift project. I call "SendPost" from button IBAction and I need it returns the data from Alamofire.request, but I don't know how to reach this. I can't get to "utf8Text" variable from out of Alamofire.request. How can I get to the data?

Thank you. :)

```<code>import Foundation
import Alamofire

  func SendPost(parameters: Parameters) -> String {

  Alamofire.request("https://hovnocuc.com/main.php", method: .post, parameters: parameters).response { response in
        print("Request: \(response.request)")
        print("Response: \(response.response)")
        print("Error: \(response.error)")

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)")

        }
    }

 return "I don't know. :(";
 }
</code>```

答:
Try with the below code </p>

```<code>func SendPost(parameters: Parameters) -> [String,AnyObject] {

       let urlstring= "https://hovnocuc.com/main.php"
       Alamofire.request(.POST, urlstring, parameters: parameters, encoding: .JSON).responseJSON { response in

                       if let JSON = response.result.value {
                           print("JSON: \(JSON)")
                           return JSON
                       }
                   }
               return "I don't know "
            }
</code>```

Body:
I'm stuck in Swift project. I call "SendPost" from button IBAction and I need it returns the data from Alamofire.request, but I don't know how to reach this. I can't get to "utf8Text" variable from out of Alamofire.request. How can I get to the data?

Thank you. :)

import Foundation
import Alamofire

  func SendPost(parameters: Parameters) -> String {

  Alamofire.request("https://hovnocuc.com/main.php", method: .post, parameters: parameters).response { response in
        print("Request: \(response.request)")
        print("Response: \(response.response)")
        print("Error: \(response.error)")

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)")

        }
    }

 return "I don't know. :(";
 }

Body:
Try with the below code

func SendPost(parameters: Parameters) -> [String,AnyObject] {

       let urlstring= "https://hovnocuc.com/main.php"
       Alamofire.request(.POST, urlstring, parameters: parameters, encoding: .JSON).responseJSON { response in

                       if let JSON = response.result.value {
                           print("JSON: \(JSON)")
                           return JSON
                       }
                   }
               return "I don't know "
            }


问:
POST value from JavaScript to PHP via AJAX without jQuery
I'm trying to send a JavaScript variable to be processed server-side by PHP then echo back the result. My ajax request results in readyState == 4 and status == 200 yet PHP keeps echoing back an empty array/value.

I'm pretty sure this comes from my Ajax call sending an empty request but everything I tried didn't work, so maybe I'm going all wrong here.

JS (from index.html) :

```<code>var valueToSend = Math.random();

var request = false;
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    request = new ActiveXObject('Microsoft.XMLHTTP');
}

function send_ajax() {
    if (request) {
        request.open('POST', 'test.php', true);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                console.log(request.responseText);
            }
        }
        request.send(valueToSend); //this line is probably not sending the value the way I expect it to
    }
}
</code>```

PHP (from test.php) :

```<code>echo $_POST['name']; //simple echo to check if PHP indeed receives valueToSend
</code>```

My last try was to change request.send(valueToSend); with .send(encodeURI('name=' + valueToSend)); but it just made the ajax call redirect the page location to a non-existing one.

What am I doing wrong ?

答:
There are few things wrong in your code, such as:

Even through you defined send_ajax() function, you didn't call it anywhere in the code.

With POST request you need to send an HTTP header setRequestHeader() along with the request, like this:

```<code>request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
</code>```

echo $_POST['name']; in test.php page won't work because name is undefined here. Your send() method call should be like this:

```<code>request.send("name="+valueToSend);
</code>```

So the complete JavaScript code would be like this:

```<code>var valueToSend = Math.random();

var request = false;
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    request = new ActiveXObject('Microsoft.XMLHTTP');
}

function send_ajax() {
    if (request) {
        request.open('POST', 'test.php', true);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                console.log(request.responseText);
            }
        }
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send("name="+valueToSend);
    }
}

send_ajax();
</code>```

Body:
I'm trying to send a JavaScript variable to be processed server-side by PHP then echo back the result. My ajax request results in readyState == 4 and status == 200 yet PHP keeps echoing back an empty array/value.

I'm pretty sure this comes from my Ajax call sending an empty request but everything I tried didn't work, so maybe I'm going all wrong here.

JS (from index.html) :

var valueToSend = Math.random();

var request = false;
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    request = new ActiveXObject('Microsoft.XMLHTTP');
}

function send_ajax() {
    if (request) {
        request.open('POST', 'test.php', true);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                console.log(request.responseText);
            }
        }
        request.send(valueToSend); //this line is probably not sending the value the way I expect it to
    }
}

PHP (from test.php) :

echo $_POST['name']; //simple echo to check if PHP indeed receives valueToSend

My last try was to change request.send(valueToSend); with .send(encodeURI('name=' + valueToSend)); but it just made the ajax call redirect the page location to a non-existing one.

What am I doing wrong ?

Body:
There are few things wrong in your code, such as:

Even through you defined send_ajax() function, you didn't call it anywhere in the code.

With POST request you need to send an HTTP header setRequestHeader() along with the request, like this:

request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

echo $_POST['name']; in test.php page won't work because name is undefined here. Your send() method call should be like this:

request.send("name="+valueToSend);

So the complete JavaScript code would be like this:

var valueToSend = Math.random();

var request = false;
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    request = new ActiveXObject('Microsoft.XMLHTTP');
}

function send_ajax() {
    if (request) {
        request.open('POST', 'test.php', true);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                console.log(request.responseText);
            }
        }
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send("name="+valueToSend);
    }
}

send_ajax();


问:
Parsing json and searching through it
I have this code

```<code>import json
from pprint import pprint
json_data=open('bookmarks.json')
jdata = json.load(json_data)
pprint (jdata)
json_data.close()
</code>```

How can I search through it for u'uri': u'http:?

答:
Seems there's a typo (missing colon) in the JSON dict provided by jro.

The correct syntax would be:

```<code>jdata = json.load('{"uri": "http:", "foo": "bar"}')
</code>```

This cleared it up for me when playing with the code.

Title: Parsing json and searching through it

Body:
I have this code

import json
from pprint import pprint
json_data=open('bookmarks.json')
jdata = json.load(json_data)
pprint (jdata)
json_data.close()

How can I search through it for u'uri': u'http:?

Body:
Seems there's a typo (missing colon) in the JSON dict provided by jro.

The correct syntax would be:

jdata = json.load('{"uri": "http:", "foo": "bar"}')

This cleared it up for me when playing with the code.


问:
ChildNode of custom type is returning Nil on Swift Playground
I have a class with name (Player.swift). then in my (Scene.swift) class, I declared my object like this.

```<code>var player: Player?
</code>```

then in my initializeGame function, I am doing like this

```<code>private func initializeGame() {

    player = childNode(withName: "Player") as? Player!;
    //print NIL
    print(player?.name);
    // initializePlayer()is declared in Player.swift
    player?.initializePlayer();
    print(player?.name);
    //Print NIL
    scoreLabel = childNode(withName: "ScoreLabel") as? SKLabelNode!;
    scoreLabel?.text = "0";
}
</code>```

I made my ios project in Xcode,  and its working fine,  then i create a Playground project and import all the xcode files in this project, My playground is running properly except the player is not functioning properly. The problem is in associating the Player Node with custom class in .sks file. The name of my Xcode project is "Game play" so  I  write Game Play in module  and Player in custom class, and using that same sks file in Playground causing problem, the name of my playground project is  "MyPlayground", so the module name should be same as project name, so i edit the module field to Myplayground, still not working. So guide me how to change that properly.

答:
1-Open your (.sks) file

2-Select the Player Node.

3-Select Show custom class inspector.

4-Write "MyPlayground_Sources" instead of just MyPlayground.

Body:
I have a class with name (Player.swift). then in my (Scene.swift) class, I declared my object like this.

var player: Player?

then in my initializeGame function, I am doing like this

private func initializeGame() {

    player = childNode(withName: "Player") as? Player!;
    //print NIL
    print(player?.name);
    // initializePlayer()is declared in Player.swift
    player?.initializePlayer();
    print(player?.name);
    //Print NIL
    scoreLabel = childNode(withName: "ScoreLabel") as? SKLabelNode!;
    scoreLabel?.text = "0";
}

I made my ios project in Xcode,  and its working fine,  then i create a Playground project and import all the xcode files in this project, My playground is running properly except the player is not functioning properly. The problem is in associating the Player Node with custom class in .sks file. The name of my Xcode project is "Game play" so  I  write Game Play in module  and Player in custom class, and using that same sks file in Playground causing problem, the name of my playground project is  "MyPlayground", so the module name should be same as project name, so i edit the module field to Myplayground, still not working. So guide me how to change that properly.