问:
How to get the 0th index key values in array object
I have one array object in that object galleryImages i having like json string , in this galleryImages i want display onely the first image value , how can get the only first image value?

My array check below

```<code>$data=Array
(
    [dbResultgallery] => Array
        (
            [0] => stdClass Object
                (
                    [gallery_id] => 1
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 1
                    [description] => gfhfg
                    [galleryImages] => ["1.jpeg","2.jpg"]
                    [reg_on] => 2017-04-03 12:21:59
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [gallery_id] => 2
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 2
                    [description] => sdfdsfsdfsdfsdf
                    [galleryImages] => ["3.jpeg","4.jpg","5.jpg"]
                    [reg_on] => 2017-04-03 12:23:37
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

        )

)
</code>```

now i am using json_decode ,see below my code

```<code>foreach ($dbResultgallery as $gal) :
    $role = json_decode($gal->galleryImages,true);
 endforeach;
</code>```

Now i am getting array format like

```<code>Array
    (
        [0] => 1.jpeg
        [1] => 2.jpg
    )

    Array
    (
        [0] => 3.jpeg
        [1] => 4.jpg
        [2] => 5.jpg
    )
</code>```

Expected results

I need only the first images value like 1.jpeg and 3.jpeg, each array i need only the 0 th key values

Updated code

var_dump(json_decode($gal->galleryImages,true))

```<code>array(2) {

 [0]=>
  string(37) "6be1954c4bec91fe26fb7447fc551782.jpeg"
  [1]=>
  string(36) "153651d989591e76444c92cf037d5ac4.jpg"
}

array(3) {
  [0]=>
  string(37) "f356ceafa408e61cd1c62cfc39752b32.jpeg"
  [1]=>
  string(36) "a4fd29005696d92e0fc4cd3931454609.jpg"
  [2]=>
  string(36) "8eaaecdac1ff219192806acba7978a1b.jpg"
}
</code>```

答:
Change to this:</p>

```<code>$role = json_decode($gal->galleryImages,true)[0];
</code>```

Body:
I have one array object in that object galleryImages i having like json string , in this galleryImages i want display onely the first image value , how can get the only first image value?

My array check below

$data=Array
(
    [dbResultgallery] => Array
        (
            [0] => stdClass Object
                (
                    [gallery_id] => 1
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 1
                    [description] => gfhfg
                    [galleryImages] => ["1.jpeg","2.jpg"]
                    [reg_on] => 2017-04-03 12:21:59
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [gallery_id] => 2
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 2
                    [description] => sdfdsfsdfsdfsdf
                    [galleryImages] => ["3.jpeg","4.jpg","5.jpg"]
                    [reg_on] => 2017-04-03 12:23:37
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

        )

)

now i am using json_decode ,see below my code

foreach ($dbResultgallery as $gal) :
    $role = json_decode($gal->galleryImages,true);
 endforeach;

Now i am getting array format like

Array
    (
        [0] => 1.jpeg
        [1] => 2.jpg
    )

    Array
    (
        [0] => 3.jpeg
        [1] => 4.jpg
        [2] => 5.jpg
    )

Expected results

I need only the first images value like 1.jpeg and 3.jpeg, each array i need only the 0 th key values

Updated code

var_dump(json_decode($gal->galleryImages,true))

array(2) {

 [0]=>
  string(37) "6be1954c4bec91fe26fb7447fc551782.jpeg"
  [1]=>
  string(36) "153651d989591e76444c92cf037d5ac4.jpg"
}

array(3) {
  [0]=>
  string(37) "f356ceafa408e61cd1c62cfc39752b32.jpeg"
  [1]=>
  string(36) "a4fd29005696d92e0fc4cd3931454609.jpg"
  [2]=>
  string(36) "8eaaecdac1ff219192806acba7978a1b.jpg"
}

Body:
Change to this:

$role = json_decode($gal->galleryImages,true)[0];


来源: stackexchange

问:
Can you use es6 import alias syntax for React Components?
I'm trying to do something like the following, however it returns null:

```<code>import { Button as styledButton } from 'component-library'
</code>```

then attempting to render it as:

```<code>import React, { PropTypes } from "react";
import cx from 'classNames';

import { Button as styledButton } from 'component-library';

export default class Button extends React.Component {
    constructor(props){
        super(props)
    }
    render() {
        return (
                <styledButton {...this.props}></styledButton>
        )
    }
}
</code>```

The reason is, I need to import the Button component from a library, and also export a wrapper component with the same name but maintaining the functionality from the imported component.  If I leave it at import { Button } from component library then of course, I get a multiple declaration error.

Any ideas?

答:
Your syntax is valid.  JSX is syntax sugar for React.createElement(type) so as long as type is a valid React type, it can be used in JSX "tags".  If Button is null, your import is not correct.  Maybe Button is a default export from component-library.  Try:

```<code>import {default as StyledButton} from "component-library";
</code>```

The other possibility is your library is using commonjs exports i.e. module.exports = foo.  In this case you can import like this:

```<code>import * as componentLibrary from "component-library";
</code>```

Update

Since this is a popular answer, here a few more tidbits:

export default Button              -> import Button from './button'
                                      const Button = require('./button').default

export const Button                -> import { Button } from './button'
                                      const { Button } = require('./button')

export { Button }                  -> import { Button } from './button'
                                      const { Button } = require('./button')

module.exports.Button              -> import { Button } from './button'
                                      const { Button } = require('./button')

module.exports.Button = Button     -> import { Button } from './button'
                                      const { Button } = require('./button')

module.exports = Button            -> import * as Button from './button'
                                      const Button = require('./button')

```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do something like the following, however it returns null:

import { Button as styledButton } from 'component-library'

then attempting to render it as:

import React, { PropTypes } from "react";
import cx from 'classNames';

import { Button as styledButton } from 'component-library';

export default class Button extends React.Component {
    constructor(props){
        super(props)
    }
    render() {
        return (

        )
    }
}

The reason is, I need to import the Button component from a library, and also export a wrapper component with the same name but maintaining the functionality from the imported component.  If I leave it at import { Button } from component library then of course, I get a multiple declaration error.

Any ideas?

Body:
Your syntax is valid.  JSX is syntax sugar for React.createElement(type) so as long as type is a valid React type, it can be used in JSX "tags".  If Button is null, your import is not correct.  Maybe Button is a default export from component-library.  Try:

import {default as StyledButton} from "component-library";

The other possibility is your library is using commonjs exports i.e. module.exports = foo.  In this case you can import like this:

import * as componentLibrary from "component-library";

Update

Since this is a popular answer, here a few more tidbits:

export default Button              -> import Button from './button'
                                      const Button = require('./button').default

export const Button                -> import { Button } from './button'
                                      const { Button } = require('./button')

export { Button }                  -> import { Button } from './button'
                                      const { Button } = require('./button')

module.exports.Button              -> import { Button } from './button'
                                      const { Button } = require('./button')

module.exports.Button = Button     -> import { Button } from './button'
                                      const { Button } = require('./button')

module.exports = Button            -> import * as Button from './button'
                                      const Button = require('./button')

ContentLicense: CC BY-SA 4.0


问:
Python: How to resolve URLs containing '..'
I need to uniquely identify and store some URLs. The problem is that sometimes they come containing ".." like http://somedomain.com/foo/bar/../../some/url which basically is http://somedomain.com/some/url if I'm not wrong.

Is there a Python function or a tricky way to resolve this URLs ?

答:
Those are file paths.  Look at os.path.normpath:

```<code>>>> import os
>>> os.path.normpath('/foo/bar/../../some/url')
'/some/url'
</code>```

EDIT:

If this is on Windows, your input path will use backslashes instead of slashes.  In this case, you still need os.path.normpath to get rid of the .. patterns (and // and /./ and whatever else is redundant), then convert the backslashes to forward slashes:

```<code>def fix_path_for_URL(path):
    result = os.path.normpath(path)
    if os.sep == '\\':
        result = result.replace('\\', '/')
    return result
</code>```

EDIT 2:

If you want to normalize URLs, do it (before you strip off the method and such) with urlparse module, as shown in the answer to this question.

EDIT 3:

It seems that urljoin doesn't normalize the base path it's given:

```<code>>>> import urlparse
>>> urlparse.urljoin('http://somedomain.com/foo/bar/../../some/url', '')
'http://somedomain.com/foo/bar/../../some/url'
</code>```

normpath by itself doesn't quite cut it either:

```<code>>>> import os
>>> os.path.normpath('http://somedomain.com/foo/bar/../../some/url')
'http:/somedomain.com/some/url'
</code>```

Note the initial double slash got eaten.

So we have to make them join forces:

```<code>def fix_URL(urlstring):
    parts = list(urlparse.urlparse(urlstring))
    parts[2] = os.path.normpath(parts[2].replace('/', os.sep)).replace(os.sep, '/')
    return urlparse.urlunparse(parts)
</code>```

Usage:

```<code>>>> fix_URL('http://somedomain.com/foo/bar/../../some/url')
'http://somedomain.com/some/url'
</code>```

Body:
Those are file paths.  Look at os.path.normpath:

>>> import os
>>> os.path.normpath('/foo/bar/../../some/url')
'/some/url'

EDIT:

If this is on Windows, your input path will use backslashes instead of slashes.  In this case, you still need os.path.normpath to get rid of the .. patterns (and // and /./ and whatever else is redundant), then convert the backslashes to forward slashes:

def fix_path_for_URL(path):
    result = os.path.normpath(path)
    if os.sep == '\\':
        result = result.replace('\\', '/')
    return result

EDIT 2:

If you want to normalize URLs, do it (before you strip off the method and such) with urlparse module, as shown in the answer to this question.

EDIT 3:

It seems that urljoin doesn't normalize the base path it's given:

>>> import urlparse
>>> urlparse.urljoin('http://somedomain.com/foo/bar/../../some/url', '')
'http://somedomain.com/foo/bar/../../some/url'

normpath by itself doesn't quite cut it either:

>>> import os
>>> os.path.normpath('http://somedomain.com/foo/bar/../../some/url')
'http:/somedomain.com/some/url'

Note the initial double slash got eaten.

So we have to make them join forces:

def fix_URL(urlstring):
    parts = list(urlparse.urlparse(urlstring))
    parts[2] = os.path.normpath(parts[2].replace('/', os.sep)).replace(os.sep, '/')
    return urlparse.urlunparse(parts)

Usage:

>>> fix_URL('http://somedomain.com/foo/bar/../../some/url')
'http://somedomain.com/some/url'

ContentLicense: CC BY-SA 2.5


问:
Once off connection to MySQL in netbeans
Is there a way that allows me to connect to a mysql server/database, once, in netbeans, throughout the duration of a program instead of having to connect every single time a query needs to be executed?

答: You can create connection pool or use another implementation. The connection pool should be singleton and to initialize at startup of application.</p>


问:
gtk display modified image
I'm changing an image's pixbuf data in response to a timer event but the changes only appear if I, for example, cover the window with another window and then uncover it. How can I get the changes to appear as soon as I make them?</p>

```<code>#include <gtk/gtk.h>
#include <stdlib.h>

#define ROWS 400
#define COLS 400  // must be divisible by 4
#define BYTES_PER_PIXEL 3

typedef struct {
  GtkImage *image;
  int stride;
} ImageData;

void free_pixels(guchar *pixels, gpointer data) {
  free(pixels);
}

void setrgb(guchar *a, int row, int col, int stride,
            guchar r, guchar g, guchar b) {
  int p = row * stride + col * BYTES_PER_PIXEL;
  a[p] = r; a[p+1] = g; a[p+2] = b;
}

int update_pic(gpointer data) {
  static int row = 0;
  if (row > 100) return FALSE;

  ImageData *id = (ImageData*)data;
  GdkPixbuf *pb = gtk_image_get_pixbuf(id->image);
  guchar *g = gdk_pixbuf_get_pixels(pb);

  for (int c = 0; c < 200; c++)
    setrgb(g, row, c, id->stride, 255, 0, 0);
  row++;

  // this is not enough to get it to show the updated picture
  gtk_widget_queue_draw(GTK_WIDGET(id->image));

  // adding this does not fix it
  while (g_main_context_pending(NULL))
    g_main_context_iteration(NULL, FALSE);

  return TRUE;
}

int main(int argc, char **argv) {
  GtkWidget *window, *image;
  GdkPixbuf *pb;
  guchar *pixels = calloc(ROWS * COLS, BYTES_PER_PIXEL);
  ImageData id;

  gtk_init(&argc, &argv);

  image = gtk_image_new();
  id.image = GTK_IMAGE(image);
  id.stride = COLS * BYTES_PER_PIXEL;  // COLS is divisible by 4
  pb = gdk_pixbuf_new_from_data(
    pixels,
    GDK_COLORSPACE_RGB,     // colorspace
    0,                      // has_alpha
    8,                      // bits-per-sample
    COLS, ROWS,             // cols, rows
    id.stride,              // rowstride
    free_pixels,            // destroy_fn
    NULL                    // destroy_fn_data
  );
  gtk_image_set_from_pixbuf(GTK_IMAGE(image), pb);
  g_object_unref(pb); // should I do this?

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(window), "image");
  gtk_window_set_default_size(GTK_WINDOW(window), COLS, ROWS);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

  gtk_container_add(GTK_CONTAINER(window), image);

  g_timeout_add(250,         // milliseconds
                update_pic,  // handler function
                &id);        // data

  gtk_widget_show_all(window);
  gtk_main();

  return 0;
}
</code>```

答:
GtkImage is not a general drawing widget, for that you would need GtkDrawingArea. I think the simplest way to do what you want with the GtkImage is to update your GdkPixBuf then set the GtkImage with the updated image. I have increased the reference count to the PixBuf, but I am not 100% sure that it is needed, but it does not do any harm.

```<code>#include <gtk/gtk.h>
#include <stdlib.h>

