问:
C++ Get string from Clipboard on Linux
Hello I'm writing a c++ program and I need to get what's on clipboard into a string variable. I found a lot of solutions but all of them were written for windows. Is there any method without using the QT libraries? I found something related to X11 but not very explicit aswell.

Thank you very much

答:
X11 uses a flexible multi-buffer multi-format asynchronous application-side clipboard protocol.

Most toolkits have it implemented (GTK's gtk_clipboard_get(), Qt's QApplication::clipboard(), Tk's clipboard_get). But you can do it manually with X11 API, for example, if you're not using toolkits, or if you must pass large amount of data through clipboard buffer without keeping it all in memory at the same time.

Theory

There may be many buffers, but you only need to know about two:

CLIPBOARD is the usual explicit buffer: you copy things there with Edit/Copy menu, and paste it with Edit/Paste menu.

PRIMARY selection is an implicit mouse selection feature: text gets in it when selected with mouse cursor, and gets pasted from it on middle-click in text input fields.

Primary selection needs no keypresses, so it's useful for copying small fragments between windows that are next to each other. This feature is mostly unix-specific, but I've seen putty, trillian and some gtk apps emulating it on Windows OS. Also firefox has "Paste & Go" feature when middle-clicking empty non-interactive space of the page.

To optimize things those are application-side buffers: instead of pushing entire clipboard/selection to the server every time it changes, application just tells the server "I own it". To get the buffer you ask the owner to give you its content. This way even a large buffer takes no resources until its actually requested.

When requesting the buffer you ask the owner for a specific format you need. For example an image copied from seamonkey browser (right-click an image and press "Copy Image") can be represented in different formats. It would appear as image URL if you paste it in terminal. It would become a picture loaded from that URL if you paste it in libreoffice writer. And it'd be the image itself if pasted in gimp. That works because seamonkey is smart and provides each application with format it asks for: text string for terminal, html for libreoffice and image data for gimp. To request text format you'd ask for UTF8_STRING format with fallback to STRING.

As you ask another application to prepare the buffer, and that may take some time, the request is asynchronous: the owner prepares the buffer, saves it in a specified location (window property is used as a temporary storage) and notifies you with SelectionNotify event when it's done.

So to get the buffer:

choose buffer name (CLIPBOARD, PRIMARY), format
(UTF8_STRING, STRING) and a window property to store result to

call XConvertSelection() to request the buffer

wait for SelectionNotify event

read buffer content from window property

Naive implementation

// gcc -o xclipget xclipget.c -lX11
#include <stdio.h>
#include <limits.h>
#include <X11/Xlib.h>

Bool PrintSelection(Display *display, Window window, const char *bufname, const char *fmtname)
{
  char *result;
  unsigned long ressize, restail;
  int resbits;
  Atom bufid = XInternAtom(display, bufname, False),
       fmtid = XInternAtom(display, fmtname, False),
       propid = XInternAtom(display, "XSEL_DATA", False),
       incrid = XInternAtom(display, "INCR", False);
  XEvent event;

  XConvertSelection(display, bufid, fmtid, propid, window, CurrentTime);
  do {
    XNextEvent(display, &event);
  } while (event.type != SelectionNotify || event.xselection.selection != bufid);

  if (event.xselection.property)
  {
    XGetWindowProperty(display, window, propid, 0, LONG_MAX/4, False, AnyPropertyType,
      &fmtid, &resbits, &ressize, &restail, (unsigned char**)&result);

    if (fmtid == incrid)
      printf("Buffer is too large and INCR reading is not implemented yet.\n");
    else
      printf("%.*s", (int)ressize, result);

    XFree(result);
    return True;
  }
  else // request failed, e.g. owner can't convert to the target format
    return False;
}

int main()
{
  Display *display = XOpenDisplay(NULL);
  unsigned long color = BlackPixel(display, DefaultScreen(display));
  Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0,0, 1,1, 0, color, color);
  Bool result = PrintSelection(display, window, "CLIPBOARD", "UTF8_STRING") ||
                PrintSelection(display, window, "CLIPBOARD", "STRING");
  XDestroyWindow(display, window);
  XCloseDisplay(display);
  return !result;
}
```

<p>This will work for many simple cases. One thing missing here is support for incremental reading of large buffers. Let's add it!</p>

<h3>Large buffers</h3>

<p>Some apps may want to copy/paste 100 gigabytes of text logs. And X11 allows that! But the data must be passed incrementally, split into chunks.</p>

<p>If the requested buffer is too large, instead of storing it into the window property, owner sets a property of format <code>INCR</code>. If you delete it, owner assumes you've read it, and puts next chunk in the same property. That continues until the last chunk is read and deleted. Finally owner sets property of size 0 to mark the end of data.</p>

<p>So to read large buffer you delete <code>INCR</code> property and wait for the property to appear again (<code>PropertyNotify</code> event, state == <code>PropertyNewValue</code>), read and delete it, wait for it to appear again, and so on until it appears with zero size.</p>

<pre class="lang-c prettyprint-override"><code>// gcc -o xclipget xclipget.c -lX11
#include <stdio.h>
#include <limits.h>
#include <X11/Xlib.h>

Bool PrintSelection(Display *display, Window window, const char *bufname, const char *fmtname)
{
  char *result;
  unsigned long ressize, restail;
  int resbits;
  Atom bufid = XInternAtom(display, bufname, False),
       fmtid = XInternAtom(display, fmtname, False),
       propid = XInternAtom(display, "XSEL_DATA", False),
       incrid = XInternAtom(display, "INCR", False);
  XEvent event;

  XSelectInput (display, window, PropertyChangeMask);
  XConvertSelection(display, bufid, fmtid, propid, window, CurrentTime);
  do {
    XNextEvent(display, &event);
  } while (event.type != SelectionNotify || event.xselection.selection != bufid);

  if (event.xselection.property)
  {
    XGetWindowProperty(display, window, propid, 0, LONG_MAX/4, True, AnyPropertyType,
      &fmtid, &resbits, &ressize, &restail, (unsigned char**)&result);
    if (fmtid != incrid)
      printf("%.*s", (int)ressize, result);
    XFree(result);

    if (fmtid == incrid)
      do {
        do {
          XNextEvent(display, &event);
        } while (event.type != PropertyNotify || event.xproperty.atom != propid || event.xproperty.state != PropertyNewValue);

        XGetWindowProperty(display, window, propid, 0, LONG_MAX/4, True, AnyPropertyType,
          &fmtid, &resbits, &ressize, &restail, (unsigned char**)&result);
        printf("%.*s", (int)ressize, result);
        XFree(result);
      } while (ressize > 0);

    return True;
  }
  else // request failed, e.g. owner can't convert to the target format
    return False;
}

int main()
{
  Display *display = XOpenDisplay(NULL);
  unsigned long color = BlackPixel(display, DefaultScreen(display));
  Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0,0, 1,1, 0, color, color);
  Bool result = PrintSelection(display, window, "CLIPBOARD", "UTF8_STRING") ||
                PrintSelection(display, window, "CLIPBOARD", "STRING");
  XDestroyWindow(display, window);
  XCloseDisplay(display);
  return !result;
}
</code>```

For example xsel tool uses INCR transfer for buffers larger than 4000. According to ICCCM, it's up to the application to choose a reasonable size limit.

The same code works for PRIMARY selection. Replace "CLIPBOARD" with "PRIMARY" to print PRIMARY selection contents.

References

X Selections summary by Jamie Zawinski

Xlib Programming Manual - Selections

ICCCM - Large Data Transfers and INCR protocol

https://github.com/exebook/x11clipboard - minimal XCopy() and XPaste() implementations

xsel and xclip sources

The Secondary Selection - history and ideas by Charles Lindsey

Title: C++ Get string from Clipboard on Linux

Body:
X11 uses a flexible multi-buffer multi-format asynchronous application-side clipboard protocol.

