qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
44,347,923 |
I'm using spring-boot `@Scheduled` annotation with fixedDelay in milliseconds as documented in javadoc:
>
> Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
>
>
>
Code:
```
@Scheduled(fixedDelay=1000)
public void task() {
LOG.info("START: " + System.currentTimeInMillis());
....do some work here...
LOG.info("END: " + System.currentTimeInMillis());
}
```
And sometimes I get such output that time between previous task end and next task starts is less than `1000ms` for about `2-30 milliseconds`.
Is it normal due to some granularity or why is it happening? Is there any guaranties about this delta value?
|
2017/06/03
|
[
"https://Stackoverflow.com/questions/44347923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308639/"
] |
There are different ways in which you can use **@Scheduled** annotation.
According to the [documentation](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-scheduled):
The **fixedRate** invokes the method every t ms but the time delay is measured from the start of the invocation. If t ms are passed and the method is still in execution then the next invocation will wait for it to finish and will invoke right after the first one. Try putting `Thread.sleep(3000)` in your method. I think that your method is taking about 950ms to complete.
If you want to wait after finishing the execution you can use **fixedDelay**.
|
How `@Scheduled(fixedDelay=1000)` works is, it will run this void method every `1000 ms`(If this task finish execution `<` `1000 ms` or this will run asynchronously). If `>` `1000ms` it the execution task will get into a task queue in the Executor service used. There is **no** connection with the **end of task and the start of next task** but a connection with the **start of a task and start of a next task**.
|
20,822,274 |
I have a chessboard that colors specific squares blue (`Color.BLUE`), and I want to have the program know when the user clicks on blue squares. I know the X and Y coordinates of the click, but how do I do this? Others create an image and then use `.getRGB()`, but is there another way?
|
2013/12/29
|
[
"https://Stackoverflow.com/questions/20822274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3141193/"
] |
You should not be trying to "get the color of a pixel". The logic that handles the chessboard knows what the board layout is and what pixels it's coloring, so it should be retaining enough of this information so that it can tell what square is being clicked on. The OOP way to do this is: define a class `Chessboard` whose purpose is to represent a chessboard drawn in the window (or Swing component, or whatever). There should be a method to draw the chessboard; that method will keep track of the range of pixels are used to draw each square. (Since each square will probably have the same height and width, you shouldn't actually need to keep an array of pixel coordinates; keeping just the coordinate of the upper left corner of the chessboard will be enough, and you'll add something like `width * columnNumber` or `height * rowNumber` to get the coordinate of each square.) The data about where the squares are drawn will be in member fields in the `Chessboard`. Then you can add a method that asks the `Chessboard` "what square contains the pixel at coordinates X and Y?". I've left out a lot of details, but I think that's the best general approach for this problem.
|
Yes there is another and a better way!
As you already have `x` and `y` coordinates of **click**, you can now check where these coordinates fall in the chess board grid and you can know exactly which box was clicked.
As chessboards squares are rendered at specific coordinates by you, i guess so, you can perform an algorithm to compare `x` and `y` coordinates against those of **square** and you will have the **position**.
If this don't help let me know with more specifics, I may be able to help you then.
|
20,822,274 |
I have a chessboard that colors specific squares blue (`Color.BLUE`), and I want to have the program know when the user clicks on blue squares. I know the X and Y coordinates of the click, but how do I do this? Others create an image and then use `.getRGB()`, but is there another way?
|
2013/12/29
|
[
"https://Stackoverflow.com/questions/20822274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3141193/"
] |
Yes there is another and a better way!
As you already have `x` and `y` coordinates of **click**, you can now check where these coordinates fall in the chess board grid and you can know exactly which box was clicked.
As chessboards squares are rendered at specific coordinates by you, i guess so, you can perform an algorithm to compare `x` and `y` coordinates against those of **square** and you will have the **position**.
If this don't help let me know with more specifics, I may be able to help you then.
|
Trying to use the color of the pixel for this is perverse... I'm horrified. No, do this:
1. Use the mouse x and y to determine which square was clicked.
2. Using the same rule you used to determine the "specific" squares to color blue: determine the nature of the clicked square and take the appropriate action.
|
20,822,274 |
I have a chessboard that colors specific squares blue (`Color.BLUE`), and I want to have the program know when the user clicks on blue squares. I know the X and Y coordinates of the click, but how do I do this? Others create an image and then use `.getRGB()`, but is there another way?
|
2013/12/29
|
[
"https://Stackoverflow.com/questions/20822274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3141193/"
] |
You should not be trying to "get the color of a pixel". The logic that handles the chessboard knows what the board layout is and what pixels it's coloring, so it should be retaining enough of this information so that it can tell what square is being clicked on. The OOP way to do this is: define a class `Chessboard` whose purpose is to represent a chessboard drawn in the window (or Swing component, or whatever). There should be a method to draw the chessboard; that method will keep track of the range of pixels are used to draw each square. (Since each square will probably have the same height and width, you shouldn't actually need to keep an array of pixel coordinates; keeping just the coordinate of the upper left corner of the chessboard will be enough, and you'll add something like `width * columnNumber` or `height * rowNumber` to get the coordinate of each square.) The data about where the squares are drawn will be in member fields in the `Chessboard`. Then you can add a method that asks the `Chessboard` "what square contains the pixel at coordinates X and Y?". I've left out a lot of details, but I think that's the best general approach for this problem.
|
Trying to use the color of the pixel for this is perverse... I'm horrified. No, do this:
1. Use the mouse x and y to determine which square was clicked.
2. Using the same rule you used to determine the "specific" squares to color blue: determine the nature of the clicked square and take the appropriate action.
|
20,822,274 |
I have a chessboard that colors specific squares blue (`Color.BLUE`), and I want to have the program know when the user clicks on blue squares. I know the X and Y coordinates of the click, but how do I do this? Others create an image and then use `.getRGB()`, but is there another way?
|
2013/12/29
|
[
"https://Stackoverflow.com/questions/20822274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3141193/"
] |
You should not be trying to "get the color of a pixel". The logic that handles the chessboard knows what the board layout is and what pixels it's coloring, so it should be retaining enough of this information so that it can tell what square is being clicked on. The OOP way to do this is: define a class `Chessboard` whose purpose is to represent a chessboard drawn in the window (or Swing component, or whatever). There should be a method to draw the chessboard; that method will keep track of the range of pixels are used to draw each square. (Since each square will probably have the same height and width, you shouldn't actually need to keep an array of pixel coordinates; keeping just the coordinate of the upper left corner of the chessboard will be enough, and you'll add something like `width * columnNumber` or `height * rowNumber` to get the coordinate of each square.) The data about where the squares are drawn will be in member fields in the `Chessboard`. Then you can add a method that asks the `Chessboard` "what square contains the pixel at coordinates X and Y?". I've left out a lot of details, but I think that's the best general approach for this problem.
|
I would store an array of `Rectangle`s and find out which one contains the point when clicked.

```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChessBoard extends JPanel {
public static final int SIZE = 400;
public static final int COUNT = 8;
public static final int TILE_SIZE = SIZE / COUNT;
public static final Color RED = Color.RED;
public static final Color BLUE = Color.BLUE;
public static Tile[][] tiles;
static {
ChessBoard c = new ChessBoard();
tiles = new Tile[COUNT][COUNT];
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
tiles[i][j] = c.new Tile(i * TILE_SIZE, j * TILE_SIZE,
TILE_SIZE, TILE_SIZE);
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
ChessBoard c = new ChessBoard();
f.setTitle("Chessboard Tile Click");
f.setContentPane(c);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public ChessBoard() {
setPreferredSize(new Dimension(SIZE, SIZE));
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
Rectangle tile = tiles[i][j];
if (tile.contains(p)) {
JOptionPane.showMessageDialog(null,
String.format("Clicked Tile: %s", tile));
break;
}
}
}
}
});
}
@Override
protected void paintComponent(Graphics g) {
boolean flip = false;
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
Rectangle tile = tiles[i][j];
g.setColor((flip = !flip) ? BLUE : RED);
g.fillRect(tile.x, tile.y, TILE_SIZE, TILE_SIZE);
g.setColor(Color.WHITE);
g.drawString(tile.toString(), tile.x + (TILE_SIZE / 2) - 8,
tile.y + (TILE_SIZE / 2) + 6);
}
flip = !flip;
}
}
private class Tile extends Rectangle {
public Tile(int x, int y, int width, int height) {
super(x, y, width, height);
}
@Override
public String toString() {
return String.format("%c%d", 'A' + x / TILE_SIZE, COUNT - y
/ TILE_SIZE);
}
}
}
```
|
20,822,274 |
I have a chessboard that colors specific squares blue (`Color.BLUE`), and I want to have the program know when the user clicks on blue squares. I know the X and Y coordinates of the click, but how do I do this? Others create an image and then use `.getRGB()`, but is there another way?
|
2013/12/29
|
[
"https://Stackoverflow.com/questions/20822274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3141193/"
] |
I would store an array of `Rectangle`s and find out which one contains the point when clicked.