#define ROWS 400
#define COLS 400  // must be divisible by 4
#define BYTES_PER_PIXEL 3

typedef struct {
  GtkImage *image;
  GdkPixbuf *pb;
  int stride;
} ImageData;

void free_pixels(guchar *pixels, gpointer data) {
  free(pixels);
}

void setrgb(guchar *a, int row, int col, int stride,
            guchar r, guchar g, guchar b) {
  int p = row * stride + col * BYTES_PER_PIXEL;
  a[p] = r; a[p+1] = g; a[p+2] = b;
}

int update_pic(gpointer data) {
  static int row = 0;
  if (row > 100) return FALSE;

  ImageData *id = (ImageData*)data;
  guchar *g = gdk_pixbuf_get_pixels(id->pb);

  for (int c = 0; c < 200; c++)
    setrgb(g, row, c, id->stride, 255, 0, 0);
  row++;

  // Update the image, by setting it.
  gtk_image_set_from_pixbuf(GTK_IMAGE(id->image), id->pb);

  return TRUE;
}

int main(int argc, char **argv) {
  GtkWidget *window;
  guchar *pixels = calloc(ROWS * COLS, BYTES_PER_PIXEL);
  ImageData id;

  gtk_init(&argc, &argv);

  id.stride = COLS * BYTES_PER_PIXEL;  // COLS is divisible by 4
  id.pb = gdk_pixbuf_new_from_data(
    pixels,
    GDK_COLORSPACE_RGB,     // colorspace
    0,                      // has_alpha
    8,                      // bits-per-sample
    COLS, ROWS,             // cols, rows
    id.stride,              // rowstride
    free_pixels,            // destroy_fn
    NULL                    // destroy_fn_data
  );
  id.image = GTK_IMAGE(gtk_image_new_from_pixbuf(id.pb));
  g_object_ref(id.pb);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(window), "image");
  gtk_window_set_default_size(GTK_WINDOW(window), COLS, ROWS);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

  gtk_container_add(GTK_CONTAINER(window), image);

  g_timeout_add(250,         // milliseconds
                update_pic,  // handler function
                &id);        // data

  gtk_widget_show_all(window);
  gtk_main();

  g_object_unref(id.pb);

  return 0;
}
</code>```

Title: gtk display modified image

Body:
I'm changing an image's pixbuf data in response to a timer event but the changes only appear if I, for example, cover the window with another window and then uncover it. How can I get the changes to appear as soon as I make them?

#include <gtk/gtk.h>
#include <stdlib.h>

#define ROWS 400
#define COLS 400  // must be divisible by 4
#define BYTES_PER_PIXEL 3

typedef struct {
  GtkImage *image;
  int stride;
} ImageData;

void free_pixels(guchar *pixels, gpointer data) {
  free(pixels);
}

void setrgb(guchar *a, int row, int col, int stride,
            guchar r, guchar g, guchar b) {
  int p = row * stride + col * BYTES_PER_PIXEL;
  a[p] = r; a[p+1] = g; a[p+2] = b;
}

int update_pic(gpointer data) {
  static int row = 0;
  if (row > 100) return FALSE;

  ImageData *id = (ImageData*)data;
  GdkPixbuf *pb = gtk_image_get_pixbuf(id->image);
  guchar *g = gdk_pixbuf_get_pixels(pb);

  for (int c = 0; c < 200; c++)
    setrgb(g, row, c, id->stride, 255, 0, 0);
  row++;

  // this is not enough to get it to show the updated picture
  gtk_widget_queue_draw(GTK_WIDGET(id->image));

  // adding this does not fix it
  while (g_main_context_pending(NULL))
    g_main_context_iteration(NULL, FALSE);

  return TRUE;
}

int main(int argc, char **argv) {
  GtkWidget *window, *image;
  GdkPixbuf *pb;
  guchar *pixels = calloc(ROWS * COLS, BYTES_PER_PIXEL);
  ImageData id;

  gtk_init(&argc, &argv);

  image = gtk_image_new();
  id.image = GTK_IMAGE(image);
  id.stride = COLS * BYTES_PER_PIXEL;  // COLS is divisible by 4
  pb = gdk_pixbuf_new_from_data(
    pixels,
    GDK_COLORSPACE_RGB,     // colorspace
    0,                      // has_alpha
    8,                      // bits-per-sample
    COLS, ROWS,             // cols, rows
    id.stride,              // rowstride
    free_pixels,            // destroy_fn
    NULL                    // destroy_fn_data
  );
  gtk_image_set_from_pixbuf(GTK_IMAGE(image), pb);
  g_object_unref(pb); // should I do this?

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(window), "image");
  gtk_window_set_default_size(GTK_WINDOW(window), COLS, ROWS);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

  gtk_container_add(GTK_CONTAINER(window), image);

  g_timeout_add(250,         // milliseconds
                update_pic,  // handler function
                &id);        // data

  gtk_widget_show_all(window);
  gtk_main();

  return 0;
}

Body:
GtkImage is not a general drawing widget, for that you would need GtkDrawingArea. I think the simplest way to do what you want with the GtkImage is to update your GdkPixBuf then set the GtkImage with the updated image. I have increased the reference count to the PixBuf, but I am not 100% sure that it is needed, but it does not do any harm.

#include <gtk/gtk.h>
#include <stdlib.h>

#define ROWS 400
#define COLS 400  // must be divisible by 4
#define BYTES_PER_PIXEL 3

typedef struct {
  GtkImage *image;
  GdkPixbuf *pb;
  int stride;
} ImageData;

void free_pixels(guchar *pixels, gpointer data) {
  free(pixels);
}

void setrgb(guchar *a, int row, int col, int stride,
            guchar r, guchar g, guchar b) {
  int p = row * stride + col * BYTES_PER_PIXEL;
  a[p] = r; a[p+1] = g; a[p+2] = b;
}

int update_pic(gpointer data) {
  static int row = 0;
  if (row > 100) return FALSE;

  ImageData *id = (ImageData*)data;
  guchar *g = gdk_pixbuf_get_pixels(id->pb);

  for (int c = 0; c < 200; c++)
    setrgb(g, row, c, id->stride, 255, 0, 0);
  row++;

  // Update the image, by setting it.
  gtk_image_set_from_pixbuf(GTK_IMAGE(id->image), id->pb);

  return TRUE;
}

int main(int argc, char **argv) {
  GtkWidget *window;
  guchar *pixels = calloc(ROWS * COLS, BYTES_PER_PIXEL);
  ImageData id;

  gtk_init(&argc, &argv);

  id.stride = COLS * BYTES_PER_PIXEL;  // COLS is divisible by 4
  id.pb = gdk_pixbuf_new_from_data(
    pixels,
    GDK_COLORSPACE_RGB,     // colorspace
    0,                      // has_alpha
    8,                      // bits-per-sample
    COLS, ROWS,             // cols, rows
    id.stride,              // rowstride
    free_pixels,            // destroy_fn
    NULL                    // destroy_fn_data
  );
  id.image = GTK_IMAGE(gtk_image_new_from_pixbuf(id.pb));
  g_object_ref(id.pb);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(window), "image");
  gtk_window_set_default_size(GTK_WINDOW(window), COLS, ROWS);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

  gtk_container_add(GTK_CONTAINER(window), image);

  g_timeout_add(250,         // milliseconds
                update_pic,  // handler function
                &id);        // data

  gtk_widget_show_all(window);
  gtk_main();

  g_object_unref(id.pb);

  return 0;
}


问:
Tesseract OCR not recognizing any character
I am working on a project that requires character recognition as a part of it. I am using a handwriting dataset by IAM, so all the images are more or less taken in the same conditions. I am using pictures of words that have been provided by the dataset and following these steps

Binarizing and thresholding

Dividing the word into the characters constituting it

Resizing the extracted character

Letting tesseract figure out what the English alphabet is

What I'm trying to achieve is to store characters of a person's document in folders categorized by the alphabet and maybe form a template from them later on. For this I need to know which character it is.

Here's what I get as a result -

All the characters are properly segmented (for most cases). This is more of a tesseract question than it is a python question, but I'm using python to write the script and calling tesseract through the pytesseract wrapper.

I'm using OpenCV to manipulate the image. Images of these letter matrices are sent as input to tesseract (handled by pytesseract). The input is not an issue, I assure you. Is there anything else I need to do for tesseract to work?

None of these characters are recognized.

答: Tesseract doesn't support handwritten text well. You should try either ABBYY OCR for that or alternative free libraries like Lipi Toolkit.</p>


问:
IIS express doesn't start but Kestrel web server instead
My application have been working well for weeks. Today I possibly did something wrong and IIS express is not starting any more (and no errors in the event log) but Kestrel appears in a command window saying it is listening for connections on 5000th port.

How to fix it and get IIS express back?

Startup.cs:

```<code>public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        if (env.IsDevelopment())
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();

        // Add functionality to inject IOptions<T>
        services.AddOptions();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseDeveloperExceptionPage();
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
</code>```

答: Okay, I still do not have any logical explanation but I accidentally fixed it. I discovered that it work on any different TCP port. It has been working for all times on 46394 but now can't start on it but starts well on any different. I netstat'ed and saw no concurrent listener on that port but for some reason iis express no more works on it. The worst thing is that no any error logs on that. Anyways it works now.</p>

Body:
My application have been working well for weeks. Today I possibly did something wrong and IIS express is not starting any more (and no errors in the event log) but Kestrel appears in a command window saying it is listening for connections on 5000th port.

How to fix it and get IIS express back?

Startup.cs:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        if (env.IsDevelopment())
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();

        // Add functionality to inject IOptions<T>
        services.AddOptions();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseDeveloperExceptionPage();
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}


问:
Cucumber reuse value from previously run scenario
I am trying to reuse a value that was created during the previously run scenario. I am not sure if there is a way in cucumber to make a value available across scenarios.
For instance:

1st scenario:

Given inputOfA

When A is created

Then A is returned

And A contains an Id

2nd Scenario:

Given IdOfA

When customer gets A by Id

Then A is returned.

For the 2nd scenario, it would be great if I can get the Id created from the first without having to persist it anywhere.
Can any of you let me know if this is possible using cucumber or do I have to persist the Id created in the first scenario?

答:
This is not something you want.

It would require the scenarios to be executed in a specific order. The scenario execution order isn't specified. It may even be random.

What you want scenarios that are independent. Scenarios you can execute in any order.

If you want to use the result from one scenario in a future scenario, you want to setup the second scenario to execute the same thing as the previous scenario should have done. This may feel like duplication and maybe it is. But the usage of BDD is to drive the implementation. The first scenario was used to drive some behaviour. The second scenario should be used to drive another behaviour.

It is possible that the first scenario can be deleted when the second is implemented. If it is redundant, remove it.

But whatever you do, avoid the path of scenarios that depends on each other. It will only lead to a bad place with seemingly random errors occurring.


问:
Safari not redrawing elements hidden by clip-path
I came across a strange safari bug that made some elements invisible until they where hovered over.

This was caused by the element previously being hidden with clip (clip-path). Safari only redrew them after a hover effect changed their design and thus forcing safari to redraw the object.

```<code>.logo-container {
  position: absolute;
  top: 0px;
  clip: rect(0, auto, auto, 0);
  clip-path: inset(0, auto, auto, 0);
}
</code>```

答:
To solve this i used a repeating css animation to force safari to redraw the elements a few times each second.

```<code>@-webkit-keyframes mymove {
from {top: 0px;}
to {top: 0.01px;}
}