Most toolkits have it implemented (GTK's gtk_clipboard_get(), Qt's QApplication::clipboard(), Tk's clipboard_get). But you can do it manually with X11 API, for example, if you're not using toolkits, or if you must pass large amount of data through clipboard buffer without keeping it all in memory at the same time.

Theory

There may be many buffers, but you only need to know about two:

CLIPBOARD is the usual explicit buffer: you copy things there with Edit/Copy menu, and paste it with Edit/Paste menu.

PRIMARY selection is an implicit mouse selection feature: text gets in it when selected with mouse cursor, and gets pasted from it on middle-click in text input fields.

Primary selection needs no keypresses, so it's useful for copying small fragments between windows that are next to each other. This feature is mostly unix-specific, but I've seen putty, trillian and some gtk apps emulating it on Windows OS. Also firefox has "Paste & Go" feature when middle-clicking empty non-interactive space of the page.

To optimize things those are application-side buffers: instead of pushing entire clipboard/selection to the server every time it changes, application just tells the server "I own it". To get the buffer you ask the owner to give you its content. This way even a large buffer takes no resources until its actually requested.

When requesting the buffer you ask the owner for a specific format you need. For example an image copied from seamonkey browser (right-click an image and press "Copy Image") can be represented in different formats. It would appear as image URL if you paste it in terminal. It would become a picture loaded from that URL if you paste it in libreoffice writer. And it'd be the image itself if pasted in gimp. That works because seamonkey is smart and provides each application with format it asks for: text string for terminal, html for libreoffice and image data for gimp. To request text format you'd ask for UTF8_STRING format with fallback to STRING.

As you ask another application to prepare the buffer, and that may take some time, the request is asynchronous: the owner prepares the buffer, saves it in a specified location (window property is used as a temporary storage) and notifies you with SelectionNotify event when it's done.

So to get the buffer:

choose buffer name (CLIPBOARD, PRIMARY), format
(UTF8_STRING, STRING) and a window property to store result to

call XConvertSelection() to request the buffer

wait for SelectionNotify event

read buffer content from window property

Naive implementation

// gcc -o xclipget xclipget.c -lX11
#include <stdio.h>
#include <limits.h>
#include <X11/Xlib.h>

Bool PrintSelection(Display *display, Window window, const char *bufname, const char *fmtname)
{
  char *result;
  unsigned long ressize, restail;
  int resbits;
  Atom bufid = XInternAtom(display, bufname, False),
       fmtid = XInternAtom(display, fmtname, False),
       propid = XInternAtom(display, "XSEL_DATA", False),
       incrid = XInternAtom(display, "INCR", False);
  XEvent event;

  XConvertSelection(display, bufid, fmtid, propid, window, CurrentTime);
  do {
    XNextEvent(display, &event);
  } while (event.type != SelectionNotify || event.xselection.selection != bufid);

  if (event.xselection.property)
  {
    XGetWindowProperty(display, window, propid, 0, LONG_MAX/4, False, AnyPropertyType,
      &fmtid, &resbits, &ressize, &restail, (unsigned char**)&result);

    if (fmtid == incrid)
      printf("Buffer is too large and INCR reading is not implemented yet.\n");
    else
      printf("%.*s", (int)ressize, result);

    XFree(result);
    return True;
  }
  else // request failed, e.g. owner can't convert to the target format
    return False;
}

int main()
{
  Display *display = XOpenDisplay(NULL);
  unsigned long color = BlackPixel(display, DefaultScreen(display));
  Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0,0, 1,1, 0, color, color);
  Bool result = PrintSelection(display, window, "CLIPBOARD", "UTF8_STRING") ||
                PrintSelection(display, window, "CLIPBOARD", "STRING");
  XDestroyWindow(display, window);
  XCloseDisplay(display);
  return !result;
}

This will work for many simple cases. One thing missing here is support for incremental reading of large buffers. Let's add it!

Large buffers

Some apps may want to copy/paste 100 gigabytes of text logs. And X11 allows that! But the data must be passed incrementally, split into chunks.

If the requested buffer is too large, instead of storing it into the window property, owner sets a property of format INCR. If you delete it, owner assumes you've read it, and puts next chunk in the same property. That continues until the last chunk is read and deleted. Finally owner sets property of size 0 to mark the end of data.

So to read large buffer you delete INCR property and wait for the property to appear again (PropertyNotify event, state == PropertyNewValue), read and delete it, wait for it to appear again, and so on until it appears with zero size.

// gcc -o xclipget xclipget.c -lX11
#include <stdio.h>
#include <limits.h>
#include <X11/Xlib.h>

Bool PrintSelection(Display *display, Window window, const char *bufname, const char *fmtname)
{
  char *result;
  unsigned long ressize, restail;
  int resbits;
  Atom bufid = XInternAtom(display, bufname, False),
       fmtid = XInternAtom(display, fmtname, False),
       propid = XInternAtom(display, "XSEL_DATA", False),
       incrid = XInternAtom(display, "INCR", False);
  XEvent event;

  XSelectInput (display, window, PropertyChangeMask);
  XConvertSelection(display, bufid, fmtid, propid, window, CurrentTime);
  do {
    XNextEvent(display, &event);
  } while (event.type != SelectionNotify || event.xselection.selection != bufid);

  if (event.xselection.property)
  {
    XGetWindowProperty(display, window, propid, 0, LONG_MAX/4, True, AnyPropertyType,
      &fmtid, &resbits, &ressize, &restail, (unsigned char**)&result);
    if (fmtid != incrid)
      printf("%.*s", (int)ressize, result);
    XFree(result);

    if (fmtid == incrid)
      do {
        do {
          XNextEvent(display, &event);
        } while (event.type != PropertyNotify || event.xproperty.atom != propid || event.xproperty.state != PropertyNewValue);

        XGetWindowProperty(display, window, propid, 0, LONG_MAX/4, True, AnyPropertyType,
          &fmtid, &resbits, &ressize, &restail, (unsigned char**)&result);
        printf("%.*s", (int)ressize, result);
        XFree(result);
      } while (ressize > 0);

    return True;
  }
  else // request failed, e.g. owner can't convert to the target format
    return False;
}

int main()
{
  Display *display = XOpenDisplay(NULL);
  unsigned long color = BlackPixel(display, DefaultScreen(display));
  Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0,0, 1,1, 0, color, color);
  Bool result = PrintSelection(display, window, "CLIPBOARD", "UTF8_STRING") ||
                PrintSelection(display, window, "CLIPBOARD", "STRING");
  XDestroyWindow(display, window);
  XCloseDisplay(display);
  return !result;
}

For example xsel tool uses INCR transfer for buffers larger than 4000. According to ICCCM, it's up to the application to choose a reasonable size limit.

The same code works for PRIMARY selection. Replace "CLIPBOARD" with "PRIMARY" to print PRIMARY selection contents.

References

X Selections summary by Jamie Zawinski

Xlib Programming Manual - Selections

ICCCM - Large Data Transfers and INCR protocol

https://github.com/exebook/x11clipboard - minimal XCopy() and XPaste() implementations

xsel and xclip sources

The Secondary Selection - history and ideas by Charles Lindsey


来源: stackexchange

问:
Vectorization: matrix array multiplication element wise one by one
I have a matrix:

R = [0 -1;1 0];

```<code>array = 1:1:10;
</code>```

Also x0 = [2;1]

How can I obtain another array in the most efficient way without loop?

```<code>array2 = [expm(1*R) expm(2*R) expm(3*R) .... expm(10*R)];
</code>```

Then I want to obtain
array3 of dimension 2 by 10 such that:

```<code>array3 = [expm(1*R)*x0 expm(2*R)*x0 expm(3*R)*x0 .... expm(10*R)*x0];
</code>```

答:
From wikipedia:

If a matrix is diagonal its exponential can be obtained by exponentiating each entry on the main diagonal.