```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChessBoard extends JPanel {
public static final int SIZE = 400;
public static final int COUNT = 8;
public static final int TILE_SIZE = SIZE / COUNT;
public static final Color RED = Color.RED;
public static final Color BLUE = Color.BLUE;
public static Tile[][] tiles;
static {
ChessBoard c = new ChessBoard();
tiles = new Tile[COUNT][COUNT];
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
tiles[i][j] = c.new Tile(i * TILE_SIZE, j * TILE_SIZE,
TILE_SIZE, TILE_SIZE);
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
ChessBoard c = new ChessBoard();
f.setTitle("Chessboard Tile Click");
f.setContentPane(c);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public ChessBoard() {
setPreferredSize(new Dimension(SIZE, SIZE));
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
Rectangle tile = tiles[i][j];
if (tile.contains(p)) {
JOptionPane.showMessageDialog(null,
String.format("Clicked Tile: %s", tile));
break;
}
}
}
}
});
}
@Override
protected void paintComponent(Graphics g) {
boolean flip = false;
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
Rectangle tile = tiles[i][j];
g.setColor((flip = !flip) ? BLUE : RED);
g.fillRect(tile.x, tile.y, TILE_SIZE, TILE_SIZE);
g.setColor(Color.WHITE);
g.drawString(tile.toString(), tile.x + (TILE_SIZE / 2) - 8,
tile.y + (TILE_SIZE / 2) + 6);
}
flip = !flip;
}
}
private class Tile extends Rectangle {
public Tile(int x, int y, int width, int height) {
super(x, y, width, height);
}
@Override
public String toString() {
return String.format("%c%d", 'A' + x / TILE_SIZE, COUNT - y
/ TILE_SIZE);
}
}
}
```
|
Trying to use the color of the pixel for this is perverse... I'm horrified. No, do this:
1. Use the mouse x and y to determine which square was clicked.
2. Using the same rule you used to determine the "specific" squares to color blue: determine the nature of the clicked square and take the appropriate action.
|
40,780 |
I wrote this function last year to convert between the two encodings and just found it. It takes a text buffer and its size, then converts to UTF-8 if there's enough space.
What should be changed to improve quality?
```
int iso88951_to_utf8(unsigned char *content, size_t max_size)
{
unsigned char *copy;
size_t conversion_count; //number of chars to convert / bytes to add
copy = content;
conversion_count = 0;
//first run to see if there's enough space for the new bytes
while(*content)
{
if(*content >= 0x80)
{
++conversion_count;
}
++content;
}
if(content - copy + conversion_count >= max_size)
{
return ERROR;
}
while(content >= copy && conversion_count)
{
//repositioning current characters to make room for new bytes
if(*content < 0x80)
{
*(content + conversion_count) = *content;
}
else
{
*(content + conversion_count) = 0x80 | (*content & 0x3f); //last byte
*(content + --conversion_count) = 0xc0 | *content >> 6; //first byte
}
--content;
}
return SUCCESS;
}
```
|
2014/02/03
|
[
"https://codereview.stackexchange.com/questions/40780",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/26675/"
] |
The character set is named ISO-8859-1, not ISO-8895-1. Rename your function accordingly.
Change the return value to be more informative:
* Return 0 on success.
* If `max_size` is too small, return the minimum value of `max_size` that would be sufficient to accommodate the output (including the trailing `\0`).
I would also change the parameter to take a signed `char *` to be a bit more natural.
I think that the implementation could look tidier if you dealt with pointers instead of offsets.
It would be nice if you NUL-terminated the result, so that the caller does not have to zero out the entire buffer before calling this function.
```
size_t iso8859_1_to_utf8(char *content, size_t max_size)
{
char *src, *dst;
//first run to see if there's enough space for the new bytes
for (src = dst = content; *src; src++, dst++)
{
if (*src & 0x80)
{
// If the high bit is set in the ISO-8859-1 representation, then
// the UTF-8 representation requires two bytes (one more than usual).
++dst;
}
}
if (dst - content + 1 > max_size)
{
// Inform caller of the space required
return dst - content + 1;
}
*(dst + 1) = '\0';
while (dst > src)
{
if (*src & 0x80)
{
*dst-- = 0x80 | (*src & 0x3f); // trailing byte
*dst-- = 0xc0 | (*((unsigned char *)src--) >> 6); // leading byte
}
else
{
*dst-- = *src--;
}
}
return 0; // SUCCESS
}
```
|
Minor quibbles.
1. I would prefer to see the variables assigned to when defined.
2. Use a macro instead of the hard coded value of 0x80 or 0x3F. For someone who is not familiar with the ins and outs of UTF-8 or ISO-8895-1 naming them something like MASK\_END or UPPER\_VALUE makes for easier understanding.
|
40,780 |
I wrote this function last year to convert between the two encodings and just found it. It takes a text buffer and its size, then converts to UTF-8 if there's enough space.
What should be changed to improve quality?
```
int iso88951_to_utf8(unsigned char *content, size_t max_size)
{
unsigned char *copy;
size_t conversion_count; //number of chars to convert / bytes to add
copy = content;
conversion_count = 0;
//first run to see if there's enough space for the new bytes
while(*content)
{
if(*content >= 0x80)
{
++conversion_count;
}
++content;
}
if(content - copy + conversion_count >= max_size)
{
return ERROR;
}
while(content >= copy && conversion_count)
{
//repositioning current characters to make room for new bytes
if(*content < 0x80)
{
*(content + conversion_count) = *content;
}
else
{
*(content + conversion_count) = 0x80 | (*content & 0x3f); //last byte
*(content + --conversion_count) = 0xc0 | *content >> 6; //first byte
}
--content;
}
return SUCCESS;
}
```
|
2014/02/03
|
[
"https://codereview.stackexchange.com/questions/40780",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/26675/"
] |
How usable is the function? It relies on the `content` string occupying a
buffer large enough to be extended. And if you take the suggestion from
@200\_success that on error the function returns the minimum size necessary,
the user then has the added complexity of having to handle that error by
allocating a buffer and it must free the allocated buffer later - but it
must keep a note of whether the buffer was allocated.
Although I dislike dynamic allocation, I think this is a case where it makes
sense always to allocate a new string in the function.
Here is a version that allocates space:
```
char* iso88959_to_utf8(const char *str)
{
char *utf8 = malloc(1 + (2 * strlen(str)));
if (utf8) {
char *c = utf8;
for (; *str; ++str) {
if (*str & 0x80) {
*c++ = *str;
} else {
*c++ = (char) (0xc0 | (unsigned) *str >> 6);
*c++ = (char) (0x80 | (*str & 0x3f));
}
}
*c++ = '\0';
}
return utf8;
}
```
You could add a `realloc` call at the end to trim the excess space if you
thought it necessary (I'm not sure that it is, but it might depend upon the
application).
|
Minor quibbles.
1. I would prefer to see the variables assigned to when defined.
2. Use a macro instead of the hard coded value of 0x80 or 0x3F. For someone who is not familiar with the ins and outs of UTF-8 or ISO-8895-1 naming them something like MASK\_END or UPPER\_VALUE makes for easier understanding.
|
40,780 |
I wrote this function last year to convert between the two encodings and just found it. It takes a text buffer and its size, then converts to UTF-8 if there's enough space.
What should be changed to improve quality?
```
int iso88951_to_utf8(unsigned char *content, size_t max_size)
{
unsigned char *copy;
size_t conversion_count; //number of chars to convert / bytes to add
copy = content;
conversion_count = 0;
//first run to see if there's enough space for the new bytes
while(*content)
{
if(*content >= 0x80)
{
++conversion_count;
}
++content;
}
if(content - copy + conversion_count >= max_size)
{
return ERROR;
}
while(content >= copy && conversion_count)
{
//repositioning current characters to make room for new bytes
if(*content < 0x80)
{
*(content + conversion_count) = *content;
}
else
{
*(content + conversion_count) = 0x80 | (*content & 0x3f); //last byte
*(content + --conversion_count) = 0xc0 | *content >> 6; //first byte
}
--content;
}
return SUCCESS;
}
```
|
2014/02/03
|
[
"https://codereview.stackexchange.com/questions/40780",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/26675/"
] |
The character set is named ISO-8859-1, not ISO-8895-1. Rename your function accordingly.
Change the return value to be more informative:
* Return 0 on success.
* If `max_size` is too small, return the minimum value of `max_size` that would be sufficient to accommodate the output (including the trailing `\0`).
I would also change the parameter to take a signed `char *` to be a bit more natural.
I think that the implementation could look tidier if you dealt with pointers instead of offsets.
It would be nice if you NUL-terminated the result, so that the caller does not have to zero out the entire buffer before calling this function.
```
size_t iso8859_1_to_utf8(char *content, size_t max_size)
{
char *src, *dst;
//first run to see if there's enough space for the new bytes
for (src = dst = content; *src; src++, dst++)
{
if (*src & 0x80)
{
// If the high bit is set in the ISO-8859-1 representation, then
// the UTF-8 representation requires two bytes (one more than usual).
++dst;
}
}
if (dst - content + 1 > max_size)
{
// Inform caller of the space required
return dst - content + 1;
}
*(dst + 1) = '\0';
while (dst > src)
{
if (*src & 0x80)
{
*dst-- = 0x80 | (*src & 0x3f); // trailing byte
*dst-- = 0xc0 | (*((unsigned char *)src--) >> 6); // leading byte
}
else
{
*dst-- = *src--;
}
}
return 0; // SUCCESS
}
```
|
I'm not sure why you have `content >= copy` in your second while loop. I would hope that `while(conversion_count)` should be sufficient.
Your `while` loops could be `for` loops.
More comments would make it easier to read:
* `//first run to see how many extra bytes we'll need`
* `//convert bytes from last to first to avoid altering not-yet-converted bytes`
* I'd appreciate a link to whichever section of an ISO-8895-1 specification which states what bit-twiddling is needed (I can see what the code does in the final loop, but have not seen the specification of what it's supposed to do so haven't verified that).
|
40,780 |
I wrote this function last year to convert between the two encodings and just found it. It takes a text buffer and its size, then converts to UTF-8 if there's enough space.
What should be changed to improve quality?
```
int iso88951_to_utf8(unsigned char *content, size_t max_size)
{
unsigned char *copy;
size_t conversion_count; //number of chars to convert / bytes to add
copy = content;
conversion_count = 0;
//first run to see if there's enough space for the new bytes
while(*content)
{
if(*content >= 0x80)
{
++conversion_count;
}
++content;
}
if(content - copy + conversion_count >= max_size)
{
return ERROR;
}
while(content >= copy && conversion_count)
{
//repositioning current characters to make room for new bytes
if(*content < 0x80)
{
*(content + conversion_count) = *content;
}
else
{
*(content + conversion_count) = 0x80 | (*content & 0x3f); //last byte
*(content + --conversion_count) = 0xc0 | *content >> 6; //first byte
}
--content;
}
return SUCCESS;
}
```
|
2014/02/03
|
[
"https://codereview.stackexchange.com/questions/40780",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/26675/"
] |
The character set is named ISO-8859-1, not ISO-8895-1. Rename your function accordingly.
Change the return value to be more informative:
* Return 0 on success.
* If `max_size` is too small, return the minimum value of `max_size` that would be sufficient to accommodate the output (including the trailing `\0`).
I would also change the parameter to take a signed `char *` to be a bit more natural.
I think that the implementation could look tidier if you dealt with pointers instead of offsets.
It would be nice if you NUL-terminated the result, so that the caller does not have to zero out the entire buffer before calling this function.
```
size_t iso8859_1_to_utf8(char *content, size_t max_size)
{
char *src, *dst;
//first run to see if there's enough space for the new bytes
for (src = dst = content; *src; src++, dst++)
{
if (*src & 0x80)
{
// If the high bit is set in the ISO-8859-1 representation, then
// the UTF-8 representation requires two bytes (one more than usual).
++dst;
}
}
if (dst - content + 1 > max_size)
{
// Inform caller of the space required
return dst - content + 1;
}
*(dst + 1) = '\0';
while (dst > src)
{
if (*src & 0x80)
{
*dst-- = 0x80 | (*src & 0x3f); // trailing byte
*dst-- = 0xc0 | (*((unsigned char *)src--) >> 6); // leading byte
}
else
{
*dst-- = *src--;
}
}
return 0; // SUCCESS
}
```
|
How usable is the function? It relies on the `content` string occupying a
buffer large enough to be extended. And if you take the suggestion from
@200\_success that on error the function returns the minimum size necessary,
the user then has the added complexity of having to handle that error by
allocating a buffer and it must free the allocated buffer later - but it
must keep a note of whether the buffer was allocated.
Although I dislike dynamic allocation, I think this is a case where it makes
sense always to allocate a new string in the function.
Here is a version that allocates space:
```
char* iso88959_to_utf8(const char *str)
{
char *utf8 = malloc(1 + (2 * strlen(str)));
if (utf8) {
char *c = utf8;
for (; *str; ++str) {
if (*str & 0x80) {
*c++ = *str;
} else {
*c++ = (char) (0xc0 | (unsigned) *str >> 6);
*c++ = (char) (0x80 | (*str & 0x3f));
}
}
*c++ = '\0';
}
return utf8;
}
```
You could add a `realloc` call at the end to trim the excess space if you
thought it necessary (I'm not sure that it is, but it might depend upon the
application).
|
40,780 |
I wrote this function last year to convert between the two encodings and just found it. It takes a text buffer and its size, then converts to UTF-8 if there's enough space.
What should be changed to improve quality?
```
int iso88951_to_utf8(unsigned char *content, size_t max_size)
{
unsigned char *copy;
size_t conversion_count; //number of chars to convert / bytes to add
copy = content;
conversion_count = 0;
//first run to see if there's enough space for the new bytes
while(*content)
{
if(*content >= 0x80)
{
++conversion_count;
}
++content;
}
if(content - copy + conversion_count >= max_size)
{
return ERROR;
}
while(content >= copy && conversion_count)
{
//repositioning current characters to make room for new bytes
if(*content < 0x80)
{
*(content + conversion_count) = *content;
}
else
{
*(content + conversion_count) = 0x80 | (*content & 0x3f); //last byte
*(content + --conversion_count) = 0xc0 | *content >> 6; //first byte
}
--content;
}
return SUCCESS;
}
```
|
2014/02/03
|
[
"https://codereview.stackexchange.com/questions/40780",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/26675/"
] |
How usable is the function? It relies on the `content` string occupying a
buffer large enough to be extended. And if you take the suggestion from
@200\_success that on error the function returns the minimum size necessary,
the user then has the added complexity of having to handle that error by
allocating a buffer and it must free the allocated buffer later - but it
must keep a note of whether the buffer was allocated.
Although I dislike dynamic allocation, I think this is a case where it makes
sense always to allocate a new string in the function.
Here is a version that allocates space:
```
char* iso88959_to_utf8(const char *str)
{
char *utf8 = malloc(1 + (2 * strlen(str)));
if (utf8) {
char *c = utf8;
for (; *str; ++str) {
if (*str & 0x80) {
*c++ = *str;
} else {
*c++ = (char) (0xc0 | (unsigned) *str >> 6);
*c++ = (char) (0x80 | (*str & 0x3f));
}
}
*c++ = '\0';
}
return utf8;
}
```
You could add a `realloc` call at the end to trim the excess space if you
thought it necessary (I'm not sure that it is, but it might depend upon the
application).
|
I'm not sure why you have `content >= copy` in your second while loop. I would hope that `while(conversion_count)` should be sufficient.
Your `while` loops could be `for` loops.
More comments would make it easier to read:
* `//first run to see how many extra bytes we'll need`
* `//convert bytes from last to first to avoid altering not-yet-converted bytes`
* I'd appreciate a link to whichever section of an ISO-8895-1 specification which states what bit-twiddling is needed (I can see what the code does in the final loop, but have not seen the specification of what it's supposed to do so haven't verified that).
|
51,298,365 |
I am fairly new to VBA and have been writing a script that does certain checks and corrections to Excel-files. I am trying to find a way to replace all commas with dots in the workbook but without success. I have tried using the Replace-method but somehow it screws up my workbook even more. I think the problem has something to do with the local settings for decimal separators.
```
Row = lRow
lRow = Cells(Rows.Count, 1).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Do While Row >= 2
Range("P" & Row).Replace What:=",", Replacement:=".", SearchOrder:=xlByColumns
Row = Row - 1
Loop
Row = lRow
Do While Row >= 2
Range("Q" & Row).Replace What:=",", Replacement:=".", SearchOrder:=xlByColumns
Row = Row - 1
Loop
Row = lRow
```
The loop is supposed to replace all commas with dots in columns P and Q. But instead of dots dashes appear.
|
2018/07/12
|
[
"https://Stackoverflow.com/questions/51298365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10068599/"
] |
You need to specify all columns which are not allowed `null` values :
```
INSERT INTO [database].table1 (Col1, Col2, Col3) --- Columns which are not allowd null values
SELECT Col1, Col2, Col3
FROM Table t;
```
|
Check if the column is an IDENTITY column or if it has ISNULL constraint enebled.
```
INSERT INTO [database].table1 (code)
SELECT sd.a1 - sd.b1 AS kalan FROM NUMBERS sd
```
|
51,298,365 |
I am fairly new to VBA and have been writing a script that does certain checks and corrections to Excel-files. I am trying to find a way to replace all commas with dots in the workbook but without success. I have tried using the Replace-method but somehow it screws up my workbook even more. I think the problem has something to do with the local settings for decimal separators.
```
Row = lRow
lRow = Cells(Rows.Count, 1).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Do While Row >= 2
Range("P" & Row).Replace What:=",", Replacement:=".", SearchOrder:=xlByColumns
Row = Row - 1
Loop
Row = lRow
Do While Row >= 2
Range("Q" & Row).Replace What:=",", Replacement:=".", SearchOrder:=xlByColumns
Row = Row - 1
Loop
Row = lRow
```
The loop is supposed to replace all commas with dots in columns P and Q. But instead of dots dashes appear.
|
2018/07/12
|
[
"https://Stackoverflow.com/questions/51298365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10068599/"
] |
You need to specify all columns which are not allowed `null` values :
```
INSERT INTO [database].table1 (Col1, Col2, Col3) --- Columns which are not allowd null values
SELECT Col1, Col2, Col3
FROM Table t;
```
|
Use `ISNULL` to convert `null` to `0`
```
INSERT INTO [database].table1 (Number)
SELECT ISNULL((sd.a1 - sd.b1),0) AS kalan
FROM NUMBERS sd
```
|
263,469 |
Recently, one of my services received a query where the JSON payload contained the string `<an-arabic-character>\u0000bՕR`. The service handled it gracefully so no real harm was done, but am I right to be suspicious of this activity ?
To make it fully clear, the first character is the "Arabic number sign" and has UTF-16 encoding `06 00`, but this site won't allow me to actually use that character in this question.
The apparent null byte is specifically 'spelled out' as such in typical Java/JavaScript notation. That, combined with the fact that `60` is the backtick character and the specific mention of `OR`, makes me think this might be an attempt to slip in a crafted message.
---
I have received a second query with a similar, though not the same, contents. Instead of the bՕR with Armenian Օ, as commented, it ends in `bֽT` (Unicode: `b\05BD T`). The full UTF-8 representations are:
* D8 80 5C 75 30 30 30 30 62 D5 95 52 for the `bՕR` message
* D8 80 5C 75 30 30 30 30 62 D6 BD 54 for the `bֽT` message
I should also note that the message may not malicious, because the same call can be made by client services. In that case, the client system is trying (and failing) to send a Date-like object in the JSON payload.
I have added some more logging to the service, so that I can get more clarity on what is going on and who or what is sending this request.
|
2022/07/19
|
[
"https://security.stackexchange.com/questions/263469",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/280622/"
] |
Mystery (mostly) solved. It was indeed one of the client applications sending a badly encoded Date, rather than a malicious actor. I will have to find exactly how the wrong value is attained, but the screenshot below amateurishly shows how we got to the byte value of one of the reported strings. The other one also checks out according to the same logic.
[](https://i.stack.imgur.com/yozxi.png)
|
I have only ever used null characters when trying to do something sneaky while pentesting. I cannot imagine a case where your average user would accidentally inject one, even with funky character sets.
|
58,681,381 |
I'm building a project to learn **[Vuex](https://vuex.vuejs.org/)**. I'm creating an array of objects in my **`store`** like so:
**Vuex Store:**
```
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
users: [
{ id: 1, name: 'John Doe', email: '[email protected]' },
{ id: 2, name: 'Jane Doe', email: '[email protected]' },
{ id: 3, name: 'Mark Greywood', email: '[email protected]' },
]
},
mutations: {},
actions: {},
modules: {}
});
```
Now, I'm accesing the **`state`** in the component with a computed property like so:
**Component:**
```
<template>
<div class="home">
<h1>Hello from Home component</h1>
<!-- I do not loop through the users, nothing shows -->
<div v-for="user in users" :key="user.id">{{ user.name }} </div>
<!-- I get the users object in the DOM -->
<div>{{ getUsers }}</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: "Index",
computed: mapState({
getUsers: state => state.users
})
};
</script>
<style scoped lang="less">
</style>
```
I don't understand what I'm doing wrong.
|
2019/11/03
|
[
"https://Stackoverflow.com/questions/58681381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9884190/"
] |
You don't have access to `users` in this line of code
`<div v-for="user in users" :key="user.id">{{ user.name }} </div>`
Your component only have access to `getUsers` (the computed property) which is mapped to the store object `users`. Thus whenever the `users` state on your store changes, `getUser` also gets updated. So you should iterate on the computed property in your component.
So, the iteration should be
`<div v-for="user in getUsers" :key="user.id">{{ user.name }} </div>`
|
Change this
```
<div v-for="user in users" :key="user.id">{{ user.name }} </div>
```
To this
```
<div v-for="user in getUsers" :key="user.id">{{ user.name }} </div>
```
With your mapState line you are kinda telling component - 'Hey my store.users are in the getUsers variable'
Component do not know about 'users'. You didn't create variable like that.
Another way is to change loop to
```
<div v-for="user in $store.state.users" :key="user.id">{{ user.name }} </div>
```
In that case you can delete computed property 'getUsers'
|
47,078,106 |
Consider this code snippet here, where I am trying to create a bunch of threads which end up processing a given task which simulates a race-condition.
```
const int thread_count = 128;
pthread_t threads[thread_count];
for (int n = 0; n != thread_count; ++n)
{
ret = pthread_create(&threads[n], 0, test_thread_fun, &test_thread_args);
if( ret != 0 )
{
fprintf( stdout, "Fail %d %d", ret, errno );
exit(0);
}
}
```
Things generally works fine except occasionally pthread\_create fails with errno EAGAIN "resource temporarily unavailable", I tried inducing usleep, and retry creating but with no real effect.
the failure is sporadic and on some boxes no failures and on some occurs very frequently.
any Idea what could be going wrong here ?
>
> Edit - 1
>
>
>
update on max-threads
```
cat /proc/sys/kernel/threads-max
256467
```
>
> Edit 2
>
>
>
I think the inputs here kept me thinking, i'll probably do the below and post any results that are worth sharing.
1. set stack size to a minimum value, I don't think thread\_function uses any large arrays.
2. increase my memory and swap ( and nullify any side effects )
3. write a script to monitor the system behavior and see any other process/system daemon is interfering when this case is run, which is in turn can cause resource crunch.
4. system hard and soft limits are pretty high so I'll leave them as they are at this point.
|
2017/11/02
|
[
"https://Stackoverflow.com/questions/47078106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853605/"
] |
If your program makes sure that it never creates more threads than the system limit allows for (by joining threads before creating new ones), then you are likely running into this kernel bug:
* [Task exit is signaled before task resource allocation, leading to bogus EAGAIN errors](https://bugzilla.kernel.org/show_bug.cgi?id=154011)
With certain kinds of container technology, the race window appears to be much larger, and the bug is much easier to trigger. (This might depend on the types of cgroups in use.)
|
You might have a system limit about the max number of thread per process. Try to see it with:
`cat /proc/sys/kernel/threads-max`
|
47,078,106 |
Consider this code snippet here, where I am trying to create a bunch of threads which end up processing a given task which simulates a race-condition.
```
const int thread_count = 128;
pthread_t threads[thread_count];
for (int n = 0; n != thread_count; ++n)
{
ret = pthread_create(&threads[n], 0, test_thread_fun, &test_thread_args);
if( ret != 0 )
{
fprintf( stdout, "Fail %d %d", ret, errno );
exit(0);
}
}
```
Things generally works fine except occasionally pthread\_create fails with errno EAGAIN "resource temporarily unavailable", I tried inducing usleep, and retry creating but with no real effect.
the failure is sporadic and on some boxes no failures and on some occurs very frequently.
any Idea what could be going wrong here ?
>
> Edit - 1
>
>
>
update on max-threads
```
cat /proc/sys/kernel/threads-max
256467
```
>
> Edit 2
>
>
>
I think the inputs here kept me thinking, i'll probably do the below and post any results that are worth sharing.
1. set stack size to a minimum value, I don't think thread\_function uses any large arrays.
2. increase my memory and swap ( and nullify any side effects )
3. write a script to monitor the system behavior and see any other process/system daemon is interfering when this case is run, which is in turn can cause resource crunch.
4. system hard and soft limits are pretty high so I'll leave them as they are at this point.
|
2017/11/02
|
[
"https://Stackoverflow.com/questions/47078106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853605/"
] |
There are not enough resources to start a new thread.
Check if you have zombie threads on your system, or that you have enough memory etc on the system.
|
You might have a system limit about the max number of thread per process. Try to see it with:
`cat /proc/sys/kernel/threads-max`
|
47,078,106 |
Consider this code snippet here, where I am trying to create a bunch of threads which end up processing a given task which simulates a race-condition.
```
const int thread_count = 128;
pthread_t threads[thread_count];
for (int n = 0; n != thread_count; ++n)
{
ret = pthread_create(&threads[n], 0, test_thread_fun, &test_thread_args);
if( ret != 0 )
{
fprintf( stdout, "Fail %d %d", ret, errno );
exit(0);
}
}
```
Things generally works fine except occasionally pthread\_create fails with errno EAGAIN "resource temporarily unavailable", I tried inducing usleep, and retry creating but with no real effect.
the failure is sporadic and on some boxes no failures and on some occurs very frequently.
any Idea what could be going wrong here ?
>
> Edit - 1
>
>
>
update on max-threads
```
cat /proc/sys/kernel/threads-max
256467
```
>
> Edit 2
>
>
>
I think the inputs here kept me thinking, i'll probably do the below and post any results that are worth sharing.
1. set stack size to a minimum value, I don't think thread\_function uses any large arrays.
2. increase my memory and swap ( and nullify any side effects )
3. write a script to monitor the system behavior and see any other process/system daemon is interfering when this case is run, which is in turn can cause resource crunch.
4. system hard and soft limits are pretty high so I'll leave them as they are at this point.
|
2017/11/02
|
[
"https://Stackoverflow.com/questions/47078106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853605/"
] |
If your program makes sure that it never creates more threads than the system limit allows for (by joining threads before creating new ones), then you are likely running into this kernel bug:
* [Task exit is signaled before task resource allocation, leading to bogus EAGAIN errors](https://bugzilla.kernel.org/show_bug.cgi?id=154011)
With certain kinds of container technology, the race window appears to be much larger, and the bug is much easier to trigger. (This might depend on the types of cgroups in use.)
|
Check `ulimit -a` at your shell. You likely have a process limit set in login policy and Linux ridiculously also applies this to threads.
|
47,078,106 |
Consider this code snippet here, where I am trying to create a bunch of threads which end up processing a given task which simulates a race-condition.
```
const int thread_count = 128;
pthread_t threads[thread_count];
for (int n = 0; n != thread_count; ++n)
{
ret = pthread_create(&threads[n], 0, test_thread_fun, &test_thread_args);
if( ret != 0 )
{
fprintf( stdout, "Fail %d %d", ret, errno );
exit(0);
}
}
```
Things generally works fine except occasionally pthread\_create fails with errno EAGAIN "resource temporarily unavailable", I tried inducing usleep, and retry creating but with no real effect.
the failure is sporadic and on some boxes no failures and on some occurs very frequently.
any Idea what could be going wrong here ?
>
> Edit - 1
>
>
>
update on max-threads
```
cat /proc/sys/kernel/threads-max
256467
```
>
> Edit 2
>
>
>
I think the inputs here kept me thinking, i'll probably do the below and post any results that are worth sharing.
1. set stack size to a minimum value, I don't think thread\_function uses any large arrays.
2. increase my memory and swap ( and nullify any side effects )
3. write a script to monitor the system behavior and see any other process/system daemon is interfering when this case is run, which is in turn can cause resource crunch.
4. system hard and soft limits are pretty high so I'll leave them as they are at this point.
|
2017/11/02
|
[
"https://Stackoverflow.com/questions/47078106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853605/"
] |
There are not enough resources to start a new thread.
Check if you have zombie threads on your system, or that you have enough memory etc on the system.
|
Check `ulimit -a` at your shell. You likely have a process limit set in login policy and Linux ridiculously also applies this to threads.
|
50,423,562 |
I looked over the docs, but cannot find a way to run Expo completely offline. I'm frequently in an area without a stable connection and this makes it exceptionally difficult to maintain a proper work flow.
I would have thought that `exp start --dev --lan` would enable offline development, but my expo client still fails on inability to connect to the expo servers.
Is there a truly offline mode for expo?
|
2018/05/19
|
[
"https://Stackoverflow.com/questions/50423562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
With the latest version of Expo (v32) you can run offline by using the following command
```
expo start --offline
```
|
1. If you experience issues when testing offline try starting the Expo packager with the command yarn start --offline command and then in Expo dev tools set the connection type to "local".
2. Or you can also use expo start --offline.
|
50,423,562 |
I looked over the docs, but cannot find a way to run Expo completely offline. I'm frequently in an area without a stable connection and this makes it exceptionally difficult to maintain a proper work flow.
I would have thought that `exp start --dev --lan` would enable offline development, but my expo client still fails on inability to connect to the expo servers.
Is there a truly offline mode for expo?
|
2018/05/19
|
[
"https://Stackoverflow.com/questions/50423562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
In order to load the bundle
```
expo start --offline
```
will work. For running it on an Android device make sure to check if your device is listed in adb available devices by running
```
adb devices
```
You can make the connection with your adb device either by connecting it through wire or attaching the bridge wirelessly. [Instructions for help!](https://stackoverflow.com/questions/2604727/how-can-i-connect-to-android-with-adb-over-tcp)
|
1. If you experience issues when testing offline try starting the Expo packager with the command yarn start --offline command and then in Expo dev tools set the connection type to "local".
2. Or you can also use expo start --offline.
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
You have binary blobs in your DB, try adding --hex-blob to your mysqldump statement.
|
I had special character in table names , like `_\` and it give error when try to import that tables.
i fixed it by changing `\` to `\\` in dumped sql.
my table names where like `rate_\` and i used this command to repair dump :
```
sed 's._\\._\\\\.g' dump.sql > dump2.sql
```
i didn't replace all backslashes , because i was not sure if there is some backslash somewhere in database that should not be replaces.
special characters in table name will be converted to @ at sign in file name.
read <http://dev.mysql.com/doc/refman/5.5/en/identifier-mapping.html>
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
You have binary blobs in your DB, try adding --hex-blob to your mysqldump statement.
|
I think you need to use `path/to/file.sql` instead of `path\to\file.sql`
Also, `database < path/to/file.sql` didn't work for me for some reason - I had to use `use database;` and `source path/to/file.sql;`.
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
I think you need to use `path/to/file.sql` instead of `path\to\file.sql`
Also, `database < path/to/file.sql` didn't work for me for some reason - I had to use `use database;` and `source path/to/file.sql;`.
|
If all else fails, use MySQLWorkbench to do the import. This solved the same problem for me.
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
You know what's going on - you have an extra single quote in your SQL!O
If you have 'awk', you probably have 'vi', which will open your line1153.sql file with ease and allow you to find the value in your database that is causing the problem.
Or... The line is probably large because it contains multiple rows. You could also use the `--skip-extended-insert` option to mysqldump so that each row got a separate insert statement.
Good luck.
|
I had the same problem because I had Chinese characters in my datasbase. Below is what I found from some Chinese forum and it worked for me.
```
mysql -u[USERNAME] -p[PASSWORD] --default-character-set=latin1
[DATABASE_NAME] < [BACKUP_SQL_FILE.sql]
```
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
You have binary blobs in your DB, try adding --hex-blob to your mysqldump statement.
|
I had the same problem because I had Chinese characters in my datasbase. Below is what I found from some Chinese forum and it worked for me.
```
mysql -u[USERNAME] -p[PASSWORD] --default-character-set=latin1
[DATABASE_NAME] < [BACKUP_SQL_FILE.sql]
```
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
You have binary blobs in your DB, try adding --hex-blob to your mysqldump statement.
|
I recently had a similar problem where I had done an sql dump on a Windows machine and tried to install it on a Linux machine. I had a fairly large SQL file and my error was happening at line 3455360. I used the following command to copy all text up to the point where I was getting an error:
>
> sed -n '1, 3455359p' < sourcefile.sql > destinationfile.sql
>
>
>
This copied all the good code into a destination file. I looked at the last few lines of the destination file and saw that it was a complete SQL command (The last line ended with a ';') so I imported the good code and didn't get any errors.
I then looked at the rest of the file which was about 20 lines. It turns out that the export might not have completed b/c I saw the following php code at the end of the code:
```
Array
(
[type] => 1
[message] => Maximum execution time of 300 seconds exceeded
[file] => C:\xampp\htdocs\openemr\phpmyadmin\libraries\Util.class.php
[line] => 296
)
```
I removed the offending php code and imported the rest of the database.
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
I had the same problem because I had Chinese characters in my datasbase. Below is what I found from some Chinese forum and it worked for me.
```
mysql -u[USERNAME] -p[PASSWORD] --default-character-set=latin1
[DATABASE_NAME] < [BACKUP_SQL_FILE.sql]
```
|
I have same error as,
```
Unknown command '\▒'.
```
when I ran this
```
mysql -u root -p trainee < /xx/yy.gz
```
So I'd followed these answers. But I did not got the restored db `trainee`. Then found that
`yy.gz` is `zip` file. So I restoring after unzip the file as:
```
mysql -u root -p trainee < /xx/yy.sql
```
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
I think you need to use `path/to/file.sql` instead of `path\to\file.sql`
Also, `database < path/to/file.sql` didn't work for me for some reason - I had to use `use database;` and `source path/to/file.sql;`.
|
I recently had a similar problem where I had done an sql dump on a Windows machine and tried to install it on a Linux machine. I had a fairly large SQL file and my error was happening at line 3455360. I used the following command to copy all text up to the point where I was getting an error:
>
> sed -n '1, 3455359p' < sourcefile.sql > destinationfile.sql
>
>
>
This copied all the good code into a destination file. I looked at the last few lines of the destination file and saw that it was a complete SQL command (The last line ended with a ';') so I imported the good code and didn't get any errors.
I then looked at the rest of the file which was about 20 lines. It turns out that the export might not have completed b/c I saw the following php code at the end of the code:
```
Array
(
[type] => 1
[message] => Maximum execution time of 300 seconds exceeded
[file] => C:\xampp\htdocs\openemr\phpmyadmin\libraries\Util.class.php
[line] => 296
)
```
I removed the offending php code and imported the rest of the database.
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
You know what's going on - you have an extra single quote in your SQL!O
If you have 'awk', you probably have 'vi', which will open your line1153.sql file with ease and allow you to find the value in your database that is causing the problem.
Or... The line is probably large because it contains multiple rows. You could also use the `--skip-extended-insert` option to mysqldump so that each row got a separate insert statement.
Good luck.
|
If all else fails, use MySQLWorkbench to do the import. This solved the same problem for me.
|
5,888,589 |
I am trying to import a mysqldump file via the command line, but continue to get an error. I dumped the file from my other server using:
```
mysqldump -u XXX -p database_name > database.sql
```
Then I try to import the file with:
```
mysql -u XXX -p database_name < database.sql
```
It loads a small portion and then gets stuck. The error I receive is:
```
ERROR at line 1153: Unknown command '\''.
```
I checked that line in the file with:
```
awk '{ if (NR==1153) print $0 }' database.sql >> line1153.sql
```
and it happens to be over 1MB in size, just for that line.
Any ideas what might be going on here?
|
2011/05/04
|
[
"https://Stackoverflow.com/questions/5888589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61195/"
] |
You have binary blobs in your DB, try adding --hex-blob to your mysqldump statement.
|
If all else fails, use MySQLWorkbench to do the import. This solved the same problem for me.
|
71,859,716 |
I recently started messing around in Unity and I'm trying to make a 2D platformer game. I tried making it so that my player is only able to jump when it is grounded and this is the code I came up with, but it isn't working for some reason and I don't understand why.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed = 5;
public float jumpSpeed = 5;
public Rigidbody2D rb;
public GameObject gameObject;
bool isGrounded;
Vector3 movement;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (isGrounded)
{
Jump();
} else
{
// do nothing
}
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
}
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(new Vector2(0f, jumpSpeed), ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
} else
{
isGrounded = false;
}
}
}
```
|
2022/04/13
|
[
"https://Stackoverflow.com/questions/71859716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18794774/"
] |
Instead of having the `else { isGrounded = false;}` inside of your collision check, add `isGrounded = false;` inside of your `Jump()` function so that you're guaranteed to only be able to jump while you're on the ground;
Additionally you could have `Jump();` without the `if` statement in your `Update()` function and have it **inside** `Jump()` like this `if (isGrounded && Input.GetKeyDown(KeyCode.Space))`
|
you can use `OnCollisionExit2D(Collision2D Collider) {}` to set `isgrounded` to false. It would look like something like this:
```
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(new Vector2(0f, jumpSpeed), ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.tag == "Ground")
{
isGrounded = true;
}
}
void OnCollisionExit2D(Collision2D Collider)
{
if (Collider.tag == "Ground")
{
isGrounded = false;
}
}
```
|
125,015 |
Ubuntu 12.04 won't come with the Windows Installer (Wubi) pre-added. But is there any way to install 12.04 using Wubi?
|
2012/04/25
|
[
"https://askubuntu.com/questions/125015",
"https://askubuntu.com",
"https://askubuntu.com/users/46933/"
] |
Wubi is still on the 12.04 CD but the ability to install inside Windows from CD has been disabled. The only way to do it is to run wubi.exe standalone available [here](http://www.ubuntu.com/download/desktop/windows-installer).
For 12.04 they have simply hobbled wubi.exe to not offer the option to install, which you can bypass with a command-line option e.g. if your CD drive is `D:` you can go to a command line and run:
```
D:\wubi.exe --force-wubi
```
The intention is to replace `wubi.exe` on the `CD ISO` in future releases with a dedicated `CD Boot Helper`, and then maintain `wubi.exe` as a separate executable. That appears to be the plan.
Here is the rationale behind disabling it, which was posted by Canonical's Rick Spencer on the [ubuntu-devel mailing list](https://lists.ubuntu.com/archives/ubuntu-devel/2012-March/034970.html):
>
> Hello all,
>
>
> This email regards wubi, a tool used to set up Ubuntu in a dual boot
> configuration in a manner that does not require disk partitioning.
> Wubi is a windows program. It is currently delivered as a standalone
> executable downloadable from the web, as well as part of official
> Ubuntu images. You can read about wubi in the excellent user guide:
> <https://wiki.ubuntu.com/WubiGuide>
>
>
> I am proposing a small but notable change to how we deliver wubi for
> 12.04. I am proposing that:
>
>
> 1. We continue to test and bug fix wubi.exe as the separate Windows program
> 2. We cotinue to offer wubi.exe for download as the separate Windows program.
> 3. We disable the ability to do a wubi installation from the Ubuntu 12.04 ISOs. (wubi will remain on the images for the purpose of providing Windows users some feedback and functionality if they put a
> Ubuntu CD into a running Windows computer, but won't offer to
> install).
>
>
> Separating the wubi.exe experience from the ISOs will give us the
> following important benefits:
>
>
> 1. We will be able to do maintenance and enhancements to wubi outside of the Ubuntu development cycle.
> 2. Significant reduciton of QA work for an already over-streched QA team.
> 3. Better overall 12.04 quality, and less stress at release time.
> 4. We won't get stuck with a poor (or worse) user experience on the CD since is a good chance that wubi will not work properly with
> Windows 8.
>
>
> I am proposing these changes to the plan because:
>
>
> 1. The key use case for wubi is being able to download and run the installer on Windows, not installing from the ISO.
> 2. Wubi is difficult to test, so has been difficult to assure that it will meet the quality standards we have set for 12.04.
> 3. There are no developers treating wubi as their top priorities. This combined with the QA difficulties has historically caused late
> breaking changes that add stress at release time and frequentily
> invalidate already executed ISO testing.
> 4. Most significantly, Windows is changing it's boot system with Windows 8, and it's not clear how wubi will work with Windows 8, if at
> all.
>
>
> Cheers, Rick
>
>
>
[Here is the bug report](https://bugs.launchpad.net/bugs/975251) that documents the request to disable install from CD.
Note:
Running wubi.exe standalone will download a preinstalled tar.xz image. You can still place the Desktop CD ISO in the same directory as wubi.exe and install it like that without downloading the ~500MB tar.xz image.
|
The daily 12.04 iso I have here when burnt has wubi. Get that, burn it and then open it in windows.

|
125,015 |
Ubuntu 12.04 won't come with the Windows Installer (Wubi) pre-added. But is there any way to install 12.04 using Wubi?
|
2012/04/25
|
[
"https://askubuntu.com/questions/125015",
"https://askubuntu.com",
"https://askubuntu.com/users/46933/"
] |
The daily 12.04 iso I have here when burnt has wubi. Get that, burn it and then open it in windows.

|
Yes you can install Ubuntu 12.04 using WUBI, just download the WUBI.exe here [Download Ubuntu Desktop | Ubuntu](http://www.ubuntu.com/download/desktop/windows-installer), then execute it, it will download the iso file.
However if you already done downloading the iso file you can use it, just mount it using DAEMON TOOL, download it here [DAEMON Tools Lite v4.48.1 (with SPTD 1.84)](http://www.disk-tools.com/download/daemon) or any where, then execute the WUBI.exe you download from.
**NOTE**: stay offline so that it will not download the iso file, instead of downloading the file from the net, it will get the file from the daemon)
JUST LEAVE your question.. if there is..
|
125,015 |
Ubuntu 12.04 won't come with the Windows Installer (Wubi) pre-added. But is there any way to install 12.04 using Wubi?
|
2012/04/25
|
[
"https://askubuntu.com/questions/125015",
"https://askubuntu.com",
"https://askubuntu.com/users/46933/"
] |
Wubi is still on the 12.04 CD but the ability to install inside Windows from CD has been disabled. The only way to do it is to run wubi.exe standalone available [here](http://www.ubuntu.com/download/desktop/windows-installer).
For 12.04 they have simply hobbled wubi.exe to not offer the option to install, which you can bypass with a command-line option e.g. if your CD drive is `D:` you can go to a command line and run:
```
D:\wubi.exe --force-wubi
```
The intention is to replace `wubi.exe` on the `CD ISO` in future releases with a dedicated `CD Boot Helper`, and then maintain `wubi.exe` as a separate executable. That appears to be the plan.
Here is the rationale behind disabling it, which was posted by Canonical's Rick Spencer on the [ubuntu-devel mailing list](https://lists.ubuntu.com/archives/ubuntu-devel/2012-March/034970.html):
>
> Hello all,
>
>
> This email regards wubi, a tool used to set up Ubuntu in a dual boot
> configuration in a manner that does not require disk partitioning.
> Wubi is a windows program. It is currently delivered as a standalone
> executable downloadable from the web, as well as part of official
> Ubuntu images. You can read about wubi in the excellent user guide:
> <https://wiki.ubuntu.com/WubiGuide>
>
>
> I am proposing a small but notable change to how we deliver wubi for
> 12.04. I am proposing that:
>
>
> 1. We continue to test and bug fix wubi.exe as the separate Windows program
> 2. We cotinue to offer wubi.exe for download as the separate Windows program.
> 3. We disable the ability to do a wubi installation from the Ubuntu 12.04 ISOs. (wubi will remain on the images for the purpose of providing Windows users some feedback and functionality if they put a
> Ubuntu CD into a running Windows computer, but won't offer to
> install).
>
>
> Separating the wubi.exe experience from the ISOs will give us the
> following important benefits:
>
>
> 1. We will be able to do maintenance and enhancements to wubi outside of the Ubuntu development cycle.
> 2. Significant reduciton of QA work for an already over-streched QA team.
> 3. Better overall 12.04 quality, and less stress at release time.
> 4. We won't get stuck with a poor (or worse) user experience on the CD since is a good chance that wubi will not work properly with
> Windows 8.
>
>
> I am proposing these changes to the plan because:
>
>
> 1. The key use case for wubi is being able to download and run the installer on Windows, not installing from the ISO.
> 2. Wubi is difficult to test, so has been difficult to assure that it will meet the quality standards we have set for 12.04.
> 3. There are no developers treating wubi as their top priorities. This combined with the QA difficulties has historically caused late
> breaking changes that add stress at release time and frequentily
> invalidate already executed ISO testing.
> 4. Most significantly, Windows is changing it's boot system with Windows 8, and it's not clear how wubi will work with Windows 8, if at
> all.
>
>
> Cheers, Rick
>
>
>
[Here is the bug report](https://bugs.launchpad.net/bugs/975251) that documents the request to disable install from CD.
Note:
Running wubi.exe standalone will download a preinstalled tar.xz image. You can still place the Desktop CD ISO in the same directory as wubi.exe and install it like that without downloading the ~500MB tar.xz image.
|
Yes you can install Ubuntu 12.04 using WUBI, just download the WUBI.exe here [Download Ubuntu Desktop | Ubuntu](http://www.ubuntu.com/download/desktop/windows-installer), then execute it, it will download the iso file.
However if you already done downloading the iso file you can use it, just mount it using DAEMON TOOL, download it here [DAEMON Tools Lite v4.48.1 (with SPTD 1.84)](http://www.disk-tools.com/download/daemon) or any where, then execute the WUBI.exe you download from.
**NOTE**: stay offline so that it will not download the iso file, instead of downloading the file from the net, it will get the file from the daemon)
JUST LEAVE your question.. if there is..
|
48,684,392 |
I'm completely new to this instrumentation concept. I have a custom jar file which has lot of methods. Lets assume for now i have start and stop method. Inorder to collect the start and stop metrics i need to call those methods after every click . Instead of doing that is there a way to instrument this. I want this methods to be called for all clickable elements dynamically before and after during runtime. Any advise on this would be great. Thanks in advance. Please find the sample code.
**Custom Methods:**
```
Public void start (){
long start = System.currentTimeMillis();
}
public void stop{
long finish= System.currentTimeMillis();
long totalTime = finish - start;
}
```
**Sample Code:**
```
start();
driver.findElement(By.name("username")).sendkeys("@@@");
stop();
start();
driver.findElement(By.name("password")).sendkeys("@@@");
stop();
start();
driver.findElement(By.name("login")).click();
stop();
```
|
2018/02/08
|
[
"https://Stackoverflow.com/questions/48684392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7605002/"
] |
Here's an example instrumentation solution using ByteBuddy, although as I mentioned in comments under this question it's probably not a best approach to solve this.
For this simple example the code only covers a case where invocations on WebDriver and WebElement are chained e.g.:
```
driver.findElement(By.name("login")).click();
driver.findElement(By.name("logout")).click();
```
Something like below fragment will not work without additional coding:
```
WebElement element1 = findElement(By.name("login"));
WebElement element2 = findElement(By.name("logout"));
element2.click();
element1.click();
```
Instrumentation code:
```
public class ByteBuddyTest {
public static void main(String[] args) throws Exception {
ByteBuddyAgent.install();
new ByteBuddy()
.redefine(RemoteWebDriver.class)
.visit(Advice.to(WebDriverAdvice.class).on(named("findElement").and(takesArguments(1))))
.make()
.load(ByteBuddyTest2.class.getClassLoader(),
ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy()
.redefine(RemoteWebElement.class)
.visit(Advice.to(WebElementAdvice.class).on(named("click")))
.make()
.load(ByteBuddyTest2.class.getClassLoader(),
ClassReloadingStrategy.fromInstalledAgent());
InternetExplorerDriver driver = new InternetExplorerDriver();
driver.get("<some webpage>");
driver.findElement(By.id("<some_id>")).click();
}
public static class WebDriverAdvice {
@Advice.OnMethodEnter
public static void enter(@Advice.Origin String method) {
System.out.printf("Driver Method Enter: %s\n", method);
Times.start = System.currentTimeMillis();
}
}
public static class WebElementAdvice {
@Advice.OnMethodExit
public static void exit(@Advice.Origin String method, @Advice.This Object target) {
System.out.printf("Element Method Exit: %s\n", method);
System.out.println("Time: " + (System.currentTimeMillis() - Times.start));
}
}
public static class Times {
public static long start = 0L;
}
}
```
**Example using WebDriverEventListener**
```
public class WebDriverEventListenerTest {
public static void main(String[] args) throws Exception {
InternetExplorerDriver driver = new InternetExplorerDriver();
EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver);
eventDriver.register(new EventHandler());
eventDriver.get("<some webpage>");
eventDriver.findElement(By.id("<some id>")).click();
eventDriver.findElement(By.id("<some id>")).click();
}
public static class EventHandler extends AbstractWebDriverEventListener {
@Override public void beforeFindBy(By by, WebElement element, WebDriver driver) {
System.out.printf("Driver Find By: %s\n", by);
Times.start = System.currentTimeMillis();
}
@Override public void afterClickOn(WebElement element, WebDriver driver) {
System.out.printf("Element Method Exit: %s\n", element);
System.out.println("Time: " + (System.currentTimeMillis() - Times.start));
}
}
public static class Times {
public static long start = 0L;
}
}
```
|
It appears you are trying to benchmark code. If so, I suggest using a benchmarking framework, such as [Google Caliper](https://github.com/google/caliper), which helps instrument code while nominally impacting the actual performance of the code, and it also helps account for JIT compiling, etc., which may alter the execution time of your method as code is executed repeatedly.
|
52,660,459 |
```
#!/bin/sh
...
read var
#user enters: it doesn't work
...
echo 'Some text and $var' > myfile.txt
```
Expected output:
```
cat myfile.txt
#Some text and it doesn't work
```
Actual output:
```
cat myfile.txt
#Some text and $var
```
So how to echo the content into the file with the value of the `$var` variable?
|
2018/10/05
|
[
"https://Stackoverflow.com/questions/52660459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10457311/"
] |
use double quote instead of simple quote to make variable remplacement available
you can also remove your quotes to make it work but it's not recommanded
<http://wiki.bash-hackers.org/syntax/quoting>
|
if you want to insert $var to last line(=append the content $var to file), please use >>
should be:
```
echo "Some text and $var" >> myfile.txt
```
the > is to override the content, whereas >> is to append the content to a file
|
63,286 |
[Add syntax highlighting and line breaks to comment formatting](https://meta.stackexchange.com/questions/4481/apply-markup-code-in-comments) explains that limited inline markup is supported in comments. This is useful, and the limitation makes sense. However it's hard to discover what markup you're allowed to use: if you're used to saying `<code>`, you might not realize you need ``` in comments. There's no help shown when you add a comment, as far as I can see.
|
2010/09/03
|
[
"https://meta.stackexchange.com/questions/63286",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/150826/"
] |
click the help link under [add comment] to see a summary of the available formatting options.

|
There's always the [formatting sandbox](https://meta.stackexchange.com/questions/3122).
You can play around with the questions / answers there and post comments to see what's allowed.
|
44,173,270 |
can enyone help me out to undersatnd this Here's [a link](https://www.twilio.com/chat)! how to use in c#
i want to know how to use it
how to use pragrammable chat of twilio in c#
|
2017/05/25
|
[
"https://Stackoverflow.com/questions/44173270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7500285/"
] |
I finally get the solution by some readings.
Sentry works on an async event based model and killing a process just after triggering sentry will not ensure the exception is reached to the servers. Hence we need to add a delay(10s), before killing the process in case of any exception to ensure sentry does it's job.
```
def process_data(data):
from configurations import SENTRY_CLIENT
try:
s = data/0
except ZeroDivisionError:
print "Sentry must report this."
import time
SENTRY_CLIENT.captureException()
time.sleep(10)
import multiprocessing
from billiard import Pool
POOL_SIZE=multiprocessing.cpu_count()
pool = Pool(POOL_SIZE)
data=[0, 1, 2, 3, 4, 5]
pool.map(process_data, data)
pool.close()
pool.terminate()
```
|
As PoloSoares [said](https://stackoverflow.com/questions/44173252/how-to-configure-sentry-to-send-exception-from-process-spawned-by-python-multipr#comment88017277_44216502), you should change a transport instead of adding any delay by sleep. Example of valid solution for 6.10.0 version of raven lib:
```python
import multiprocessing
from billiard import Pool
from raven import Client
from raven.transport.http import HTTPTransport
SENTRY_CLIENT = Client("dsn", transport=HTTPTransport)
def process_data(data):
try:
s = data / 0
except ZeroDivisionError:
print("Sentry must report this.")
SENTRY_CLIENT.captureException()
POOL_SIZE = multiprocessing.cpu_count()
pool = Pool(POOL_SIZE)
data = [0, 1, 2, 3, 4, 5]
pool.map(process_data, data)
pool.close()
pool.terminate()
```
|
915,540 |
Find all positive real number $\beta$,there are infinitely many relatively prime integers $(p,q)$ such that
$$\left|\dfrac{p}{q}-\sqrt{2}\right|<\dfrac{\beta}{q^2}$$
maybe this problem background is [Hurwitz's theorem](https://en.wikipedia.org/wiki/Hurwitz%27s_theorem_%28number_theory%29):
$$\left|\sqrt{2}-\dfrac{p}{q}\right|<\dfrac{1}{\sqrt{5}q^2}$$
so I guess my problem ? $\beta\ge\dfrac{1}{\sqrt{5}}$
and this problem is Germany National Olympiad 2013 last problem (1), see: <http://www.mathematik-olympiaden.de/aufgaben/52/4/A52124b.pdf>
|
2014/09/01
|
[
"https://math.stackexchange.com/questions/915540",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/58742/"
] |
Proof sketch. First write
$$\left|\frac{p}{q}-\sqrt{2}\right| = \frac{|p^2-2q^2|}{q^2\left|\frac{p}{q} + \sqrt{2}\right|}$$
The [Pell equation](http://en.wikipedia.org/wiki/Pell%27s_equation) $$p^2 - 2q^2 = 1$$
is known to have infinitely many solutions (should be proven) so
$$\left|\frac{p}{q}-\sqrt{2}\right| = \frac{|p^2-2q^2|}{q^2\left|\frac{p}{q} + \sqrt{2}\right|} = \frac{1}{q^2}\frac{1}{\left|\sqrt{2 + \frac{1}{q^2}} + \sqrt{2}\right|}$$
for infinitely many $p,q$ so all $\beta \geq \frac{1}{\sqrt{8}}$ are possible. Now try to show that it fails for $\beta < \frac{1}{\sqrt{8}}$. Let $p^2 - 2q^2 = k$ then $p/q = \sqrt{2 + k/q^2}$ and by inserting this into the inequality above show that it cannot hold for large enough $q$.
|
Hints:
* For all $p,q$ we have $$\left|\left(\frac pq-\sqrt2\right)\left(\frac pq+\sqrt2\right)\right|=\frac{|p^2-2q^2|}{q^2}\ge\frac1{q^2},$$ because $\sqrt2$ is irrational.
* The Pell equations $p^2-2q^2=\pm1$ have infinitely many solutions $(p\_n,q\_n)$. For example those determined by $$(\sqrt2-1)^n=p\_n-q\_n\sqrt2.$$
* When $p\_n$ and $q\_n$ are large, $p\_n/q\_n\approx\sqrt2$.
|
915,540 |
Find all positive real number $\beta$,there are infinitely many relatively prime integers $(p,q)$ such that
$$\left|\dfrac{p}{q}-\sqrt{2}\right|<\dfrac{\beta}{q^2}$$
maybe this problem background is [Hurwitz's theorem](https://en.wikipedia.org/wiki/Hurwitz%27s_theorem_%28number_theory%29):
$$\left|\sqrt{2}-\dfrac{p}{q}\right|<\dfrac{1}{\sqrt{5}q^2}$$
so I guess my problem ? $\beta\ge\dfrac{1}{\sqrt{5}}$
and this problem is Germany National Olympiad 2013 last problem (1), see: <http://www.mathematik-olympiaden.de/aufgaben/52/4/A52124b.pdf>
|
2014/09/01
|
[
"https://math.stackexchange.com/questions/915540",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/58742/"
] |
Proof sketch. First write
$$\left|\frac{p}{q}-\sqrt{2}\right| = \frac{|p^2-2q^2|}{q^2\left|\frac{p}{q} + \sqrt{2}\right|}$$
The [Pell equation](http://en.wikipedia.org/wiki/Pell%27s_equation) $$p^2 - 2q^2 = 1$$
is known to have infinitely many solutions (should be proven) so
$$\left|\frac{p}{q}-\sqrt{2}\right| = \frac{|p^2-2q^2|}{q^2\left|\frac{p}{q} + \sqrt{2}\right|} = \frac{1}{q^2}\frac{1}{\left|\sqrt{2 + \frac{1}{q^2}} + \sqrt{2}\right|}$$
for infinitely many $p,q$ so all $\beta \geq \frac{1}{\sqrt{8}}$ are possible. Now try to show that it fails for $\beta < \frac{1}{\sqrt{8}}$. Let $p^2 - 2q^2 = k$ then $p/q = \sqrt{2 + k/q^2}$ and by inserting this into the inequality above show that it cannot hold for large enough $q$.
|
To supplement @Winther's good answer, regarding the constraint on viable constants $\beta$: this is an instance of Liouville's theorem on the not-good-approximability of non-rational algebraic numbers... using the mean value theorem from calculus, charmingly enough:
Let $f(x)=x^2-2$. For every rational $p/q$, by the mean value theorem,
$$
f(p/q)-f(\sqrt{2}) \;=\; f'(y)\cdot ({p\over q}-\sqrt{2})
$$
for some $y$ between $p/q$ and $\sqrt{2}$. Since $f(\sqrt{2})=0$, and since $|f(p/q)|=|{p^2-2q^2\over q^2}|\ge{1\over q^2}$,
$$
{1\over q^2}\;\le\; |f'(y)|\cdot |{p\over q}-\sqrt{2}|
$$
As $p/q\to \sqrt{2}$, necessarily also $y\to \sqrt{2}$, and $f'(y)\to f'(\sqrt{2})=2\sqrt{2}$...
|
915,540 |
Find all positive real number $\beta$,there are infinitely many relatively prime integers $(p,q)$ such that
$$\left|\dfrac{p}{q}-\sqrt{2}\right|<\dfrac{\beta}{q^2}$$
maybe this problem background is [Hurwitz's theorem](https://en.wikipedia.org/wiki/Hurwitz%27s_theorem_%28number_theory%29):
$$\left|\sqrt{2}-\dfrac{p}{q}\right|<\dfrac{1}{\sqrt{5}q^2}$$
so I guess my problem ? $\beta\ge\dfrac{1}{\sqrt{5}}$
and this problem is Germany National Olympiad 2013 last problem (1), see: <http://www.mathematik-olympiaden.de/aufgaben/52/4/A52124b.pdf>
|
2014/09/01
|
[
"https://math.stackexchange.com/questions/915540",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/58742/"
] |
Hints:
* For all $p,q$ we have $$\left|\left(\frac pq-\sqrt2\right)\left(\frac pq+\sqrt2\right)\right|=\frac{|p^2-2q^2|}{q^2}\ge\frac1{q^2},$$ because $\sqrt2$ is irrational.
* The Pell equations $p^2-2q^2=\pm1$ have infinitely many solutions $(p\_n,q\_n)$. For example those determined by $$(\sqrt2-1)^n=p\_n-q\_n\sqrt2.$$
* When $p\_n$ and $q\_n$ are large, $p\_n/q\_n\approx\sqrt2$.
|
To supplement @Winther's good answer, regarding the constraint on viable constants $\beta$: this is an instance of Liouville's theorem on the not-good-approximability of non-rational algebraic numbers... using the mean value theorem from calculus, charmingly enough:
Let $f(x)=x^2-2$. For every rational $p/q$, by the mean value theorem,
$$
f(p/q)-f(\sqrt{2}) \;=\; f'(y)\cdot ({p\over q}-\sqrt{2})
$$
for some $y$ between $p/q$ and $\sqrt{2}$. Since $f(\sqrt{2})=0$, and since $|f(p/q)|=|{p^2-2q^2\over q^2}|\ge{1\over q^2}$,
$$
{1\over q^2}\;\le\; |f'(y)|\cdot |{p\over q}-\sqrt{2}|
$$
As $p/q\to \sqrt{2}$, necessarily also $y\to \sqrt{2}$, and $f'(y)\to f'(\sqrt{2})=2\sqrt{2}$...
|
59,863,167 |
I would like to have the respective short description of the product / article displayed in WOOCOMMERCE in the order overview "Order-Details-Item" (template / woocommerce / order / order-details-item.php) about the product Permalink.
I found the following code on the web to allow a brief description.
Here is the code for this:
```
```html
<div class="product_short_description_cart_default">
<?php
$product_id = $_product->get_parent_id();
$product = wc_get_product($product_id);
echo $product->get_short_description();
?>
</div>
```
```
But how do I incorporate them into my order-details-item.php file?
Here is the code for this:
```html
<?php
/**
* Order Item Details
*
* This template can be overridden by copying it to yourtheme/woocommerce/order/order-details-item.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @package WooCommerce/Templates
* @version 3.7.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
return;
}
?>
<tr class="<?php echo esc_attr( apply_filters( 'woocommerce_order_item_class', 'woocommerce-table__line-item order_item', $item, $order ) ); ?>">
<td class="woocommerce-table__product-name product-name">
<div class="order-details-item-default-product-name-left">
<?php
echo '<div class="product-image">'.$product->get_image(array( 80, 80)).'</div>';
$is_visible = $product && $product->is_visible();
$product_permalink = apply_filters( 'woocommerce_order_item_permalink', $is_visible ? $product->get_permalink( $item ) : '', $item, $order );
?>
</div>
<div class="order-details-item-default-product-name-right">
<?php
echo apply_filters( 'woocommerce_order_item_name', $product_permalink ? sprintf( '<a href="%s">%s</a>', $product_permalink, $item->get_name() ) : $item->get_name(), $item, $is_visible ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
$qty = $item->get_quantity();
$refunded_qty = $order->get_qty_refunded_for_item( $item_id );
if ( $refunded_qty ) {
$qty_display = '<del>' . esc_html( $qty ) . '</del> <ins>' . esc_html( $qty - ( $refunded_qty * -1 ) ) . '</ins>';
} else {
$qty_display = esc_html( $qty );
}
echo apply_filters( 'woocommerce_order_item_quantity_html', ' <strong class="product-quantity">' . sprintf( '× %s', $qty_display ) . '</strong>', $item ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
do_action( 'woocommerce_order_item_meta_start', $item_id, $item, $order, false );
wc_display_item_meta( $item ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
do_action( 'woocommerce_order_item_meta_end', $item_id, $item, $order, false );
// SKU mit Sprachdatei
echo '<div class="cart-sku-item">' . __( "SKU:", "woostroid") . $product->sku . '</div>';
?>
</div>
</td>
<td class="woocommerce-table__product-total product-total">
<?php echo $order->get_formatted_line_subtotal( $item ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</td>
</tr>
<?php if ( $show_purchase_note && $purchase_note ) : ?>
<tr class="woocommerce-table__product-purchase-note product-purchase-note">
<td colspan="2"><?php echo wpautop( do_shortcode( wp_kses_post( $purchase_note ) ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td>
</tr>
<?php endif; ?>
```
Can you please help me there!
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59863167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12762630/"
] |
Update: i found the problem:
The default YAML file for GitHub Builds does NOT include a "publish" Step. After adding this to the end of the Build YAML
```
- task: PublishBuildArtifacts@1
inputs:
PathtoPublish: '$(Build.ArtifactStagingDirectory)'
ArtifactName: 'drop'
publishLocation: 'Container'
```
it in fact creates the "Artifacts" Tab:
[](https://i.stack.imgur.com/FUfC8.png)
Thanks for the help anyone
|
This seems be the different UI of `classic` and `YAML`.
To see the artifacts structure, you can go **summary** page(*<https://dev.azure.com/xxxx/xxxx/_build/results?buildId=xxx&view=results>*) of one build. Then focus one the right part and you will see like below:
[](https://i.stack.imgur.com/bZRNP.png)
Click on it, then you will see its folder structure(*<https://dev.azure.com/xxx/xxx/_build/results?buildId=xxx&view=artifacts&type=publishedArtifacts>*):
[](https://i.stack.imgur.com/vB6nl.png)
|
2,676,462 |
Given m > 0, show that there exists a 2$\times$2 matrix T that
$T^{-1}$$\pmatrix{n&1\\0&n}$T = $\pmatrix{n&m\\0&n}$.
Not really sure how to work it out. Thanks!
|
2018/03/04
|
[
"https://math.stackexchange.com/questions/2676462",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/535906/"
] |
So you know how $\sin$ and $\cos$ relate the side lengths of right triangles on the unit circle to the interior angle? Well, $\sinh$ and $\cosh$ do the same but the instead of having right triangle which lie on the unit circle we have them lie on the unit hyperbola.
The equation for the unit circle is,
$$x^2+y^2 = 1$$
While the equation for the unit hyperbola is,
$$x^2 -y^2 = 1$$
This picture helps depict what I am describing, <https://en.wikipedia.org/wiki/Hyperbolic_function#/media/File:Hyperbolic_functions-2.svg>
|
The hyperbolic functions $\sinh$ and $\cosh$ parameterize the hyperbola $x^2-y^2=1$ since $\cosh^2 t-\sinh^2 t=1$ for all $t\in\mathbb{R}$.
|
2,676,462 |
Given m > 0, show that there exists a 2$\times$2 matrix T that
$T^{-1}$$\pmatrix{n&1\\0&n}$T = $\pmatrix{n&m\\0&n}$.
Not really sure how to work it out. Thanks!
|
2018/03/04
|
[
"https://math.stackexchange.com/questions/2676462",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/535906/"
] |
So you know how $\sin$ and $\cos$ relate the side lengths of right triangles on the unit circle to the interior angle? Well, $\sinh$ and $\cosh$ do the same but the instead of having right triangle which lie on the unit circle we have them lie on the unit hyperbola.
The equation for the unit circle is,
$$x^2+y^2 = 1$$
While the equation for the unit hyperbola is,
$$x^2 -y^2 = 1$$
This picture helps depict what I am describing, <https://en.wikipedia.org/wiki/Hyperbolic_function#/media/File:Hyperbolic_functions-2.svg>
|
The **imverse** hyperbolic functions are particularly useful in integration, for example when dealing with positive quadratic functions inside square roots. Although such integrals can be done with trig functions, using hyperbolic functions makes them much easier.
Find $\int\sqrt{x^2-1}dx$ for example
|
2,676,462 |
Given m > 0, show that there exists a 2$\times$2 matrix T that
$T^{-1}$$\pmatrix{n&1\\0&n}$T = $\pmatrix{n&m\\0&n}$.
Not really sure how to work it out. Thanks!
|
2018/03/04
|
[
"https://math.stackexchange.com/questions/2676462",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/535906/"
] |
So you know how $\sin$ and $\cos$ relate the side lengths of right triangles on the unit circle to the interior angle? Well, $\sinh$ and $\cosh$ do the same but the instead of having right triangle which lie on the unit circle we have them lie on the unit hyperbola.
The equation for the unit circle is,
$$x^2+y^2 = 1$$
While the equation for the unit hyperbola is,
$$x^2 -y^2 = 1$$
This picture helps depict what I am describing, <https://en.wikipedia.org/wiki/Hyperbolic_function#/media/File:Hyperbolic_functions-2.svg>
|
Every real functions can be uniquely represented by the sum of the even function and the odd function.
$$f(x)=\frac{f(x)+f(-x)}{2}+\frac{f(x)-f(-x)}{2}$$
Now let's put $f(x)=e^x$.
|
2,676,462 |
Given m > 0, show that there exists a 2$\times$2 matrix T that
$T^{-1}$$\pmatrix{n&1\\0&n}$T = $\pmatrix{n&m\\0&n}$.
Not really sure how to work it out. Thanks!
|
2018/03/04
|
[
"https://math.stackexchange.com/questions/2676462",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/535906/"
] |
The hyperbolic functions $\sinh$ and $\cosh$ parameterize the hyperbola $x^2-y^2=1$ since $\cosh^2 t-\sinh^2 t=1$ for all $t\in\mathbb{R}$.
|
Every real functions can be uniquely represented by the sum of the even function and the odd function.
$$f(x)=\frac{f(x)+f(-x)}{2}+\frac{f(x)-f(-x)}{2}$$
Now let's put $f(x)=e^x$.
|
2,676,462 |
Given m > 0, show that there exists a 2$\times$2 matrix T that
$T^{-1}$$\pmatrix{n&1\\0&n}$T = $\pmatrix{n&m\\0&n}$.
Not really sure how to work it out. Thanks!
|
2018/03/04
|
[
"https://math.stackexchange.com/questions/2676462",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/535906/"
] |
The *catenary* ( or *chaînette*) is the shape of the curve assumed by a hanging chain or cable with the two ends fixed, under its own weight. It happens its equation is
$$y=a\cosh \frac xa$$
where the constant $a$ depends on physical parameters (tension and mass per unit length).
It is used in architecture and engineering for archs, bridges, &c.
You also find a derived curve in the shape of a skipping rope.
|
The hyperbolic functions $\sinh$ and $\cosh$ parameterize the hyperbola $x^2-y^2=1$ since $\cosh^2 t-\sinh^2 t=1$ for all $t\in\mathbb{R}$.
|
2,676,462 |
Given m > 0, show that there exists a 2$\times$2 matrix T that
$T^{-1}$$\pmatrix{n&1\\0&n}$T = $\pmatrix{n&m\\0&n}$.
Not really sure how to work it out. Thanks!
|
2018/03/04
|
[
"https://math.stackexchange.com/questions/2676462",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/535906/"
] |
The **imverse** hyperbolic functions are particularly useful in integration, for example when dealing with positive quadratic functions inside square roots. Although such integrals can be done with trig functions, using hyperbolic functions makes them much easier.
Find $\int\sqrt{x^2-1}dx$ for example
|
Every real functions can be uniquely represented by the sum of the even function and the odd function.
$$f(x)=\frac{f(x)+f(-x)}{2}+\frac{f(x)-f(-x)}{2}$$
Now let's put $f(x)=e^x$.
|
2,676,462 |
Given m > 0, show that there exists a 2$\times$2 matrix T that
$T^{-1}$$\pmatrix{n&1\\0&n}$T = $\pmatrix{n&m\\0&n}$.
Not really sure how to work it out. Thanks!
|
2018/03/04
|
[
"https://math.stackexchange.com/questions/2676462",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/535906/"
] |
The *catenary* ( or *chaînette*) is the shape of the curve assumed by a hanging chain or cable with the two ends fixed, under its own weight. It happens its equation is
$$y=a\cosh \frac xa$$
where the constant $a$ depends on physical parameters (tension and mass per unit length).
It is used in architecture and engineering for archs, bridges, &c.
You also find a derived curve in the shape of a skipping rope.
|
The **imverse** hyperbolic functions are particularly useful in integration, for example when dealing with positive quadratic functions inside square roots. Although such integrals can be done with trig functions, using hyperbolic functions makes them much easier.
Find $\int\sqrt{x^2-1}dx$ for example
|
2,676,462 |
Given m > 0, show that there exists a 2$\times$2 matrix T that
$T^{-1}$$\pmatrix{n&1\\0&n}$T = $\pmatrix{n&m\\0&n}$.
Not really sure how to work it out. Thanks!
|
2018/03/04
|
[
"https://math.stackexchange.com/questions/2676462",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/535906/"
] |
The *catenary* ( or *chaînette*) is the shape of the curve assumed by a hanging chain or cable with the two ends fixed, under its own weight. It happens its equation is
$$y=a\cosh \frac xa$$
where the constant $a$ depends on physical parameters (tension and mass per unit length).
It is used in architecture and engineering for archs, bridges, &c.
You also find a derived curve in the shape of a skipping rope.
|
Every real functions can be uniquely represented by the sum of the even function and the odd function.
$$f(x)=\frac{f(x)+f(-x)}{2}+\frac{f(x)-f(-x)}{2}$$
Now let's put $f(x)=e^x$.
|
23,961,349 |
I'm still reading Stephen Prata's "C Primer Plus". The following code is my attempt to solve the 10th programming exercise of the 7th chapter.
My Question: Why does the program loop infinitely when a character is entered instead of an integer and how can I prevent this behavior.
```
#include <stdio.h>
// taxrates
#define TAXRATE_1 .15
#define TAXRATE_2 .28
// category limits
#define SINGLE_LIMIT 17850
#define HEAD_OF_HOUSEHOLD_LIMIT 23900
#define MARRIED_JOINT_LIMIT 29750
#define MARRIED_SEPARAT_LIMIT 14875
// bases
#define SINGLE_BASE SINGLE_LIMIT * TAXRATE_1
#define HEAD_OF_HOUSEHOLD_BASE HEAD_OF_HOUSEHOLD_LIMIT * TAXRATE_1
#define MARRIED_JOINT_BASE MARRIED_JOINT_LIMIT * TAXRATE_1
#define MARRIED_SEPARAT_BASE MARRIED_SEPARAT_LIMIT * TAXRATE_1
int main(void)
{
int selection;
float income, tax;
while (1)
{
printf("*******************************************************\n"
"Please enter the number of your category:\n"
"1) Single\n2) Head of Household\n3) Married, Joint\n4) Married, Separat\n5) quit\n"
"*******************************************************\n");
scanf("%d", &selection);
if (selection >= 1 && selection <= 4)
{
printf("Enter income: ");
scanf("%f", &income);
switch (selection)
{
case 1:
if (income < SINGLE_LIMIT)
tax = income * TAXRATE_1;
else
tax = SINGLE_BASE + (income - SINGLE_LIMIT) * TAXRATE_2;
printf("Single income of: %.2f$ Tax: %.2f$\n", income, tax);
break;
case 2:
if (income < HEAD_OF_HOUSEHOLD_LIMIT)
tax = income * TAXRATE_1;
else
tax = HEAD_OF_HOUSEHOLD_BASE+ (income - HEAD_OF_HOUSEHOLD_LIMIT) * TAXRATE_2;
printf("Head of Household income of: %.2f$ Tax: %.2f$\n", income, tax);
break;
case 3:
if (income < MARRIED_JOINT_LIMIT)
tax = income * TAXRATE_1;
else
tax = MARRIED_JOINT_BASE + (income - MARRIED_JOINT_LIMIT) * TAXRATE_2;
printf("Married joint income of: %.2f$ Tax: %.2f$\n", income, tax);
break;
case 4:
if (income < MARRIED_SEPARAT_LIMIT)
tax = income * TAXRATE_1;
else
tax = MARRIED_SEPARAT_BASE + (income - MARRIED_SEPARAT_LIMIT) * TAXRATE_2;
printf("Married separat income of: %.2f$ Tax: %.2f$\n", income, tax);
break;
}
}
else if (selection == 5)
{
printf("Done.");
break;
}
else
printf("Please enter a number between 1 and 5.\n");
}
return 0;
}
```
|
2014/05/30
|
[
"https://Stackoverflow.com/questions/23961349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657262/"
] |
>
> My Question: Why does the program loop infinitely when a character is
> entered instead of an integer and how can I prevent this behavior.
>
>
>
When you input something is not expected by `scanf()` (as defined by the format string you pass to scanf), it ignores it and returns. But that invalid input is not cleared from the input stream. So the loop carries on forever as read-ignore-loop-again continues in your program.
So to address it:
* Avoid `scanf()` whenever possible. Use `fgets()` and process the input using `sscanf()`, which provides better error control.
* Check the return value `scanf()` to decide if the scanning was successful.
The usual way to clear is to read out all the characters in the input stream when you encounter invalid input:
```
else {
int c;
printf("Please enter a number between 1 and 5.\n");
while((c = getchar()) != '\n' && c != EOF) ; /* reads and discards */
}
```
|
While loop in the program exits when only when the value of selection in the else part is 5.
But whenever you will enter a character the value of selection can't be 5, so it never comes out of the loop and makes the program loop to run infinitely.
|
4,191 |
I'm adding a column to the order grid using observer approach:
1. On the event -> `sales_order_grid_collection_load_before` I'm adding a join to the collection
2. On the event -> `core_block_abstract_prepare_layout_before` I'm adding a column to the grid
**EDIT** More Info:
On Event (1):
```
public function salesOrderGridCollectionLoadBefore($observer)
{
$collection = $observer->getOrderGridCollection();
$collection->addFilterToMap('store_id', 'main_table.store_id');
$select = $collection->getSelect();
$select->joinLeft(array('oe' => $collection->getTable('sales/order')), 'oe.entity_id=main_table.entity_id', array('oe.customer_group_id'));
}
```
On Event (2):
```
public function appendCustomColumn(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
if (!isset($block)) {
return $this;
}
if ($block->getType() == 'adminhtml/sales_order_grid') {
/* @var $block Mage_Adminhtml_Block_Customer_Grid */
$this->_addColumnToGrid($block);
}
}
protected function _addColumnToGrid($grid)
{
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionHash();
$groups[0] = 'Guest';
/* @var $block Mage_Adminhtml_Block_Customer_Grid */
$grid->addColumnAfter('customer_group_id', array(
'header' => Mage::helper('customer')->__('Customer Group'),
'index' => 'customer_group_id',
'filter_index' => 'oe.customer_group_id',
'type' => 'options',
'options' => $groups,
), 'shipping_name');
}
```
Everything work fine until I filter the grid with store view filter:
**Column ‘store\_id’ in where clause is ambiguous issue**
I have printed the query:
```
SELECT `main_table`.*, `oe`.`customer_group_id`
FROM `sales_flat_order_grid` AS `main_table`
LEFT JOIN `sales_flat_order` AS `oe` ON oe.entity_id=main_table.entity_id
WHERE (store_id = '5') AND (oe.customer_group_id = '6')
```
As you case see `store_id` miss `main_table` alias.
To accomplish this I just need to set the `filter_index` for store Id column but **through the observer**
So the question is how can I do it **on the fly** ?
**Without overriding the block** class ? ( otherwise the observer approach is useless )
|
2013/05/29
|
[
"https://magento.stackexchange.com/questions/4191",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/70/"
] |
Let's try this again with on other solution I mentioned before to you :-) , I have build the complete extension to show you how to add the field to the grid table. After that you only need a layout update file to add the column to you order grid page.
I called the extension Example\_SalesGrid, but you can change it to your own needs.
Let's start by creating the module init xml in **/app/etc/modules/Example\_SalesGrid.xml**:
```
<?xml version="1.0" encoding="UTF-8"?>
<!--
Module bootstrap file
-->
<config>
<modules>
<Example_SalesGrid>
<active>true</active>
<codePool>community</codePool>
<depends>
<Mage_Sales />
</depends>
</Example_SalesGrid>
</modules>
</config>
```
Next we create our module config xml in **/app/code/community/Example/SalesGrid/etc/config.xml**:
```
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Example_SalesGrid>
<version>0.1.0</version> <!-- define version for sql upgrade -->
</Example_SalesGrid>
</modules>
<global>
<models>
<example_salesgrid>
<class>Example_SalesGrid_Model</class>
</example_salesgrid>
</models>
<blocks>
<example_salesgrid>
<class>Example_SalesGrid_Block</class>
</example_salesgrid>
</blocks>
<events>
<!-- Add observer configuration -->
<sales_order_resource_init_virtual_grid_columns>
<observers>
<example_salesgrid>
<model>example_salesgrid/observer</model>
<method>addColumnToResource</method>
</example_salesgrid>
</observers>
</sales_order_resource_init_virtual_grid_columns>
</events>
<resources>
<!-- initialize sql upgrade setup -->
<example_salesgrid_setup>
<setup>
<module>Example_SalesGrid</module>
<class>Mage_Sales_Model_Mysql4_Setup</class>
</setup>
</example_salesgrid_setup>
</resources>
</global>
<adminhtml>
<layout>
<!-- layout upgrade configuration -->
<updates>
<example_salesgrid>
<file>example/salesgrid.xml</file>
</example_salesgrid>
</updates>
</layout>
</adminhtml>
</config>
```
Now we create the sql upgrade script in **/app/code/community/Example/SalesGrid/sql/example\_salesgrid\_setup/install-0.1.0.php**:
```
<?php
/**
* Setup scripts, add new column and fulfills
* its values to existing rows
*
*/
$this->startSetup();
// Add column to grid table
$this->getConnection()->addColumn(
$this->getTable('sales/order_grid'),
'customer_group_id',
'smallint(6) DEFAULT NULL'
);
// Add key to table for this field,
// it will improve the speed of searching & sorting by the field
$this->getConnection()->addKey(
$this->getTable('sales/order_grid'),
'customer_group_id',
'customer_group_id'
);
// Now you need to fullfill existing rows with data from address table
$select = $this->getConnection()->select();
$select->join(
array('order'=>$this->getTable('sales/order')),
$this->getConnection()->quoteInto(
'order.entity_id = order_grid.entity_id'
),
array('customer_group_id' => 'customer_group_id')
);
$this->getConnection()->query(
$select->crossUpdateFromSelect(
array('order_grid' => $this->getTable('sales/order_grid'))
)
);
$this->endSetup();
```
Next we create the layout update file in **/app/design/adminhtml/default/default/layout/example/salesgrid.xml:**
```
<?xml version="1.0"?>
<layout>
<!-- main layout definition that adds the column -->
<add_order_grid_column_handle>
<reference name="sales_order.grid">
<action method="addColumnAfter">
<columnId>customer_group_id</columnId>
<arguments module="sales" translate="header">
<header>Customer Group</header>
<index>customer_group_id</index>
<type>options</type>
<filter>Example_SalesGrid_Block_Widget_Grid_Column_Customer_Group</filter>
<renderer>Example_SalesGrid_Block_Widget_Grid_Column_Renderer_Customer_Group</renderer>
<width>200</width>
</arguments>
<after>grand_total</after>
</action>
</reference>
</add_order_grid_column_handle>
<!-- order grid action -->
<adminhtml_sales_order_grid>
<!-- apply the layout handle defined above -->
<update handle="add_order_grid_column_handle" />
</adminhtml_sales_order_grid>
<!-- order grid view action -->
<adminhtml_sales_order_index>
<!-- apply the layout handle defined above -->
<update handle="add_order_grid_column_handle" />
</adminhtml_sales_order_index>
</layout>
```
Now we need two Block files, one to create the filter options, **/app/code/community/Example/SalesGrid/Block/Widget/Grid/Column/Customer/Group.php:**
```
<?php
class Example_SalesGrid_Block_Widget_Grid_Column_Customer_Group extends Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Select {
protected $_options = false;
protected function _getOptions(){
if(!$this->_options) {
$methods = array();
$methods[] = array(
'value' => '',
'label' => ''
);
$methods[] = array(
'value' => '0',
'label' => 'Guest'
);
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionArray();
$this->_options = array_merge($methods,$groups);
}
return $this->_options;
}
}
```
And the second to translate the row values to the correct text that will be displayed, **/app/code/community/Example/SalesGrid/Block/Widget/Grid/Column/Renderer/Customer/Group.php**:
```
<?php
class Example_SalesGrid_Block_Widget_Grid_Column_Renderer_Customer_Group extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {
protected $_options = false;
protected function _getOptions(){
if(!$this->_options) {
$methods = array();
$methods[0] = 'Guest';
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionHash();
$this->_options = array_merge($methods,$groups);
}
return $this->_options;
}
public function render(Varien_Object $row){
$value = $this->_getValue($row);
$options = $this->_getOptions();
return isset($options[$value]) ? $options[$value] : $value;
}
}
```
The last file needed is only needed if you create an extra column from a table other than sales/order (sales\_flat\_order). All fields in sales/order\_grid matching the column name from sales/order is automatically updated in the sales/order\_grid table. If you need to add the payment option for example you will need this observer to add the field to the query so the data can be copied to the correct table. The observer used for this is in **/app/code/community/Example/SalesGrid/Model/Observer.php**:
```
<?php
/**
* Event observer model
*
*
*/
class Example_SalesGrid_Model_Observer {
public function addColumnToResource(Varien_Event_Observer $observer) {
// Only needed if you use a table other than sales/order (sales_flat_order)
//$resource = $observer->getEvent()->getResource();
//$resource->addVirtualGridColumn(
// 'payment_method',
// 'sales/order_payment',
// array('entity_id' => 'parent_id'),
// 'method'
//);
}
}
```
This code is based on the example from <http://www.ecomdev.org/2010/07/27/adding-order-attribute-to-orders-grid-in-magento-1-4-1.html>
Hope the example above solves your problem.
|
Do you really need in your method `salesOrderGridCollectionLoadBefore` the following code `$collection->addFilterToMap('store_id', 'main_table.store_id');`? If not remove it and try the following:
```
protected function _addColumnToGrid($grid)
{
....... // here you code from your post above
$storeIdColumn = $grid->getColumn('store_id');
if($storeIdColumn) {
$storeIdColumn->addData(array('filter_index' => 'main_table.store_id'));
}
}
```
|
4,191 |
I'm adding a column to the order grid using observer approach:
1. On the event -> `sales_order_grid_collection_load_before` I'm adding a join to the collection
2. On the event -> `core_block_abstract_prepare_layout_before` I'm adding a column to the grid
**EDIT** More Info:
On Event (1):
```
public function salesOrderGridCollectionLoadBefore($observer)
{
$collection = $observer->getOrderGridCollection();
$collection->addFilterToMap('store_id', 'main_table.store_id');
$select = $collection->getSelect();
$select->joinLeft(array('oe' => $collection->getTable('sales/order')), 'oe.entity_id=main_table.entity_id', array('oe.customer_group_id'));
}
```
On Event (2):
```
public function appendCustomColumn(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
if (!isset($block)) {
return $this;
}
if ($block->getType() == 'adminhtml/sales_order_grid') {
/* @var $block Mage_Adminhtml_Block_Customer_Grid */
$this->_addColumnToGrid($block);
}
}
protected function _addColumnToGrid($grid)
{
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionHash();
$groups[0] = 'Guest';
/* @var $block Mage_Adminhtml_Block_Customer_Grid */
$grid->addColumnAfter('customer_group_id', array(
'header' => Mage::helper('customer')->__('Customer Group'),
'index' => 'customer_group_id',
'filter_index' => 'oe.customer_group_id',
'type' => 'options',
'options' => $groups,
), 'shipping_name');
}
```
Everything work fine until I filter the grid with store view filter:
**Column ‘store\_id’ in where clause is ambiguous issue**
I have printed the query:
```
SELECT `main_table`.*, `oe`.`customer_group_id`
FROM `sales_flat_order_grid` AS `main_table`
LEFT JOIN `sales_flat_order` AS `oe` ON oe.entity_id=main_table.entity_id
WHERE (store_id = '5') AND (oe.customer_group_id = '6')
```
As you case see `store_id` miss `main_table` alias.
To accomplish this I just need to set the `filter_index` for store Id column but **through the observer**
So the question is how can I do it **on the fly** ?
**Without overriding the block** class ? ( otherwise the observer approach is useless )
|
2013/05/29
|
[
"https://magento.stackexchange.com/questions/4191",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/70/"
] |
Let's try this again with on other solution I mentioned before to you :-) , I have build the complete extension to show you how to add the field to the grid table. After that you only need a layout update file to add the column to you order grid page.
I called the extension Example\_SalesGrid, but you can change it to your own needs.
Let's start by creating the module init xml in **/app/etc/modules/Example\_SalesGrid.xml**:
```
<?xml version="1.0" encoding="UTF-8"?>
<!--
Module bootstrap file
-->
<config>
<modules>
<Example_SalesGrid>
<active>true</active>
<codePool>community</codePool>
<depends>
<Mage_Sales />
</depends>
</Example_SalesGrid>
</modules>
</config>
```
Next we create our module config xml in **/app/code/community/Example/SalesGrid/etc/config.xml**:
```
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Example_SalesGrid>
<version>0.1.0</version> <!-- define version for sql upgrade -->
</Example_SalesGrid>
</modules>
<global>
<models>
<example_salesgrid>
<class>Example_SalesGrid_Model</class>
</example_salesgrid>
</models>
<blocks>
<example_salesgrid>
<class>Example_SalesGrid_Block</class>
</example_salesgrid>
</blocks>
<events>
<!-- Add observer configuration -->
<sales_order_resource_init_virtual_grid_columns>
<observers>
<example_salesgrid>
<model>example_salesgrid/observer</model>
<method>addColumnToResource</method>
</example_salesgrid>
</observers>
</sales_order_resource_init_virtual_grid_columns>
</events>
<resources>
<!-- initialize sql upgrade setup -->
<example_salesgrid_setup>
<setup>
<module>Example_SalesGrid</module>
<class>Mage_Sales_Model_Mysql4_Setup</class>
</setup>
</example_salesgrid_setup>
</resources>
</global>
<adminhtml>
<layout>
<!-- layout upgrade configuration -->
<updates>
<example_salesgrid>
<file>example/salesgrid.xml</file>
</example_salesgrid>
</updates>
</layout>
</adminhtml>
</config>
```
Now we create the sql upgrade script in **/app/code/community/Example/SalesGrid/sql/example\_salesgrid\_setup/install-0.1.0.php**:
```
<?php
/**
* Setup scripts, add new column and fulfills
* its values to existing rows
*
*/
$this->startSetup();
// Add column to grid table
$this->getConnection()->addColumn(
$this->getTable('sales/order_grid'),
'customer_group_id',
'smallint(6) DEFAULT NULL'
);
// Add key to table for this field,
// it will improve the speed of searching & sorting by the field
$this->getConnection()->addKey(
$this->getTable('sales/order_grid'),
'customer_group_id',
'customer_group_id'
);
// Now you need to fullfill existing rows with data from address table
$select = $this->getConnection()->select();
$select->join(
array('order'=>$this->getTable('sales/order')),
$this->getConnection()->quoteInto(
'order.entity_id = order_grid.entity_id'
),
array('customer_group_id' => 'customer_group_id')
);
$this->getConnection()->query(
$select->crossUpdateFromSelect(
array('order_grid' => $this->getTable('sales/order_grid'))
)
);
$this->endSetup();
```
Next we create the layout update file in **/app/design/adminhtml/default/default/layout/example/salesgrid.xml:**
```
<?xml version="1.0"?>
<layout>
<!-- main layout definition that adds the column -->
<add_order_grid_column_handle>
<reference name="sales_order.grid">
<action method="addColumnAfter">
<columnId>customer_group_id</columnId>
<arguments module="sales" translate="header">
<header>Customer Group</header>
<index>customer_group_id</index>
<type>options</type>
<filter>Example_SalesGrid_Block_Widget_Grid_Column_Customer_Group</filter>
<renderer>Example_SalesGrid_Block_Widget_Grid_Column_Renderer_Customer_Group</renderer>
<width>200</width>
</arguments>
<after>grand_total</after>
</action>
</reference>
</add_order_grid_column_handle>
<!-- order grid action -->
<adminhtml_sales_order_grid>
<!-- apply the layout handle defined above -->
<update handle="add_order_grid_column_handle" />
</adminhtml_sales_order_grid>
<!-- order grid view action -->
<adminhtml_sales_order_index>
<!-- apply the layout handle defined above -->
<update handle="add_order_grid_column_handle" />
</adminhtml_sales_order_index>
</layout>
```
Now we need two Block files, one to create the filter options, **/app/code/community/Example/SalesGrid/Block/Widget/Grid/Column/Customer/Group.php:**
```
<?php
class Example_SalesGrid_Block_Widget_Grid_Column_Customer_Group extends Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Select {
protected $_options = false;
protected function _getOptions(){
if(!$this->_options) {
$methods = array();
$methods[] = array(
'value' => '',
'label' => ''
);
$methods[] = array(
'value' => '0',
'label' => 'Guest'
);
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionArray();
$this->_options = array_merge($methods,$groups);
}
return $this->_options;
}
}
```
And the second to translate the row values to the correct text that will be displayed, **/app/code/community/Example/SalesGrid/Block/Widget/Grid/Column/Renderer/Customer/Group.php**:
```
<?php
class Example_SalesGrid_Block_Widget_Grid_Column_Renderer_Customer_Group extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {
protected $_options = false;
protected function _getOptions(){
if(!$this->_options) {
$methods = array();
$methods[0] = 'Guest';
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionHash();
$this->_options = array_merge($methods,$groups);
}
return $this->_options;
}
public function render(Varien_Object $row){
$value = $this->_getValue($row);
$options = $this->_getOptions();
return isset($options[$value]) ? $options[$value] : $value;
}
}
```
The last file needed is only needed if you create an extra column from a table other than sales/order (sales\_flat\_order). All fields in sales/order\_grid matching the column name from sales/order is automatically updated in the sales/order\_grid table. If you need to add the payment option for example you will need this observer to add the field to the query so the data can be copied to the correct table. The observer used for this is in **/app/code/community/Example/SalesGrid/Model/Observer.php**:
```
<?php
/**
* Event observer model
*
*
*/
class Example_SalesGrid_Model_Observer {
public function addColumnToResource(Varien_Event_Observer $observer) {
// Only needed if you use a table other than sales/order (sales_flat_order)
//$resource = $observer->getEvent()->getResource();
//$resource->addVirtualGridColumn(
// 'payment_method',
// 'sales/order_payment',
// array('entity_id' => 'parent_id'),
// 'method'
//);
}
}
```
This code is based on the example from <http://www.ecomdev.org/2010/07/27/adding-order-attribute-to-orders-grid-in-magento-1-4-1.html>
Hope the example above solves your problem.
|
Try to use these:
```
public function salesOrderGridCollectionLoadBefore($observer)
{
/**
* @var $select Varien_DB_Select
*/
$collection = $observer->getOrderGridCollection();
$collection->addFilterToMap('store_id', 'main_table.store_id');
$select = $collection->getSelect();
$select->joinLeft(array('oe' => $collection->getTable('sales/order')), 'oe.entity_id=main_table.entity_id', array('oe.customer_group_id'));
if ($where = $select->getPart('where')) {
foreach ($where as $key=> $condition) {
if (strpos($condition, 'store_id')) {
$value = explode('=', trim($condition, ')'));
$value = trim($value[1], "' ");
$where[$key] = "(main_table.store_id = '$value')";
}
}
$select->setPart('where', $where);
}
}
```
|
4,191 |
I'm adding a column to the order grid using observer approach:
1. On the event -> `sales_order_grid_collection_load_before` I'm adding a join to the collection
2. On the event -> `core_block_abstract_prepare_layout_before` I'm adding a column to the grid
**EDIT** More Info:
On Event (1):
```
public function salesOrderGridCollectionLoadBefore($observer)
{
$collection = $observer->getOrderGridCollection();
$collection->addFilterToMap('store_id', 'main_table.store_id');
$select = $collection->getSelect();
$select->joinLeft(array('oe' => $collection->getTable('sales/order')), 'oe.entity_id=main_table.entity_id', array('oe.customer_group_id'));
}
```
On Event (2):
```
public function appendCustomColumn(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
if (!isset($block)) {
return $this;
}
if ($block->getType() == 'adminhtml/sales_order_grid') {
/* @var $block Mage_Adminhtml_Block_Customer_Grid */
$this->_addColumnToGrid($block);
}
}
protected function _addColumnToGrid($grid)
{
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionHash();
$groups[0] = 'Guest';
/* @var $block Mage_Adminhtml_Block_Customer_Grid */
$grid->addColumnAfter('customer_group_id', array(
'header' => Mage::helper('customer')->__('Customer Group'),
'index' => 'customer_group_id',
'filter_index' => 'oe.customer_group_id',
'type' => 'options',
'options' => $groups,
), 'shipping_name');
}
```
Everything work fine until I filter the grid with store view filter:
**Column ‘store\_id’ in where clause is ambiguous issue**
I have printed the query:
```
SELECT `main_table`.*, `oe`.`customer_group_id`
FROM `sales_flat_order_grid` AS `main_table`
LEFT JOIN `sales_flat_order` AS `oe` ON oe.entity_id=main_table.entity_id
WHERE (store_id = '5') AND (oe.customer_group_id = '6')
```
As you case see `store_id` miss `main_table` alias.
To accomplish this I just need to set the `filter_index` for store Id column but **through the observer**
So the question is how can I do it **on the fly** ?
**Without overriding the block** class ? ( otherwise the observer approach is useless )
|
2013/05/29
|
[
"https://magento.stackexchange.com/questions/4191",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/70/"
] |
Let's try this again with on other solution I mentioned before to you :-) , I have build the complete extension to show you how to add the field to the grid table. After that you only need a layout update file to add the column to you order grid page.
I called the extension Example\_SalesGrid, but you can change it to your own needs.
Let's start by creating the module init xml in **/app/etc/modules/Example\_SalesGrid.xml**:
```
<?xml version="1.0" encoding="UTF-8"?>
<!--
Module bootstrap file
-->
<config>
<modules>
<Example_SalesGrid>
<active>true</active>
<codePool>community</codePool>
<depends>
<Mage_Sales />
</depends>
</Example_SalesGrid>
</modules>
</config>
```
Next we create our module config xml in **/app/code/community/Example/SalesGrid/etc/config.xml**:
```
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Example_SalesGrid>
<version>0.1.0</version> <!-- define version for sql upgrade -->
</Example_SalesGrid>
</modules>
<global>
<models>
<example_salesgrid>
<class>Example_SalesGrid_Model</class>
</example_salesgrid>
</models>
<blocks>
<example_salesgrid>
<class>Example_SalesGrid_Block</class>
</example_salesgrid>
</blocks>
<events>
<!-- Add observer configuration -->
<sales_order_resource_init_virtual_grid_columns>
<observers>
<example_salesgrid>
<model>example_salesgrid/observer</model>
<method>addColumnToResource</method>
</example_salesgrid>
</observers>
</sales_order_resource_init_virtual_grid_columns>
</events>
<resources>
<!-- initialize sql upgrade setup -->
<example_salesgrid_setup>
<setup>
<module>Example_SalesGrid</module>
<class>Mage_Sales_Model_Mysql4_Setup</class>
</setup>
</example_salesgrid_setup>
</resources>
</global>
<adminhtml>
<layout>
<!-- layout upgrade configuration -->
<updates>
<example_salesgrid>
<file>example/salesgrid.xml</file>
</example_salesgrid>
</updates>
</layout>
</adminhtml>
</config>
```
Now we create the sql upgrade script in **/app/code/community/Example/SalesGrid/sql/example\_salesgrid\_setup/install-0.1.0.php**:
```
<?php
/**
* Setup scripts, add new column and fulfills
* its values to existing rows
*
*/
$this->startSetup();
// Add column to grid table
$this->getConnection()->addColumn(
$this->getTable('sales/order_grid'),
'customer_group_id',
'smallint(6) DEFAULT NULL'
);
// Add key to table for this field,
// it will improve the speed of searching & sorting by the field
$this->getConnection()->addKey(
$this->getTable('sales/order_grid'),
'customer_group_id',
'customer_group_id'
);
// Now you need to fullfill existing rows with data from address table
$select = $this->getConnection()->select();
$select->join(
array('order'=>$this->getTable('sales/order')),
$this->getConnection()->quoteInto(
'order.entity_id = order_grid.entity_id'
),
array('customer_group_id' => 'customer_group_id')
);
$this->getConnection()->query(
$select->crossUpdateFromSelect(
array('order_grid' => $this->getTable('sales/order_grid'))
)
);
$this->endSetup();
```
Next we create the layout update file in **/app/design/adminhtml/default/default/layout/example/salesgrid.xml:**
```
<?xml version="1.0"?>
<layout>
<!-- main layout definition that adds the column -->
<add_order_grid_column_handle>
<reference name="sales_order.grid">
<action method="addColumnAfter">
<columnId>customer_group_id</columnId>
<arguments module="sales" translate="header">
<header>Customer Group</header>
<index>customer_group_id</index>
<type>options</type>
<filter>Example_SalesGrid_Block_Widget_Grid_Column_Customer_Group</filter>
<renderer>Example_SalesGrid_Block_Widget_Grid_Column_Renderer_Customer_Group</renderer>
<width>200</width>
</arguments>
<after>grand_total</after>
</action>
</reference>
</add_order_grid_column_handle>
<!-- order grid action -->
<adminhtml_sales_order_grid>
<!-- apply the layout handle defined above -->
<update handle="add_order_grid_column_handle" />
</adminhtml_sales_order_grid>
<!-- order grid view action -->
<adminhtml_sales_order_index>
<!-- apply the layout handle defined above -->
<update handle="add_order_grid_column_handle" />
</adminhtml_sales_order_index>
</layout>
```
Now we need two Block files, one to create the filter options, **/app/code/community/Example/SalesGrid/Block/Widget/Grid/Column/Customer/Group.php:**
```
<?php
class Example_SalesGrid_Block_Widget_Grid_Column_Customer_Group extends Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Select {
protected $_options = false;
protected function _getOptions(){
if(!$this->_options) {
$methods = array();
$methods[] = array(
'value' => '',
'label' => ''
);
$methods[] = array(
'value' => '0',
'label' => 'Guest'
);
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionArray();
$this->_options = array_merge($methods,$groups);
}
return $this->_options;
}
}
```
And the second to translate the row values to the correct text that will be displayed, **/app/code/community/Example/SalesGrid/Block/Widget/Grid/Column/Renderer/Customer/Group.php**:
```
<?php
class Example_SalesGrid_Block_Widget_Grid_Column_Renderer_Customer_Group extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {
protected $_options = false;
protected function _getOptions(){
if(!$this->_options) {
$methods = array();
$methods[0] = 'Guest';
$groups = Mage::getResourceModel('customer/group_collection')
->addFieldToFilter('customer_group_id', array('gt' => 0))
->load()
->toOptionHash();
$this->_options = array_merge($methods,$groups);
}
return $this->_options;
}
public function render(Varien_Object $row){
$value = $this->_getValue($row);
$options = $this->_getOptions();
return isset($options[$value]) ? $options[$value] : $value;
}
}
```
The last file needed is only needed if you create an extra column from a table other than sales/order (sales\_flat\_order). All fields in sales/order\_grid matching the column name from sales/order is automatically updated in the sales/order\_grid table. If you need to add the payment option for example you will need this observer to add the field to the query so the data can be copied to the correct table. The observer used for this is in **/app/code/community/Example/SalesGrid/Model/Observer.php**:
```
<?php
/**
* Event observer model
*
*
*/
class Example_SalesGrid_Model_Observer {
public function addColumnToResource(Varien_Event_Observer $observer) {
// Only needed if you use a table other than sales/order (sales_flat_order)
//$resource = $observer->getEvent()->getResource();
//$resource->addVirtualGridColumn(
// 'payment_method',
// 'sales/order_payment',
// array('entity_id' => 'parent_id'),
// 'method'
//);
}
}
```
This code is based on the example from <http://www.ecomdev.org/2010/07/27/adding-order-attribute-to-orders-grid-in-magento-1-4-1.html>
Hope the example above solves your problem.
|
Instead of using the static column name you can use below method for all column. I can understand if use mageUz's answer that will work for one column and if you go for some other column then you might be getting same error. So below code gives you solution for all column simultaneously.
```
public function salesOrderGridCollectionLoadBefore(Varien_Event_Observer $observer)
{
$collection = $observer->getOrderGridCollection();
$select = $collection->getSelect();
$select->joinLeft(array('order' => $collection->getTable('sales/order')), 'order.entity_id=main_table.entity_id',array('shipping_arrival_date' => 'shipping_arrival_date'));
if ($where = $select->getPart('where')) {
foreach ($where as $key=> $condition) {
$parsedString = $this->get_string_between($condition, '`', '`');
$yes = $this->checkFiledExistInTable('order_grid',$parsedString);
if($yes){
$condition = str_replace('`','',$condition);
$where[$key] = str_replace($parsedString,"main_table.".$parsedString,$condition);
}
}
$select->setPart('where', $where);
}
}
public function checkFiledExistInTable($entity=null,$parsedString=null){
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
if($entity == 'order'){
$table = 'sales/order';
}elseif($entity == 'order_grid'){
$table = 'sales/order_grid';
}else{
return false;
}
$tableName = $resource->getTableName($table);
$saleField = $readConnection->describeTable($tableName);
if (array_key_exists($parsedString,$saleField)){
return true;
}else{
return false;
}
}
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
```
|
33,322,003 |
I'm working with MySQL through phpMyAdmin. I need to reset the ID fields in one of the tables in my database, but I need to do it based on the publication date of each row. I've been looking everywhere and I can't seem to find a solution :(
The following lines of code work fine, but do not do exactly what I require based on the datetime column:
```
SET @count = 0;
UPDATE `table_name` SET `table_name`.`ID` = @count:= @count + 1;
```
So this is what I have:
```
+----+---------------------+
| ID | post_date |
+----+---------------------+
| 1 | 2013-11-04 20:06:28 |
| 2 | 2012-03-30 11:20:22 |
| 3 | 2014-06-26 22:59:51 |
+----+---------------------+
```
And this is what I need:
```
+----+---------------------+
| ID | post_date |
+----+---------------------+
| 1 | 2005-08-02 16:51:48 |
| 2 | 2005-08-02 16:59:36 |
| 3 | 2005-08-02 17:01:54 |
+----+---------------------+
```
Thanks in advance, guys :)
|
2015/10/24
|
[
"https://Stackoverflow.com/questions/33322003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1374576/"
] |
Try this, a simple approach though.
>
> But you will lose all the relations to other tables since you are
> resetting the PRIMARY `ID` Keys.
>
>
>
```
# Copy entire table to a temporary one based on the publication date
CREATE TEMPORARY TABLE IF NOT EXISTS `#temp_table` AS SELECT * FROM `wp_posts` ORDER BY `post_date`;
# Drop `ID` column from the temporary table
ALTER TABLE `#temp_table` DROP COLUMN `ID`;
# Reset the table `wp_posts` as well as its `ID`
TRUNCATE TABLE `wp_posts`;
# Exclude `ID` column in the INSERT statement below
INSERT INTO `wp_posts`(`post_author`, `post_date`, ..., `comment_count`) SELECT * FROM `#temp_table`;
# Remove the temporary table
DROP TABLE `#temp_table`;
```
Also see the ERD for WP3.0 below,
[](https://i.stack.imgur.com/kH5M0.png)
Ref: <https://codex.wordpress.org/Database_Description/3.3>
|
Try doing it with the following script. It selects every row of your table and orders the rows by its date ascending. Then your Update-Command will be executed within a loop.
Add the type of the ID of your table to the DECLARE-Statement and change the
field-Name in the UPDATE-Statement to your ID-Column name.
```
BEGIN
DECLARE col_id BIGINT;
DECLARE stepLoopDone BOOLEAN DEFAULT FALSE;
DECLARE counter INT DEFAULT 1;
DECLARE ORDER_CURSOR CURSOR FOR
SELECT id
FROM wp_posts
ORDER BY post_date ASC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET stepLoopDone = TRUE;
OPEN ORDER_CURSOR;
myLoop: LOOP
FETCH ORDER_CURSOR INTO col_id;
IF stepLoopDone THEN
LEAVE myLoop;
END IF;
/*YOUR UPDATE COMMAND*/
UPDATE wp_posts
SET id = counter
WHERE id = col_id;
/*YOUR UPDATE COMMAND*/
SET counter = counter + 1;
END LOOP;
CLOSE ORDER_CURSOR;
END
```
|
1,425,950 |
I thought I had the answer to this problem but I seem to be off, something is wrong.
The prompt:
>
> Find the exact solution to the following recursive formulas. You may guess the solution and then prove it by induction.
>
>
> $T(1) = 1$ and $T(n) = T(n-1) + (2n-1)$
>
>
>
Working out the first few in the series:
$T(2) = 4$
$T(3) = 9$
$T(4) = 16$
So I would assume the formula is $T(n) = n^2$
To prove by induction the base case (1) works out, since $1^2 = 1$. Then if I assume $T(n) = n^2$, I try to prove:
$T(n+1) = (n+1)^2$
$T(n) + (2n-1) = (n+1)(n+1)$
$n^2 + 2n-1=n^2+2n+1$
That obviously doesn't add up, so where'd I go wrong?
|
2015/09/07
|
[
"https://math.stackexchange.com/questions/1425950",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/181285/"
] |
Since
$T(n)
=T(n-1)+2n-1
$,
replacing $n$
by $n+1$,
this becomes
$T(n+1)
=T(n)+2(n+1)-1
=T(n)+2n+1
$.
This makes your induction work,
because
$T(n)+2n+1
=n^2+2n+1
=(n+1)^2
=T(n+1)
$.
|
Note that you have
$$T(n+1)=T(n)+2(\color{red}{n+1})-1$$
in the inductive step.
|
2,683,697 |
I have a class diagram ("Customer") with some private and public attributes as well as some operations. Now I want to model a dialog (GUI) for editing this customer. The window represents the class Customer and some drop downs and checkboxes the attributes. The operations ("save", "refresh") are represented by buttons.
Design Question: Do I design my GUI dialog only for editing public attributes or also for editing private attributes?
(This is a pure object-oriented design question, there is no implementation.)
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2683697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76371/"
] |
I've been struggling with this one for while and when I recently installed Toad for MySQL I got the same issue.
I installed sysInternals process monitor tool to try and work out which file was causing the issue.
The answer is temp files.
Both SQL server management studio and toad use a similar naming convention for their temp files. Both use the temp directory under your user account in Documents and Settings. In my case, there were over 60 thousand \*.tmp files in that directory.
Watching the query execute through process monitor I could see the SQL IDE continually trying and failing to identify a temp file name which didn't exist until it finally gives up with a "The file exists" error.
The solution is simply to clear out the \*.tmp files in your local settings temp directory.
Both SQL Management Studio and Toad for MySQL are now working fine on my machine.
Hope this helps.
|
I ran into the same issue with SQL Server 2012 running on Windows 8.1. As @Stephen mentioned, the issue is with the temp files but I couldn't find them in the location he mentioned. Solved the problem by running disk cleanup and directing it to delete Temporary Files.
|
2,683,697 |
I have a class diagram ("Customer") with some private and public attributes as well as some operations. Now I want to model a dialog (GUI) for editing this customer. The window represents the class Customer and some drop downs and checkboxes the attributes. The operations ("save", "refresh") are represented by buttons.
Design Question: Do I design my GUI dialog only for editing public attributes or also for editing private attributes?
(This is a pure object-oriented design question, there is no implementation.)
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2683697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76371/"
] |
I've been struggling with this one for while and when I recently installed Toad for MySQL I got the same issue.
I installed sysInternals process monitor tool to try and work out which file was causing the issue.
The answer is temp files.
Both SQL server management studio and toad use a similar naming convention for their temp files. Both use the temp directory under your user account in Documents and Settings. In my case, there were over 60 thousand \*.tmp files in that directory.
Watching the query execute through process monitor I could see the SQL IDE continually trying and failing to identify a temp file name which didn't exist until it finally gives up with a "The file exists" error.
The solution is simply to clear out the \*.tmp files in your local settings temp directory.
Both SQL Management Studio and Toad for MySQL are now working fine on my machine.
Hope this helps.
|
Going further into Stephen's answer, the path would be:
* For Windows XP: `C:\Documents and Settings\%USERNAME%\Local Settings\Temp`
* For Vista and above: `C:\Users\%USERNAME%\AppData\Local\Temp`
* Or simply paste `%TEMP%` into the Windows Explorer address bar to get the path.
I recommend this little plugin in case you can't access the route:
**Take Ownership**
<http://www.sevenforums.com/tutorials/1911-take-ownership-shortcut.html>
|
2,683,697 |
I have a class diagram ("Customer") with some private and public attributes as well as some operations. Now I want to model a dialog (GUI) for editing this customer. The window represents the class Customer and some drop downs and checkboxes the attributes. The operations ("save", "refresh") are represented by buttons.
Design Question: Do I design my GUI dialog only for editing public attributes or also for editing private attributes?
(This is a pure object-oriented design question, there is no implementation.)
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2683697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76371/"
] |
I've been struggling with this one for while and when I recently installed Toad for MySQL I got the same issue.
I installed sysInternals process monitor tool to try and work out which file was causing the issue.
The answer is temp files.
Both SQL server management studio and toad use a similar naming convention for their temp files. Both use the temp directory under your user account in Documents and Settings. In my case, there were over 60 thousand \*.tmp files in that directory.
Watching the query execute through process monitor I could see the SQL IDE continually trying and failing to identify a temp file name which didn't exist until it finally gives up with a "The file exists" error.
The solution is simply to clear out the \*.tmp files in your local settings temp directory.
Both SQL Management Studio and Toad for MySQL are now working fine on my machine.
Hope this helps.
|
I have cleared temp files although issue was not solved hence I uninstalled the software through revo uninstaller thus it cleared all the software logs and software related registry data. And after re-installing problem was solved
|
2,683,697 |
I have a class diagram ("Customer") with some private and public attributes as well as some operations. Now I want to model a dialog (GUI) for editing this customer. The window represents the class Customer and some drop downs and checkboxes the attributes. The operations ("save", "refresh") are represented by buttons.
Design Question: Do I design my GUI dialog only for editing public attributes or also for editing private attributes?
(This is a pure object-oriented design question, there is no implementation.)
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2683697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76371/"
] |
Going further into Stephen's answer, the path would be:
* For Windows XP: `C:\Documents and Settings\%USERNAME%\Local Settings\Temp`
* For Vista and above: `C:\Users\%USERNAME%\AppData\Local\Temp`
* Or simply paste `%TEMP%` into the Windows Explorer address bar to get the path.
I recommend this little plugin in case you can't access the route:
**Take Ownership**
<http://www.sevenforums.com/tutorials/1911-take-ownership-shortcut.html>
|
I ran into the same issue with SQL Server 2012 running on Windows 8.1. As @Stephen mentioned, the issue is with the temp files but I couldn't find them in the location he mentioned. Solved the problem by running disk cleanup and directing it to delete Temporary Files.
|
2,683,697 |
I have a class diagram ("Customer") with some private and public attributes as well as some operations. Now I want to model a dialog (GUI) for editing this customer. The window represents the class Customer and some drop downs and checkboxes the attributes. The operations ("save", "refresh") are represented by buttons.
Design Question: Do I design my GUI dialog only for editing public attributes or also for editing private attributes?
(This is a pure object-oriented design question, there is no implementation.)
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2683697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76371/"
] |
I ran into the same issue with SQL Server 2012 running on Windows 8.1. As @Stephen mentioned, the issue is with the temp files but I couldn't find them in the location he mentioned. Solved the problem by running disk cleanup and directing it to delete Temporary Files.
|
I have cleared temp files although issue was not solved hence I uninstalled the software through revo uninstaller thus it cleared all the software logs and software related registry data. And after re-installing problem was solved
|
2,683,697 |
I have a class diagram ("Customer") with some private and public attributes as well as some operations. Now I want to model a dialog (GUI) for editing this customer. The window represents the class Customer and some drop downs and checkboxes the attributes. The operations ("save", "refresh") are represented by buttons.
Design Question: Do I design my GUI dialog only for editing public attributes or also for editing private attributes?
(This is a pure object-oriented design question, there is no implementation.)
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2683697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76371/"
] |
Going further into Stephen's answer, the path would be:
* For Windows XP: `C:\Documents and Settings\%USERNAME%\Local Settings\Temp`
* For Vista and above: `C:\Users\%USERNAME%\AppData\Local\Temp`
* Or simply paste `%TEMP%` into the Windows Explorer address bar to get the path.
I recommend this little plugin in case you can't access the route:
**Take Ownership**
<http://www.sevenforums.com/tutorials/1911-take-ownership-shortcut.html>
|
I have cleared temp files although issue was not solved hence I uninstalled the software through revo uninstaller thus it cleared all the software logs and software related registry data. And after re-installing problem was solved
|
22,541,623 |
I want to copy several 2-dimensional subarrays of 3-dimensional arrays (e.g. array1[n][rows][cols], ..., array4[n][rows][cols]), which are dynamically allocated (but with fixed length), into a 1-dimensional array (e.g. array[4\*rows\*cols]), which is statically allocated, in C. As there will be many rows and columns (e.g. 10000 rows and 500 columns), I was wondering which of the following three possibilities will be the fastest:
```
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
array[i*cols+j]=array1[2][i][j];
}
}
...
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
array[3*rows*cols+i*cols+j]=array4[2][i][j];
}
}
```
or
```
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
array[i*cols+j]=array1[2][i][j];
}
...
for(j=0;j<cols;j++){
array[3*rows*cols+i*cols+j]=array4[2][i][j];
}
}
```
or
```
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
array[i*cols+j]=array1[2][i][j];
...
array[3*rows*cols+i*cols+j]=array4[2][i][j];
}
}
```
Or is there even a faster way of performing this task in C (not C++)?
Thanks a lot! (I thought there should be a similar question already, but unfortunately did not find exactly what I was looking for. So, I am sorry if I missed such a question.)
Edit:
The reason for wanting to do this is the following: The information stored in those 2-dimensional (sub-)arrays has to be communicated via MPI. So, clients will do the above and the master (kind of) the other way round (i.e. 1-dimensional -> 2-dimensional). So, is there even a better way to do this overall?
|
2014/03/20
|
[
"https://Stackoverflow.com/questions/22541623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635727/"
] |
Assuming linear arrays and the same dimensions (which would invalidate my answer):
This
```
for(i=0;i<rows;i++) {
for(j=0;j<cols;j++) {
array[i*cols+j]=array1[2][i][j];
}
}
```
could be replace by:
```
memcpy(array, array1[2], sizeof(array1[2]));
```
Accordingly this one:
```
for(i=0;i<rows;i++) {
for(j=0;j<cols;j++) {
array[3*rows*cols+i*cols+j]=array4[2][i][j];
}
}
```
is going to be:
```
memcpy(array + 3*cols*rows, array4[2], sizeof(array4[2]));
```
|
C specifies arrays are stored in [row-major order](https://en.wikipedia.org/wiki/Row-major_order), so each `i` wrapping every `j` (and each `j` wrapping every `k`, and so on) is going to be faster than the alternative due to "[locality of reference](https://en.wikipedia.org/wiki/Locality_of_reference)."
However, as mentioned in comments, `memcpy()` will copy the entire space linearly, ignoring the ordering. So, it's almost certainly no worse and it will be far easier to keep straight, with only one call. Just be sure to use `sizeof()` to get the size of the array as stored, since the actual storage may be larger than just `rows*cols`.
The only case where `memcpy()` *might* be worse is if your array elements are pointers to something else. At that point, you would only be copying the map to the real data, which may not be what you want.
|
4,508,230 |
does exist a library that gives you undo/redo capability with history for a web app? An idea would be a php/javascript/ajax system in which you can register for every user action an opposite action and the variable state (like a normal undo manager!). and it should work both at client level and server level.
Did i ask too much?
|
2010/12/22
|
[
"https://Stackoverflow.com/questions/4508230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380403/"
] |
<https://github.com/jscott1989/jsundoable> is pretty good. Flexible.
You can use <http://www.openjs.com/scripts/events/keyboard_shortcuts> to attach the shortcut key
The thing I like about this one is the group facility. You implement the undo functionality at the lowest levels possible and then in the higher functions, you don't have to bother about any of the undoing, just group each discrete action under a different group. I find this extremely intuitive since logically, if u reverse every small action that you take, then the whole process will be flawlessly reversed.
It is also very easy to merge into an existing project since I have just recently done so to a large code of mine that handles a lot of DOM manipulations and processing.
|
Some pretty good link that might interest you as well:
>
>
> ```
> Undo.js
>
> Undo.js provides an abstraction for undoing and redoing any task.
> It can run both in the browser and on the server (targetted at node.js).
>
> ```
>
>
Checkout their demos:
<https://github.com/jzaefferer/undo>
<http://jzaefferer.github.com/undo/demos/>
<http://jzaefferer.github.com/undo/demos/contenteditable.html>
|
71,287,214 |
This is how I load the dataset but the dataset is too big. There are about 60k images. so I would like to limit it to 1/10 for training. Is there any built-in method I can do that?
```
from torchvision import datasets
import torchvision.transforms as transforms
train_data = datasets.MNIST(
root='data',
train=True,
transform=transforms.Compose(
[transforms.ToTensor()]
),
download=True
)
print(train_data)
print(train_data.data.size())
print(train_data.targets.size())
loaders = {
'train': DataLoader(train_data,
batch_size=100),
}
```
|
2022/02/27
|
[
"https://Stackoverflow.com/questions/71287214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16971617/"
] |
Instead of the `.forEach()` use `.mapToObject()`, as forEach doesn't return anything that could be processed further.
This is the code I would try:
```
List<double[]> listArray = IntStream.range(0,5)
.mapToObj(CollectingStreams::methodReturnArray)
.collect(Collectors.toList());
```
|
```
List<int> numbers = new ArrayList<>();
List<double> numbers.stream().map(number -> (double) number).toList();
```
|
71,287,214 |
This is how I load the dataset but the dataset is too big. There are about 60k images. so I would like to limit it to 1/10 for training. Is there any built-in method I can do that?
```
from torchvision import datasets
import torchvision.transforms as transforms
train_data = datasets.MNIST(
root='data',
train=True,
transform=transforms.Compose(
[transforms.ToTensor()]
),
download=True
)
print(train_data)
print(train_data.data.size())
print(train_data.targets.size())
loaders = {
'train': DataLoader(train_data,
batch_size=100),
}
```
|
2022/02/27
|
[
"https://Stackoverflow.com/questions/71287214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16971617/"
] |
Instead of the `.forEach()` use `.mapToObject()`, as forEach doesn't return anything that could be processed further.
This is the code I would try:
```
List<double[]> listArray = IntStream.range(0,5)
.mapToObj(CollectingStreams::methodReturnArray)
.collect(Collectors.toList());
```
|
You don't need a method to return the array. You can do it like this.
```
List<double[]> listArray= IntStream.range(0,5)
.mapToObj(i->new double[]{i*1, i*2})
.toList();
listArray.forEach(s->System.out.println(Arrays.toString(s)));
```
prints
```
[0.0, 0.0]
[1.0, 2.0]
[2.0, 4.0]
[3.0, 6.0]
[4.0, 8.0]
```
|
71,287,214 |
This is how I load the dataset but the dataset is too big. There are about 60k images. so I would like to limit it to 1/10 for training. Is there any built-in method I can do that?
```
from torchvision import datasets
import torchvision.transforms as transforms
train_data = datasets.MNIST(
root='data',
train=True,
transform=transforms.Compose(
[transforms.ToTensor()]
),
download=True
)
print(train_data)
print(train_data.data.size())
print(train_data.targets.size())
loaders = {
'train': DataLoader(train_data,
batch_size=100),
}
```
|
2022/02/27
|
[
"https://Stackoverflow.com/questions/71287214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16971617/"
] |
You don't need a method to return the array. You can do it like this.
```
List<double[]> listArray= IntStream.range(0,5)
.mapToObj(i->new double[]{i*1, i*2})
.toList();
listArray.forEach(s->System.out.println(Arrays.toString(s)));
```
prints
```
[0.0, 0.0]
[1.0, 2.0]
[2.0, 4.0]
[3.0, 6.0]
[4.0, 8.0]
```
|
```
List<int> numbers = new ArrayList<>();
List<double> numbers.stream().map(number -> (double) number).toList();
```
|
11,765,386 |
I'm trying to do something like the following in order for the user to select their recurring subscription plan.
I keep getting the following error in PayPal when trying to submit this form:
*'Invalid Regular period. You must specify valid values for the A3, P3, and T3 parameters for a subscription.'*
I've specified the A3, P3, and T3 params in the form, so I'm not sure what's going on. Can someone help? Thanks in advance!
```
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick-subscriptions">
<table>
<tr><td>Frequency</td></tr><tr><td>
<select name="a3">
<option value="438.00">Every 2 weeks: $438.00 USD - monthly</option>
<option value="219.00">Every 4 weeks: $219.00 USD - monthly</option>
<option value="146.00">Every 6 weeks: $146.00 USD - monthly</option>
<option value="109.50">Every 8 weeks: $109.50 USD - monthly</option>
</select> </td></tr>
<tr><td>Coffee Selection</td></tr><tr><td>
<select name="item_name">
<option value="Ethiopian Ground Subscription">Ethiopian Ground</option>
<option value="Colombian Ground Subscription">Colombian Ground</option>
<option value="Colombian Whole Bean Subscription">Colombian Whole Bean</option>
<option value="Guatemalan Ground Subscription">Guatemalan Ground</option>
<option value="Guatemalan Whole Bean Subscription">Guatemalan Whole Bean</option>
<option value="Decaf Ground Subscription">Decaf Ground</option>
<option value="Decaf Whole Bean Subscription">Decaf Whole Bean</option>
</select> </td></tr>
</table>
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="t3" value="M"> <!-- billing cycle unit=month -->
<input type="hidden" name="p3" value="1"> <!-- billing cycle length -->
<input type="hidden" name="src" value="1"> <!-- recurring=yes -->
<input type="hidden" name="sra" value="1"> <!-- reattempt=yes -->
<input type="hidden" name="return" value="http://www.gobena.org">
<input type="hidden" name="cancel_return" value="http://www.gobena.org">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_subscribe_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
```
|
2012/08/01
|
[
"https://Stackoverflow.com/questions/11765386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538143/"
] |
Write them in capital letters in your code and see if it works.
```
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick-subscriptions">
<table>
<tr><td>Frequency</td></tr><tr><td>
<select name="A3">
<option value="438.00">Every 2 weeks: $438.00 USD - monthly</option>
<option value="219.00">Every 4 weeks: $219.00 USD - monthly</option>
<option value="146.00">Every 6 weeks: $146.00 USD - monthly</option>
<option value="109.50">Every 8 weeks: $109.50 USD - monthly</option>
</select> </td></tr>
<tr><td>Coffee Selection</td></tr><tr><td>
<select name="item_name">
<option value="Ethiopian Ground Subscription">Ethiopian Ground</option>
<option value="Colombian Ground Subscription">Colombian Ground</option>
<option value="Colombian Whole Bean Subscription">Colombian Whole Bean</option>
<option value="Guatemalan Ground Subscription">Guatemalan Ground</option>
<option value="Guatemalan Whole Bean Subscription">Guatemalan Whole Bean</option>
<option value="Decaf Ground Subscription">Decaf Ground</option>
<option value="Decaf Whole Bean Subscription">Decaf Whole Bean</option>
</select> </td></tr>
</table>
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="T3" value="M"> <!-- billing cycle unit=month -->
<input type="hidden" name="P3" value="1"> <!-- billing cycle length -->
<input type="hidden" name="src" value="1"> <!-- recurring=yes -->
<input type="hidden" name="sra" value="1"> <!-- reattempt=yes -->
<input type="hidden" name="return" value="http://www.gobena.org">
<input type="hidden" name="cancel_return" value="http://www.gobena.org">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_subscribe_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
```
|
This code ended up working fine. I was running into a caching issue, which is why I kept receiving the error. :)
|
17,981 |
I've probably done about 20k on the rotors I bought the bike with. They still work fine, but are visibly worn and slightly grooved from me not replacing the pads soon enough a few times.
How do I know when it's time to get new rotors (apart from by finding out the hard way, of course)?
|
2013/10/08
|
[
"https://bicycles.stackexchange.com/questions/17981",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/896/"
] |
Normally the manufacturer of the brakes gives some minimum value for the rotor thickness. For higher prized brakes they often even provide some gauge that lets you easily check if the rotor is still thick enough.
Typically the minimum thickness might be somewhere below 2mm (I believe to remember that the absolute minimum for Magura discs should be 1.7 or 1.8 mm). But as said, this should be an information that should be in the manual fo your brakes.
|
In my 14 years cycling career only once I had to replace rotor due to wear. And that rotor was 6 years old and used for heavy downhill riding in all conditions. I've gone through a lot of pads on that rotor (like 20-30 pairs). And only when I could actually feel with my fingers the groove on the surface, I replaced it. Also it started eating pads like mad - uneven breaking surface wore pads much quicker.
I'd say rotors is something you would not replace quite often. And rotors would not fail on you like a worn-out rims - rotors won't split easily. So for a sake of measurements, 30% thickness reduction would be a good indication to replace the poor thing.
|
17,981 |
I've probably done about 20k on the rotors I bought the bike with. They still work fine, but are visibly worn and slightly grooved from me not replacing the pads soon enough a few times.
How do I know when it's time to get new rotors (apart from by finding out the hard way, of course)?
|
2013/10/08
|
[
"https://bicycles.stackexchange.com/questions/17981",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/896/"
] |
Normally the manufacturer of the brakes gives some minimum value for the rotor thickness. For higher prized brakes they often even provide some gauge that lets you easily check if the rotor is still thick enough.
Typically the minimum thickness might be somewhere below 2mm (I believe to remember that the absolute minimum for Magura discs should be 1.7 or 1.8 mm). But as said, this should be an information that should be in the manual fo your brakes.
|
Shimano recommends that its rotors, which start out 1.8mm thick, should be replaced when the braking surface has been reduced to 1.5mm. Credit <https://road.cc/content/feature/when-should-you-get-new-disc-brake-rotors-257623>
|
43,331,113 |
This is the code snippet. The query returns in json form but how do I write these values in a JSON file?
```
app.get('/users', function(req, res) {
User.find({}, function(err, docs) {
res.json(docs);
console.error(err);
})
});
```
|
2017/04/10
|
[
"https://Stackoverflow.com/questions/43331113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7846790/"
] |
If you're going to be writing to a file within a route callback handler you should use the Asynchronous `writeFile()` function or the `fs.createWriteStream()` function which are a part of the `fs` Module in the Node.js Core API . If not, your server will be unresponsive to any subsequent requests because the Node.js thread will be blocking while it is writing to the file system.
Here is an example usage of [`writeFile`](https://nodejs.org/dist/latest-v7.x/docs/api/fs.html#fs_fs_writefile_file_data_options_callback) within your route callback handler. This code will overwrite the `./docs.json` file every time the route is called.
```
const fs = require('fs')
const filepath = './docs.json'
app.get('/users', (req, res) => {
Users.find({}, (err, docs) => {
if (err)
return res.sendStatus(500)
fs.writeFile(filepath, JSON.stringify(docs, null, 2), err => {
if (err)
return res.sendStatus(500)
return res.json(docs)
})
})
})
```
Here is an example usage of writing your JSON to a file with Streams. `fs.createReadStream()` is used to create a readable stream of the stringified `docs` object. Then that Readable is written to the filepath with a Writable stream that has the Readable data piped into it.
```
const fs = require('fs')
app.get('/users', (req, res) => {
Users.find({}, (err, docs) => {
if (err)
return res.sendStatus(500)
let reader = fs.createReadStream(JSON.stringify(docs, null, 2))
let writer = fs.createWriteStream(filename)
reader.on('error', err => {
// an error occurred while reading
writer.end() // explicitly close writer
return res.sendStatus(500)
})
write.on('error', err => {
// an error occurred writing
return res.sendStatus(500)
})
write.on('close', () => {
// writer is done writing the file contents, respond to requester
return res.json(docs)
})
// pipe the data from reader to writer
reader.pipe(writer)
})
})
```
|
Use node's file system library 'fs'.
```
const fs = require('fs');
const jsonData = { "Hello": "World" };
fs.writeFileSync('output.json', JSON.strigify(jsonData));
```
Docs: [fs.writeFileSync(file, data[, options])](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options)
|
35,541,881 |
I'm building my own tag system for a forum I'm making. Everything is working perfectly, but I am trying to echo a list of the most popular tags but I can't find which query to use..
My tables look like this:

I need a list of the 20 most popular tags, so the tag\_names of which the tag\_id appear the most in the article\_tag\_xref table. Anyone who has an idea what the query should look like? Thanks!
|
2016/02/21
|
[
"https://Stackoverflow.com/questions/35541881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4274031/"
] |
You can use the following query:
```sql
SELECT t.tag_id, t.tag_name, COUNT(article_id) AS cnt
FROM Article_Tag_Xref AS a
INNER JOIN Tag AS t ON a.tag_id = t.tag_id
GROUP BY t.tag_id, t.tag_name
ORDER BY COUNT(article_id) DESC LIMIT 20
```
`COUNT(article_id)` returns the number of appearances of each `tag_ig` in the `Article_Tag_Xref` table. Thus, order by this count in descending order and applying a `LIMIT 20` returns the 20 most popular `tag_ig` values.
|
The following should work out for you, as you only asked about the tag\_names without their count.
```
SELECT tag_name
FROM Tag
WHERE tag_id IN ( SELECT tag_id, COUNT(article_id)
FROM Article_Tag_Xref
GROUP BY tag_id
ORDER BY COUNT(article_id) DESC
LIMIT 20)
```
The subquery returns the top 20 `tag_ids` and their count.
|
3,494,673 |
>
> Let $F:\mathbb{R}\to\mathbb{R}$ be a strictly convex function. Let $u:[0,1]\to\mathbb{R} $ be a continuous function, with
> $$\int\_{0}^{1}u(x)\,dx=0$$
> Show that
> $$\int\_{0}^{1}F(u(x))\,dx\leqslant\frac{F(\| u\|\_\infty)+F(-\| u\|\_\infty)}{2}$$
> where
> $$\| u\|\_\infty:=\sup\_{x\in [0,1]}|u(x)|$$
> Also determine where the equality occurs.
>
>
>
I have tried to use Jensen inequality but I failed.
|
2020/01/02
|
[
"https://math.stackexchange.com/questions/3494673",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/738762/"
] |
Any ring homomorphism $\phi: \mathbb{Z}\_{11} \to \mathbb{Z}\_{13}$ is also a group homomorphism. The kernel of $\phi$ must have index dividing 11 and 13 (why?) and hence has index dividing $\gcd(13,11)=1$. Hence $\ker \phi= \mathbb{Z}\_{11}$. And hence no group homomorphism sending $1\_{11}$ to $1\_{13}$.
|
**Hint.** What happens if you add the equality $f(1\_{11})=1\_{13}$ to itself $13$ times?
|
3,494,673 |
>
> Let $F:\mathbb{R}\to\mathbb{R}$ be a strictly convex function. Let $u:[0,1]\to\mathbb{R} $ be a continuous function, with
> $$\int\_{0}^{1}u(x)\,dx=0$$
> Show that
> $$\int\_{0}^{1}F(u(x))\,dx\leqslant\frac{F(\| u\|\_\infty)+F(-\| u\|\_\infty)}{2}$$
> where
> $$\| u\|\_\infty:=\sup\_{x\in [0,1]}|u(x)|$$
> Also determine where the equality occurs.
>
>
>
I have tried to use Jensen inequality but I failed.
|
2020/01/02
|
[
"https://math.stackexchange.com/questions/3494673",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/738762/"
] |
Any ring homomorphism $\phi: \mathbb{Z}\_{11} \to \mathbb{Z}\_{13}$ is also a group homomorphism. The kernel of $\phi$ must have index dividing 11 and 13 (why?) and hence has index dividing $\gcd(13,11)=1$. Hence $\ker \phi= \mathbb{Z}\_{11}$. And hence no group homomorphism sending $1\_{11}$ to $1\_{13}$.
|
Since a ring homomorphism is a group homomorphism, you can invoke Lagrange's theorem to get a contradiction. That is, $\varphi (\Bbb Z\_{11})\cong \Bbb Z\_{11}/\operatorname {ker}\phi$, so has order dividing $11$. But $\varphi (\Bbb Z\_{11})\le\Bbb Z\_{13}$. Thus the image has order $1$, or $\varphi $ is trivial.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
You can subclass your own field with needed `formfield` method:
```
class CharFieldWithTextarea(models.CharField):
def formfield(self, **kwargs):
kwargs.update({"widget": forms.Textarea})
return super(CharFieldWithTextarea, self).formfield(**kwargs)
```
This will take affect on all generated forms.
|
If you are trying to change the Textarea on admin.py, this is the solution that worked for me:
```
from django import forms
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from books.models import Book
class BookForm(forms.ModelForm):
description = forms.CharField( widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))
class Meta:
model = Book
class BookAdmin(admin.ModelAdmin):
form = BookForm
admin.site.register(Book, BookAdmin)
```
If you are using a MySQL DB, your column length will usually be autoset to 250 characters, so you will want to run an ALTER TABLE to change the length in you MySQL DB, so that you can take advantage of the new larger Textarea that you have in you Admin Django site.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
You can use `models.TextField` for this purpose:
```
class Sample(models.Model):
field1 = models.CharField(max_length=128)
field2 = models.TextField(max_length=1024*2) # Will be rendered as textarea
```
|
Wanted to expand on Carl Meyer's answer, which works perfectly till this date.
I always use `TextField` instead of `CharField` (with or without choices) and impose character limits on UI/API side rather than at DB level. To make this work dynamically:
```
from django import forms
from django.contrib import admin
class BaseAdmin(admin.ModelAdmin):
"""
Base admin capable of forcing widget conversion
"""
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(BaseAdmin, self).formfield_for_dbfield(
db_field, **kwargs)
display_as_charfield = getattr(self, 'display_as_charfield', [])
display_as_choicefield = getattr(self, 'display_as_choicefield', [])
if db_field.name in display_as_charfield:
formfield.widget = forms.TextInput(attrs=formfield.widget.attrs)
elif db_field.name in display_as_choicefield:
formfield.widget = forms.Select(choices=formfield.choices,
attrs=formfield.widget.attrs)
return formfield
```
I have a model name `Post` where `title`, `slug` & `state` are `TextField`s and `state` has choices. The admin definition looks like:
```
@admin.register(Post)
class PostAdmin(BaseAdmin):
list_display = ('pk', 'title', 'author', 'org', 'state', 'created',)
search_fields = [
'title',
'author__username',
]
display_as_charfield = ['title', 'slug']
display_as_choicefield = ['state']
```
Thought others looking for answers might find this useful.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
You don't need to create the form class yourself:
```
from django.contrib import admin
from django import forms
class MyModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
kwargs['widgets'] = {'descr': forms.Textarea}
return super().get_form(request, obj, **kwargs)
admin.site.register(MyModel, MyModelAdmin)
```
See [ModelAdmin.get\_form](https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form).
|
If you are trying to change the Textarea on admin.py, this is the solution that worked for me:
```
from django import forms
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from books.models import Book
class BookForm(forms.ModelForm):
description = forms.CharField( widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))
class Meta:
model = Book
class BookAdmin(admin.ModelAdmin):
form = BookForm
admin.site.register(Book, BookAdmin)
```
If you are using a MySQL DB, your column length will usually be autoset to 250 characters, so you will want to run an ALTER TABLE to change the length in you MySQL DB, so that you can take advantage of the new larger Textarea that you have in you Admin Django site.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
You don't need to create the form class yourself:
```
from django.contrib import admin
from django import forms
class MyModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
kwargs['widgets'] = {'descr': forms.Textarea}
return super().get_form(request, obj, **kwargs)
admin.site.register(MyModel, MyModelAdmin)
```
See [ModelAdmin.get\_form](https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form).
|
Instead of a `models.CharField`, use a `models.TextField` for `descr`.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
You will have to create a `forms.ModelForm` that will describe how you want the `descr` field to be displayed, and then tell `admin.ModelAdmin` to use that form. For example:
```
from django import forms
class CabModelForm( forms.ModelForm ):
descr = forms.CharField( widget=forms.Textarea )
class Meta:
model = Cab
class Cab_Admin( admin.ModelAdmin ):
form = CabModelForm
```
The `form` attribute of `admin.ModelAdmin` is documented in the official Django documentation. Here is [one place to look at](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin).
|
You can use `models.TextField` for this purpose:
```
class Sample(models.Model):
field1 = models.CharField(max_length=128)
field2 = models.TextField(max_length=1024*2) # Will be rendered as textarea
```
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
For this case, the best option is probably just to use a TextField instead of CharField in your model. You can also override the `formfield_for_dbfield` method of your `ModelAdmin` class:
```
class CabAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(CabAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'descr':
formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
return formfield
```
|
Ayaz has pretty much spot on, except for a slight change(?!):
```
class MessageAdminForm(forms.ModelForm):
class Meta:
model = Message
widgets = {
'text': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class MessageAdmin(admin.ModelAdmin):
form = MessageAdminForm
admin.site.register(Message, MessageAdmin)
```
So, you don't need to redefine a field in the ModelForm to change it's widget, just set the widgets dict in Meta.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
For this case, the best option is probably just to use a TextField instead of CharField in your model. You can also override the `formfield_for_dbfield` method of your `ModelAdmin` class:
```
class CabAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(CabAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'descr':
formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
return formfield
```
|
If you are trying to change the Textarea on admin.py, this is the solution that worked for me:
```
from django import forms
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from books.models import Book
class BookForm(forms.ModelForm):
description = forms.CharField( widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))
class Meta:
model = Book
class BookAdmin(admin.ModelAdmin):
form = BookForm
admin.site.register(Book, BookAdmin)
```
If you are using a MySQL DB, your column length will usually be autoset to 250 characters, so you will want to run an ALTER TABLE to change the length in you MySQL DB, so that you can take advantage of the new larger Textarea that you have in you Admin Django site.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
Ayaz has pretty much spot on, except for a slight change(?!):
```
class MessageAdminForm(forms.ModelForm):
class Meta:
model = Message
widgets = {
'text': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class MessageAdmin(admin.ModelAdmin):
form = MessageAdminForm
admin.site.register(Message, MessageAdmin)
```
So, you don't need to redefine a field in the ModelForm to change it's widget, just set the widgets dict in Meta.
|
If you are trying to change the Textarea on admin.py, this is the solution that worked for me:
```
from django import forms
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from books.models import Book
class BookForm(forms.ModelForm):
description = forms.CharField( widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))
class Meta:
model = Book
class BookAdmin(admin.ModelAdmin):
form = BookForm
admin.site.register(Book, BookAdmin)
```
If you are using a MySQL DB, your column length will usually be autoset to 250 characters, so you will want to run an ALTER TABLE to change the length in you MySQL DB, so that you can take advantage of the new larger Textarea that you have in you Admin Django site.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
Instead of a `models.CharField`, use a `models.TextField` for `descr`.
|
Wanted to expand on Carl Meyer's answer, which works perfectly till this date.
I always use `TextField` instead of `CharField` (with or without choices) and impose character limits on UI/API side rather than at DB level. To make this work dynamically:
```
from django import forms
from django.contrib import admin
class BaseAdmin(admin.ModelAdmin):
"""
Base admin capable of forcing widget conversion
"""
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(BaseAdmin, self).formfield_for_dbfield(
db_field, **kwargs)
display_as_charfield = getattr(self, 'display_as_charfield', [])
display_as_choicefield = getattr(self, 'display_as_choicefield', [])
if db_field.name in display_as_charfield:
formfield.widget = forms.TextInput(attrs=formfield.widget.attrs)
elif db_field.name in display_as_choicefield:
formfield.widget = forms.Select(choices=formfield.choices,
attrs=formfield.widget.attrs)
return formfield
```
I have a model name `Post` where `title`, `slug` & `state` are `TextField`s and `state` has choices. The admin definition looks like:
```
@admin.register(Post)
class PostAdmin(BaseAdmin):
list_display = ('pk', 'title', 'author', 'org', 'state', 'created',)
search_fields = [
'title',
'author__username',
]
display_as_charfield = ['title', 'slug']
display_as_choicefield = ['state']
```
Thought others looking for answers might find this useful.
|
430,592 |
I have
```
class Cab(models.Model):
name = models.CharField( max_length=20 )
descr = models.CharField( max_length=2000 )
class Cab_Admin(admin.ModelAdmin):
ordering = ('name',)
list_display = ('name','descr', )
# what to write here to make descr using TextArea?
admin.site.register( Cab, Cab_Admin )
```
how to assign TextArea widget to 'descr' field in admin interface?
**upd:**
In **Admin** interface only!
Good idea to use ModelForm.
|
2009/01/10
|
[
"https://Stackoverflow.com/questions/430592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21152/"
] |
You will have to create a `forms.ModelForm` that will describe how you want the `descr` field to be displayed, and then tell `admin.ModelAdmin` to use that form. For example:
```
from django import forms
class CabModelForm( forms.ModelForm ):
descr = forms.CharField( widget=forms.Textarea )
class Meta:
model = Cab
class Cab_Admin( admin.ModelAdmin ):
form = CabModelForm
```
The `form` attribute of `admin.ModelAdmin` is documented in the official Django documentation. Here is [one place to look at](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin).
|
If you are trying to change the Textarea on admin.py, this is the solution that worked for me:
```
from django import forms
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from books.models import Book
class BookForm(forms.ModelForm):
description = forms.CharField( widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))
class Meta:
model = Book
class BookAdmin(admin.ModelAdmin):
form = BookForm
admin.site.register(Book, BookAdmin)
```
If you are using a MySQL DB, your column length will usually be autoset to 250 characters, so you will want to run an ALTER TABLE to change the length in you MySQL DB, so that you can take advantage of the new larger Textarea that you have in you Admin Django site.
|
1,407,037 |
My new project is to build an application to use the cell phone camera as the main camera from my PC.
How can I do this kind of stuff?
I thought of using bluetooth, but how my PC define the cell phone as the main camera?
Best reguards.
|
2009/09/10
|
[
"https://Stackoverflow.com/questions/1407037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58251/"
] |
I have to manage lots of changes every day in Visual Studio, and I've got a few tips for you, but no silver bullet:
Use `Ctrl`+`A` to select all items and then press a checkbox to toggle the checkboxes for all items. This can be useful when performing changes to only a few items -- just uncheck everything, then make sure you have only the items checked that you'd like to update.
Use `Ctrl`+Click (then right-click) to 'Undo' selected changes. By default, the undo action will only apply to the selected items.
You might want to experiment with **using multiple Workspaces** -- and then filtering changes by workspace or by solution.
|
No, I don't know of a way to fix your problems. It sounds like the best answer would be to refactor your configuration settings or code so that you can check in all of your changes.
|
1,407,037 |
My new project is to build an application to use the cell phone camera as the main camera from my PC.
How can I do this kind of stuff?
I thought of using bluetooth, but how my PC define the cell phone as the main camera?
Best reguards.
|
2009/09/10
|
[
"https://Stackoverflow.com/questions/1407037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58251/"
] |
No, I don't know of a way to fix your problems. It sounds like the best answer would be to refactor your configuration settings or code so that you can check in all of your changes.
|
You can also use `Ctrl`+`A` to select all items and then press `Spacebar` to toggle the checkedboxes as checked/unchecked.
|
1,407,037 |
My new project is to build an application to use the cell phone camera as the main camera from my PC.
How can I do this kind of stuff?
I thought of using bluetooth, but how my PC define the cell phone as the main camera?
Best reguards.
|
2009/09/10
|
[
"https://Stackoverflow.com/questions/1407037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58251/"
] |
I have to manage lots of changes every day in Visual Studio, and I've got a few tips for you, but no silver bullet:
Use `Ctrl`+`A` to select all items and then press a checkbox to toggle the checkboxes for all items. This can be useful when performing changes to only a few items -- just uncheck everything, then make sure you have only the items checked that you'd like to update.
Use `Ctrl`+Click (then right-click) to 'Undo' selected changes. By default, the undo action will only apply to the selected items.
You might want to experiment with **using multiple Workspaces** -- and then filtering changes by workspace or by solution.
|
If your changes are in different projects you can partition what you check in using the Source Control Explorer by right clicking on the project folder and checking in that way. It will auto check only the files in the folder you right click on. Just keep in mind the Source Control Explorer gives you some other options. Otherwise, I do not know of a way to manually control your change sets file-by-file thought if this exists I would like to know about it too.
|
1,407,037 |
My new project is to build an application to use the cell phone camera as the main camera from my PC.
How can I do this kind of stuff?
I thought of using bluetooth, but how my PC define the cell phone as the main camera?
Best reguards.
|
2009/09/10
|
[
"https://Stackoverflow.com/questions/1407037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58251/"
] |
I have to manage lots of changes every day in Visual Studio, and I've got a few tips for you, but no silver bullet:
Use `Ctrl`+`A` to select all items and then press a checkbox to toggle the checkboxes for all items. This can be useful when performing changes to only a few items -- just uncheck everything, then make sure you have only the items checked that you'd like to update.
Use `Ctrl`+Click (then right-click) to 'Undo' selected changes. By default, the undo action will only apply to the selected items.
You might want to experiment with **using multiple Workspaces** -- and then filtering changes by workspace or by solution.
|
You can also use `Ctrl`+`A` to select all items and then press `Spacebar` to toggle the checkedboxes as checked/unchecked.
|
1,407,037 |
My new project is to build an application to use the cell phone camera as the main camera from my PC.
How can I do this kind of stuff?
I thought of using bluetooth, but how my PC define the cell phone as the main camera?
Best reguards.
|
2009/09/10
|
[
"https://Stackoverflow.com/questions/1407037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58251/"
] |
If your changes are in different projects you can partition what you check in using the Source Control Explorer by right clicking on the project folder and checking in that way. It will auto check only the files in the folder you right click on. Just keep in mind the Source Control Explorer gives you some other options. Otherwise, I do not know of a way to manually control your change sets file-by-file thought if this exists I would like to know about it too.
|
You can also use `Ctrl`+`A` to select all items and then press `Spacebar` to toggle the checkedboxes as checked/unchecked.
|
35,280,125 |
I have a function which takes a String containing a math expression such as `6+9*8` or `4+9` and it evaluates them from left to right (without normal order of operation rules).
I've been stuck with this problem for the past couple of hours and have finally found the culprit BUT I have no idea why it is doing what it does. When I split the string through regex (`.split("\\d")` and `.split("\\D")`), I make it go into 2 arrays, one is a `int[]` where it contains the numbers involved in the expression and a `String[]` where it contains the operations.
What I've realized is that when I do the following:
```
String question = "5+9*8";
String[] mathOperations = question.split("\\d");
for(int i = 0; i < mathOperations.length; i++) {
System.out.println("Math Operation at " + i + " is " + mathOperations[i]);
}
```
it does not put the first operation sign in index 0, rather it puts it in index 1. Why is this?
This is the `system.out` on the console:
```
Math Operation at 0 is
Math Operation at 1 is +
Math Operation at 2 is *
```
|
2016/02/08
|
[
"https://Stackoverflow.com/questions/35280125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4333115/"
] |
Because on position 0 of `mathOperations` there's an empty String. In other words
```
mathOperations = {"", "+", "*"};
```
According to `split` [documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29)
>
> The array returned by this method contains each substring of this
> string that is terminated by another substring that matches the given
> expression or is terminated by the end of the string. ...
>
>
>
Why isn't there an empty string at the end of the array too?
>
> Trailing empty strings are therefore not included in the resulting
> array.
>
>
>
More detailed explanation - your regex matched the String like this:
```
"(5)+(9)*(8)" -> "" + (5) + "+" + (9) + "*" + (8) + ""
```
but the trailing empty string is discarded as specified by the documentation.
(hope this silly illustration helps)
**Also** a thing worth noting, the regex you used `"\\d"`, would split following string `"55+5"` into
```
["", "", "+"]
```
That's because you match only a single character, you should probably use `"\\d+"`
|
You may find the following variation on your program helpful, as one split does the jobs of both of yours...
```
public class zw {
public static void main(String[] args) {
String question = "85+9*8-900+77";
String[] bits = question.split("\\b");
for (int i = 0; i < bits.length; ++i) System.out.println("[" + bits[i] + "]");
}
}
```
and its output:
>
> []
>
> [85]
>
> [+]
>
> [9]
>
> [\*]
>
> [8]
>
> [-]
>
> [900]
>
> [+]
>
> [77]
>
>
>
In this program, I used `\b` as a "zero-width boundary" to do the splitting. No characters were harmed during the split, they all went into the array.
More info here: <https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html>
and here: <http://www.regular-expressions.info/wordboundaries.html>
|
34,525,240 |
I have a form in which the user must initial a bunch of different sections.
```
<script>
$.function(){
$('.initialMe').change(function(){
var id = $(this).attr('id');
alert(id);
});
});
</script>
<?php
echo "<div class='signature'>Initial Here:<input type='text' class='initialMe' id='sign[service1]' name='sign[service1]' size='4'></div>";
echo "<div class='signature'>Initial Here:<input type='text' class='initialMe' id='sign[service2]' name='sign[service2]' size='4'></div>";
?>
```
I want to fire off an action when they are done initializing the text box. I don't want to use change because they have to click off somewhere for event to be fired. I don't want to use `keyup`, because event will fire after first letter of initials. I do not know if user will use 2 letters or 3 for initials. This is not a submittable form. Think of it as a legal document where the user has to initial different sections of the page. What options do I have?
|
2015/12/30
|
[
"https://Stackoverflow.com/questions/34525240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2187142/"
] |
You can use a combination of `keyup` and `setTimeout`. What I am trying to say is, bind it in `keyup` and give some time for the user to feel like it's done and then check.
```js
$(function () {
var tmr = 0;
$("input").keyup(function () {
clearTimeout(tmr);
tmr = setTimeout(function () {
alert("Checking...");
}, 1000);
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input />
```
This way, it is checked every time, but gives some time. When the user types again within a second, it clears the previous timer, so the check will not happen.
|
Why not do it on `blur()`?
If the user has clicked or tabbed away from the field then that gives an indication they're done imho.
Another option, if it's the same user initialing several parts of a form - you could wait until the first field is done, check with the user that it's correct, then don't do anything with the others until then initials match the first completed field.
|
1,650,399 |
I need to implement self-sorted data structure with random access. Any ideas?
|
2009/10/30
|
[
"https://Stackoverflow.com/questions/1650399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199719/"
] |
Maintaining a sorted list and accessing it arbitrarily requires at least O(lgN) / operation. So, look for [AVL](http://en.wikipedia.org/wiki/AVL_tree), [red-black trees](http://en.wikipedia.org/wiki/Red-black_tree), [treaps](http://en.wikipedia.org/wiki/Treap) or any other similar data structure and enrich them to support random indexing. I suggest [treaps](http://en.wikipedia.org/wiki/Treap) since they are the easiest to understand/implement.
One way to enrich the treap tree is to keep in each node the count of nodes in the subtree rooted at that node. You'll have to update the count when you modify the tree (eg: insertion/deletion).
|
Self sorting is a little bit to ambigious. First of all
**What kind of data structure?**
There are a lot of different data structures out there, such as:
* Linked list
* Double linked list
* Binary tree
* Hash set / map
* Stack
* Heap
And many more and each of them behave differently than others and have their benefits of course.
Now, not all of them could or should be self-sorting, such as the Stack, it would be weird if that one were self-sorting.
However, the Linked List and the Binary Tree could be self sorting, and for this you could sort it in different ways and on different times.
**For Linked Lists**
I would preffere [Insertion sort](http://en.wikipedia.org/wiki/Insertion_sort) for this, you can read various good articles about this on both wikis and other places. I like the pasted link though. Look at it and try to understand the concept.
If you want to sort after it is inserted, i.e. on random times, well then you can just implement a sorting algororithm different than insertion sort maybe, [bubblesort](http://en.wikipedia.org/wiki/Bubble_sort) or maybe [quicksort](http://sv.wikipedia.org/wiki/Quicksort), I would avoid bubblesort though, it's a lot slower! But easier to gasp the mind around.
**Random Access**
Random is always something thats being discusses around so have a read about how to perform good randomization and you will be on your way, if you have a linked list and have a "getAt"-method, you could just randomize an index between 0 and n and get the item at that index.
|
1,650,399 |
I need to implement self-sorted data structure with random access. Any ideas?
|
2009/10/30
|
[
"https://Stackoverflow.com/questions/1650399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199719/"
] |
I'm not too much involved lately with data structures implementation. Probably this answer is not an answer at all... you should see "Introduction to algorithms" written by Thomas Cormen. That book has many "recipes" with explanations about the inner workings of many data structures.
On the other hand you have to take into account how much time do you want to spend writing an algorithm, the size of the input and the if there is an actual necessity of an special kind of datastructure.
|
Self sorting is a little bit to ambigious. First of all
**What kind of data structure?**
There are a lot of different data structures out there, such as:
* Linked list
* Double linked list
* Binary tree
* Hash set / map
* Stack
* Heap
And many more and each of them behave differently than others and have their benefits of course.
Now, not all of them could or should be self-sorting, such as the Stack, it would be weird if that one were self-sorting.
However, the Linked List and the Binary Tree could be self sorting, and for this you could sort it in different ways and on different times.
**For Linked Lists**
I would preffere [Insertion sort](http://en.wikipedia.org/wiki/Insertion_sort) for this, you can read various good articles about this on both wikis and other places. I like the pasted link though. Look at it and try to understand the concept.
If you want to sort after it is inserted, i.e. on random times, well then you can just implement a sorting algororithm different than insertion sort maybe, [bubblesort](http://en.wikipedia.org/wiki/Bubble_sort) or maybe [quicksort](http://sv.wikipedia.org/wiki/Quicksort), I would avoid bubblesort though, it's a lot slower! But easier to gasp the mind around.
**Random Access**
Random is always something thats being discusses around so have a read about how to perform good randomization and you will be on your way, if you have a linked list and have a "getAt"-method, you could just randomize an index between 0 and n and get the item at that index.
|
1,650,399 |
I need to implement self-sorted data structure with random access. Any ideas?
|
2009/10/30
|
[
"https://Stackoverflow.com/questions/1650399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199719/"
] |
A self sorted data structure can be binary search trees. If you want a self sorted data structure and a self balanced one. AVL tree is the way to go. Retrieval time will be O(lgn) for random access.
|
Self sorting is a little bit to ambigious. First of all
**What kind of data structure?**
There are a lot of different data structures out there, such as:
* Linked list
* Double linked list
* Binary tree
* Hash set / map
* Stack
* Heap
And many more and each of them behave differently than others and have their benefits of course.
Now, not all of them could or should be self-sorting, such as the Stack, it would be weird if that one were self-sorting.
However, the Linked List and the Binary Tree could be self sorting, and for this you could sort it in different ways and on different times.
**For Linked Lists**
I would preffere [Insertion sort](http://en.wikipedia.org/wiki/Insertion_sort) for this, you can read various good articles about this on both wikis and other places. I like the pasted link though. Look at it and try to understand the concept.
If you want to sort after it is inserted, i.e. on random times, well then you can just implement a sorting algororithm different than insertion sort maybe, [bubblesort](http://en.wikipedia.org/wiki/Bubble_sort) or maybe [quicksort](http://sv.wikipedia.org/wiki/Quicksort), I would avoid bubblesort though, it's a lot slower! But easier to gasp the mind around.
**Random Access**
Random is always something thats being discusses around so have a read about how to perform good randomization and you will be on your way, if you have a linked list and have a "getAt"-method, you could just randomize an index between 0 and n and get the item at that index.
|
1,650,399 |
I need to implement self-sorted data structure with random access. Any ideas?
|
2009/10/30
|
[
"https://Stackoverflow.com/questions/1650399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199719/"
] |
I see one thing missing from the answers here, the Skiplist
<https://en.wikipedia.org/wiki/Skip_list>
You get order automatically, there is a probabilistic element to search and creation.
Fits the question no worse than binary trees.
|
Self sorting is a little bit to ambigious. First of all
**What kind of data structure?**
There are a lot of different data structures out there, such as:
* Linked list
* Double linked list
* Binary tree
* Hash set / map
* Stack
* Heap
And many more and each of them behave differently than others and have their benefits of course.
Now, not all of them could or should be self-sorting, such as the Stack, it would be weird if that one were self-sorting.
However, the Linked List and the Binary Tree could be self sorting, and for this you could sort it in different ways and on different times.
**For Linked Lists**
I would preffere [Insertion sort](http://en.wikipedia.org/wiki/Insertion_sort) for this, you can read various good articles about this on both wikis and other places. I like the pasted link though. Look at it and try to understand the concept.
If you want to sort after it is inserted, i.e. on random times, well then you can just implement a sorting algororithm different than insertion sort maybe, [bubblesort](http://en.wikipedia.org/wiki/Bubble_sort) or maybe [quicksort](http://sv.wikipedia.org/wiki/Quicksort), I would avoid bubblesort though, it's a lot slower! But easier to gasp the mind around.
**Random Access**
Random is always something thats being discusses around so have a read about how to perform good randomization and you will be on your way, if you have a linked list and have a "getAt"-method, you could just randomize an index between 0 and n and get the item at that index.
|
1,650,399 |
I need to implement self-sorted data structure with random access. Any ideas?
|
2009/10/30
|
[
"https://Stackoverflow.com/questions/1650399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199719/"
] |
A self sorted data structure can be binary search trees. If you want a self sorted data structure and a self balanced one. AVL tree is the way to go. Retrieval time will be O(lgn) for random access.
|
Maintaining a sorted list and accessing it arbitrarily requires at least O(lgN) / operation. So, look for [AVL](http://en.wikipedia.org/wiki/AVL_tree), [red-black trees](http://en.wikipedia.org/wiki/Red-black_tree), [treaps](http://en.wikipedia.org/wiki/Treap) or any other similar data structure and enrich them to support random indexing. I suggest [treaps](http://en.wikipedia.org/wiki/Treap) since they are the easiest to understand/implement.
One way to enrich the treap tree is to keep in each node the count of nodes in the subtree rooted at that node. You'll have to update the count when you modify the tree (eg: insertion/deletion).
|
1,650,399 |
I need to implement self-sorted data structure with random access. Any ideas?
|
2009/10/30
|
[
"https://Stackoverflow.com/questions/1650399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199719/"
] |
A self sorted data structure can be binary search trees. If you want a self sorted data structure and a self balanced one. AVL tree is the way to go. Retrieval time will be O(lgn) for random access.
|
I'm not too much involved lately with data structures implementation. Probably this answer is not an answer at all... you should see "Introduction to algorithms" written by Thomas Cormen. That book has many "recipes" with explanations about the inner workings of many data structures.
On the other hand you have to take into account how much time do you want to spend writing an algorithm, the size of the input and the if there is an actual necessity of an special kind of datastructure.
|
1,650,399 |
I need to implement self-sorted data structure with random access. Any ideas?
|
2009/10/30
|
[
"https://Stackoverflow.com/questions/1650399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199719/"
] |
A self sorted data structure can be binary search trees. If you want a self sorted data structure and a self balanced one. AVL tree is the way to go. Retrieval time will be O(lgn) for random access.
|
I see one thing missing from the answers here, the Skiplist
<https://en.wikipedia.org/wiki/Skip_list>
You get order automatically, there is a probabilistic element to search and creation.
Fits the question no worse than binary trees.
|
389,366 |
I need a solution for file write speeds around 200MB per second.
Data redundancy is not necessary, therefore RAID 0 will probably be used.
Finally, data will be streaming for potentially hours, so SSD's are out of the question.
Is an external RAID enclosure the answer here?
To prevent this from being closed due to openness, you could explain why this solution will/will not work, and point me towards a better alternative if there is one?
A simple "yes" will tell me that this is the solution for me.
Edit: Grammar
|
2012/05/15
|
[
"https://serverfault.com/questions/389366",
"https://serverfault.com",
"https://serverfault.com/users/121161/"
] |
200MB/s comes to about 703GB/hour, and you said "several hours". So it could be several terabytes before the write session is done. And it's nice an sequential.
Write rates like that are easily handled with rotational media. You'll definitely want a fast connection, so no USB2 and probably not Firewire. 3G SAS or SATA will work, I've seen them handle speeds like that. I'd personally put no fewer than 3 drives in the RAID0 set, but 7.2K RPM drives should be able to handle that kind of write pattern.
|
Once you've decided on disk versus SSD, the only question is where you put them. An external direct attached shelf is indeed an option, as is internal disks if you have enough bays.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.