.logo-container {
  position: absolute;
  top: 0px;
  clip: rect(0, auto, auto, 0);
  clip-path: inset(0, auto, auto, 0);
  -webkit-animation: mymove 0.1s infinite; /* Safari 4.0 - 8.0 */
}
</code>```

Now the element is redrawn and visibility works as intended.

Please answer this question if there are any better solutions to this problem :)

Body:
I came across a strange safari bug that made some elements invisible until they where hovered over.

This was caused by the element previously being hidden with clip (clip-path). Safari only redrew them after a hover effect changed their design and thus forcing safari to redraw the object.

.logo-container {
  position: absolute;
  top: 0px;
  clip: rect(0, auto, auto, 0);
  clip-path: inset(0, auto, auto, 0);
}

Body:
To solve this i used a repeating css animation to force safari to redraw the elements a few times each second.

@-webkit-keyframes mymove {
from {top: 0px;}
to {top: 0.01px;}
}

.logo-container {
  position: absolute;
  top: 0px;
  clip: rect(0, auto, auto, 0);
  clip-path: inset(0, auto, auto, 0);
  -webkit-animation: mymove 0.1s infinite; /* Safari 4.0 - 8.0 */
}

Now the element is redrawn and visibility works as intended.

Please answer this question if there are any better solutions to this problem :)


问:
ArrayList's instantiating of the inner T[] array
I've found out that if you have a generic class with an array that depends of type parameter of that class, you can't initialize that array in a usual way:

```<code>class Foo<T>  {
    private T[] a;

    Foo()  {
       a=new T[5]; //doesn't compile
    }
}
</code>```

You can only do something like this:

```<code>class Foo<T>  {
        private T[] a;

        Foo(T[] a)  {
           this.a=a;
        }
    }
</code>```

But this code is possible:

```<code>ArrayList<Integer> list=new ArrayList<>();
</code>```

Why? How does the ArrayList overcome that thing? I've looked into its code but couldn't figure it out. It seems like it just stores things in Object[] array which seems wrong.

答:
Consider this as an analogy:

You own a pencil company. You drive around with pencils in your van.

You could put flowers in your van: it's a van, after all, so you could put anything you want (that fits) in there. Baseballs, gorillas, helium balloons.

But you choose not to: you're a pencil company, so all you put into your van is pencils. If your friend from the burger company asks you to put some burger patties in your van, you will say no: this van is only for pencils.

So, when you come to take something out of your van, you know it's going to be a pencil, because you made sure the only thing that went in through those doors was a pencil.

And so it is with an ArrayList<T>: you could store anything in that Object[], but you don't: you can only store Ts in there, because you can only add things to it through the add(T) or addAll(Collection<? extends T>) methods.

So it doesn't matter that your elements are being stored in an Object[], rather than more-specifically typed array: the only things that you'll get out of an ArrayList<T> - via its get() (etc) methods - are instances of T, or one of its subtypes.

Body:
I've found out that if you have a generic class with an array that depends of type parameter of that class, you can't initialize that array in a usual way:

class Foo<T>  {
    private T[] a;

    Foo()  {
       a=new T[5]; //doesn't compile
    }
}

You can only do something like this:

class Foo<T>  {
        private T[] a;

        Foo(T[] a)  {
           this.a=a;
        }
    }

But this code is possible:

ArrayList<Integer> list=new ArrayList<>();

Why? How does the ArrayList overcome that thing? I've looked into its code but couldn't figure it out. It seems like it just stores things in Object[] array which seems wrong.


问:
Inner / static nested classes in Java - outer class' name
I'd like to ask when it's required to explicitly write the name of the outer class when referring to the inner class or static nested class.

Ex:

```<code>class B {
    static class Inner {
        int a = 10;
    }
}

class Test extends B {
    public static void main(String[] args) {
        Test t = new Test();
        Inner obj = new Inner();
        System.out.println(obj.a);
    }
}
</code>```

What I'd like to ask is under which circumstances it's needed to write:

```<code>B.Inner obj = new B.Inner();
</code>```

instead of

```<code>Inner obj = new Inner();
</code>```

答: If you are inside the scope of class B then new Inner() can be used. Outside of class B new B.Inner() must be used.

Body:
I'd like to ask when it's required to explicitly write the name of the outer class when referring to the inner class or static nested class.

Ex:

class B {
    static class Inner {
        int a = 10;
    }
}

class Test extends B {
    public static void main(String[] args) {
        Test t = new Test();
        Inner obj = new Inner();
        System.out.println(obj.a);
    }
}

What I'd like to ask is under which circumstances it's needed to write:

B.Inner obj = new B.Inner();

instead of

Inner obj = new Inner();


问:
How to install luasql on Linux CentOS 7?
I tried to install luasql on my Linux CentOS 7 computer with this command:

luarocks install luasql-postgres

but unfortunately I got the following error:

```<code>Installing https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/luasql-postgres-2.3.5-2.rockspec...
Using https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/luasql-postgres-2.3.5-2.rockspec... switching to 'build' mode

Error: Could not find header file for PGSQL
  No file libpq-fe.h in /usr/local/include
  No file libpq-fe.h in /usr/include