Given that a block diagonal matrix can be created from {1*R, 2*R,...} then its exponential can be obtained and reshaped to a [2 * n] and it can be multiplied by x0.
However its performance may be worse than for loop.

```<code>R = [0 -1;1 0];
array = 1:1:10;
x0 = [2;1]
n = numel(array);
result = reshape(expm(kron(spdiags(array.',0,n,n),R))*repmat(x0,n,1),2,[]);
</code>```

For array of small size (less than 70 elements) full matrix is more efficient:

```<code>result = reshape(expm(kron(diag(array),R))*repmat(x0,n,1),2,[]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a matrix:

R = [0 -1;1 0];

array = 1:1:10;

Also x0 = [2;1]

How can I obtain another array in the most efficient way without loop?

array2 = [expm(1*R) expm(2*R) expm(3*R) .... expm(10*R)];

Then I want to obtain
array3 of dimension 2 by 10 such that:

array3 = [expm(1*R)*x0 expm(2*R)*x0 expm(3*R)*x0 .... expm(10*R)*x0];

Body:
From wikipedia:

If a matrix is diagonal its exponential can be obtained by exponentiating each entry on the main diagonal.

Given that a block diagonal matrix can be created from {1*R, 2*R,...} then its exponential can be obtained and reshaped to a [2 * n] and it can be multiplied by x0.
However its performance may be worse than for loop.

R = [0 -1;1 0];
array = 1:1:10;
x0 = [2;1]
n = numel(array);
result = reshape(expm(kron(spdiags(array.',0,n,n),R))*repmat(x0,n,1),2,[]);

For array of small size (less than 70 elements) full matrix is more efficient:

result = reshape(expm(kron(diag(array),R))*repmat(x0,n,1),2,[]);


问:
Python - Best way to integrate Java GUI and python code
I want to make a desktop GUI that interacts with the user's files (with permission of course). My code to download files and put it in the user's choice of directory is all written in python. There is much more to this code, but everything is written in python.

I want the GUI part to be a desktop app, so the client can easily interact and function the program.

I want to make this GUI in java and have it interact with the python code once someone presses a button.

What are the best approaches to make this happen?

答:
I would do it like this:

```<code>Process p = Runtime.getRuntime().exec("python app.py");
</code>```

You can also pass arguments into the python program as command line arguments, like this:

```<code>Process p = Runtime.getRuntime().exec("python app.py arg1 arg2");
</code>```

Body:
I would do it like this:

Process p = Runtime.getRuntime().exec("python app.py");

You can also pass arguments into the python program as command line arguments, like this:

Process p = Runtime.getRuntime().exec("python app.py arg1 arg2");


问:
Django choices. How to set a option to be selected only once
I am working on a blog. I have a section where there will be a special post. And another page where I have collection of special posts. Here is my model.py

```<code>class Post(models.Model):
    post = models.TextField()
    SPECIAL = (
        ('0', 'Special Post'),
        ('1', 'General Post'),
        ('2', 'Inactive Special Post'),
    )
    specialpost = models.CharField(max_length=1, choices=SPECIAL, default='1', )
</code>```

Only One post should be in the Special Post. When new special post is added, the old special post should be shifted to Inactive Special Post. So it can be shown in the Collection of Special post page. How can I do this?

答:
As @neeraj-kumar mentioned in comment, you can achieve this by overriding model's save() method. Add to Post class something like this:

```<code>class Post(models.Model):
    ...

    def save(self, *args, **kwargs):
        special_post = Post.objects.filter(specialpost='0')
        if self.specialpost == '0' and special_post:
            special_post.update(specialpost='2')
        super(Post, self).save(*args, **kwargs)
</code>```

Body:
I am working on a blog. I have a section where there will be a special post. And another page where I have collection of special posts. Here is my model.py

class Post(models.Model):
    post = models.TextField()
    SPECIAL = (
        ('0', 'Special Post'),
        ('1', 'General Post'),
        ('2', 'Inactive Special Post'),
    )
    specialpost = models.CharField(max_length=1, choices=SPECIAL, default='1', )

Only One post should be in the Special Post. When new special post is added, the old special post should be shifted to Inactive Special Post. So it can be shown in the Collection of Special post page. How can I do this?

Body:
As @neeraj-kumar mentioned in comment, you can achieve this by overriding model's save() method. Add to Post class something like this:

class Post(models.Model):
    ...

    def save(self, *args, **kwargs):
        special_post = Post.objects.filter(specialpost='0')
        if self.specialpost == '0' and special_post:
            special_post.update(specialpost='2')
        super(Post, self).save(*args, **kwargs)


问:
Falsy Freecodecamp algorithm challenge
This code is supposed to remove all falsy values from an array.
Am I close to getting it or should I scrap what I'm doing? I tend to get close only to give up later.</p>

```<code>function bouncer(arr) {

var bouncer = arr.filter(function(bouncer)undefined, null, NaN, 0, "", false); return arr; }

bouncer([7, "ate", "", false, 9]);
</code>```

答:
This isn't really an answer, just advice...

If you're learning to code you should be writing your code so that it's obvious and clear (to you) what's happening. For example, here's some code that's a little pedantic but hopefully understandable:

```<code>function copy_truthies(in_values) {
  let out_values = [];

  in_values.forEach(value => {
    if (value) {
      out_values.push(value);
    }
  });

  return out_values;
}