You may have to install PGSQL in your system and/or pass PGSQL_DIR or PGSQL_INCDIR to the luarocks command.
Example: luarocks install luasql-postgres PGSQL_DIR=/usr/local
</code>```

I tried then to run the last line luarocks install luasql-postgres PGSQL_DIR=/usr/local but I had no improvement...

What should I do?

答:
The Lua bits of this are fine; the error you're getting is that the C bits aren't there.

In general, when you are interfacing with a C library, you need to make sure you have the C library's -dev (for Debianish) or -devel (for Redhatish) package installed.

In your case, you can probably just do the following as root on your box:

```<code>yum install postgresql-devel
</code>```

...and then attempt your luarocks install again.

Or, you could try the OS native package instead:

```<code>yum install lua-sql-postgresql
</code>```

I personally prefer using the OS packages for stable Lua libs that don't change much, but it's your call...

Body:
I tried to install luasql on my Linux CentOS 7 computer with this command:

luarocks install luasql-postgres

but unfortunately I got the following error:

Installing https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/luasql-postgres-2.3.5-2.rockspec...
Using https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/luasql-postgres-2.3.5-2.rockspec... switching to 'build' mode

Error: Could not find header file for PGSQL
  No file libpq-fe.h in /usr/local/include
  No file libpq-fe.h in /usr/include
You may have to install PGSQL in your system and/or pass PGSQL_DIR or PGSQL_INCDIR to the luarocks command.
Example: luarocks install luasql-postgres PGSQL_DIR=/usr/local

I tried then to run the last line luarocks install luasql-postgres PGSQL_DIR=/usr/local but I had no improvement...

What should I do?

Body:
The Lua bits of this are fine; the error you're getting is that the C bits aren't there.

In general, when you are interfacing with a C library, you need to make sure you have the C library's -dev (for Debianish) or -devel (for Redhatish) package installed.

In your case, you can probably just do the following as root on your box:

yum install postgresql-devel

...and then attempt your luarocks install again.

Or, you could try the OS native package instead:

yum install lua-sql-postgresql

I personally prefer using the OS packages for stable Lua libs that don't change much, but it's your call...


问:
Add files of one type to one zip file and clean up using PowerShell
How can I create a PowerShell script to get all files of type .BAK and add them to a ZIP file (can I have my PowerShell script take a parameter when called to control the name of the ZIP file that will house all the .bak files? Deleting the .bak files once successfully zipped up.

The current directory is:

```
C:\SQLBackups
+- a.bak
+- b.bak
`- c.bak
```

Goal is:

```
C:\SQLBackups
`- v4.14.4_backups.zip
```

I'm pretty new to PowerShell, and I have currently the script zipping every .bak file into a .zip file which is no good.

$filePath = "C:\SQLBackups\"
$bak = Get-ChildItem -Recurse -Path $filePath |
       Where-Object { $_.Extension -eq ".bak" }

if (-not (Test-Path "$env:C:\Program Files\7-Zip\7z.exe")) {
  throw "$env:Program Files (x86)\7-Zip\7z.exe needed"
}
Set-Alias sz "$env:ProgramFiles\7-Zip\7z.exe"

foreach ($file in $bak) {
  $name = $file.Name
  $directory = $file.DirectoryName
  $zipfile = $name.Replace(".bak", ".zip")
  sz a -t7z "$directory\$zipfile" "$directory\$name"
}
```

<p>The current output would be:</p>

```
a.bak
a.zip
b.bak
b.zip
c.bak
c.zip
```

答:
If you're using PowerShell v5 then you can use the Compress-Archive function instead of using 7zip:

```<code>$filePath = "C:\SQLBackups"
$ZipName = "v4.14.4_backups.zip"

$BakFiles = Get-ChildItem -Recurse -Path $filePath -Include *.bak

$BakFiles | Compress-Archive -DestinationPath "$filePath\$ZipName"
$BakFiles | Remove-Item -Force
</code>```