let all_values = [7, "ate", "", false, 9];
let truthy_values = copy_truthies(all_values);
console.log(truthy_values);
</code>```

Tushar's solution is idiomatic, elegant, and does the same thing; but it might not be immediately understood by someone just starting out:

```<code>console.log([7, "ate", "", false, 9].filter(e=>e))
</code>```

Just give it a few months and you'll be thinking fluently in one-liners :)

Title: Falsy Freecodecamp algorithm challenge

Body:
This code is supposed to remove all falsy values from an array.
Am I close to getting it or should I scrap what I'm doing? I tend to get close only to give up later.

function bouncer(arr) {

var bouncer = arr.filter(function(bouncer)undefined, null, NaN, 0, "", false); return arr; }

bouncer([7, "ate", "", false, 9]);

Body:
This isn't really an answer, just advice...

If you're learning to code you should be writing your code so that it's obvious and clear (to you) what's happening. For example, here's some code that's a little pedantic but hopefully understandable:

function copy_truthies(in_values) {
  let out_values = [];

  in_values.forEach(value => {
    if (value) {
      out_values.push(value);
    }
  });

  return out_values;
}

let all_values = [7, "ate", "", false, 9];
let truthy_values = copy_truthies(all_values);
console.log(truthy_values);

Tushar's solution is idiomatic, elegant, and does the same thing; but it might not be immediately understood by someone just starting out:

console.log([7, "ate", "", false, 9].filter(e=>e))

Just give it a few months and you'll be thinking fluently in one-liners :)


问:
Codeigniter URL shortening or routing Failed
I am trying to shorten the url

```<code>https://www.example.com/Flight_booking/search?flight%5Bjourneytype%5D=1&flight%5Bflyingfrom%5D%5B%5D=BLR&flight%5Bflyingto%5D%5B%5D=DEL&flight%5Bdepartingon%5D%5B%5D=31%2F07%2F2017&flight%5Badults%5D=1&flight%5Bchildren%5D=0&flight%5Binfant%5D=0&flight%5BFlightCabinClass%5D=2&seo=bangalore-delhi-flight
</code>```

to

```<code>mywebsiteurl/fly-to-a-beautiful-destination
</code>```

checked many examples and tried(both .htaccess url rewriting and and codeigniter routes), but no luck. Does any one have any solution for the same?
Tried:

Specify search friendly URLs

```<code>RewriteRule ^a-beautiful-url$ /Flight_booking/search?flight%5Bjourneytype%5D=1&flight%5Bflyingfrom%5D%5B%5D=BLR&flight%5Bflyingto%5D%5B%5D=DEL&flight%5Bdepartingon%5D%5B%5D=31%2F07%2F2017&flight%5Badults%5D=1&flight%5Bchildren%5D=0&flight%5Binfant%5D=0&flight%5BFlightCabinClass%5D=2&seo=bangalore-delhi-flight [L]
</code>```

Also in codeigniter routes tried:

```<code>$routes['a-beautiful-url'] = 'Flight_booking/search?flight%5Bjourneytype%5D=1&flight%5Bflyingfrom%5D%5B%5D=BLR&flight%5Bflyingto%5D%5B%5D=DEL&flight%5Bdepartingon%5D%5B%5D=31%2F07%2F2017&flight%5Badults%5D=1&flight%5Bchildren%5D=0&flight%5Binfant%5D=0&flight%5BFlightCabinClass%5D=2&seo=bangalore-delhi-flight';
</code>```

答:
If you specify your route as "a-beautiful-url", that's what it's going to be looking for. If you want it to go to "fly-to-a-beautiful-destination", that's what needs to be specified in the routing.

Also, routing is for the controller and a parameter. So the route would look something like

```<code>$route['fly-to-a-beautiful-destination/search/(:any)'] = 'flight_booking/search/$1';
</code>```

For SEO, CI discourages the use of the URI string. If you must use it, you'll have to figure out how to parse that.

Body:
I am trying to shorten the url

https://www.example.com/Flight_booking/search?flight%5Bjourneytype%5D=1&flight%5Bflyingfrom%5D%5B%5D=BLR&flight%5Bflyingto%5D%5B%5D=DEL&flight%5Bdepartingon%5D%5B%5D=31%2F07%2F2017&flight%5Badults%5D=1&flight%5Bchildren%5D=0&flight%5Binfant%5D=0&flight%5BFlightCabinClass%5D=2&seo=bangalore-delhi-flight

to

mywebsiteurl/fly-to-a-beautiful-destination

checked many examples and tried(both .htaccess url rewriting and and codeigniter routes), but no luck. Does any one have any solution for the same?
Tried:

Specify search friendly URLs

RewriteRule ^a-beautiful-url$ /Flight_booking/search?flight%5Bjourneytype%5D=1&flight%5Bflyingfrom%5D%5B%5D=BLR&flight%5Bflyingto%5D%5B%5D=DEL&flight%5Bdepartingon%5D%5B%5D=31%2F07%2F2017&flight%5Badults%5D=1&flight%5Bchildren%5D=0&flight%5Binfant%5D=0&flight%5BFlightCabinClass%5D=2&seo=bangalore-delhi-flight [L]

Also in codeigniter routes tried:

$routes['a-beautiful-url'] = 'Flight_booking/search?flight%5Bjourneytype%5D=1&flight%5Bflyingfrom%5D%5B%5D=BLR&flight%5Bflyingto%5D%5B%5D=DEL&flight%5Bdepartingon%5D%5B%5D=31%2F07%2F2017&flight%5Badults%5D=1&flight%5Bchildren%5D=0&flight%5Binfant%5D=0&flight%5BFlightCabinClass%5D=2&seo=bangalore-delhi-flight';

Body:
If you specify your route as "a-beautiful-url", that's what it's going to be looking for. If you want it to go to "fly-to-a-beautiful-destination", that's what needs to be specified in the routing.

Also, routing is for the controller and a parameter. So the route would look something like

$route['fly-to-a-beautiful-destination/search/(:any)'] = 'flight_booking/search/$1';

For SEO, CI discourages the use of the URI string. If you must use it, you'll have to figure out how to parse that.


答:
when you add a new post, filter the query like this change_actual_post = Post.objects.get(specialpost=0) and then change the status of your old post change_actual_post.specialpost = 2 finally save change_actual_post.save().

Add these 3 lines into your views.py file before add a new special post

Title: Django choices. How to set a option to be selected only once


问:
"ValueError: setting an array element with a sequence." TensorFlow
I tried to explore a simple demo，but got this error. How could I modify my code?

```<code>import tensorflow as tf

sess = tf.Session()

x_ = tf.Variable([[-9,6,-2,3], [-4,3,-1,10]], dtype=tf.float32)
x = tf.placeholder(tf.float32, shape=[4,2])
y = tf.nn.relu(x)

sess.run(tf.global_variables_initializer())
print(sess.run(x_))
print(sess.run(y,feed_dict={x:x_}))
</code>```

The output I get is:

```<code>[[ -9.   6.  -2.   3.]
 [ -4.   3.  -1.  10.]]

Traceback (most recent call last):
  File "C:\Users\jy\Documents\NetSarang\Xftp\Temporary\test.py", line 19, in <module>
    print(sess.run(y,feed_dict={x:x_}))
  File "C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 767, in run
    run_metadata_ptr)
  File "C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 938, in _run
    np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
  File "C:\Program Files\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 482, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.
</code>```

答:
First, the dimensionality of your x_ variable wrong: currently, it's of shape [2, 4], but you're attempting to use it in a slot that's expecting data of shape [4, 2].

Second, tf.Variable is meant to represent literally a variable (in the mathematical sense) within your neural net model that'll be tuned as you train your model -- it's a mechanism for maintaining state.

To provide actual input to train your model, you can simply pass in a regular Python array (or numpy array) instead.

Here's a fixed version of your code that appears to do what you want:

```<code>import tensorflow as tf

sess = tf.Session()

x = tf.placeholder(tf.float32, shape=[4,2])
y = tf.nn.relu(x)
sess.run(tf.global_variables_initializer())

x_ = [[-9, -4], [6, 3], [-2, -1], [3, 10]]
print(sess.run(y, feed_dict={x:x_}))
</code>```

If you really did want a node within your neural net to start off initialized with those values, I'd get rid of the placeholder and use x_directly:

```<code>import tensorflow as tf

sess = tf.Session()

x = tf.Variable([[-9, -4], [6, 3], [-2, -1], [3, 10]], dtype=tf.float32)
y = tf.nn.relu(x)
sess.run(tf.global_variables_initializer())

print(sess.run(y))
</code>```

This is probably not what you meant to do, though -- it's sort of unusual to have a model that doesn't accept any input.

Body:
I tried to explore a simple demo，but got this error. How could I modify my code?

import tensorflow as tf

sess = tf.Session()

x_ = tf.Variable([[-9,6,-2,3], [-4,3,-1,10]], dtype=tf.float32)
x = tf.placeholder(tf.float32, shape=[4,2])
y = tf.nn.relu(x)

sess.run(tf.global_variables_initializer())
print(sess.run(x_))
print(sess.run(y,feed_dict={x:x_}))

The output I get is:

[[ -9.   6.  -2.   3.]
 [ -4.   3.  -1.  10.]]

Traceback (most recent call last):
  File "C:\Users\jy\Documents\NetSarang\Xftp\Temporary\test.py", line 19, in <module>
    print(sess.run(y,feed_dict={x:x_}))
  File "C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 767, in run
    run_metadata_ptr)
  File "C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 938, in _run
    np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
  File "C:\Program Files\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 482, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

Body:
First, the dimensionality of your x_ variable wrong: currently, it's of shape [2, 4], but you're attempting to use it in a slot that's expecting data of shape [4, 2].

Second, tf.Variable is meant to represent literally a variable (in the mathematical sense) within your neural net model that'll be tuned as you train your model -- it's a mechanism for maintaining state.

To provide actual input to train your model, you can simply pass in a regular Python array (or numpy array) instead.

Here's a fixed version of your code that appears to do what you want:

import tensorflow as tf

sess = tf.Session()

x = tf.placeholder(tf.float32, shape=[4,2])
y = tf.nn.relu(x)
sess.run(tf.global_variables_initializer())

x_ = [[-9, -4], [6, 3], [-2, -1], [3, 10]]
print(sess.run(y, feed_dict={x:x_}))

If you really did want a node within your neural net to start off initialized with those values, I'd get rid of the placeholder and use x_directly:

import tensorflow as tf

sess = tf.Session()

x = tf.Variable([[-9, -4], [6, 3], [-2, -1], [3, 10]], dtype=tf.float32)
y = tf.nn.relu(x)
sess.run(tf.global_variables_initializer())

print(sess.run(y))

This is probably not what you meant to do, though -- it's sort of unusual to have a model that doesn't accept any input.


问:
Create Pages Automatically
Is there any method in Php by which I can create a page automatically based on a predefined template. Like if we create a new post in blogger it automatically creates page for that post with the name of that post, like this one:

http://learntoflash.blogspot.com/2009/12/exit-button-in-flash.html

Here Exit Button In Flash is the name of my post I have written and an automatic page is created for it.

Or like here on this website if we ask a question it automatically creates a page for that question. I want to know can I achieve this in Php or anything close to this ?

答:
...here on this website if we ask a question it automatically creates a page for that question.

It sounds like you may believe an actual file is created when you post a question. My bet would be that this page is generated via the question id in the URL.

The only files created would be cached output, which may or may not resemble actual HTML pages.

ContentLicense: CC BY-SA 2.5

Title: Create Pages Automatically


问:
Want to make it so prices actually reflect the choices
Hope everyone is having a good weekend!

If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!

var pizzaPrice = 0;

function Pizza(size,toppings,pizzaPrice) {
  this.size = size;
  this.toppings = toppings;
  this.pizzaPrice = 0;
}

Pizza.prototype.price = function() {
  if (this.size === "Small") {
    this.pizzaPrice += 2;
  }
  else if (this.size === "Medium") {
    this.pizzaPrice += 3;
  }
  else if (this.size === "Large") {
    this.pizzaPrice += 4;
  }
  if (this.toppings === "Cheese") {
    this.pizzaPrice += 3;
  }

  else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
    this.pizzaPrice += 10;
    console.log("hey");

  }

  else if (this.toppings === "Vegetarian") {
    this.pizzaPrice += 2;
  }
  else if (this.toppings === "Supreme") {
    this.pizzaPrice += 4;
  }
  else if (this.toppings === "Pepperoni") {
    this.pizzaPrice += 3;
  }

return this.pizzaPrice;
}

$(document).ready(function(){
  $("form#pizza").submit(function(event){
    event.preventDefault();

    var size = $("input[type=radio][name=size]:checked").val();
    var toppings = $("input[type=checkbox][name=toppings]:checked").val();
    var newPizza = new Pizza(size,toppings,pizzaPrice);
    newPizza.price();

    $("#responses").append("
" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "
");

      });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <title>Pizza Pizza</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.2.0.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <h2>Pizza Toppings</h2>
      </div>
      <form id="pizza">
        <div class="form-group">
          <p>What size would you like your pizza:</p>
          <input type="radio" name="size" value="Small">Small.<br>
          <input type="radio" name="size" value="Medium">Medium.<br>
          <input type="radio" name="size" value="Large">Large.<br>
        </div>
        <div class="form-group">
          <p>Which toppings would you like</p>
          <input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
          <input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
          <input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
          <input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
          <input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
          <input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
          <input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
          <input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
        </div>
       <button type="submit">Let's get your order</button>
      </form>
      <ul id="responses">
      </ul>
    </div>
  </body>
</html></code>```

答:
There are a number of issues -

1.) When you do

```<code>var toppings = $("input[type=checkbox][name=toppings]:checked").val();
</code>```

you already lost all the toppings except the first one. Instead you could use

```<code>var toppings = $("input[type=checkbox][name=toppings]:checked");
    var i = 0;
    var toppingVal;
    while(i < toppings.length){
        toppingVal += " "+(toppings[i]).value;
      i++;
    }
</code>```

2.) When you are calculating the price, you make use of if..else..if blocks. How can you add up multiple toppings, only one block would execute. use only if

3.) As per my suggestion you would get a string of toppings seperated by a space(' '). So you cannot be using === for comparison. Use indexOf to find if the toppings string contains a specific topping.

Take a look at this fiddle
https://jsfiddle.net/8u67x4nm/1/ . Works fine.

Body:
Hope everyone is having a good weekend!

If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!

var pizzaPrice = 0;

function Pizza(size,toppings,pizzaPrice) {
  this.size = size;
  this.toppings = toppings;
  this.pizzaPrice = 0;
}

Pizza.prototype.price = function() {
  if (this.size === "Small") {
    this.pizzaPrice += 2;
  }
  else if (this.size === "Medium") {
    this.pizzaPrice += 3;
  }
  else if (this.size === "Large") {
    this.pizzaPrice += 4;
  }
  if (this.toppings === "Cheese") {
    this.pizzaPrice += 3;
  }

  else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
    this.pizzaPrice += 10;
    console.log("hey");

  }

  else if (this.toppings === "Vegetarian") {
    this.pizzaPrice += 2;
  }
  else if (this.toppings === "Supreme") {
    this.pizzaPrice += 4;
  }
  else if (this.toppings === "Pepperoni") {
    this.pizzaPrice += 3;
  }

return this.pizzaPrice;
}

$(document).ready(function(){
  $("form#pizza").submit(function(event){
    event.preventDefault();

    var size = $("input[type=radio][name=size]:checked").val();
    var toppings = $("input[type=checkbox][name=toppings]:checked").val();
    var newPizza = new Pizza(size,toppings,pizzaPrice);
    newPizza.price();

    $("#responses").append("
" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "
");

      });
    });

<!DOCTYPE html>

    <title>Pizza Pizza</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">

Pizza Toppings

      <form id="pizza">

What size would you like your pizza:

          <input type="radio" name="size" value="Small">Small.

          <input type="radio" name="size" value="Medium">Medium.

          <input type="radio" name="size" value="Large">Large.

Which toppings would you like

          <input type="checkbox" name="toppings" value="Cheese">Cheese.

          <input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.

          <input type="checkbox" name="toppings" value="Supreme">Supreme.

          <input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.

          <input type="checkbox" name="toppings" value="Fruit">Fruit.

          <input type="checkbox" name="toppings" value="Bacon">Bacon.

          <input type="checkbox" name="toppings" value="Artichoke">Artichoke.

          <input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.

       <button type="submit">Let's get your order</button>
      </form>

Body:
There are a number of issues -

1.) When you do

var toppings = $("input[type=checkbox][name=toppings]:checked").val();

you already lost all the toppings except the first one. Instead you could use

var toppings = $("input[type=checkbox][name=toppings]:checked");
    var i = 0;
    var toppingVal;
    while(i < toppings.length){
        toppingVal += " "+(toppings[i]).value;
      i++;
    }

2.) When you are calculating the price, you make use of if..else..if blocks. How can you add up multiple toppings, only one block would execute. use only if

3.) As per my suggestion you would get a string of toppings seperated by a space(' '). So you cannot be using === for comparison. Use indexOf to find if the toppings string contains a specific topping.

Take a look at this fiddle
https://jsfiddle.net/8u67x4nm/1/ . Works fine.


问:
Illegal expression when pattern matching with maps in Erlang
I'm trying to execute sample code on the interactive shell from Armstrong's Erlang book. This is what the book says is the case:

```<code>1> Henry8 = #{ class => king, born => 1491, died => 1547 }. #{ born =>
1491, class=> king, died => 1547 }.
2> #{ born => B } = Henry8.
#{ born => 1491, class=> king, died => 1547 }.
</code>```

However, this is what I'm getting on the shell, it seems the pattern matching is failing:

```<code>1> Henry8 = #{ class => king, born => 1491, died => 1547 }.
#{born => 1491,class => king,died => 1547}
2> #{ born => B } = Henry8.
* 1: illegal pattern
</code>```

答:
=> is for constructing a map. To pattern match a map, you need to use := instead.

```<code>1> Henry8 = #{ class => king, born => 1491, died => 1547 }.
#{born => 1491,class => king,died => 1547}
2> #{ born := B } = Henry8.
#{born => 1491,class => king,died => 1547}
3> B.
1491
</code>```