Body:
How can I create a PowerShell script to get all files of type .BAK and add them to a ZIP file (can I have my PowerShell script take a parameter when called to control the name of the ZIP file that will house all the .bak files? Deleting the .bak files once successfully zipped up.

The current directory is:

C:\SQLBackups
+- a.bak
+- b.bak
`- c.bak

Goal is:

C:\SQLBackups
`- v4.14.4_backups.zip

I'm pretty new to PowerShell, and I have currently the script zipping every .bak file into a .zip file which is no good.

$filePath = "C:\SQLBackups\"
$bak = Get-ChildItem -Recurse -Path $filePath |
       Where-Object { $_.Extension -eq ".bak" }

if (-not (Test-Path "$env:C:\Program Files\7-Zip\7z.exe")) {
  throw "$env:Program Files (x86)\7-Zip\7z.exe needed"
}
Set-Alias sz "$env:ProgramFiles\7-Zip\7z.exe"

foreach ($file in $bak) {
  $name = $file.Name
  $directory = $file.DirectoryName
  $zipfile = $name.Replace(".bak", ".zip")
  sz a -t7z "$directory\$zipfile" "$directory\$name"
}

The current output would be:

a.bak
a.zip
b.bak
b.zip
c.bak
c.zip

Body:
If you're using PowerShell v5 then you can use the Compress-Archive function instead of using 7zip:

$filePath = "C:\SQLBackups"
$ZipName = "v4.14.4_backups.zip"

$BakFiles = Get-ChildItem -Recurse -Path $filePath -Include *.bak

$BakFiles | Compress-Archive -DestinationPath "$filePath\$ZipName"
$BakFiles | Remove-Item -Force


问:
Visual studio 2015 no Basic page when adding new item?
So I want to start doing c# from head first c# 3rd edition, the big problem is that I can't find neither blank page and I saw alot of people saying that using WPF is okay, but when I try and add a new item I see nothing related to c# or what I actually need, what I need is a basic page, here is how it looks like:

now the problem is I can't fix it to show me what I need only for c# I tried, community,enterprise.
Does anyone have any idea of how to fix this?

答:
You seem to be trying to add an item at the solution level. Note that in the screenshot it says "Add New Item - Solution Items". This will create files that exist in the solution, but no belong to any particular project, not affecting the output of compilation of any project. That's the reason why you don't see anything code related, you're not editing a code project.

Instead, right click on the project item on the solution explorer (not on the top solution item) and add a new item there. The selection of options will be specific to the type of code there. For example for WPF you'll get all XAML-based file types, or for Winforms you'll see forms and control classes.


问:
POST Variable Array and filter_input
While using filter_input, I'm not able to pull in a POST array variable. The POST input:

```<code>type              => 'container',
action            => 'edit',
data[display]     => 1,
data[query_limit] => 100
</code>```

I can access the data variable from the $_POST superglobal correctly as an array, but the filter_input function returns nothing:

```<code>$data   = $_POST['data']; // Working, woot
$data   = filter_input(INPUT_POST, 'data'); // returns null, should return array
$action = filter_input(INPUT_POST, 'action'); // returns "edit" (correctly)
</code>```

Is it not possible to use filter_input for a POST array variable?

答:
I have used FormData in javascript and post the fields with jquery ajax.
The way I receive all these field is:

```<code>$arrFields = array('field1','field2','field2','field3', 'field4','field5');
foreach($arrFields as $field){
   $params[$field] = filter_input(INPUT_POST, $field, FILTER_DEFAULT);
}
var_dump($params);
</code>```

Then I will get all the data into an array which I can pass on...

Title: POST Variable Array and filter_input

Body:
While using filter_input, I'm not able to pull in a POST array variable. The POST input:

type              => 'container',
action            => 'edit',
data[display]     => 1,
data[query_limit] => 100

I can access the data variable from the $_POST superglobal correctly as an array, but the filter_input function returns nothing:

$data   = $_POST['data']; // Working, woot
$data   = filter_input(INPUT_POST, 'data'); // returns null, should return array
$action = filter_input(INPUT_POST, 'action'); // returns "edit" (correctly)

Is it not possible to use filter_input for a POST array variable?

Body:
I have used FormData in javascript and post the fields with jquery ajax.
The way I receive all these field is:

$arrFields = array('field1','field2','field2','field3', 'field4','field5');
foreach($arrFields as $field){
   $params[$field] = filter_input(INPUT_POST, $field, FILTER_DEFAULT);
}
var_dump($params);

Then I will get all the data into an array which I can pass on...


问:
Why the following error is showing while importing an project?
Why the following error is showing in android studio while importing a external project (https://github.com/udacity/ud839_Miwok/tree/Starter-code)?

Error: Gradle 'ud839_Miwok-Starter-code' project refresh failed

Error:Content is not allowed in prolog.

答:
Try to clean and to rebuild your project. This is located at the Build Menu.

If this does not help, please show more details like your project tree, especially your resource diretory. It may also be that you created something at a place where it is not allowed to be.


问:
Rails Meta Tags, undefined method `set_meta_tags' in Rails 4
Using the gem Meta Tags

The documentation states to put this in the controller:

```<code>set_meta_tags :title => 'Member Login',
              :description => 'Member login page.',
              :keywords => 'Site, Login, Members'
</code>```

But, thats what I did, not sure if I need to have something wrapped around it:

```<code>class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to main_app.root_path, :alert => exception.message
  end
  protect_from_forgery with: :null_session
  before_filter :configure_devise_params, if: :devise_controller?

  set_meta_tags :og => {
                    :title    => 'The Rock',
                    :type     => 'video.movie',
                    :url      => 'http://www.imdb.com/title/tt0117500/',
                    :image    => 'http://ia.media-imdb.com/rock.jpg',
                    :video    => {
                      :director => 'http://www.imdb.com/name/nm0000881/',
                      :writer   => ['http://www.imdb.com/name/nm0918711/', 'http://www.imdb.com/name/nm0177018/']
                    }
                  }
end
</code>```

Then in my view:

```<code><%= display_meta_tags %>
</code>```

But I'm getting the error undefined method 'set_meta_tags'

答:
I usually place it in the application controller to keep the view tidy.

# app/config/application.rb

# ...

before_action :please_set_meta_tags

def please_set_meta_tags
  set_meta_tags title:       'website name',
                description: 'website description',
                og: {
                  title:     'website name',
                  type:      'website',
                  url:       request.original_url,
                  image:     { _: view_context.image_url('myimage1.jpg'), width: 1200, height: 630 },
                             { _: view_context.image_url('myimage2.jpg'), width: 1200, height: 630 }
                }
end
# ...
```

<pre class="lang-rb prettyprint-override"><code># app/views/layouts/application.html.erb

...
<head>
  <%= display_meta_tags %>
  ...
</code>```

I use view_context.image_url() instead of image_url() to get the image as I'm not in a view (therefore view_context is needed).

And remember to restart the server once you installed the gem! (it might be so obvious that you forget it)

Body:
Using the gem Meta Tags

The documentation states to put this in the controller:

set_meta_tags :title => 'Member Login',
              :description => 'Member login page.',
              :keywords => 'Site, Login, Members'

But, thats what I did, not sure if I need to have something wrapped around it:

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to main_app.root_path, :alert => exception.message
  end
  protect_from_forgery with: :null_session
  before_filter :configure_devise_params, if: :devise_controller?

  set_meta_tags :og => {
                    :title    => 'The Rock',
                    :type     => 'video.movie',
                    :url      => 'http://www.imdb.com/title/tt0117500/',
                    :image    => 'http://ia.media-imdb.com/rock.jpg',
                    :video    => {
                      :director => 'http://www.imdb.com/name/nm0000881/',
                      :writer   => ['http://www.imdb.com/name/nm0918711/', 'http://www.imdb.com/name/nm0177018/']
                    }
                  }
end

Then in my view:

<%= display_meta_tags %>

But I'm getting the error undefined method 'set_meta_tags'

Body:
I usually place it in the application controller to keep the view tidy.

# app/config/application.rb

# ...

before_action :please_set_meta_tags

def please_set_meta_tags
  set_meta_tags title:       'website name',
                description: 'website description',
                og: {
                  title:     'website name',
                  type:      'website',
                  url:       request.original_url,
                  image:     { _: view_context.image_url('myimage1.jpg'), width: 1200, height: 630 },
                             { _: view_context.image_url('myimage2.jpg'), width: 1200, height: 630 }
                }
end
# ...

# app/views/layouts/application.html.erb

...
<head>
  <%= display_meta_tags %>
  ...

I use view_context.image_url() instead of image_url() to get the image as I'm not in a view (therefore view_context is needed).

And remember to restart the server once you installed the gem! (it might be so obvious that you forget it)


问:
Fixed point implementation of Kalman filter behaving strangely
I have implemented several implementations of a linear Kalman filter tracking a sine wave. I have a Python and a C implementation that both work.

However I have also developed a version that uses a fixed point implementation and it works, but I am seeing an odd effect where it initially seems to fit and then diverges from the output of the other Kalman filter codes.

See the plots below:

I was wondering if anyone has some intuition for what might be going wrong in the fixed point implementation?

答:
Hopefully you're long past this problem now, but, in case not - here's what I usually have to do with a fixed-point KF.  Problems arise from the limited range of values available. If we set the fixed-point such that the initial covariance matrix is representable, we often do not have a lot of bits to the right of the decimal point and to represent the gain and state update for the solution once it begins to converge.

That's a long way of stating the obvious - we like floating point for filters - and in particular since the covariance matrix is squared standard deviations - it is stepping through orders-of-magnitude 'quickly' if you will, while the state update is not squared - so we are in a bind trying to select a single fixed-point location that allows us to reasonably represent the squared covariance elements and the not-squared state update.

So I often end-up with a gear shift or two - I've used up to  '5-speed' fixed-point KF's in the past.  When I get to the end of the time update step - I have the largest values for the covariance I am going to get for that cycle.  Measurement processing will only decrease the covariance.  If my Kalman filter fixed-point representation is more than 2 bits larger than I need for the covariance, I shift left and change the fixed-point on the fly.  This keeps a reasonable number of bits for the gain and state update values.

This is in effect a poor-man's floating point, but I have only one decimal point location for all the filter elements.  I use some hysteresis to keep from shifting all the time.  When I get that working properly - I cannot distinguish the fixed and floating point results - which is more or less what we should expect as it's "floating the point".


问:
Looking for a short term fix for limiting record display number without :limit => 10
I am wondering if there is a way to complete this hack that I am trying to do with my Ruby on Rails app. I'm having trouble with some associations and I can't find the solution. You can see that question here.

In the mean time I am wanting to limit the display of records to a number like 10 but I don't want to do it in the controller through the :limit => 10 manner because I need to loop through all the records. I'm not even sure if this is possible but thought I would ask.

My view code is:

```<code><% @comments.each do |comment| %>
  <% if comment.workout.user_id == current_user.id %><br/>
    <%= link_to (comment.user.username), comment.user %> <br/>
    <%= time_ago_in_words(comment.created_at) %> <br/>
    <%= link_to (comment.workout.title), comment.workout %><br/>
    <%= sanitize(simple_format(comment.body), :tags => %w(p)) %>
  <% end %>
<% end %>
</code>```

My controller is simply calling

```<code>@comments = Comment.all(:order => "created_at DESC")
</code>```

答:
Is the will-paginate gem the droid you're looking for?

After adding the gem to your environment.rb and installing it, you would modify your controller so that it calls paginate rather than find or all:

```<code>@comments = Comment.paginate(:all, :order => "created_at DESC", :per_page => 10)
</code>```

And then in your view, add the pagination controls (links to advance a page, go back a page, &c.)

```<code><%= will_paginate @comments %>
</code>```

Body:
I am wondering if there is a way to complete this hack that I am trying to do with my Ruby on Rails app. I'm having trouble with some associations and I can't find the solution. You can see that question here.

In the mean time I am wanting to limit the display of records to a number like 10 but I don't want to do it in the controller through the :limit => 10 manner because I need to loop through all the records. I'm not even sure if this is possible but thought I would ask.

My view code is:

<% @comments.each do |comment| %>
  <% if comment.workout.user_id == current_user.id %>

    <%= link_to (comment.user.username), comment.user %>

    <%= time_ago_in_words(comment.created_at) %>

    <%= link_to (comment.workout.title), comment.workout %>

    <%= sanitize(simple_format(comment.body), :tags => %w(p)) %>
  <% end %>
<% end %>

My controller is simply calling

@comments = Comment.all(:order => "created_at DESC")

Body:
Is the will-paginate gem the droid you're looking for?

After adding the gem to your environment.rb and installing it, you would modify your controller so that it calls paginate rather than find or all:

@comments = Comment.paginate(:all, :order => "created_at DESC", :per_page => 10)

And then in your view, add the pagination controls (links to advance a page, go back a page, &c.)

<%= will_paginate @comments %>


问:
Filter rows based on uniqueness of a column
I'm sure I'm overthinking a problem again. All I'm trying to achieve is a result array that only contains rows where the data in first column is unique and sorted.

So using an example array (say sheet 'DB')

```<code>A     B     C     D
Me    Pink  Car   Top
Me    Blue  Bike  Middle
You   Pink  Car   Bottom
They  Pink  Bike  Bottom
You   Blue  Bike  Top
Them  Red   Car   Middle
Them  Blue  Car   Top
Me          Bike  Middle
You         Car
Us                Top
</code>```

Results in another sheet (say 'Results')

```<code>A     B     C     D
Me    Pink  Car   Top
Them  Red   Car   Middle
They  Pink  Bike  Bottom
Us                Top
You   Pink  Car   Bottom
</code>```

Ideally a single formula will go in 'Results!A1'.

Ignoring the SORT element for the moment, this sledgehammer only works for small arrays

```<code>=filter(A1:D13,mmult((A1:D13=transpose(A1:D13))*(row(A1:D13)>=transpose(row(A1:D13))),row(A1:D13)^0)=1)
</code>```

but my DB table is 25,000+ rows (10+ wide) so seems to break the GS 2m cell limit (>matrix 1414*1414) - large arrays produce a 'Column expected 21,414, actual column 1' type error - rather than a more useful 'You broke a limit!'

Note. The above solution works best so far because the originating data is not sorted.

I've tried QUERY() but again, breaks on the UNIQUE() element.

```<code>=Query('DB!A2:I, "select * where Col1 matches '"&UNIQUE(DB!A2:A)&"'",0))
</code>```

error 'No Col1/A'

UNIQUE(...) works fine in terms of stripping duplicates in the key column but how do I then express the rest of the row to each unique entry?

UNIQUE({A1:A;FILTER({A1:D...)}) results in 'No values found'

I was hoping a simple SORT(UNIQUE(...)) would be the ideal solution but alas it seems I'm looking in the wrong haystack.

I've also tried the following structures but either the length of time taken to process or my syntax has crippled any result.

The resulting array btw will just be a helper array for a more rational user sheet that will use IMPORTRANGE() on the result above.

thx to Yogi-Anand for the first solution.

答:
This should do the trick for the above data:

```<code>=sort(iferror(ARRAYFORMULA(VLOOKUP(UNIQUE(A2:A),A2:D,{1,2,3,4},false)),""),1,true)
</code>```

Gives the following result:

```<code>Me      Pink    Car     Top
Them    Red     Car     Middle
They    Pink    Bike    Bottom
Us                      Top
You     Pink    Car     Bottom
</code>```

if you have more columns you need to be included in your vlookup you can add it like so:

```<code>VLOOKUP(UNIQUE(A2:A),A2:(till which Column),{1,2,3,4,5... (Add your columns here)},false
</code>```

However, note Vlookup will return the first row corresponding to the match in Column A. That means the order of the data in the input array matters.

Hope that helps!

Body:
I'm sure I'm overthinking a problem again. All I'm trying to achieve is a result array that only contains rows where the data in first column is unique and sorted.

So using an example array (say sheet 'DB')

A     B     C     D
Me    Pink  Car   Top
Me    Blue  Bike  Middle
You   Pink  Car   Bottom
They  Pink  Bike  Bottom
You   Blue  Bike  Top
Them  Red   Car   Middle
Them  Blue  Car   Top
Me          Bike  Middle
You         Car
Us                Top

Results in another sheet (say 'Results')

A     B     C     D
Me    Pink  Car   Top
Them  Red   Car   Middle
They  Pink  Bike  Bottom
Us                Top
You   Pink  Car   Bottom

Ideally a single formula will go in 'Results!A1'.

Ignoring the SORT element for the moment, this sledgehammer only works for small arrays

=filter(A1:D13,mmult((A1:D13=transpose(A1:D13))*(row(A1:D13)>=transpose(row(A1:D13))),row(A1:D13)^0)=1)

but my DB table is 25,000+ rows (10+ wide) so seems to break the GS 2m cell limit (>matrix 1414*1414) - large arrays produce a 'Column expected 21,414, actual column 1' type error - rather than a more useful 'You broke a limit!'

Note. The above solution works best so far because the originating data is not sorted.

I've tried QUERY() but again, breaks on the UNIQUE() element.

=Query('DB!A2:I, "select * where Col1 matches '"&UNIQUE(DB!A2:A)&"'",0))

error 'No Col1/A'

UNIQUE(...) works fine in terms of stripping duplicates in the key column but how do I then express the rest of the row to each unique entry?

UNIQUE({A1:A;FILTER({A1:D...)}) results in 'No values found'

I was hoping a simple SORT(UNIQUE(...)) would be the ideal solution but alas it seems I'm looking in the wrong haystack.

I've also tried the following structures but either the length of time taken to process or my syntax has crippled any result.

The resulting array btw will just be a helper array for a more rational user sheet that will use IMPORTRANGE() on the result above.

thx to Yogi-Anand for the first solution.

Body:
This should do the trick for the above data:

=sort(iferror(ARRAYFORMULA(VLOOKUP(UNIQUE(A2:A),A2:D,{1,2,3,4},false)),""),1,true)

Gives the following result:

Me      Pink    Car     Top
Them    Red     Car     Middle
They    Pink    Bike    Bottom
Us                      Top
You     Pink    Car     Bottom

if you have more columns you need to be included in your vlookup you can add it like so:

VLOOKUP(UNIQUE(A2:A),A2:(till which Column),{1,2,3,4,5... (Add your columns here)},false

However, note Vlookup will return the first row corresponding to the match in Column A. That means the order of the data in the input array matters.

Hope that helps!


问:
What argument should I use with SqlFunctions.DateName to get the month like "MM"?
Is it possible with SqlFunctions.DateName (or any other SqlFunctions method) to get the month in two digits? eg: August --> "08"

I tried all these:

```<code>  test1 = SqlFunctions.DateName("MM", e.Date),
  test2 = SqlFunctions.DateName("m", e.Date),
  test3 = SqlFunctions.DateName("mm", e.Date),
</code>```

But they all return "August"

There is also SqlFunctions.DatePart but it returns an integer, eg: SqlFunctions("mm", e.Date) returns the integer 8

答:
You can do it like this:

```<code>.Select(c => DbFunctions.Right("00" + c.Date.Month, 2))
</code>```

RIGHT (SQL function) returns x rightmost characters from given string (2 in this case) and we prepend month with 2 zeroes so that if month has 1 digit, result is "00x" so "0x" is returned, and when month has 2 digits - result is "00xx" and "xx" is returned.

The resulting sql query will be just:

```<code>RIGHT(N'00' + CASE WHEN (DATEPART (month, [Extent1].[Date]) IS NULL)
    THEN N'' ELSE  CAST( DATEPART (month, [Extent1].[Date])
</code>```

As a bonus, this code is not sql-server specific and will work with other providers.

Body:
Is it possible with SqlFunctions.DateName (or any other SqlFunctions method) to get the month in two digits? eg: August --> "08"

I tried all these:

  test1 = SqlFunctions.DateName("MM", e.Date),
  test2 = SqlFunctions.DateName("m", e.Date),
  test3 = SqlFunctions.DateName("mm", e.Date),

But they all return "August"

There is also SqlFunctions.DatePart but it returns an integer, eg: SqlFunctions("mm", e.Date) returns the integer 8

Body:
You can do it like this:

.Select(c => DbFunctions.Right("00" + c.Date.Month, 2))

RIGHT (SQL function) returns x rightmost characters from given string (2 in this case) and we prepend month with 2 zeroes so that if month has 1 digit, result is "00x" so "0x" is returned, and when month has 2 digits - result is "00xx" and "xx" is returned.

The resulting sql query will be just:

RIGHT(N'00' + CASE WHEN (DATEPART (month, [Extent1].[Date]) IS NULL)
    THEN N'' ELSE  CAST( DATEPART (month, [Extent1].[Date])

As a bonus, this code is not sql-server specific and will work with other providers.


问:
How to remove this object from a Swift array?
What would be an appropriate command for removing formattedCoordinate from the array? I know a removeObject exists for Objective-C, but how about Swift?</p>

```<code>var markersArray: Array<CLLocationCoordinate2D> = []

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker){
    let lat: CLLocationDegrees = marker.position.latitude
    let lng: CLLocationDegrees = marker.position.longitude
    var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
    //markersArray.remove(formattedCoordinate) need to fix this
    self.clean()
    //    return 0; not sure if we need this here
}

func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker){
    let lat: CLLocationDegrees = marker.position.latitude
    let lng: CLLocationDegrees = marker.position.longitude
    var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
    // markersArray.remove(formattedCoordinate) need to fix this
}
</code>```

答:
I would suggest</p>

```<code>self.markersArray = self.markersArray.filter({ !(($0.latitude == formattedCoordinate.latitude) && ($0.longitude == formattedCoordinate.longitude)) })
</code>```

Body:
What would be an appropriate command for removing formattedCoordinate from the array? I know a removeObject exists for Objective-C, but how about Swift?

var markersArray: Array<CLLocationCoordinate2D> = []

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker){
    let lat: CLLocationDegrees = marker.position.latitude
    let lng: CLLocationDegrees = marker.position.longitude
    var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
    //markersArray.remove(formattedCoordinate) need to fix this
    self.clean()
    //    return 0; not sure if we need this here
}

func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker){
    let lat: CLLocationDegrees = marker.position.latitude
    let lng: CLLocationDegrees = marker.position.longitude
    var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
    // markersArray.remove(formattedCoordinate) need to fix this
}

Body:
I would suggest

self.markersArray = self.markersArray.filter({ !(($0.latitude == formattedCoordinate.latitude) && ($0.longitude == formattedCoordinate.longitude)) })


问:
system() not working in C on cron job
The system() function does not work when the program is run from a cron job, but it works fine when I manually execute the program.

C Code:

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

int main(){

char command[256];

strcpy(command, "mpg123 /home/vlad/MIA/Alarm/test.mp3");
printf("Commnd Executed");
system(command);

return 0;
}
</code>```

Crontab File:

```<code>*/1 * * * * /home/vlad/MIA/Alarm/test >> /home/vlad/MIA/debug_test.txt
</code>```

答:
Cron jobs run with a limited set of environment variables.

To see what the environment looks like, you can create a temporary cron job like this:

```<code>* * * * * printenv > cron-env
</code>```

The most likely culprit is the $PATH variable. It's likely that the mpg123 command is in a directory that's in your $PATH in an interactive shell, but is not in the default $PATH provided to cron jobs.

UPDATE : I see that the mpg123 command is provided (on Ubuntu) by the mpg321 package, which presumably installs it as /usr/bin/mpg123. But I don't know what the command does, or how you can tell that it didn't run. Your first step in debugging this should be to try running a simple command so that you can clearly tell whether it ran or not. And just be sure, you are feeding your crontab to the crontab command, yes? If so, it should appear in the output of crontab -l.

Title: system() not working in C on cron job

Body:
The system() function does not work when the program is run from a cron job, but it works fine when I manually execute the program.

C Code:

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

int main(){

char command[256];

strcpy(command, "mpg123 /home/vlad/MIA/Alarm/test.mp3");
printf("Commnd Executed");
system(command);

return 0;
}

Crontab File:

*/1 * * * * /home/vlad/MIA/Alarm/test >> /home/vlad/MIA/debug_test.txt

Body:
Cron jobs run with a limited set of environment variables.

To see what the environment looks like, you can create a temporary cron job like this:

* * * * * printenv > cron-env

The most likely culprit is the $PATH variable. It's likely that the mpg123 command is in a directory that's in your $PATH in an interactive shell, but is not in the default $PATH provided to cron jobs.

UPDATE : I see that the mpg123 command is provided (on Ubuntu) by the mpg321 package, which presumably installs it as /usr/bin/mpg123. But I don't know what the command does, or how you can tell that it didn't run. Your first step in debugging this should be to try running a simple command so that you can clearly tell whether it ran or not. And just be sure, you are feeding your crontab to the crontab command, yes? If so, it should appear in the output of crontab -l.


问:
Error while launching TOR browser with Selenium WebDriver
I'm using Selenium 2.53.0 Java, Tor 6.0.4 and Firefox 43. I'm executing tor with firefox by loading the profile.default archive with the Firefoxprofile() and a Firefoxbinary() with firefox.exe. Tor launchs, but it doesn't initiate, it shows two errors:  Could not connect to Tor control port and Tor failed to start.

I've followed this post to Using Selenium WebDriver with Tor to set up the Firefox driver.

See below the code. Thanks!

```<code>String torPath = "C:\\Users\\Jose Bernhardt\\Desktop\\Tor Browser\\Browser\\firefox.exe";
    String profilePath = "C:\\Users\\Jose Bernhardt\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default";

    File torProfileDir = new File(profilePath);
    FirefoxBinary binary = new FirefoxBinary(new File(torPath));
    FirefoxProfile torProfile = new FirefoxProfile(torProfileDir);
    FirefoxDriver driver = new FirefoxDriver(binary, torProfile);
</code>```

These are the Exceptions thrown:

```<code>org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
Exception in thread "main" org.openqa.selenium.WebDriverException: Failed to connect to binary FirefoxBinary(C:\Users\Jose Bernhardt\Desktop\Tor Browser\Browser\firefox.exe) on port 7055; process output follows
</code>```

答:
I think this is because you are using a wrong version of firefox driver

try below :

```<code>public WebDriver driver;
system.setproperty("webdriver.gecko.driver","path to your firefoxdriver");
driver = new FierfoxDriver();
</code>```

Body:
I'm using Selenium 2.53.0 Java, Tor 6.0.4 and Firefox 43. I'm executing tor with firefox by loading the profile.default archive with the Firefoxprofile() and a Firefoxbinary() with firefox.exe. Tor launchs, but it doesn't initiate, it shows two errors:  Could not connect to Tor control port and Tor failed to start.

I've followed this post to Using Selenium WebDriver with Tor to set up the Firefox driver.

See below the code. Thanks!

String torPath = "C:\\Users\\Jose Bernhardt\\Desktop\\Tor Browser\\Browser\\firefox.exe";
    String profilePath = "C:\\Users\\Jose Bernhardt\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default";

    File torProfileDir = new File(profilePath);
    FirefoxBinary binary = new FirefoxBinary(new File(torPath));
    FirefoxProfile torProfile = new FirefoxProfile(torProfileDir);
    FirefoxDriver driver = new FirefoxDriver(binary, torProfile);

These are the Exceptions thrown:

org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
Exception in thread "main" org.openqa.selenium.WebDriverException: Failed to connect to binary FirefoxBinary(C:\Users\Jose Bernhardt\Desktop\Tor Browser\Browser\firefox.exe) on port 7055; process output follows

Body:
I think this is because you are using a wrong version of firefox driver

try below :

public WebDriver driver;
system.setproperty("webdriver.gecko.driver","path to your firefoxdriver");
driver = new FierfoxDriver();


问:
Cross-platform way to check admin rights in a Python script under Windows?
Is there any cross-platform way to check that my Python script is executed with admin rights? Unfortunately, os.getuid() is UNIX-only and is not available under Windows.

答:
Here's a utility function I created from the accepted answer:</p>

```<code>import os
import ctypes

class AdminStateUnknownError(Exception):
    """Cannot determine whether the user is an admin."""
    pass

def is_user_admin():
    # type: () -> bool
    """Return True if user has admin privileges.

    Raises:
        AdminStateUnknownError if user privileges cannot be determined.
    """
    try:
        return os.getuid() == 0
    except AttributeError:
        pass
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() == 1
    except AttributeError:
        raise AdminStateUnknownError
</code>```

Body:
Here's a utility function I created from the accepted answer:

import os
import ctypes

class AdminStateUnknownError(Exception):
    """Cannot determine whether the user is an admin."""
    pass

def is_user_admin():
    # type: () -> bool
    """Return True if user has admin privileges.

    Raises:
        AdminStateUnknownError if user privileges cannot be determined.
    """
    try:
        return os.getuid() == 0
    except AttributeError:
        pass
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() == 1
    except AttributeError:
        raise AdminStateUnknownError


问:
iPhone: Update Localizable.strings files using genstrings?
I have generated my strings file correctly using genstrings.  I have changed the localized strings for my different languages.  Now, I have added a few more NSLocalizedString() occurrences and I want to generate those into all of my localized strings files.

But, running genstrings again does not seem to update my strings files.  Am I doing something wrong?

答:
Usually this is because you've got genstrings looking in the wrong folder, or in the wrong files. I had a problem where it wasn't picking up all of my strings, and I realized it was only searching for *.m files (not *.mm) and it wasn't parsing the files in my Classes folder. A small change fixed that:

```<code>genstrings -o Classes/en.lproj Classes/*.{m,mm}
</code>```

The first parameter tells genstrings where I want the .strings file.

-o Classes/en.lprog

The second parameter tells genstrings where to look. Remember I'm running genstrings from the project root, so I needed to specify Classes/.m, or more specifically Classes/.{m,mm} so it would parse .m and .mm files.

Body:
Usually this is because you've got genstrings looking in the wrong folder, or in the wrong files. I had a problem where it wasn't picking up all of my strings, and I realized it was only searching for *.m files (not *.mm) and it wasn't parsing the files in my Classes folder. A small change fixed that:

genstrings -o Classes/en.lproj Classes/*.{m,mm}

The first parameter tells genstrings where I want the .strings file.

-o Classes/en.lprog

The second parameter tells genstrings where to look. Remember I'm running genstrings from the project root, so I needed to specify Classes/.m, or more specifically Classes/.{m,mm} so it would parse .m and .mm files.


问:
What are all the possibilities to pass the data one component to another component without navigation or route in angular 2 type script?
I am a beginner for learning  Angular 2 type script. I want to pass the data between one component to another component?

Serives.ts

```<code>    import {Component, Injectable} from '@angular/core';

    // Name Service
    export interface myData {
       myDataname:any;
    }

    @Injectable()
    export class GetService {
        sharingData:any={myDataname:"My data string"};

        saveData(str:any){
            alert("Save Data");
        // console.log('save data function called' + JSON.stringify(str));
        this.sharingData.myDataname=str;
        console.log(JSON.stringify(this.sharingData.myDataname));
      }
      getData():any{
     console.log('get data function called');
     console.log(JSON.stringify(this.sharingData.myDataname)+ "Get dats service s");
        return this.sharingData.myDataname;
}
    }
</code>```

First Component.ts

```<code>import { GetService } from '../service/get-service';

    @Component({
      selector: 'firstcomponent,
      templateUrl: 'firstcomponent.html',
      providers:[GetService]
    })

    export class firstcomponentDetails {
    firstname:string;
    lastname:string;

      constructor(public getservice: GetService ) {
         this.getservice= getservice;

    submitForm(value: any):void{
            console.log(' Personal Details Form submited!');
        console.log(value);
        this.getservice.saveData(value);
    }
}
    }
</code>```

Second Component.ts

```<code> import { GetService } from '../service/get-service';
    @Component({
      selector: 'secondpage',
      templateUrl: 'secondpage.html',
       providers: [GetService],
    })
    export class SecondPage {
     getDatavaluesServices:any;
     constructor( public getservice:GetService){
    this.getservice = getservice;
     this.getDatavaluesServices=getservice.getData();
      console.log(this.getDatavaluesServices );
    }
    }
</code>```

This is my code. I tried this code passing data first component to second component. I am getting to string value my data string. How to get first component value?

答:
You should provide the service by the parent component or module to be sure only one instance is shared between components. Having providers:[GetService] on child components recreate the service when the componet is instantiated. Thus, you lose data set by the other component.

If you followed the guide Parent and children communicate via a service, you can see that children components don't have providers of the shared service on which communication is performed, but a parent mission-control component provides only one instance per every child such as my-astronaut.

In the mission-control template the my-astronaut component instantiated several times via *ngFor directive.

If it is not enough, you can create your own provider for the service using singleton pattern. (See also how it's implemented in this answer.) In this way using the provider you can provide the service to any component.

Body:
I am a beginner for learning  Angular 2 type script. I want to pass the data between one component to another component?

Serives.ts

    import {Component, Injectable} from '@angular/core';

    // Name Service
    export interface myData {
       myDataname:any;
    }

    @Injectable()
    export class GetService {
        sharingData:any={myDataname:"My data string"};

        saveData(str:any){
            alert("Save Data");
        // console.log('save data function called' + JSON.stringify(str));
        this.sharingData.myDataname=str;
        console.log(JSON.stringify(this.sharingData.myDataname));
      }
      getData():any{
     console.log('get data function called');
     console.log(JSON.stringify(this.sharingData.myDataname)+ "Get dats service s");
        return this.sharingData.myDataname;
}
    }

First Component.ts

import { GetService } from '../service/get-service';

    @Component({
      selector: 'firstcomponent,
      templateUrl: 'firstcomponent.html',
      providers:[GetService]
    })

    export class firstcomponentDetails {
    firstname:string;
    lastname:string;

      constructor(public getservice: GetService ) {
         this.getservice= getservice;

    submitForm(value: any):void{
            console.log(' Personal Details Form submited!');
        console.log(value);
        this.getservice.saveData(value);
    }
}
    }

Second Component.ts

 import { GetService } from '../service/get-service';
    @Component({
      selector: 'secondpage',
      templateUrl: 'secondpage.html',
       providers: [GetService],
    })
    export class SecondPage {
     getDatavaluesServices:any;
     constructor( public getservice:GetService){
    this.getservice = getservice;
     this.getDatavaluesServices=getservice.getData();
      console.log(this.getDatavaluesServices );
    }
    }

This is my code. I tried this code passing data first component to second component. I am getting to string value my data string. How to get first component value?


问:
Sending JSON to PHP via AJAX is failing
I am trying to send a JSON string to a PHP file via ajax. The issue is that the variable I'm posting over is not being delivered when I use the JQUERY ajax method as shown below:

<DOCTYPE html>

    <title>Assignment 4</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <form action="json.php" method="POST">

          Username:
          <input type="text" class="form-control" id="userid" name="userid">

          Password:
          <input type="password" class="form-control" id="pwd" name="pwd">

        <button type="submit" class="btn btn-default" id='btn' onclick="JSONstring()">Submit</button>
      </form>

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

<p>Oddly enough when I try and AJAX the old fashioned way, I am able to get the RAW POST data that I would expect:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var jsonObj = JSON.stringify(obj);

request = new XMLHttpRequest();

request.open("POST", "json.php", true);

request.setRequestHeader("Content-type", "application/json");

request.send(obj);</code>```

My php file is simply trying to get the variable and dump it:

```<code>    <?php

   $directions = json_decode($_POST['json']);
    var_dump($directions);

?>
</code>```

Can someone please point me in the right direction?

答:
dataType only means that you expect a JSON response.

Try using contentType instead.

```<code>$.ajax({
      type: 'POST',
      contentType: "application/json",
      url: 'json.php',
      data: {
        json: jsonObj
      },
      dataType: 'json'
    });
</code>```

Title: Sending JSON to PHP via AJAX is failing

Body:
I am trying to send a JSON string to a PHP file via ajax. The issue is that the variable I'm posting over is not being delivered when I use the JQUERY ajax method as shown below:

<DOCTYPE html>

    <title>Assignment 4</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <form action="json.php" method="POST">

          Username:
          <input type="text" class="form-control" id="userid" name="userid">

          Password:
          <input type="password" class="form-control" id="pwd" name="pwd">

        <button type="submit" class="btn btn-default" id='btn' onclick="JSONstring()">Submit</button>
      </form>

Oddly enough when I try and AJAX the old fashioned way, I am able to get the RAW POST data that I would expect:

var jsonObj = JSON.stringify(obj);

request = new XMLHttpRequest();

request.open("POST", "json.php", true);

request.setRequestHeader("Content-type", "application/json");

request.send(obj);

My php file is simply trying to get the variable and dump it:

    <?php

   $directions = json_decode($_POST['json']);
    var_dump($directions);

?>

Can someone please point me in the right direction?

Body:
dataType only means that you expect a JSON response.

Try using contentType instead.

$.ajax({
      type: 'POST',
      contentType: "application/json",
      url: 'json.php',
      data: {
        json: jsonObj
      },
      dataType: 'json'
    });


问:
Unable to compile Riak on Raspberry Pi 3
currenty I'm trying  to install Riak on the Raspberry Pi 3 for testing purposes. I used the following instruction from basho:

http://docs.basho.com/riak/kv/2.2.2/setup/installing/source/

I'm having problems compiling it from source. I tried to compile it on Raspbian Jessie and then switched to Ubuntu Server 16.04. Both times with the same result. It is not compiling and aborts at a certain point. I don't know what causes the problem since it only says: recipe for target 'util/perf_count.o' failed. Searching Google and the mailing list from basho weren't successful.

The version of gcc is gcc (Raspbian 4.9.2-10) 4.9.2. The version of Erlang is  Erlang R16B02_basho8 (erts-5.10.3)

The commands i used are the following:

Installing Erlang:

```<code>wget http://s3.amazonaws.com/downloads.basho.com/erlang/otp_src_R16B02basho10.tar.gz

tar zxvf otp_src_R16B02-basho10.tar.gz

cd OTP_R16B02_basho10
./otp_build autoconf
./configure && make && sudo make install
</code>```

Installing Riak:

```<code>wget http://s3.amazonaws.com/downloads.basho.com/riak/2.2/2.2.1/riak-2.2.1.tar.gz

tar zxvf riak-2.2.1.tar.gz

cd riak-2.2.1
make locked-deps
make rel
</code>```

Any suggestions are welcome.

Output:

```<code>`./include/leveldb/atomics.h:155:15: note:
template argument deduction/substitution failed util/perf_count.cc:439:40:
note: deduced conflicting types for parameter ‘ValueT’
(‘unsigned int’ and‘int’ add_and_fetch(ptr_32, 1);`

`Makefile:190: recipe for target 'util/perf_count.o' failed
make[1]: *** [util/perf_count.o] Error 1
make[1]: *** Waiting for unfinished jobs....
make[1]: Leaving directory '/home/pi/Riak/riak/deps/eleveldb/c_src/leveldb'
ERROR: Command [compile] failed!
Makefile:23: recipe for target 'compile' failed
make: *** [compile] Error 1`
</code>```

答:
After digging deeper I got some help from Basho's mailing list (many thanks).
The Link below shows the steps to solve this problem:

http://lists.basho.com/pipermail/riak-users_lists.basho.com/2017-April/019187.html

The next link is a detailed instruction, which helps to install Riak on the Raspberry Pi 3:

http://docs.basho.com/riak/kv/2.2.2/setup/installing/source/

Body:
currenty I'm trying  to install Riak on the Raspberry Pi 3 for testing purposes. I used the following instruction from basho:

http://docs.basho.com/riak/kv/2.2.2/setup/installing/source/

I'm having problems compiling it from source. I tried to compile it on Raspbian Jessie and then switched to Ubuntu Server 16.04. Both times with the same result. It is not compiling and aborts at a certain point. I don't know what causes the problem since it only says: recipe for target 'util/perf_count.o' failed. Searching Google and the mailing list from basho weren't successful.

The version of gcc is gcc (Raspbian 4.9.2-10) 4.9.2. The version of Erlang is  Erlang R16B02_basho8 (erts-5.10.3)

The commands i used are the following:

Installing Erlang:

wget http://s3.amazonaws.com/downloads.basho.com/erlang/otp_src_R16B02basho10.tar.gz

tar zxvf otp_src_R16B02-basho10.tar.gz

cd OTP_R16B02_basho10
./otp_build autoconf
./configure && make && sudo make install

Installing Riak:

wget http://s3.amazonaws.com/downloads.basho.com/riak/2.2/2.2.1/riak-2.2.1.tar.gz

tar zxvf riak-2.2.1.tar.gz

cd riak-2.2.1
make locked-deps
make rel

Any suggestions are welcome.

Output:

`./include/leveldb/atomics.h:155:15: note:
template argument deduction/substitution failed util/perf_count.cc:439:40:
note: deduced conflicting types for parameter ‘ValueT’
(‘unsigned int’ and‘int’ add_and_fetch(ptr_32, 1);`

`Makefile:190: recipe for target 'util/perf_count.o' failed
make[1]: *** [util/perf_count.o] Error 1
make[1]: *** Waiting for unfinished jobs....
make[1]: Leaving directory '/home/pi/Riak/riak/deps/eleveldb/c_src/leveldb'
ERROR: Command [compile] failed!
Makefile:23: recipe for target 'compile' failed
make: *** [compile] Error 1`


问:
Crop camera preview
I want to run android camera preview with a 640x480 resolution but display just 480x360. Right now I'm getting a stretched preview, even though I've tried to put the surface view in a frame layout or srollview. Can anyone tell me how this can be done?
A similar question has been asked before: How to crop camera preview?, but nobody answered.
Thanks</p>

答:
This can be achieved by using TextureView for camera preview. See https://developer.android.com/reference/android/view/TextureView.html.

Unlike SurfaceView, TextureView does not create a separate window but behaves as  a regular View. This key difference allows a TextureView to be moved, transformed, animated, etc. For instance, you can make a TextureView semi-translucent by calling myView.setAlpha(0.5f).

Title: Crop camera preview


问:
Javascript prevent "undefined" value with dynamic array
I have dynamic form elements and trying to add values to input's value attribute which is coming from as a array. However sometimes there are no any data ,then javascript prints undefined to value area of the input element.

How can i check it and dont print undefined in dynamic element?

```<code>$("#test").append("<input type='text' name='first-test' class='form-control' value='"+testarray['first-test']+"' >
</code>```

When we check the textbox , it shows "undefined" as a value.

答:
Here is working example, we pass an array with objects into our function. For loop simply skips if value is not found.

var yourArray = [
  { name: 'Janet' },
  { name: 'Jane', value: 1 },
  { name: 'Tom', value: 2 },
  { name: 'Kate', value: 3},
  { name: 'Mark' },
  { name: 'Tom' }
];

function addInputs(array) {
  for (i = 0; i < array.length; i++) {
    var element = array[i];

    // Skips if no value found
    if (element.value === undefined) {
      continue;
    }

    var html = '<input type="text" name="' + element.name + '" class="form-control" value="' + element.value + '" />';

    $('#test').append(html);
  }
};

addInputs(yourArray);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test"></div></code>```

Body:
I have dynamic form elements and trying to add values to input's value attribute which is coming from as a array. However sometimes there are no any data ,then javascript prints undefined to value area of the input element.

How can i check it and dont print undefined in dynamic element?

$("#test").append("<input type='text' name='first-test' class='form-control' value='"+testarray['first-test']+"' >

When we check the textbox , it shows "undefined" as a value.

Body:
Here is working example, we pass an array with objects into our function. For loop simply skips if value is not found.

var yourArray = [
  { name: 'Janet' },
  { name: 'Jane', value: 1 },
  { name: 'Tom', value: 2 },
  { name: 'Kate', value: 3},
  { name: 'Mark' },
  { name: 'Tom' }
];

function addInputs(array) {
  for (i = 0; i < array.length; i++) {
    var element = array[i];

    // Skips if no value found
    if (element.value === undefined) {
      continue;
    }

    var html = '<input type="text" name="' + element.name + '" class="form-control" value="' + element.value + '" />';

    $('#test').append(html);
  }
};

addInputs(yourArray);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test"></div>


问:
Redirect all files in sub-directory to root via htaccess
I would like to redirect all files in my domain's sub-directory to the root directory in order to hide the sub-directory from the URL. For example, I would like www.domain.com/blog/test1.php to redirect to www.domain.com/test1.php and www.domain.com/blog/test2.php to redirect to www.domain.com/test2.php etc.

How can I achieve this via the .htaccess file? Everything I tried until now just redirects all files in the sub-directory to www.domain.com.
Thank you for your help.

I've tried using:

```<code>RedirectMatch 301 ^/blog/$ example.com
RewriteRule /blog/(.*) /$1 [PT]
RewriteCond %{HTTP_HOST} ^www.example.com
RewriteRule ^blog/(.*)$ example.com/$1 [L,R=301]
</code>```

This all just redirects to www.example.com.

答:
I am just learning mod_rewrite myself, but I think you have an extra '/' in the first RewriteRule and an unnecessary hostname in the second.  I believe this is worth a try:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^blog/(.*) $1 [L]
</IfModule>
</code>```

Body:
I would like to redirect all files in my domain's sub-directory to the root directory in order to hide the sub-directory from the URL. For example, I would like www.domain.com/blog/test1.php to redirect to www.domain.com/test1.php and www.domain.com/blog/test2.php to redirect to www.domain.com/test2.php etc.

How can I achieve this via the .htaccess file? Everything I tried until now just redirects all files in the sub-directory to www.domain.com.
Thank you for your help.

I've tried using:

RedirectMatch 301 ^/blog/$ example.com
RewriteRule /blog/(.*) /$1 [PT]
RewriteCond %{HTTP_HOST} ^www.example.com
RewriteRule ^blog/(.*)$ example.com/$1 [L,R=301]

This all just redirects to www.example.com.

Body:
I am just learning mod_rewrite myself, but I think you have an extra '/' in the first RewriteRule and an unnecessary hostname in the second.  I believe this is worth a try:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^blog/(.*) $1 [L]
</IfModule>


问:
how to redirect a git-server address?
(suppose) I have my own git, so you can do

```<code>  git clone https://official.example.org/myproject.git
</code>```

But, at my server official.example.org I want to redirect it to Github. How to do it at UBUNTU 16LTS standard git-server? It is an usual web-server redirect (eg. Apache)  or need special preparation?

PS: the technology exist, as announced here.

答:
I use the git post-receive hook in my buildfarm to automatically build projects in Jenkins when code is pushed to my git repository.  You could do something similar with some of the other git hooks on your server to push code to github.

Similarly, on github you could define a webhook to update your git repository on official.example.org whenever code in the github repository is updated.  Something like this answer maybe.

Title: how to redirect a git-server address?

Body:
(suppose) I have my own git, so you can do

  git clone https://official.example.org/myproject.git

But, at my server official.example.org I want to redirect it to Github. How to do it at UBUNTU 16LTS standard git-server? It is an usual web-server redirect (eg. Apache)  or need special preparation?

PS: the technology exist, as announced here.