This is documented in the section "Maps in Patterns" here.

Body:
I'm trying to execute sample code on the interactive shell from Armstrong's Erlang book. This is what the book says is the case:

1> Henry8 = #{ class => king, born => 1491, died => 1547 }. #{ born =>
1491, class=> king, died => 1547 }.
2> #{ born => B } = Henry8.
#{ born => 1491, class=> king, died => 1547 }.

However, this is what I'm getting on the shell, it seems the pattern matching is failing:

1> Henry8 = #{ class => king, born => 1491, died => 1547 }.
#{born => 1491,class => king,died => 1547}
2> #{ born => B } = Henry8.
* 1: illegal pattern

Body:
=> is for constructing a map. To pattern match a map, you need to use := instead.

1> Henry8 = #{ class => king, born => 1491, died => 1547 }.
#{born => 1491,class => king,died => 1547}
2> #{ born := B } = Henry8.
#{born => 1491,class => king,died => 1547}
3> B.
1491

This is documented in the section "Maps in Patterns" here.


问:
Why can't I query more than 1000 results for JIRA?
I'm using the Logstash Input Plugin exec to run a command periodically to get JIRA data. Even if I set maxResults=99999, only 1000 results are returned. Here is my code right now:

```<code>input {
    exec {
        command => "curl -u username:password https://mycompany.atlassian.net/rest/api/latest/search?project=project&maxResults=8500"
        interval => 300
        type => "issues"
    }

} output {
    elasticsearch {
        hosts => "localhost:9200"
        index => "jira"
    }
}
</code>```

I found online that if you run around 10 execs, and you set startAt to 0, 1000, 2000, etc, you get around 10000 responses. Is this faster than just one exec that pulls 8000 requests? How do I return more than 1000 responses with 1 exec?

答:
```<code><?php
$username="JIRA Email";
$password="JIRA Password";
$handle = curl_init();
$project_url="https://jirasite.atlassian.net/rest/api/2/search?jql=project='project id'&maxResults=100";
$project_url=trim($project_url);
 curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "GET");
 curl_setopt_array($handle, array(
    CURLOPT_URL => $project_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_HTTPHEADER => array("content-type:application/json"),
    CURLOPT_HEADER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_ENCODING => '',
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    CURLOPT_USERPWD => $username . ':' . $password
      ));
     $response   = curl_exec($handle);
     print_r($response);
</code>```

<p>?>
Response Wille be
{"expand":"schema,names","startAt":0,"maxResults":100,"total":52,"issues":[{"expand":............</p>

Body:
I'm using the Logstash Input Plugin exec to run a command periodically to get JIRA data. Even if I set maxResults=99999, only 1000 results are returned. Here is my code right now:

input {
    exec {
        command => "curl -u username:password https://mycompany.atlassian.net/rest/api/latest/search?project=project&maxResults=8500"
        interval => 300
        type => "issues"
    }

} output {
    elasticsearch {
        hosts => "localhost:9200"
        index => "jira"
    }
}

I found online that if you run around 10 execs, and you set startAt to 0, 1000, 2000, etc, you get around 10000 responses. Is this faster than just one exec that pulls 8000 requests? How do I return more than 1000 responses with 1 exec?

Body:
<?php
$username="JIRA Email";
$password="JIRA Password";
$handle = curl_init();
$project_url="https://jirasite.atlassian.net/rest/api/2/search?jql=project='project id'&maxResults=100";
$project_url=trim($project_url);
 curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "GET");
 curl_setopt_array($handle, array(
    CURLOPT_URL => $project_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_HTTPHEADER => array("content-type:application/json"),
    CURLOPT_HEADER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_ENCODING => '',
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    CURLOPT_USERPWD => $username . ':' . $password
      ));
     $response   = curl_exec($handle);
     print_r($response);

?>
Response Wille be
{"expand":"schema,names","startAt":0,"maxResults":100,"total":52,"issues":[{"expand":............


问:
spring boot application showing ??? characters instead of unicode
While reading from database the logs in my dao class shows junk characters in place of unicode characters. Sql developer shows correct values from oracle database also correct NLS language encoding is set on the database.

Below code works for standard jdbc:

```<code>connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "adminuser", "oracle");
Statement st=connection.createStatement();
ResultSet res=st.executeQuery("SELECT menu_item_name from pending_menu_item
where menu_item_id=6062");

    while(res.next()){
        System.out.println("itemName: "+res.getString(1));
    }
</code>```

Below is the url for springboot project which shows junk characters, I
uploaded to git hub.https://github.com/AyubOpen/spring-boot-jdbc/

```<code>package com.mkyong;

import com.mkyong.dao.CustomerRepository;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.List;
import static java.lang.System.exit;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

@Autowired
DataSource dataSource;

@Autowired
private CustomerRepository customerRepository;

@Autowired
private JdbcTemplate jdbcTemplate;

  public static void main(String[] args) throws Exception {
      SpringApplication.run(SpringBootConsoleApplication.class, args);
}

@Override
public void run(String... args) throws Exception {

// If you want to check the HikariDataSource settings
 HikariDataSource newds = (HikariDataSource)dataSource;
  System.out.println("getMaximumPoolSize = " + ((HikariDataSource)
  dataSource).getMaximumPoolSize());
  System.out.println("DATASOURCE = " +
  newds.getDataSourceProperties().getProperty("hikari.useUnicode"));

  if (args.length <= 0) {
    System.err.println("[Usage] java xxx.jar {display}");
   } else {
        if (args[0].equalsIgnoreCase("display")) {
        System.out.println("Display items...");
        List<String> list = customerRepository.findAll();
        list.forEach(x -> System.out.println(x));
      }
      System.out.println("Done!");
   }
  exit(0);
 }
}

package com.mkyong.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class CustomerRepository {

   @Autowired
   private JdbcTemplate jdbcTemplate;

   public List<String> findAll() {

    List<String> result = jdbcTemplate.query(
        "SELECT menu_item_name from pending_menu_item where
            menu_item_id=6062",
        (rs, rowNum) -> rs.getString("menu_item_name")
    );
  return result;
  }
}

application.properties
----------------------
spring.main.banner-mode=off
spring.datasource.initialize=true
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/xe
spring.datasource.username=jahezdbapp
spring.datasource.password=oracle
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.hikari.useUnicode=true
spring.datasource.hikari.characterEncoding=utf-8
spring.datasource.hikari.characterSetResults=utf8

# HikariCP settings
#60 sec
spring.datasource.hikari.connection-timeout=60000
# max 5
spring.datasource.hikari.maximum-pool-size=5
</code>```

答:
Add ?useUnicode=yes&characterEncoding=UTF-8 at the end of spring.datasource.url.

Set spring.datasource.sqlScriptEncoding=UTF-8 in application.properties

1 itself should solve the issue, 2 may not be necessary.

Body:
While reading from database the logs in my dao class shows junk characters in place of unicode characters. Sql developer shows correct values from oracle database also correct NLS language encoding is set on the database.

Below code works for standard jdbc:

connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "adminuser", "oracle");
Statement st=connection.createStatement();
ResultSet res=st.executeQuery("SELECT menu_item_name from pending_menu_item
where menu_item_id=6062");

    while(res.next()){
        System.out.println("itemName: "+res.getString(1));
    }

Below is the url for springboot project which shows junk characters, I
uploaded to git hub.https://github.com/AyubOpen/spring-boot-jdbc/

package com.mkyong;

import com.mkyong.dao.CustomerRepository;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.List;
import static java.lang.System.exit;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

@Autowired
DataSource dataSource;

@Autowired
private CustomerRepository customerRepository;

@Autowired
private JdbcTemplate jdbcTemplate;

  public static void main(String[] args) throws Exception {
      SpringApplication.run(SpringBootConsoleApplication.class, args);
}

@Override
public void run(String... args) throws Exception {

// If you want to check the HikariDataSource settings
 HikariDataSource newds = (HikariDataSource)dataSource;
  System.out.println("getMaximumPoolSize = " + ((HikariDataSource)
  dataSource).getMaximumPoolSize());
  System.out.println("DATASOURCE = " +
  newds.getDataSourceProperties().getProperty("hikari.useUnicode"));

  if (args.length <= 0) {
    System.err.println("[Usage] java xxx.jar {display}");
   } else {
        if (args[0].equalsIgnoreCase("display")) {
        System.out.println("Display items...");
        List<String> list = customerRepository.findAll();
        list.forEach(x -> System.out.println(x));
      }
      System.out.println("Done!");
   }
  exit(0);
 }
}

package com.mkyong.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class CustomerRepository {

   @Autowired
   private JdbcTemplate jdbcTemplate;

   public List<String> findAll() {

    List<String> result = jdbcTemplate.query(
        "SELECT menu_item_name from pending_menu_item where
            menu_item_id=6062",
        (rs, rowNum) -> rs.getString("menu_item_name")
    );
  return result;
  }
}

application.properties
----------------------
spring.main.banner-mode=off
spring.datasource.initialize=true
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/xe
spring.datasource.username=jahezdbapp
spring.datasource.password=oracle
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.hikari.useUnicode=true
spring.datasource.hikari.characterEncoding=utf-8
spring.datasource.hikari.characterSetResults=utf8

# HikariCP settings
#60 sec
spring.datasource.hikari.connection-timeout=60000
# max 5
spring.datasource.hikari.maximum-pool-size=5


问:
ASP Core: URL Rewrite not working when using AddIISUrlRewrite
I am trying to re-write my URL for the 3 following condition:
1. Remove .php extention
2. Remove .html extention
3. redirect all "www" to non-www

I was trying to use the ASP Core's Rewrite package and run the following code:

```<code>app.UseRewriter(new RewriteOptions().AddIISUrlRewrite(env.WebRootFileProvider, "files/IISUrlRewrite.xml"));
</code>```

on files/IISUrlRewrite.xml, I have this code:

```<code><rewrite>
  <rules>
    <rule name="RemovePHP">
      <match url="^(.*).php$" />
      <action type="Rewrite" url="{R:1}" />
    </rule>
    <rule name="RemoveHTML">
      <match url="^(.*).html" />
      <action type="Rewrite" url="{R:1}" />
    </rule>
    <rule name="www to non-www" stopProcessing="true">
      <match url="(www.*)" negate="false"></match>
      <action type="Redirect" url="http://example.com/{R:1}"></action>
      <conditions>
        <add input="{HTTP_HOST}" pattern="^example\.com$" negate="true"></add>
      </conditions>
    </rule>
  </rules>
</rewrite>
</code>```

However, this is not working. www's are not being redirected, .php are not being removed. This code works fine when I put it in my web.config file.

Also, I understand I could do the same thing using the middleware Microsoft Documentation: Url Rewriting

Thank you for the help.

答:
This usually happens when you add the RewriteMiddleware after configuring the static file handling using the app.UseStaticFiles() method: if you do that, the RewriteMiddleware might be superseeded by the one in charge of the static files, which could mess up your rewrite rules.

In other words, do not do this:

```<code>app.UseDefaultFiles();

app.UseStaticFiles(new StaticFileOptions(...));

app.UseRewriter(new RewriteOptions(...)); // <- MIGHT NOT WORK AS EXPECTED
</code>```

And do this instead:

```<code>app.UseDefaultFiles();

app.UseRewriter(new RewriteOptions(...));  // <- WORKS

app.UseStaticFiles(new StaticFileOptions(...));
</code>```

Body:
I am trying to re-write my URL for the 3 following condition:
1. Remove .php extention
2. Remove .html extention
3. redirect all "www" to non-www

I was trying to use the ASP Core's Rewrite package and run the following code:

app.UseRewriter(new RewriteOptions().AddIISUrlRewrite(env.WebRootFileProvider, "files/IISUrlRewrite.xml"));

on files/IISUrlRewrite.xml, I have this code:

<rewrite>
  <rules>
    <rule name="RemovePHP">
      <match url="^(.*).php$" />
      <action type="Rewrite" url="{R:1}" />
    </rule>
    <rule name="RemoveHTML">
      <match url="^(.*).html" />
      <action type="Rewrite" url="{R:1}" />
    </rule>
    <rule name="www to non-www" stopProcessing="true">
      <match url="(www.*)" negate="false"></match>
      <action type="Redirect" url="http://example.com/{R:1}"></action>
      <conditions>
        <add input="{HTTP_HOST}" pattern="^example\.com$" negate="true"></add>
      </conditions>
    </rule>
  </rules>
</rewrite>

However, this is not working. www's are not being redirected, .php are not being removed. This code works fine when I put it in my web.config file.

Also, I understand I could do the same thing using the middleware Microsoft Documentation: Url Rewriting

Thank you for the help.

Body:
This usually happens when you add the RewriteMiddleware after configuring the static file handling using the app.UseStaticFiles() method: if you do that, the RewriteMiddleware might be superseeded by the one in charge of the static files, which could mess up your rewrite rules.

In other words, do not do this:

app.UseDefaultFiles();

app.UseStaticFiles(new StaticFileOptions(...));

app.UseRewriter(new RewriteOptions(...)); // <- MIGHT NOT WORK AS EXPECTED

And do this instead:

app.UseDefaultFiles();

app.UseRewriter(new RewriteOptions(...));  // <- WORKS

app.UseStaticFiles(new StaticFileOptions(...));


问:
Add the same event handler to radio buttons and checkboxes
I am trying to have a function add the values of selected check boxes and radio buttons.  I have created a function that can add the values of the check boxes and a function for the radio buttons but am having trouble combining the two into one working function.  I think my issue is with having both radio and checkbox elements associated with the .click()

My code can be seen here:
https://jsfiddle.net/Buleria28/nz43u7x8/2/

The HTML is:

```<code><input type="checkbox" value="1" />test 1<br/>
<input type="checkbox" value="2" />test 2<br/>
<input type="checkbox" value="3" />test 3<br/>

<input type="radio" name="test" value="1" />test 4
<input type="radio" name="test" value="2" />test 5
<div id='sum'></div>
</code>```

The jQuery is:

```<code>jQuery(document).ready(function($) {
var sum = 0;

$("input:checkbox"),$("input:radio").click(function() {
   sum = 0;
    $("input:checkbox:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });

   sum = 0;
    $("input:radio:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });
    $('#sum').html(sum);
  });
});
</code>```

答:
Here you go with the solution https://jsfiddle.net/nz43u7x8/5/</p>

```<code>jQuery(document).ready(function($) {
    var sum = 0;

    $("input:checkbox, input:radio").click(function() {
        sum = 0;
        $("input:checkbox:checked").each(function(idx, elm) {
            sum += parseInt(elm.value, 10);
        });

        $("input:radio:checked").each(function(idx, elm) {
            sum += parseInt(elm.value, 10);
        });
        $('#sum').html(sum);
    });
});
</code>```

Body:
I am trying to have a function add the values of selected check boxes and radio buttons.  I have created a function that can add the values of the check boxes and a function for the radio buttons but am having trouble combining the two into one working function.  I think my issue is with having both radio and checkbox elements associated with the .click()

My code can be seen here:
https://jsfiddle.net/Buleria28/nz43u7x8/2/

The HTML is:

<input type="checkbox" value="1" />test 1

<input type="checkbox" value="2" />test 2

<input type="checkbox" value="3" />test 3

<input type="radio" name="test" value="1" />test 4
<input type="radio" name="test" value="2" />test 5

The jQuery is:

jQuery(document).ready(function($) {
var sum = 0;

$("input:checkbox"),$("input:radio").click(function() {
   sum = 0;
    $("input:checkbox:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });

   sum = 0;
    $("input:radio:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });
    $('#sum').html(sum);
  });
});

Body:
Here you go with the solution https://jsfiddle.net/nz43u7x8/5/

jQuery(document).ready(function($) {
    var sum = 0;

    $("input:checkbox, input:radio").click(function() {
        sum = 0;
        $("input:checkbox:checked").each(function(idx, elm) {
            sum += parseInt(elm.value, 10);
        });

        $("input:radio:checked").each(function(idx, elm) {
            sum += parseInt(elm.value, 10);
        });
        $('#sum').html(sum);
    });
});


问:
Debugging on Windows 98: Get code line from EIP
I am coding in Windows 98(DOS mode) and my program is crashing badly. I can reproduce the crash just fine, but my normal debugging tricks(stack trace, printf the whole thing to isolate the crash) are failing, because the combination of graphics mode(VBE), DOS mode and interrupt handling is apparently not what GDB was made for.

I've tried commenting parts of my code to isolate the problem but I can not trace the code location of the crash exactly.

So all I can get is a bunch of registers. Is there any way to retrieve a line of code from registers(like EIP)? I am coding in C.

答:
After some googling, I found some GDB documentation with this:

info symbol addr

Using this command seems to be the closest thing I could find to get a function name from an address. It won't give the exact line of code, but it's better than nothing.


问:
Write multiple cells at once in Excel VBA
In Excel VBA I am using some code to update the cells. Like:

```<code>for i = 1 to 1000
    for j = 1 to 1000
        cells(j,i)=<whatever_different_in_each_cell>
    next
next
</code>```

Is there a way to update all cells at once, instead of updating each cell individually ? Reason is that updating one cell in Excel is time consuming and when there are many of them, then it quickly becomes endless.

答:
```<code>Range(<...>).Value = Array (value1, value2, <...>, valueN)
</code>```

The number of values must be exactly the same as the number of cells in the Range, otherwise, the range will be filled with #VALUE!s.

Body:
In Excel VBA I am using some code to update the cells. Like:

for i = 1 to 1000
    for j = 1 to 1000
        cells(j,i)=<whatever_different_in_each_cell>
    next
next

Is there a way to update all cells at once, instead of updating each cell individually ? Reason is that updating one cell in Excel is time consuming and when there are many of them, then it quickly becomes endless.

Body:
Range(<...>).Value = Array (value1, value2, <...>, valueN)

The number of values must be exactly the same as the number of cells in the Range, otherwise, the range will be filled with #VALUE!s.


问:
Single.just exception
I'm stuck to understand why RxJava does not capture my exception and it just crashes. The exception occurs while getting the object to emit.

Here is how my code looks like:

```<code>TestService testService = new TestService();
Single.just(testService.testGetUser())
      .subscribeOn(Schedulers.newThread())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(new DisposableSingleObserver<User>() {
        @Override
        public void onSuccess(@NonNull User user) {
          Log.d(TAG, "onSuccess(): Launching Home Activity");
          Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
          startActivity(intent);
        }

        @Override
        public void onError(@NonNull Throwable e) {
          Log.d(TAG, "onError()");
        }
      });
</code>```

My TestService class looks like:

```<code>public class TestService {
public User logInUser(LogInData logInData) throws RuntimeException {
        Log.d(TAG, "logInUser(): Logging user in");
        User user = this.guideMeAroundData.logInUser(logInData);
        return user;
      }
}
</code>```

In my logInUser() method I'm throwing an exception if the user is not valid. This causes my whole Android app to crash.

It looks like this is not the correct way to do it. Could anybody please tell how should I handle an scenario where an exception is thrown while getting the object(s) to be emitted?

答:
Unchecked exceptions are catched by the RxJava for the most part.

But for checked exceptions you need to provide your own try{}catch(){}
block.

One example would be -

```<code>String transform(String input) throws IOException;

Observable.just("Hello!")
  .map(input -> {
    try {
      return transform(input);
    } catch (Throwable t) {
      throw Exceptions.propagate(t);
    }
  })
</code>```

Check out this post for info, it explained very well.

http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/

Title: Single.just exception

Body:
I'm stuck to understand why RxJava does not capture my exception and it just crashes. The exception occurs while getting the object to emit.

Here is how my code looks like:

TestService testService = new TestService();
Single.just(testService.testGetUser())
      .subscribeOn(Schedulers.newThread())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(new DisposableSingleObserver<User>() {
        @Override
        public void onSuccess(@NonNull User user) {
          Log.d(TAG, "onSuccess(): Launching Home Activity");
          Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
          startActivity(intent);
        }

        @Override
        public void onError(@NonNull Throwable e) {
          Log.d(TAG, "onError()");
        }
      });

My TestService class looks like:

public class TestService {
public User logInUser(LogInData logInData) throws RuntimeException {
        Log.d(TAG, "logInUser(): Logging user in");
        User user = this.guideMeAroundData.logInUser(logInData);
        return user;
      }
}

In my logInUser() method I'm throwing an exception if the user is not valid. This causes my whole Android app to crash.

It looks like this is not the correct way to do it. Could anybody please tell how should I handle an scenario where an exception is thrown while getting the object(s) to be emitted?

Body:
Unchecked exceptions are catched by the RxJava for the most part.

But for checked exceptions you need to provide your own try{}catch(){}
block.

One example would be -

String transform(String input) throws IOException;

Observable.just("Hello!")
  .map(input -> {
    try {
      return transform(input);
    } catch (Throwable t) {
      throw Exceptions.propagate(t);
    }
  })

Check out this post for info, it explained very well.

http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/


问:
Golang Decode a BSON with special character Keys to a struct
I have a Golang struct called Person where all the properties have to be exported:

```<code>type Person struct {
    Id         string
    Name       string
}
</code>```

Now I need to encode my MongoDB BSON response to this Person struct.  The BSON looks like:

```<code>{
  "_id": "ajshJSH78N",
  "Name": "Athavan Kanapuli"
}
</code>```

The Golang code to encode the BSON is:

```<code>    mongoRecord := Person{}
    c := response.session.DB("mydb").C("users")
    err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)
</code>```

The Problem:

_id is not getting encoded into Id

If I change the Person property into _Id, then it won't be exported.

How can I solve this problem?

答:
I tried to put a json tag like ,

```<code>type Person struct {
    Id         string   `json:"_id"`
    Name       string  // this field match with json, so mapping not need
}
</code>```

But still it didn't work.  Because the Mongodb returns '_id' which is of type bson.ObjectId  .  Hence changing the Struct tag to   bson:"_id" and the type of the Person struct has been changed from string to bson.ObjectId. The changes done are as follows ,

```<code>type Person struct {
    Id         bson.ObjectId `bson:"_id"`
    Name       string
    UserName   string
    IsAdmin    bool
    IsApprover bool
}
</code>```

And It works!

Body:
I have a Golang struct called Person where all the properties have to be exported:

type Person struct {
    Id         string
    Name       string
}

Now I need to encode my MongoDB BSON response to this Person struct.  The BSON looks like:

{
  "_id": "ajshJSH78N",
  "Name": "Athavan Kanapuli"
}

The Golang code to encode the BSON is:

    mongoRecord := Person{}
    c := response.session.DB("mydb").C("users")
    err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)

The Problem:

_id is not getting encoded into Id

If I change the Person property into _Id, then it won't be exported.

How can I solve this problem?

Body:
I tried to put a json tag like ,

type Person struct {
    Id         string   `json:"_id"`
    Name       string  // this field match with json, so mapping not need
}

But still it didn't work.  Because the Mongodb returns '_id' which is of type bson.ObjectId  .  Hence changing the Struct tag to   bson:"_id" and the type of the Person struct has been changed from string to bson.ObjectId. The changes done are as follows ,

type Person struct {
    Id         bson.ObjectId `bson:"_id"`
    Name       string
    UserName   string
    IsAdmin    bool
    IsApprover bool
}

And It works!